feat(redshift): take a DynamoDB table and a Serverless namespace in zero-ETL integrations (#7332)

* feat(redshift): take a DynamoDB table and a Serverless namespace in zero-ETL integrations

CreateIntegration took only a DynamoDB stream ARN as SourceArn and a provisioned cluster ARN as
TargetArn. AWS takes the table ARN and a Redshift Serverless namespace ARN (its model allows no
cluster: ARN), so a Terraform aws_redshift_integration written for AWS failed to create.

Both AWS forms are now accepted and the original ones are kept. A missing table is
IntegrationSourceNotFoundFault and a missing namespace IntegrationTargetNotFoundFault, as the API
reference lists. A namespace is written through its workgroup into the namespace's database. A
table source reads changes from the table's latest stream, following one turned on after the
integration was created.

Stream records never landed: the writer bound ApproximateCreationDateTime as an Instant, which the
PostgreSQL driver refuses, so only backfilled items reached the landing table. It now binds an
OffsetDateTime as TIMESTAMPTZ.

* fix(redshift): drain a table's replaced stream and match the source table ARN

A table source moved to the table's latest stream as soon as it changed, dropping records the old
stream still held, and moved to no stream when DynamoDB Local reported none for a table whose streams
were turned off. It now reads the followed stream until a read comes back empty, or until the stream
has expired, before moving, keeps it while the table reports no stream, and persists the move.

A source table ARN was resolved by its table name alone, so a table of another account, or an ARN
with more after the name, was taken for the caller's table of that name. The resolved table must now
have the supplied ARN. The docs no longer promise IntegrationSourceNotFoundFault for a missing stream.

* test(redshift): use the shared Docker probe and Query request helpers in the zero-ETL test
This commit is contained in:
Ovidiu (Ovi) authored and GitHub committed 2026-11-02 21:13:21 -04:00
1 parent 56efb188b1
commit 6abdb4cc44
11 files changed
+852 -62

No files matched your search

+1 -1
View File
@@ -118,7 +118,7 @@ DynamoDB Streams are supported via a separate target (`DynamoDBStreams_20120810`
| `GetRecords` | Read stream records from a shard |
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 target,
[Redshift DynamoDB zero-ETL](redshift.md#dynamodb-zero-etl) section for the supported sources and targets,
landing table, checkpoint, and retry behavior.
Stream records are held in memory. `POST /_floci/state/reset` removes every stream along with the
+26 -6
View File
@@ -140,7 +140,7 @@ The attributes follow the [CloudFormation resource schema](https://docs.aws.amaz
| `DeleteTags` | Remove tags by key from a resource |
| `DescribeTags` | List tagged resources and their tags |
| `CreateClusterSubnetGroup` | Register a cluster subnet group (metadata only) |
| `CreateIntegration` | Create a DynamoDB Streams to provisioned Redshift zero-ETL integration. Accepts `Description`, `KMSKeyId`, `AdditionalEncryptionContext` and `TagList` |
| `CreateIntegration` | Create a DynamoDB zero-ETL integration from a table (or a stream) to a Redshift Serverless namespace (or a provisioned cluster). Accepts `Description`, `KMSKeyId`, `AdditionalEncryptionContext` and `TagList` |
| `DescribeIntegrations` | List integrations with `Filters`, `MaxRecords` and `Marker` pagination, or the one an `IntegrationArn` names |
| `DeleteIntegration` | Remove a zero-ETL integration |
| `DescribeClusterSubnetGroups` | List subnet groups, optionally filtered by name |
@@ -375,9 +375,28 @@ Set `FLOCI_SERVICES_REDSHIFT_CLOUDWATCH_METRICS_ENABLED=false` to turn publishin
## DynamoDB zero-ETL
The supported zero-ETL path is DynamoDB Streams to a provisioned Redshift cluster. The source ARN
must identify an enabled local DynamoDB stream, and the target ARN must identify an existing
provisioned Redshift cluster.
As in AWS, `SourceArn` is a DynamoDB table ARN and `TargetArn` is a Redshift Serverless namespace
ARN. Floci also accepts a DynamoDB stream ARN as the source and a provisioned cluster ARN
(`arn:aws:redshift:<region>:<account>:cluster:<identifier>`) as the target. A source table that
does not exist is refused with `IntegrationSourceNotFoundFault`, and a namespace that does not exist
with `IntegrationTargetNotFoundFault`. A source stream that does not exist is refused with DynamoDB's
`ResourceNotFoundException`, and a provisioned cluster target that does not exist with `ClusterNotFound`.
```bash
aws --endpoint-url http://localhost:4566 redshift create-integration \
--integration-name orders-zero-etl \
--source-arn arn:aws:dynamodb:us-east-1:000000000000:table/orders \
--target-arn arn:aws:redshift-serverless:us-east-1:000000000000:namespace/<namespace-id>
```
A namespace target is written through the namespace's workgroup, into the namespace's database as
its admin user. Until the namespace has a workgroup, polling fails and the integration reports
`failed`; it becomes `active` on the first poll after the workgroup exists.
AWS reads the changes of a table source without DynamoDB Streams. Floci reads them from the table's
latest stream, so a table source replicates changes only while the table has one, and a table that
never had a stream gets its initial backfill only. The integration picks up a stream turned on after
it was created, and moves to the new stream when streams are turned off and on again.
Each stream record is written to a stable landing table named `floci_zetl_<integration-id>`.
The landing table stores the event id, event name, source, region, sequence number, creation time,
@@ -422,8 +441,9 @@ 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.
Serverless Redshift targets, schema inference, and relational projection are not supported in this
first implementation.
Schema inference, relational projection and `CREATE DATABASE ... FROM INTEGRATION` are not
supported, and a provisioned cluster's namespace ARN (`arn:aws:redshift:<region>:<account>:namespace:<id>`)
is not accepted as a target.
## CloudFormation
@@ -137,29 +137,94 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
if (targetPaused(integration)) {
return;
}
writer.createLandingTable(integration.getAccountId(), integration.getTargetClusterIdentifier(),
writer.createLandingTable(integration.getAccountId(), integration.getTargetArn(),
integration.getLandingTableName());
if (!integration.isBackfillCompleted()) {
pollBackfillPage(integration);
return;
}
DynamoDbStreamReader.Stream stream = DynamoDbStreamReader.Stream.of(integration.getSourceStreamArn());
String streamArn = followedStream(integration);
if (streamArn == null) {
// A table that never had a stream has nothing to replicate after its backfill.
redshiftService.recoverIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn());
return;
}
DynamoDbStreamReader.Stream stream = DynamoDbStreamReader.Stream.of(streamArn);
List<DynamoDbStreamReader.Shard> shards;
try {
shards = streamReader.shards(stream);
} catch (AwsException e) {
// A stream the table has replaced and that has since expired has nothing left to read.
if (!"ResourceNotFoundException".equals(e.getErrorCode()) || !moveToLatestStream(integration)) {
throw e;
}
return;
}
Set<String> finished = finishedShards.computeIfAbsent(integration.getIntegrationArn(),
ignored -> ConcurrentHashMap.newKeySet());
// ponytail: a shard whose read or write throws ends the tick for the shards after it; the next
// tick starts over from committed progress, so it only delays them.
boolean checkpointPersisted = false;
for (DynamoDbStreamReader.Shard shard : DynamoDbStreamReader.readable(streamReader.shards(stream), finished)) {
for (DynamoDbStreamReader.Shard shard : DynamoDbStreamReader.readable(shards, finished)) {
if (pollShard(integration, stream, shard.shardId(), finished)) {
checkpointPersisted = true;
}
}
if (!checkpointPersisted) {
// Every record of the followed stream has landed, so a newer stream of the table takes over.
moveToLatestStream(integration);
redshiftService.recoverIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn());
}
}
/**
* The stream to read changes from. A stream source is that stream. A table source follows the
* stream it already reads, or the table's latest stream when it reads none yet.
*/
private String followedStream(Integration integration) {
if (integration.getSourceStreamArn() == null) {
moveToLatestStream(integration);
}
return integration.getSourceStreamArn();
}
/**
* Moves a table source to the table's latest stream when that is another stream: none exists until
* streams are first turned on, and a new one each time they are turned on again. Callers move only
* once the followed stream has been read to its end or has expired, since a disabled stream stays
* readable and its last records must still land. A table whose streams are off reports no latest
* stream, so the followed one is kept. Shard ids repeat across a table's streams, so the move drops
* the checkpoints of the old stream; the new one is read from its trim horizon.
*
* @return whether the integration moved to another stream
*/
private boolean moveToLatestStream(Integration integration) {
String sourceArn = integration.getSourceArn();
if (sourceArn == null || RedshiftZeroEtlEndpoints.isStreamArn(sourceArn)) {
return false;
}
String region = AwsArnUtils.parse(sourceArn).region();
String latest = RequestScopes.callAs(integration.getAccountId(), region, () -> {
TableDefinition table = dynamoDb.tables().describeTable(new Scope(integration.getAccountId(), region),
RedshiftZeroEtlEndpoints.tableName(sourceArn));
return table.getStreamArn();
});
if (latest == null || latest.equals(integration.getSourceStreamArn())) {
return false;
}
integration.getShardSequenceNumbers().clear();
finishedShards.remove(integration.getIntegrationArn());
integration.setSourceStreamArn(latest);
redshiftService.updateIntegrationSourceStream(integration.getAccountId(), integration.getIntegrationArn(),
latest);
return true;
}
private boolean targetPaused(Integration integration) {
if (integration.getTargetClusterIdentifier() == null) {
// Only a provisioned cluster pauses.
return false;
}
try {
return redshiftService.describeClustersForAccount(integration.getAccountId(),
integration.getTargetClusterIdentifier()).stream()
@@ -196,7 +261,7 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
}
return false;
}
writer.writeBatch(integration.getAccountId(), integration.getTargetClusterIdentifier(),
writer.writeBatch(integration.getAccountId(), integration.getTargetArn(),
integration.getLandingTableName(),
records.stream().map(DynamoDbStreamReader.Record::awsRecord).toList());
committed.put(shardId, records.get(records.size() - 1).sequenceNumber());
@@ -207,8 +272,10 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
private void pollBackfillPage(Integration integration) {
RequestScopes.runAs(integration.getAccountId(), () -> {
String tableName = extractTableName(integration.getSourceStreamArn());
String region = AwsArnUtils.parse(integration.getSourceStreamArn()).region();
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);
TableDefinition table = dynamoDb.tables().describeTable(scope, tableName);
JsonNode exclusiveStartKey = parseBackfillKey(integration.getBackfillLastEvaluatedKey());
@@ -219,7 +286,7 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
List<JsonNode> records = result.items().stream()
.map(item -> toBackfillRecord(integration, item, table))
.toList();
writer.writeBatch(integration.getAccountId(), integration.getTargetClusterIdentifier(),
writer.writeBatch(integration.getAccountId(), integration.getTargetArn(),
integration.getLandingTableName(), records);
}
@@ -250,11 +317,6 @@ public class RedshiftDynamoDbZeroEtlConsumer implements Resettable {
return record;
}
private static String extractTableName(String sourceStreamArn) {
String resource = AwsArnUtils.parse(sourceStreamArn).resource();
return resource.substring("table/".length(), resource.indexOf("/stream/"));
}
private JsonNode parseBackfillKey(String backfillLastEvaluatedKey) {
if (backfillLastEvaluatedKey == null) {
return null;
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
@@ -111,6 +112,7 @@ public class RedshiftService implements ManagedSecretRotator {
private final RedshiftEventService events;
private final RedshiftIntegrationEventPublisher integrationEvents;
private final Ec2Service ec2Service;
private final RedshiftZeroEtlEndpoints zeroEtlEndpoints;
// Proxy ports currently handed out, so allocateProxyPort never double-assigns within this JVM.
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
private final ConcurrentHashMap<ResourceKey, ResourceLock> resourceLocks = new ConcurrentHashMap<>();
@@ -194,7 +196,7 @@ public class RedshiftService implements ManagedSecretRotator {
SecretsManagerService secretsManagerService, ObjectMapper objectMapper,
DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher,
RedshiftEventService events, RedshiftIntegrationEventPublisher integrationEvents,
Ec2Service ec2Service) {
Ec2Service ec2Service, RedshiftZeroEtlEndpoints zeroEtlEndpoints) {
this.clusters = storageFactory.create("redshift", "redshift-clusters.json", new TypeReference<Map<String, Cluster>>() {});
this.snapshots = storageFactory.create("redshift", "redshift-snapshots.json", new TypeReference<Map<String, Snapshot>>() {});
this.snapshotCopies = storageFactory.create("redshift", "redshift-snapshot-copies.json", new TypeReference<Map<String, Snapshot>>() {});
@@ -218,6 +220,7 @@ public class RedshiftService implements ManagedSecretRotator {
this.events = events;
this.integrationEvents = integrationEvents;
this.ec2Service = ec2Service;
this.zeroEtlEndpoints = zeroEtlEndpoints;
}
// Hand-built test constructions need not supply EC2; a null ec2Service skips subnet resolution.
@@ -229,7 +232,20 @@ public class RedshiftService implements ManagedSecretRotator {
RedshiftEventService events, RedshiftIntegrationEventPublisher integrationEvents) {
this(storageFactory, containerManager, config, regionResolver, proxyManager, dockerHostResolver,
credentialBroker, secretsManagerService, objectMapper, streamReader, auditLogPublisher, events,
integrationEvents, null);
integrationEvents, null, null);
}
// Hand-built test constructions that create integrations in the AWS form need the endpoints.
RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager,
EmulatorConfig config, RegionResolver regionResolver, RedshiftProxyManager proxyManager,
DockerHostResolver dockerHostResolver, RedshiftCredentialBroker credentialBroker,
SecretsManagerService secretsManagerService, ObjectMapper objectMapper,
DynamoDbStreamReader streamReader, RedshiftAuditLogPublisher auditLogPublisher,
RedshiftEventService events, RedshiftIntegrationEventPublisher integrationEvents,
RedshiftZeroEtlEndpoints zeroEtlEndpoints) {
this(storageFactory, containerManager, config, regionResolver, proxyManager, dockerHostResolver,
credentialBroker, secretsManagerService, objectMapper, streamReader, auditLogPublisher, events,
integrationEvents, null, zeroEtlEndpoints);
}
RedshiftService(StorageFactory storageFactory, RedshiftContainerManager containerManager,
@@ -554,8 +570,7 @@ public class RedshiftService implements ManagedSecretRotator {
// ── Zero-ETL integrations ────────────────────────────────────
//
// Metadata only: no data is replicated from the source. The shape and the lower case status
// were captured from a live integration in us-west-2.
// The shape and the lower case status were captured from a live integration in us-west-2.
public Integration createIntegration(String integrationName, String sourceArn, String targetArn,
String kmsKeyId, String description,
@@ -586,26 +601,41 @@ public class RedshiftService implements ManagedSecretRotator {
if (targetArn == null || targetArn.isBlank()) {
throw new AwsException("InvalidParameterValue", "TargetArn is required.", 400);
}
AwsArnUtils.Arn source = parseZeroEtlArn(sourceArn, "DynamoDB stream");
if (!"dynamodb".equals(source.service()) || !source.resource().startsWith("table/")
|| !source.resource().contains("/stream/")) {
// AWS takes a DynamoDB table as the source. A stream ARN is Floci's original form and is kept.
AwsArnUtils.Arn source = parseZeroEtlArn(sourceArn, "DynamoDB table");
if (!"dynamodb".equals(source.service()) || !source.resource().startsWith("table/")) {
throw new AwsException("InvalidParameterValue",
"SourceArn must identify a DynamoDB stream.", 400);
"SourceArn must identify a DynamoDB table or stream.", 400);
}
if (streamReader == null) {
throw new AwsException("InternalFailure", "DynamoDB stream service is unavailable.", 500);
String sourceStreamArn;
if (RedshiftZeroEtlEndpoints.isStreamArn(sourceArn)) {
if (streamReader == null) {
throw new AwsException("InternalFailure", "DynamoDB stream service is unavailable.", 500);
}
streamReader.describeStream(DynamoDbStreamReader.Stream.of(sourceArn), null, null);
sourceStreamArn = sourceArn;
} else {
TableDefinition table = requireZeroEtlEndpoints().sourceTable(integrations.accountId(), sourceArn);
// Changes are read from the table's latest stream; the consumer follows one enabled later.
sourceStreamArn = table.getStreamArn();
}
streamReader.describeStream(DynamoDbStreamReader.Stream.of(sourceArn), null, null);
AwsArnUtils.Arn target = parseZeroEtlArn(targetArn, "Redshift cluster");
if (!"redshift".equals(target.service()) || !target.resource().startsWith("cluster:")) {
// AWS takes a Redshift Serverless namespace as the target. A provisioned cluster ARN is
// Floci's original form and is kept.
AwsArnUtils.Arn target = parseZeroEtlArn(targetArn, "Redshift");
String clusterIdentifier = null;
if (RedshiftZeroEtlEndpoints.isNamespaceArn(targetArn)) {
requireZeroEtlEndpoints().requireTargetNamespace(targetArn);
} else if ("redshift".equals(target.service()) && target.resource().startsWith("cluster:")) {
clusterIdentifier = target.resource().substring("cluster:".length());
if (clusterIdentifier.isBlank()) {
throw new AwsException("InvalidParameterValue", "TargetArn must identify a Redshift cluster.", 400);
}
describeClusters(clusterIdentifier);
} else {
throw new AwsException("InvalidParameterValue",
"TargetArn must identify a provisioned Redshift cluster.", 400);
"TargetArn must identify a Redshift Serverless namespace or a provisioned Redshift cluster.",
400);
}
String clusterIdentifier = target.resource().substring("cluster:".length());
if (clusterIdentifier.isBlank()) {
throw new AwsException("InvalidParameterValue", "TargetArn must identify a Redshift cluster.", 400);
}
describeClusters(clusterIdentifier);
if (description != null && description.length() > MAX_INTEGRATION_DESCRIPTION) {
throw new AwsException("InvalidParameterValue",
"Description must be at most " + MAX_INTEGRATION_DESCRIPTION + " characters.", 400);
@@ -632,7 +662,7 @@ public class RedshiftService implements ManagedSecretRotator {
integration.setIntegrationName(integrationName);
integration.setSourceArn(sourceArn);
integration.setTargetArn(targetArn);
integration.setSourceStreamArn(sourceArn);
integration.setSourceStreamArn(sourceStreamArn);
integration.setTargetClusterIdentifier(clusterIdentifier);
integration.setLandingTableName("floci_zetl_" + integrationId.replace('-', '_'));
integration.setRetryCount(0);
@@ -651,6 +681,13 @@ public class RedshiftService implements ManagedSecretRotator {
return integration;
}
private RedshiftZeroEtlEndpoints requireZeroEtlEndpoints() {
if (zeroEtlEndpoints == null) {
throw new AwsException("InternalFailure", "Zero-ETL endpoint resolution is unavailable.", 500);
}
return zeroEtlEndpoints;
}
private static AwsArnUtils.Arn parseZeroEtlArn(String arn, String resourceType) {
try {
return AwsArnUtils.parse(arn);
@@ -711,7 +748,9 @@ public class RedshiftService implements ManagedSecretRotator {
public List<Integration> listDynamoDbZeroEtlIntegrations() {
return integrations.scanAllAccountEntries(key -> true).stream()
.filter(entry -> entry.value().getSourceStreamArn() != null
// A table source without a stream still has its backfill to run.
.filter(entry -> "dynamodb".equals(sourceType(entry.value().getSourceArn()))
|| entry.value().getSourceStreamArn() != null
&& !entry.value().getSourceStreamArn().isBlank())
.map(entry -> {
Integration integration = entry.value();
@@ -774,6 +813,23 @@ public class RedshiftService implements ManagedSecretRotator {
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) {
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();
integration.setSourceStreamArn(sourceStreamArn);
integration.setShardSequenceNumbers(null);
integrations.putForAccount(accountId, key, integration);
return;
}
throw new AwsException("IntegrationNotFoundFault", "The requested integration doesn't exist.", 404);
}
public void updateIntegrationBackfillProgress(String accountId, String integrationArn,
String backfillLastEvaluatedKey, boolean backfillCompleted) {
updateIntegrationBackfillProgressLocked(accountId, integrationArn, backfillLastEvaluatedKey,
@@ -0,0 +1,90 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations.Scope;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
/**
* The endpoints of a DynamoDB zero-ETL integration in the form AWS takes them: a DynamoDB table as
* the source and a Redshift Serverless namespace as the target.
*/
@ApplicationScoped
public class RedshiftZeroEtlEndpoints {
private final DynamoDbFacade dynamoDb;
private final RedshiftServerlessService serverless;
@Inject
public RedshiftZeroEtlEndpoints(DynamoDbFacade dynamoDb, RedshiftServerlessService serverless) {
this.dynamoDb = dynamoDb;
this.serverless = serverless;
}
/**
* The table a table ARN names, read as {@code accountId} in the ARN's Region. The table must have
* exactly that ARN, so a table of another account, or an ARN with more after the table name, is
* not mistaken for the caller's table of the same name.
*/
public TableDefinition sourceTable(String accountId, String tableArn) {
String region = AwsArnUtils.parse(tableArn).region();
TableDefinition table;
try {
table = RequestScopes.callAs(accountId, region, () ->
dynamoDb.tables().describeTable(new Scope(accountId, region), tableName(tableArn)));
} catch (AwsException e) {
if ("ResourceNotFoundException".equals(e.getErrorCode())) {
throw sourceNotFound();
}
throw e;
}
if (!tableArn.equals(table.getTableArn())) {
throw sourceNotFound();
}
return table;
}
private static AwsException sourceNotFound() {
return new AwsException("IntegrationSourceNotFoundFault",
"The specified integration source can't be found.", 404);
}
/** Refuses a namespace ARN that names no namespace of the caller. */
public void requireTargetNamespace(String namespaceArn) {
if (serverless.findNamespaceByArn(namespaceArn, AwsArnUtils.parse(namespaceArn).region()).isEmpty()) {
throw new AwsException("IntegrationTargetNotFoundFault",
"The specified integration target can't be found.", 404);
}
}
/** The workgroup that serves the namespace, as {@code accountId}. */
public RedshiftServerlessService.WorkgroupTarget targetWorkgroup(String accountId, String namespaceArn) {
String region = AwsArnUtils.parse(namespaceArn).region();
return RequestScopes.callAs(accountId, region,
() -> serverless.getNamespaceWorkgroupTarget(namespaceArn, region));
}
/** Whether a DynamoDB ARN names a stream ({@code table/<name>/stream/<label>}) rather than a table. */
public static boolean isStreamArn(String dynamoDbArn) {
return AwsArnUtils.parse(dynamoDbArn).resource().contains("/stream/");
}
/** Whether an ARN names a Redshift Serverless namespace. */
public static boolean isNamespaceArn(String arn) {
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
return "redshift-serverless".equals(parsed.service()) && parsed.resource().startsWith("namespace/");
}
/** The table name in a table ARN or a stream ARN. */
public static String tableName(String tableOrStreamArn) {
String resource = AwsArnUtils.parse(tableOrStreamArn).resource();
String name = resource.substring("table/".length());
int stream = name.indexOf('/');
return stream < 0 ? name : name.substring(0, stream);
}
}
@@ -3,9 +3,12 @@ package io.github.hectorvent.floci.services.redshiftdata;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.RedshiftZeroEtlEndpoints;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -15,6 +18,8 @@ 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.List;
import java.util.regex.Pattern;
@@ -38,21 +43,25 @@ public class RedshiftZeroEtlWriter {
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (event_id) DO NOTHING";
private final RedshiftService redshiftService;
private final RedshiftZeroEtlEndpoints endpoints;
private final RedshiftDataConnectionFactory connectionFactory;
private final ObjectMapper objectMapper;
@Inject
RedshiftZeroEtlWriter(RedshiftService redshiftService,
RedshiftZeroEtlEndpoints endpoints,
RedshiftDataConnectionFactory connectionFactory,
ObjectMapper objectMapper) {
this.redshiftService = redshiftService;
this.endpoints = endpoints;
this.connectionFactory = connectionFactory;
this.objectMapper = objectMapper;
}
public void createLandingTable(String accountId, String clusterIdentifier, String tableName) {
/** {@code targetArn} names a Redshift Serverless namespace or a provisioned cluster. */
public void createLandingTable(String accountId, String targetArn, String tableName) {
String safeTableName = validateTableName(tableName);
try (Connection connection = connectionFactory.open(target(accountId, clusterIdentifier));
try (Connection connection = connectionFactory.open(target(accountId, targetArn));
Statement statement = connection.createStatement()) {
statement.executeUpdate(LANDING_TABLE_DDL.formatted(safeTableName) + ")");
} catch (SQLException e) {
@@ -61,12 +70,12 @@ public class RedshiftZeroEtlWriter {
}
/** Writes AWS DynamoDB Streams {@code Records[]} elements, skipping event ids already landed. */
public void writeBatch(String accountId, String clusterIdentifier, String tableName, List<JsonNode> records) {
public void writeBatch(String accountId, String targetArn, String tableName, List<JsonNode> records) {
if (records == null || records.isEmpty()) {
return;
}
String safeTableName = validateTableName(tableName);
try (Connection connection = connectionFactory.open(target(accountId, clusterIdentifier));
try (Connection connection = connectionFactory.open(target(accountId, targetArn));
PreparedStatement statement = connection.prepareStatement(INSERT_RECORD.formatted(safeTableName))) {
for (JsonNode record : records) {
bind(statement, record);
@@ -86,7 +95,9 @@ public class RedshiftZeroEtlWriter {
statement.setString(5, text(dynamodb, "SequenceNumber"));
long approximateCreationDateTime = dynamodb.path("ApproximateCreationDateTime").asLong();
if (approximateCreationDateTime > 0) {
statement.setObject(6, Instant.ofEpochSecond(approximateCreationDateTime));
// The PostgreSQL driver binds an OffsetDateTime to TIMESTAMPTZ but cannot infer a type for an Instant.
statement.setObject(6, OffsetDateTime.ofInstant(Instant.ofEpochSecond(approximateCreationDateTime),
ZoneOffset.UTC), Types.TIMESTAMP_WITH_TIMEZONE);
} else {
statement.setNull(6, Types.TIMESTAMP_WITH_TIMEZONE);
}
@@ -120,7 +131,17 @@ public class RedshiftZeroEtlWriter {
}
}
private RedshiftDataResourceResolver.DatabaseTarget target(String accountId, String clusterIdentifier) {
/**
* A namespace is written through its workgroup, into the namespace's database as its admin user, the
* same identity a cluster target is written with.
*/
private RedshiftDataResourceResolver.DatabaseTarget target(String accountId, String targetArn) {
if (RedshiftZeroEtlEndpoints.isNamespaceArn(targetArn)) {
RedshiftServerlessService.WorkgroupTarget workgroup = endpoints.targetWorkgroup(accountId, targetArn);
return new RedshiftDataResourceResolver.DatabaseTarget(workgroup.arn(), workgroup.host(),
workgroup.port(), workgroup.database(), workgroup.masterUsername(), workgroup.masterPassword());
}
String clusterIdentifier = AwsArnUtils.parse(targetArn).resource().substring("cluster:".length());
Cluster cluster;
try {
cluster = redshiftService.describeClustersForAccount(accountId, clusterIdentifier).get(0);
@@ -1234,6 +1234,27 @@ public class RedshiftServerlessService implements Resettable {
}
}
/** The namespace a namespace ARN names in the Region, empty when there is none. */
public Optional<Namespace> findNamespaceByArn(String namespaceArn, String region) {
return namespaceArn == null ? Optional.empty() : namespaceByArn(namespaceArn, region);
}
/**
* The live connection details of the workgroup that serves the namespace a namespace ARN names. A
* namespace has at most one workgroup, so this is how a zero-ETL integration that targets a
* namespace reaches its database.
*/
public WorkgroupTarget getNamespaceWorkgroupTarget(String namespaceArn, String region) {
Namespace namespace = findNamespaceByArn(namespaceArn, region)
.orElseThrow(() -> resourceNotFound(namespaceArn));
Workgroup workgroup = workgroups.scan(key -> key.startsWith(region + "::")).stream()
.filter(candidate -> namespace.getNamespaceName().equals(candidate.getNamespaceName()))
.findFirst()
.orElseThrow(() -> ServerlessSupport.validation(
"Namespace " + namespace.getNamespaceName() + " has no workgroup."));
return getWorkgroupTarget(workgroup.getWorkgroupName(), region);
}
/** The workgroup a workgroup name or ARN names in the Region, as the Data API reads either; empty when none. */
public Optional<Workgroup> findWorkgroupByNameOrArn(String nameOrArn, String region) {
return AwsArnUtils.looksLikeArn(nameOrArn) ? workgroupByArn(nameOrArn, region)
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.dynamodb.backend.RecordingDynamoDbBac
import io.github.hectorvent.floci.services.dynamodb.backend.RecordingDynamoDbBackend.Invocation;
import io.github.hectorvent.floci.services.dynamodb.model.AttributeDefinition;
import io.github.hectorvent.floci.services.dynamodb.model.KeySchemaElement;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.model.Integration;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftZeroEtlWriter;
@@ -69,6 +70,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
DynamoDbFacade dynamoDb;
private static final String SHARD_ID = "shardId-0000000001-00000000001";
private static final String WAREHOUSE_ARN = "arn:aws:redshift:us-east-1:111111111111:cluster:warehouse";
@Test
void healthyIdlePollsDoNotRewriteCheckpointState() {
@@ -111,7 +113,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
verify(service, never()).updateIntegrationRuntime(any(), any(), any(), anyBoolean(), any());
cluster.setClusterStatus("available");
consumer.pollOnce(integration);
verify(writer).writeBatch(integration.getAccountId(), "warehouse", "floci_zetl_orders",
verify(writer).writeBatch(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders",
List.of(streamRecord("s2").awsRecord()));
assertEquals(Map.of(SHARD_ID, "s2"), integration.getShardSequenceNumbers());
}
@@ -169,6 +171,9 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
private final List<Shard> shards = new CopyOnWriteArrayList<>();
private final Map<String, List<Record>> records = new ConcurrentHashMap<>();
private final Set<String> closed = ConcurrentHashMap.newKeySet();
/** Shards of one named stream, for tests that tell a table's streams apart. */
private final Map<String, List<Shard>> streamShards = new ConcurrentHashMap<>();
private final Set<String> expired = ConcurrentHashMap.newKeySet();
private final CheckpointLifetime lifetime;
FakeStreamReader(CheckpointLifetime lifetime) {
@@ -180,24 +185,39 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
return records.computeIfAbsent(shardId, ignored -> new CopyOnWriteArrayList<>());
}
List<Record> shard(String streamArn, String shardId, String parentShardId) {
streamShards.computeIfAbsent(streamArn, ignored -> new CopyOnWriteArrayList<>())
.add(new Shard(shardId, parentShardId, null, null));
return records.computeIfAbsent(streamArn + " " + shardId, ignored -> new CopyOnWriteArrayList<>());
}
void close(String shardId) {
closed.add(shardId);
}
void expire(String streamArn) {
expired.add(streamArn);
}
@Override
public ShardsPage describeStream(Stream stream, String exclusiveStartShardId, Integer limit) {
return new ShardsPage(stream, List.copyOf(shards), null);
if (expired.contains(stream.arn())) {
throw new AwsException("ResourceNotFoundException", "Stream not found: " + stream.arn(), 400);
}
return new ShardsPage(stream, List.copyOf(streamShards.getOrDefault(stream.arn(), shards)), null);
}
@Override
public Cursor getShardIterator(Stream stream, String shardId, Position position, String sequenceNumber) {
iteratorRequests.add(shardId + ":" + position + ":" + sequenceNumber);
iteratorRequests.add((streamShards.containsKey(stream.arn()) ? stream.arn() + " " : "")
+ shardId + ":" + position + ":" + sequenceNumber);
return new Cursor(stream, shardId, position == Position.TRIM_HORIZON ? "" : sequenceNumber);
}
@Override
public RecordsPage getRecords(Cursor cursor, int limit) {
List<Record> held = new ArrayList<>(records.get(cursor.shardId()));
List<Record> held = new ArrayList<>(records.getOrDefault(cursor.stream().arn() + " " + cursor.shardId(),
records.get(cursor.shardId())));
String after = cursor.token();
if (!after.isEmpty() && !held.isEmpty() && after.compareTo(held.get(0).sequenceNumber()) < 0) {
throw new AwsException("TrimmedDataAccessException",
@@ -232,8 +252,8 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer).pollOnce(integration);
verify(writer).createLandingTable(integration.getAccountId(), "warehouse", "floci_zetl_orders");
verify(writer).writeBatch(integration.getAccountId(), "warehouse", "floci_zetl_orders",
verify(writer).createLandingTable(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders");
verify(writer).writeBatch(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders",
List.of(first.awsRecord(), second.awsRecord()));
verify(redshiftService).updateIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn(),
Map.of(SHARD_ID, "s2"), true, null);
@@ -282,7 +302,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
consumer.pollOnce(integration);
verify(writer, times(2)).writeBatch(integration.getAccountId(), "warehouse", "floci_zetl_orders",
verify(writer, times(2)).writeBatch(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders",
List.of(second.awsRecord()));
assertEquals(Map.of(SHARD_ID, "s2"), integration.getShardSequenceNumbers());
}
@@ -414,7 +434,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
consumer.afterReset();
consumer.pollOnce(integration);
verify(writer).writeBatch(integration.getAccountId(), "warehouse", "floci_zetl_orders",
verify(writer).writeBatch(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders",
List.of(second.awsRecord()));
assertEquals(Map.of(SHARD_ID, "s2"), integration.getShardSequenceNumbers());
}
@@ -441,7 +461,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
consumer.pollTask(integration).run();
verify(writer).writeBatch(integration.getAccountId(), "warehouse", "floci_zetl_orders",
verify(writer).writeBatch(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders",
List.of(first.awsRecord()));
verify(redshiftService).updateIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn(),
Map.of(SHARD_ID, "s1"), true, null);
@@ -576,7 +596,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
@SuppressWarnings("unchecked")
ArgumentCaptor<List<JsonNode>> captor = ArgumentCaptor.forClass(List.class);
verify(writer).writeBatch(eq(integration.getAccountId()), eq("warehouse"), eq("floci_zetl_orders"),
verify(writer).writeBatch(eq(integration.getAccountId()), eq(WAREHOUSE_ARN), eq("floci_zetl_orders"),
captor.capture());
assertEquals(100, captor.getValue().size());
JsonNode written = captor.getValue().get(0);
@@ -659,6 +679,158 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
new Invocation("scan", "111111111111", "eu-west-1")), backend.invocations());
}
@Test
void aTableSourceDrainsItsStreamBeforeMovingToTheTablesLatestAndDropsItsCheckpoints() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
String tableName = "orders-streamed-" + System.nanoTime();
TableDefinition table = createTableAs("111111111111", tableName, true);
Integration integration = tableSourceIntegration(table);
integration.setBackfillCompleted(true);
// Progress made on the stream the table had before its streams were turned off and on again,
// which still holds a record the integration has not read.
String previous = table.getTableArn() + "/stream/2026-01-01T00:00:00.000";
integration.setSourceStreamArn(previous);
integration.setShardSequenceNumbers(Map.of(SHARD_ID, "s1"));
DynamoDbStreamReader.Record unread = streamRecord("s2");
streams.shard(previous, SHARD_ID, null).addAll(List.of(streamRecord("s1"), unread));
DynamoDbStreamReader.Record first = streamRecord("s1");
DynamoDbStreamReader.Record second = streamRecord("s2");
streams.shard(table.getStreamArn(), SHARD_ID, null).addAll(List.of(first, second));
RedshiftDynamoDbZeroEtlConsumer consumer =
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer);
consumer.pollOnce(integration);
assertEquals(previous, integration.getSourceStreamArn());
verify(writer).writeBatch(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders",
List.of(unread.awsRecord()));
consumer.pollOnce(integration);
assertEquals(table.getStreamArn(), integration.getSourceStreamArn());
assertTrue(integration.getShardSequenceNumbers().isEmpty());
verify(redshiftService).updateIntegrationSourceStream(integration.getAccountId(),
integration.getIntegrationArn(), table.getStreamArn());
consumer.pollOnce(integration);
assertEquals(List.of(
previous + " " + SHARD_ID + ":AFTER_SEQUENCE_NUMBER:s1",
previous + " " + SHARD_ID + ":AFTER_SEQUENCE_NUMBER:s2",
table.getStreamArn() + " " + SHARD_ID + ":TRIM_HORIZON:null"), streams.iteratorRequests);
verify(writer).writeBatch(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders",
List.of(first.awsRecord(), second.awsRecord()));
assertEquals(Map.of(SHARD_ID, "s2"), integration.getShardSequenceNumbers());
}
@Test
void aTableSourceKeepsReadingItsStreamWhileTheTableHasStreamsTurnedOff() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
String tableName = "orders-stream-off-" + System.nanoTime();
// A backend that reports no stream for a table whose streams are off, as DynamoDB Local does.
TableDefinition table = createTableAs("111111111111", tableName, false);
Integration integration = tableSourceIntegration(table);
integration.setBackfillCompleted(true);
String disabled = table.getTableArn() + "/stream/2026-01-01T00:00:00.000";
integration.setSourceStreamArn(disabled);
DynamoDbStreamReader.Record last = streamRecord("s1");
streams.shard(disabled, SHARD_ID, null).add(last);
RedshiftDynamoDbZeroEtlConsumer consumer =
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer);
consumer.pollOnce(integration);
consumer.pollOnce(integration);
assertEquals(disabled, integration.getSourceStreamArn());
verify(writer).writeBatch(integration.getAccountId(), WAREHOUSE_ARN, "floci_zetl_orders",
List.of(last.awsRecord()));
assertEquals(Map.of(SHARD_ID, "s1"), integration.getShardSequenceNumbers());
verify(redshiftService, never()).updateIntegrationSourceStream(any(), any(), any());
}
@Test
void aTableSourceMovesOnWhenItsReplacedStreamHasExpired() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
String tableName = "orders-stream-expired-" + System.nanoTime();
TableDefinition table = createTableAs("111111111111", tableName, true);
Integration integration = tableSourceIntegration(table);
integration.setBackfillCompleted(true);
String expired = table.getTableArn() + "/stream/2026-01-01T00:00:00.000";
integration.setSourceStreamArn(expired);
integration.setShardSequenceNumbers(Map.of(SHARD_ID, "s1"));
streams.expire(expired);
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer).pollOnce(integration);
assertEquals(table.getStreamArn(), integration.getSourceStreamArn());
assertTrue(integration.getShardSequenceNumbers().isEmpty());
verify(redshiftService).updateIntegrationSourceStream(integration.getAccountId(),
integration.getIntegrationArn(), table.getStreamArn());
}
@Test
void aTableSourceWithoutAStreamIsBackfilledAndThenIdle() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
String tableName = "orders-unstreamed-" + System.nanoTime();
TableDefinition table = createTableAs("111111111111", tableName, false);
RequestScopes.runAs("111111111111",
() -> dynamoDbService.putItem(tableName, itemWithId("1"), "us-east-1"));
Integration integration = tableSourceIntegration(table);
streams.shard(SHARD_ID, null).add(streamRecord("s1"));
RedshiftDynamoDbZeroEtlConsumer consumer =
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer);
consumer.pollOnce(integration);
consumer.pollOnce(integration);
assertTrue(integration.isBackfillCompleted());
verify(writer, times(1)).writeBatch(any(), eq(WAREHOUSE_ARN), any(), any());
verify(redshiftService).recoverIntegrationRuntime(integration.getAccountId(), integration.getIntegrationArn());
assertTrue(streams.iteratorRequests.isEmpty());
}
@Test
void aServerlessTargetIsNeverPausedAndIsWrittenByItsArn() {
FakeStreamReader streams = new FakeStreamReader(CheckpointLifetime.PROCESS);
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlWriter writer = mock(RedshiftZeroEtlWriter.class);
String namespaceArn = "arn:aws:redshift-serverless:us-east-1:111111111111:namespace/"
+ "8f3e0b52-6c1a-4f0e-9d7b-2a4c5e6f7a8b";
Integration integration = streamingIntegration();
integration.setTargetArn(namespaceArn);
integration.setTargetClusterIdentifier(null);
DynamoDbStreamReader.Record first = streamRecord("s1");
streams.shard(SHARD_ID, null).add(first);
new RedshiftDynamoDbZeroEtlConsumer(streams, dynamoDb, redshiftService, writer).pollOnce(integration);
verify(redshiftService, never()).describeClustersForAccount(any(), any());
verify(writer).createLandingTable(integration.getAccountId(), namespaceArn, "floci_zetl_orders");
verify(writer).writeBatch(integration.getAccountId(), namespaceArn, "floci_zetl_orders",
List.of(first.awsRecord()));
}
private TableDefinition createTableAs(String accountId, String tableName, boolean streamed) {
return RequestScopes.callAs(accountId, () -> {
dynamoDbService.createTable(tableName, List.of(new KeySchemaElement("id", "HASH")),
List.of(new AttributeDefinition("id", "S")), 5L, 5L, "us-east-1");
return streamed ? dynamoDbService.enableStream(tableName, null, "us-east-1")
: dynamoDbService.describeTable(tableName, "us-east-1");
});
}
private static Integration tableSourceIntegration(TableDefinition table) {
Integration integration = integration(table.getTableName());
integration.setSourceArn(table.getTableArn());
integration.setSourceStreamArn(table.getStreamArn());
return integration;
}
private static ObjectNode itemWithId(String id) {
ObjectNode item = MAPPER.createObjectNode();
ObjectNode idAttr = MAPPER.createObjectNode();
@@ -672,6 +844,7 @@ class RedshiftDynamoDbZeroEtlConsumerTest {
integration.setIntegrationArn("arn:aws:redshift:us-east-1:111111111111:integration:one");
integration.setAccountId("111111111111");
integration.setSourceStreamArn("arn:aws:dynamodb:us-east-1:111111111111:table/" + tableName + "/stream/one");
integration.setTargetArn(WAREHOUSE_ARN);
integration.setTargetClusterIdentifier("warehouse");
integration.setLandingTableName("floci_zetl_orders");
integration.setPollingEnabled(true);
@@ -0,0 +1,187 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService;
import io.github.hectorvent.floci.testing.DockerAvailability;
import io.github.hectorvent.floci.testing.QueryRequests;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ExtractableResponse;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A DynamoDB zero-ETL integration in the form AWS takes it, a table ARN as {@code SourceArn} and a
* Redshift Serverless namespace ARN as {@code TargetArn}, replicating into the namespace's workgroup.
* Needs Docker.
*/
@QuarkusTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class RedshiftServerlessZeroEtlIntegrationTest {
private static final String TABLE = "zetl-serverless-orders";
private static final String NAMESPACE = "zetl-serverless-ns";
private static final String WORKGROUP = "zetl-serverless-wg";
private static final String ADMIN_PASSWORD = "Secret123";
// Not "dev", to show the landing table goes to the namespace's own database.
private static final String DATABASE = "warehouse";
private static final String REGION = "us-east-1";
@Inject
RedshiftServerlessService serverless;
private String tableArn;
private String namespaceArn;
private int endpointPort;
private boolean created;
/** Creates the resources once, after Quarkus has pointed RestAssured at the test server. */
@BeforeEach
void ensureResources() throws InterruptedException {
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for Redshift Serverless zero-ETL tests");
RestAssuredJsonUtils.configureAwsContentTypes();
if (created) {
return;
}
tableArn = dynamoDb("CreateTable", """
{
"TableName": "%s",
"KeySchema": [{"AttributeName":"id","KeyType":"HASH"}],
"AttributeDefinitions": [{"AttributeName":"id","AttributeType":"S"}],
"BillingMode": "PAY_PER_REQUEST",
"StreamSpecification": {"StreamEnabled": true, "StreamViewType": "NEW_AND_OLD_IMAGES"}
}
""".formatted(TABLE)).path("TableDescription.TableArn");
putItem("before-integration");
namespaceArn = RestAssuredJsonUtils.awsAction("RedshiftServerless", "CreateNamespace", """
{"namespaceName":"%s","adminUsername":"admin","adminUserPassword":"%s","dbName":"%s"}
""".formatted(NAMESPACE, ADMIN_PASSWORD, DATABASE)).then().statusCode(200)
.extract().path("namespace.namespaceArn");
created = true;
endpointPort = RestAssuredJsonUtils.awsAction("RedshiftServerless", "CreateWorkgroup", """
{"workgroupName":"%s","namespaceName":"%s"}
""".formatted(WORKGROUP, NAMESPACE)).then().statusCode(200)
.extract().path("workgroup.endpoint.port");
}
/** Through the service: Quarkus has already pointed RestAssured away from the test server by now. */
@AfterAll
void deleteResources() {
if (created) {
serverless.deleteWorkgroup(WORKGROUP, REGION);
serverless.deleteNamespace(NAMESPACE, REGION);
}
}
@Test
void aTableReplicatesIntoTheNamespaceWorkgroup() throws SQLException {
String response = redshift("CreateIntegration", "IntegrationName", "zetl-serverless",
"SourceArn", tableArn, "TargetArn", namespaceArn)
.then().statusCode(200)
.body(containsString("<SourceArn>" + tableArn + "</SourceArn>"))
.body(containsString("<TargetArn>" + namespaceArn + "</TargetArn>"))
.extract().body().asString();
String integrationArn = response.substring(response.indexOf("<IntegrationArn>") + "<IntegrationArn>".length(),
response.indexOf("</IntegrationArn>"));
String landingTable = "floci_zetl_"
+ integrationArn.substring(integrationArn.lastIndexOf(':') + 1).replace('-', '_');
try {
awaitLanded(landingTable, "before-integration", true);
Awaitility.await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(500))
.untilAsserted(() -> redshift("DescribeIntegrations", "IntegrationArn", integrationArn)
.then().statusCode(200)
.body(containsString("<Status>active</Status>"))
.body(containsString("<SourceArn>" + tableArn + "</SourceArn>"))
.body(containsString("<TargetArn>" + namespaceArn + "</TargetArn>")));
putItem("after-integration");
awaitLanded(landingTable, "after-integration", false);
} finally {
redshift("DeleteIntegration", "IntegrationArn", integrationArn).then().statusCode(200);
}
}
@Test
void aTableThatDoesNotExistIsIntegrationSourceNotFound() {
redshift("CreateIntegration", "IntegrationName", "zetl-no-source",
"SourceArn", tableArn.replace(TABLE, "no-such-table"), "TargetArn", namespaceArn)
.then().statusCode(404)
.body(containsString("IntegrationSourceNotFoundFault"));
}
@Test
void aNamespaceThatDoesNotExistIsIntegrationTargetNotFound() {
String otherNamespace = namespaceArn.substring(0, namespaceArn.lastIndexOf('/') + 1)
+ "00000000-0000-0000-0000-000000000000";
redshift("CreateIntegration", "IntegrationName", "zetl-no-target",
"SourceArn", tableArn, "TargetArn", otherNamespace)
.then().statusCode(404)
.body(containsString("IntegrationTargetNotFoundFault"));
}
private void awaitLanded(String landingTable, String itemId, boolean backfilled) {
Awaitility.await()
.atMost(Duration.ofSeconds(30))
.pollInterval(Duration.ofMillis(500))
.ignoreExceptions()
.untilAsserted(() -> assertTrue(landedEventIds(landingTable, itemId).stream()
.anyMatch(eventId -> eventId.startsWith("backfill#") == backfilled)));
}
/** Event ids of the landed records whose new image is the item with this id. */
private List<String> landedEventIds(String landingTable, String itemId) throws SQLException {
// 127.0.0.1 rather than the advertised address: CI sets floci.emulator.hostname to a name
// that does not resolve from the test JVM.
String url = "jdbc:postgresql://127.0.0.1:" + endpointPort + "/" + DATABASE;
List<String> eventIds = new ArrayList<>();
try (Connection connection = DriverManager.getConnection(url, "admin", ADMIN_PASSWORD);
Statement statement = connection.createStatement();
ResultSet rows = statement.executeQuery("SELECT event_id, new_image_json FROM " + landingTable)) {
while (rows.next()) {
if (rows.getString(2) != null && rows.getString(2).contains("\"" + itemId + "\"")) {
eventIds.add(rows.getString(1));
}
}
}
return eventIds;
}
private static void putItem(String id) {
dynamoDb("PutItem", """
{"TableName": "%s", "Item": {"id": {"S": "%s"}}}
""".formatted(TABLE, id));
}
private static ExtractableResponse<Response> dynamoDb(String action, String body) {
return given()
.header("X-Amz-Target", "DynamoDB_20120810." + action)
.contentType("application/x-amz-json-1.0")
.body(body)
.when().post("/")
.then().statusCode(200).extract();
}
private static Response redshift(String action, String... params) {
return QueryRequests.request("test", "redshift", action, params)
.formParam("Version", "2012-12-01")
.when().post("/");
}
}
@@ -9,9 +9,12 @@ import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbApiStreamReader;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbOperations;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbStreamReader.CheckpointLifetime;
import io.github.hectorvent.floci.services.dynamodb.backend.DynamoDbTableAccess;
import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager;
@@ -26,6 +29,8 @@ import io.github.hectorvent.floci.services.redshift.model.Snapshot;
import io.github.hectorvent.floci.services.redshift.model.SnapshotCopyGrant;
import io.github.hectorvent.floci.services.redshift.model.SnapshotSchedule;
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService;
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import jakarta.ws.rs.core.MultivaluedHashMap;
@@ -863,6 +868,8 @@ class RedshiftServiceTest {
private RedshiftEventService events;
private final Set<String> existingStreams = new HashSet<>();
private RedshiftIntegrationEventPublisher integrationEvents;
private DynamoDbTableAccess zeroEtlTables;
private RedshiftServerlessService zeroEtlServerless;
private RedshiftService service;
@BeforeEach
@@ -911,6 +918,7 @@ class RedshiftServiceTest {
when(sf.<Integration>create(eq("redshift"), eq("redshift-integrations.json"), any())).thenReturn(integrationBackend);
when(sf.<SnapshotSchedule>create(eq("redshift"), eq("redshift-snapshot-schedules.json"), any())).thenReturn(snapshotScheduleBackend);
when(clusterBackend.accountId()).thenReturn("111111111111");
when(integrationBackend.accountId()).thenReturn("111111111111");
regionResolver = new RegionResolver("us-east-1", "111111111111");
@@ -929,9 +937,121 @@ class RedshiftServiceTest {
};
integrationEvents = mock(RedshiftIntegrationEventPublisher.class);
DynamoDbFacade zeroEtlDynamoDb = mock(DynamoDbFacade.class);
zeroEtlTables = mock(DynamoDbTableAccess.class);
when(zeroEtlDynamoDb.tables()).thenReturn(zeroEtlTables);
zeroEtlServerless = mock(RedshiftServerlessService.class);
service = new RedshiftService(sf, cm, config, regionResolver, proxyManager, dockerHostResolver,
credentialBroker, secretsManagerService, mapper,
new DynamoDbApiStreamReader(streams, CheckpointLifetime.PROCESS), null, events, integrationEvents);
new DynamoDbApiStreamReader(streams, CheckpointLifetime.PROCESS), null, events, integrationEvents,
new RedshiftZeroEtlEndpoints(zeroEtlDynamoDb, zeroEtlServerless));
}
private static final String ORDERS_TABLE_ARN = "arn:aws:dynamodb:us-east-1:111111111111:table/orders";
private static final String NAMESPACE_ARN = "arn:aws:redshift-serverless:us-east-1:111111111111:namespace/"
+ "8f3e0b52-6c1a-4f0e-9d7b-2a4c5e6f7a8b";
@Test
void createsAnIntegrationFromATableToAServerlessNamespaceAsAwsTakesThem() {
TableDefinition table = new TableDefinition();
table.setTableName("orders");
table.setTableArn(ORDERS_TABLE_ARN);
table.setStreamArn(ORDERS_TABLE_ARN + "/stream/2026-09-18T00:00:00.000");
when(zeroEtlTables.describeTable(any(), eq("orders"))).thenReturn(table);
when(zeroEtlServerless.findNamespaceByArn(NAMESPACE_ARN, "us-east-1")).thenReturn(Optional.of(new Namespace()));
when(integrationBackend.scan(any())).thenReturn(List.of());
Integration integration = service.createIntegration("orders-to-warehouse", ORDERS_TABLE_ARN, NAMESPACE_ARN,
null, null, Map.of(), Map.of(), "us-east-1");
assertEquals(ORDERS_TABLE_ARN, integration.getSourceArn());
assertEquals(NAMESPACE_ARN, integration.getTargetArn());
assertEquals(table.getStreamArn(), integration.getSourceStreamArn());
assertNull(integration.getTargetClusterIdentifier());
assertEquals("syncing", integration.getStatus());
verify(integrationBackend).put(any(), eq(integration));
}
@Test
void aTableThatNeverHadAStreamIsAcceptedAsTheSource() {
TableDefinition table = new TableDefinition();
table.setTableName("orders");
table.setTableArn(ORDERS_TABLE_ARN);
when(zeroEtlTables.describeTable(any(), eq("orders"))).thenReturn(table);
when(zeroEtlServerless.findNamespaceByArn(NAMESPACE_ARN, "us-east-1")).thenReturn(Optional.of(new Namespace()));
when(integrationBackend.scan(any())).thenReturn(List.of());
Integration integration = service.createIntegration("orders-to-warehouse", ORDERS_TABLE_ARN, NAMESPACE_ARN,
null, null, Map.of(), Map.of(), "us-east-1");
assertNull(integration.getSourceStreamArn());
}
@Test
void aTableArnOfAnotherAccountOrWithASuffixIsNotTheCallersSameNamedTable() {
TableDefinition table = new TableDefinition();
table.setTableName("orders");
table.setTableArn(ORDERS_TABLE_ARN);
when(zeroEtlTables.describeTable(any(), eq("orders"))).thenReturn(table);
for (String sourceArn : List.of("arn:aws:dynamodb:us-east-1:222222222222:table/orders",
ORDERS_TABLE_ARN + "/bogus")) {
AwsException error = assertThrows(AwsException.class, () -> service.createIntegration(
"orders-to-warehouse", sourceArn, NAMESPACE_ARN, null, null, Map.of(), Map.of(), "us-east-1"));
assertEquals("IntegrationSourceNotFoundFault", error.getErrorCode(), sourceArn);
assertEquals(404, error.getHttpStatus());
}
verify(integrationBackend, never()).put(any(), any());
}
@Test
void aMissingSourceTableIsIntegrationSourceNotFound() {
when(zeroEtlTables.describeTable(any(), eq("orders"))).thenThrow(
new AwsException("ResourceNotFoundException", "Requested resource not found", 400));
AwsException error = assertThrows(AwsException.class, () -> service.createIntegration(
"orders-to-warehouse", ORDERS_TABLE_ARN, NAMESPACE_ARN, null, null, Map.of(), Map.of(), "us-east-1"));
assertEquals("IntegrationSourceNotFoundFault", error.getErrorCode());
assertEquals("The specified integration source can't be found.", error.getMessage());
assertEquals(404, error.getHttpStatus());
verify(integrationBackend, never()).put(any(), any());
}
@Test
void aMissingTargetNamespaceIsIntegrationTargetNotFound() {
TableDefinition table = new TableDefinition();
table.setTableName("orders");
table.setTableArn(ORDERS_TABLE_ARN);
when(zeroEtlTables.describeTable(any(), eq("orders"))).thenReturn(table);
when(zeroEtlServerless.findNamespaceByArn(NAMESPACE_ARN, "us-east-1")).thenReturn(Optional.empty());
AwsException error = assertThrows(AwsException.class, () -> service.createIntegration(
"orders-to-warehouse", ORDERS_TABLE_ARN, NAMESPACE_ARN, null, null, Map.of(), Map.of(), "us-east-1"));
assertEquals("IntegrationTargetNotFoundFault", error.getErrorCode());
assertEquals("The specified integration target can't be found.", error.getMessage());
assertEquals(404, error.getHttpStatus());
verify(integrationBackend, never()).put(any(), any());
}
@ParameterizedTest
@ValueSource(strings = {
"arn:aws:redshift-serverless:us-east-1:111111111111:workgroup/8f3e0b52-6c1a-4f0e-9d7b-2a4c5e6f7a8b",
"arn:aws:s3:::warehouse-bucket"})
void aTargetThatIsNeitherANamespaceNorAClusterIsRefused(String targetArn) {
TableDefinition table = new TableDefinition();
table.setTableName("orders");
table.setTableArn(ORDERS_TABLE_ARN);
when(zeroEtlTables.describeTable(any(), eq("orders"))).thenReturn(table);
AwsException error = assertThrows(AwsException.class, () -> service.createIntegration(
"orders-to-warehouse", ORDERS_TABLE_ARN, targetArn, null, null, Map.of(), Map.of(), "us-east-1"));
assertEquals("InvalidParameterValue", error.getErrorCode());
assertEquals("TargetArn must identify a Redshift Serverless namespace or a provisioned Redshift cluster.",
error.getMessage());
}
@Test
@@ -4,22 +4,30 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.RedshiftZeroEtlEndpoints;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Types;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
class RedshiftZeroEtlWriterTest {
private static final String WAREHOUSE_ARN = "arn:aws:redshift:us-east-1:111111111111:cluster:warehouse";
@Test
void createsLandingTableWithStableEventColumns() throws Exception {
RedshiftService redshiftService = mock(RedshiftService.class);
@@ -32,8 +40,9 @@ class RedshiftZeroEtlWriterTest {
when(connectionFactory.open(any())).thenReturn(connection);
when(connection.createStatement()).thenReturn(statement);
RedshiftZeroEtlWriter writer = new RedshiftZeroEtlWriter(redshiftService, connectionFactory, objectMapper);
writer.createLandingTable("111111111111", "warehouse", "floci_zetl_orders");
RedshiftZeroEtlWriter writer = new RedshiftZeroEtlWriter(redshiftService,
mock(RedshiftZeroEtlEndpoints.class), connectionFactory, objectMapper);
writer.createLandingTable("111111111111", WAREHOUSE_ARN, "floci_zetl_orders");
verify(statement).executeUpdate(contains("event_id TEXT PRIMARY KEY"));
verify(statement).executeUpdate(contains("new_image_json TEXT"));
@@ -53,9 +62,10 @@ class RedshiftZeroEtlWriterTest {
JsonNode first = record("event-1", "000000000000000000001");
JsonNode second = record("event-2", "000000000000000000002");
RedshiftZeroEtlWriter writer = new RedshiftZeroEtlWriter(redshiftService, connectionFactory, objectMapper);
RedshiftZeroEtlWriter writer = new RedshiftZeroEtlWriter(redshiftService,
mock(RedshiftZeroEtlEndpoints.class), connectionFactory, objectMapper);
writer.writeBatch("111111111111", "warehouse", "floci_zetl_orders", List.of(first, second));
writer.writeBatch("111111111111", WAREHOUSE_ARN, "floci_zetl_orders", List.of(first, second));
verify(statement, times(2)).executeUpdate();
verify(statement).setString(1, "event-1");
@@ -64,13 +74,43 @@ class RedshiftZeroEtlWriterTest {
verify(statement, times(2)).setString(3, "aws:dynamodb");
verify(statement, times(2)).setString(4, "us-east-1");
verify(statement).setString(5, "000000000000000000002");
verify(statement, times(2)).setObject(6, Instant.ofEpochSecond(1_758_153_600L));
verify(statement, times(2)).setObject(6,
OffsetDateTime.ofInstant(Instant.ofEpochSecond(1_758_153_600L), ZoneOffset.UTC),
Types.TIMESTAMP_WITH_TIMEZONE);
verify(statement, times(2)).setString(7, "{\"id\":\"1\"}");
verify(statement, times(2)).setNull(8, Types.VARCHAR);
verify(statement, times(2)).setString(9, "{\"value\":\"new\"}");
verify(connection).close();
}
@Test
void writesANamespaceThroughItsWorkgroupIntoTheNamespaceDatabase() throws Exception {
String namespaceArn = "arn:aws:redshift-serverless:us-east-1:111111111111:namespace/"
+ "8f3e0b52-6c1a-4f0e-9d7b-2a4c5e6f7a8b";
RedshiftService redshiftService = mock(RedshiftService.class);
RedshiftZeroEtlEndpoints endpoints = mock(RedshiftZeroEtlEndpoints.class);
RedshiftDataConnectionFactory connectionFactory = mock(RedshiftDataConnectionFactory.class);
Connection connection = mock(Connection.class);
when(connection.createStatement()).thenReturn(mock(Statement.class));
when(endpoints.targetWorkgroup("111111111111", namespaceArn)).thenReturn(
new RedshiftServerlessService.WorkgroupTarget(
"arn:aws:redshift-serverless:us-east-1:111111111111:workgroup/analytics", "analytics",
"localhost", 5433, "warehouse", "admin", "password", "admin"));
ArgumentCaptor<RedshiftDataResourceResolver.DatabaseTarget> target =
ArgumentCaptor.forClass(RedshiftDataResourceResolver.DatabaseTarget.class);
when(connectionFactory.open(target.capture())).thenReturn(connection);
new RedshiftZeroEtlWriter(redshiftService, endpoints, connectionFactory, new ObjectMapper())
.createLandingTable("111111111111", namespaceArn, "floci_zetl_orders");
assertEquals("localhost", target.getValue().host());
assertEquals(5433, target.getValue().port());
assertEquals("warehouse", target.getValue().database());
assertEquals("admin", target.getValue().user());
assertEquals("password", target.getValue().password());
verifyNoInteractions(redshiftService);
}
private static Cluster cluster() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("warehouse");