From 6abdb4cc44a7839b8a4b8cd74f470f6a912b0945 Mon Sep 17 00:00:00 2001 From: "Ovidiu (Ovi)" <163712869+ovi-fabric@users.noreply.github.com> Date: Tue, 3 Nov 2026 03:13:21 +0200 Subject: [PATCH] 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 --- docs/services/dynamodb.md | 2 +- docs/services/redshift.md | 32 ++- .../RedshiftDynamoDbZeroEtlConsumer.java | 86 ++++++-- .../services/redshift/RedshiftService.java | 98 +++++++-- .../redshift/RedshiftZeroEtlEndpoints.java | 90 ++++++++ .../redshiftdata/RedshiftZeroEtlWriter.java | 33 ++- .../RedshiftServerlessService.java | 21 ++ .../RedshiftDynamoDbZeroEtlConsumerTest.java | 193 +++++++++++++++++- ...shiftServerlessZeroEtlIntegrationTest.java | 187 +++++++++++++++++ .../redshift/RedshiftServiceTest.java | 122 ++++++++++- .../RedshiftZeroEtlWriterTest.java | 50 ++++- 11 files changed, 852 insertions(+), 62 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftZeroEtlEndpoints.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServerlessZeroEtlIntegrationTest.java diff --git a/docs/services/dynamodb.md b/docs/services/dynamodb.md index 7f81fa02e6..d017dd6d48 100644 --- a/docs/services/dynamodb.md +++ b/docs/services/dynamodb.md @@ -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 diff --git a/docs/services/redshift.md b/docs/services/redshift.md index d120014535..3812988edc 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -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:::cluster:`) 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/ +``` + +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_`. 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:::namespace:`) +is not accepted as a target. ## CloudFormation diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java index 6dced63c57..0cd1e86ad2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftDynamoDbZeroEtlConsumer.java @@ -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 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 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 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; diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java index c669ff975c..f4d97aec38 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java @@ -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 usedPorts = ConcurrentHashMap.newKeySet(); private final ConcurrentHashMap 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>() {}); this.snapshots = storageFactory.create("redshift", "redshift-snapshots.json", new TypeReference>() {}); this.snapshotCopies = storageFactory.create("redshift", "redshift-snapshot-copies.json", new TypeReference>() {}); @@ -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 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 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, diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftZeroEtlEndpoints.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftZeroEtlEndpoints.java new file mode 100644 index 0000000000..1277312455 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftZeroEtlEndpoints.java @@ -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//stream/