feat(rds): add zero-ETL integration control plane (#9335)

RDS now answers CreateIntegration, DescribeIntegrations, ModifyIntegration and DeleteIntegration for zero-ETL integrations from an aurora-postgresql DB cluster or a standalone postgres DB instance into a Redshift Serverless namespace or a provisioned Redshift cluster. It refuses a source or target that does not exist or is of another kind, a duplicate name or source and target pair, an AdditionalEncryptionContext without a KMSKeyId, and a PostgreSQL DataFilter that breaks AWS's rules. DescribeIntegrations takes an ARN, id or name, its filters, MaxRecords and Marker.

No data is copied yet: an integration reports creating, then active. The initial load follows under #7984.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-24 07:24:26 -04:00
1 parent ab46b4b169
commit 660ad99997
13 files changed
+1717 -5

No files matched your search

@@ -0,0 +1,80 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.CreateIntegrationResponse;
import software.amazon.awssdk.services.rds.model.DbClusterNotFoundException;
import software.amazon.awssdk.services.rds.model.Integration;
import software.amazon.awssdk.services.rds.model.IntegrationNotFoundException;
import software.amazon.awssdk.services.rds.model.IntegrationStatus;
import software.amazon.awssdk.services.redshiftserverless.RedshiftServerlessClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DisplayName("RDS zero-ETL integrations")
class RdsZeroEtlIntegrationTest {
@Test
@DisplayName("An Aurora PostgreSQL to Redshift Serverless integration is created, described, modified and deleted")
void integrationLifecycle() {
String clusterId = TestFixtures.uniqueName("sdk-zetl-src");
String namespaceName = TestFixtures.uniqueName("sdk-zetl-dest");
String integrationName = TestFixtures.uniqueName("sdk-zetl");
try (RdsClient rds = TestFixtures.rdsClient();
RedshiftServerlessClient serverless = TestFixtures.redshiftServerlessClient()) {
boolean clusterCreated = false;
boolean namespaceCreated = false;
try {
String sourceArn = rds.createDBCluster(request -> request.dbClusterIdentifier(clusterId)
.engine("aurora-postgresql").masterUsername("postgres")
.masterUserPassword("Secret12345")).dbCluster().dbClusterArn();
clusterCreated = true;
String targetArn = serverless.createNamespace(request -> request.namespaceName(namespaceName))
.namespace().namespaceArn();
namespaceCreated = true;
CreateIntegrationResponse created = rds.createIntegration(request -> request
.integrationName(integrationName).sourceArn(sourceArn).targetArn(targetArn)
.dataFilter("include: orders.*.*"));
assertThat(created.status()).isEqualTo(IntegrationStatus.CREATING);
assertThat(created.integrationArn()).contains(":integration:");
Integration described = rds.describeIntegrations(request -> request
.integrationIdentifier(created.integrationArn())).integrations().get(0);
assertThat(described.status()).isEqualTo(IntegrationStatus.ACTIVE);
assertThat(described.sourceArn()).isEqualTo(sourceArn);
assertThat(described.targetArn()).isEqualTo(targetArn);
assertThat(rds.modifyIntegration(request -> request
.integrationIdentifier(created.integrationArn()).description("orders"))
.status()).isEqualTo(IntegrationStatus.MODIFYING);
assertThat(rds.deleteIntegration(request -> request
.integrationIdentifier(created.integrationArn())).status())
.isEqualTo(IntegrationStatus.DELETING);
assertThatThrownBy(() -> rds.describeIntegrations(request -> request
.integrationIdentifier(created.integrationArn())))
.isInstanceOf(IntegrationNotFoundException.class);
assertThatThrownBy(() -> rds.createIntegration(request -> request
.integrationName(integrationName)
.sourceArn(sourceArn.replace(clusterId, clusterId + "-missing"))
.targetArn(targetArn).dataFilter("include: orders.*.*")))
.isInstanceOf(DbClusterNotFoundException.class);
} finally {
try {
if (namespaceCreated) {
serverless.deleteNamespace(request -> request.namespaceName(namespaceName));
}
} finally {
if (clusterCreated) {
rds.deleteDBCluster(request -> request.dbClusterIdentifier(clusterId)
.skipFinalSnapshot(true));
}
}
}
}
}
}
+1 -1
View File
@@ -83,7 +83,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 38 |
| [MemoryDB](memorydb.md) | `POST /` + `X-Amz-Target: AmazonMemoryDB.*` + TCP proxy | JSON 1.1 + RESP | 13 |
| [Aurora DSQL](dsql.md) | `/cluster`, `/cluster/{identifier}`, `/cluster/{identifier}/policy` + TLS endpoint | REST JSON + wire | 9 |
| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 121 |
| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 125 |
| [RDS Data API](rds-data.md) | `/Execute`, `/BatchExecute`, `/BeginTransaction`, `/CommitTransaction`, `/RollbackTransaction` | REST JSON | 5 |
| [Timestream for InfluxDB](timestream-influxdb.md) | `POST /` + `X-Amz-Target: AmazonTimestreamInfluxDB.*` + InfluxDB container | JSON 1.0 + InfluxDB HTTP | 24 |
| [MSK](msk.md) | `/v1/clusters/...`, `/api/v2/clusters/...` + Redpanda broker | REST JSON + Kafka | 21 |
+42
View File
@@ -157,6 +157,10 @@ RDS endpoints return the us-east-1 hosted zone ID `Z2R2ITUGPM61AM` in all region
| `StartExportTask` | Export a DB snapshot or DB cluster snapshot to S3 as Parquet; see [Exporting snapshots to Amazon S3](#exporting-snapshots-to-amazon-s3) |
| `DescribeExportTasks` | List export tasks, by `ExportTaskIdentifier`, `SourceArn`, `SourceType` and the `export-task-identifier`, `s3-bucket`, `source-arn` and `status` filters |
| `CancelExportTask` | Cancel a running export task; what it already wrote stays in the bucket |
| `CreateIntegration` | Create a zero-ETL integration from an Aurora PostgreSQL cluster or a PostgreSQL instance into a Redshift Serverless namespace or a provisioned cluster; see [Zero-ETL integrations with Amazon Redshift](#zero-etl-integrations-with-amazon-redshift) |
| `DescribeIntegrations` | List integrations, by `IntegrationIdentifier` (ARN, id or name) and the `integration-identifier`, `integration-name`, `source-arn`, `target-arn` and `status` filters |
| `ModifyIntegration` | Change an active integration's name, `DataFilter` or description |
| `DeleteIntegration` | Delete an integration |
| `DescribeGlobalClusters` | List the account's global clusters with their primary and secondary members; see [Global clusters](#global-clusters) |
| `CreateGlobalCluster` | Create an Aurora global database, empty or with an existing Aurora cluster as its primary |
| `ModifyGlobalCluster` | Rename a global cluster, set deletion protection, or upgrade its engine version (members follow) |
@@ -1151,6 +1155,44 @@ What differs from RDS:
- `TotalExtractedDataInGB` is the size of the rows Floci read, in whole gigabytes, and is 0 for
most local data sets.
## Zero-ETL integrations with Amazon Redshift
`CreateIntegration` records a zero-ETL integration from an RDS PostgreSQL source into Redshift.
`IntegrationName`, `SourceArn` and `TargetArn` are required, and `DataFilter`, `Description`,
`KMSKeyId`, `AdditionalEncryptionContext` and `Tags` are optional. The integration ARN is
`arn:aws:rds:<region>:<account>:integration:<uuid>`, and `DescribeIntegrations`,
`ModifyIntegration` and `DeleteIntegration` find an integration by that ARN, by the id at its end
or by its name.
- `SourceArn` names an `aurora-postgresql` DB cluster or a standalone `postgres` DB instance in the
request's account and Region. A cluster or instance that does not exist is refused with
`DBClusterNotFoundFault` or `DBInstanceNotFound`. An Aurora member instance is refused: use its
cluster's ARN.
- `TargetArn` names a Redshift Serverless namespace (`arn:aws:redshift-serverless:...:namespace/<id>`)
or a provisioned cluster (`arn:aws:redshift:...:cluster:<name>`) in the same account and Region.
- `DataFilter` is required and must include at least one database, as RDS requires of a PostgreSQL
source: `include: <database>.*.*`. Each entry is `include:` or `exclude:` followed by
`database.schema.table`, where the schema and table may be `*` or a `/regex/`, with at most 99
patterns of at most 256 characters each.
- `AdditionalEncryptionContext` is only accepted with `KMSKeyId`. An `IntegrationName` already used
in the Region is refused with `IntegrationAlreadyExistsFault`.
`CreateIntegration` reports `creating`, `ModifyIntegration` reports `modifying` and
`DeleteIntegration` reports `deleting`, as on AWS. `ModifyIntegration` only accepts an `active`
integration, otherwise it fails with `InvalidIntegrationStateFault`.
What differs from RDS:
- No data is copied into Redshift yet: an integration reads back as `active` straight after it is
created or modified, without passing through `syncing`.
- Only PostgreSQL sources are accepted. An `aurora-mysql`, `mysql` or `mariadb` source, and a
Multi-AZ `postgres` DB cluster, are refused with `InvalidParameterValue`.
- A target that does not exist is refused with `InvalidParameterValue`. The target's resource
policy, the source's parameter group settings and the KMS key are not checked, and cross-account
sources or targets are not supported.
- The tagging actions do not take an integration ARN yet; `Tags` given on create are kept and
reported back.
## Global clusters
`CreateGlobalCluster` creates an Aurora global database (`aurora-mysql` or `aurora-postgresql`),
@@ -16,6 +16,7 @@ import io.floci.aws.core.common.docker.ContainerRejectedException;
import io.floci.aws.services.docdb.DocDbQueryHandler;
import io.floci.aws.services.neptune.NeptuneQueryHandler;
import io.floci.aws.services.rds.export.RdsExportTaskService;
import io.floci.aws.services.rds.integration.RdsIntegrationService;
import io.floci.aws.services.rds.model.BlueGreenDeployment;
import io.floci.aws.services.rds.model.DatabaseEngine;
import io.floci.aws.services.rds.model.DbCluster;
@@ -43,6 +44,7 @@ import io.floci.aws.services.rds.model.EventSubscription;
import io.floci.aws.services.rds.model.ExportTask;
import io.floci.aws.services.rds.model.GlobalCluster;
import io.floci.aws.services.rds.model.GlobalClusterMember;
import io.floci.aws.services.rds.model.Integration;
import io.floci.aws.services.rds.model.LogExportChanges;
import io.floci.aws.services.rds.model.OptionGroup;
import io.floci.aws.services.rds.model.OptionGroupOption;
@@ -82,16 +84,19 @@ public class RdsQueryHandler {
private final RdsService service;
private final RdsExportTaskService exportTaskService;
private final RdsIntegrationService integrationService;
private final DocDbQueryHandler docDbQueryHandler;
private final NeptuneQueryHandler neptuneQueryHandler;
private final EmulatorConfig config;
private final RegionResolver regionResolver;
@Inject
public RdsQueryHandler(RdsService service, RdsExportTaskService exportTaskService, EmulatorConfig config,
public RdsQueryHandler(RdsService service, RdsExportTaskService exportTaskService,
RdsIntegrationService integrationService, EmulatorConfig config,
RegionResolver regionResolver, DocDbQueryHandler docDbQueryHandler,
NeptuneQueryHandler neptuneQueryHandler) {
this.exportTaskService = exportTaskService;
this.integrationService = integrationService;
this.docDbQueryHandler = docDbQueryHandler;
this.neptuneQueryHandler = neptuneQueryHandler;
this.service = service;
@@ -219,6 +224,10 @@ public class RdsQueryHandler {
case "StartExportTask" -> handleStartExportTask(params, region);
case "DescribeExportTasks" -> handleDescribeExportTasks(params, region);
case "CancelExportTask" -> handleCancelExportTask(params, region);
case "CreateIntegration" -> handleCreateIntegration(params, region);
case "DescribeIntegrations" -> handleDescribeIntegrations(params, region);
case "ModifyIntegration" -> handleModifyIntegration(params, region);
case "DeleteIntegration" -> handleDeleteIntegration(params, region);
case "DescribeGlobalClusters" -> handleDescribeGlobalClusters(params);
case "CreateGlobalCluster" -> handleCreateGlobalCluster(params, region);
case "ModifyGlobalCluster" -> handleModifyGlobalCluster(params);
@@ -2389,6 +2398,127 @@ public class RdsQueryHandler {
return xml.build();
}
// ── Zero-ETL integrations ─────────────────────────────────────────────────
private Response handleCreateIntegration(MultivaluedMap<String, String> params, String region) {
String integrationName = params.getFirst("IntegrationName");
String sourceArn = params.getFirst("SourceArn");
String targetArn = params.getFirst("TargetArn");
Response missing = firstMissingParam(
"SourceArn", sourceArn,
"TargetArn", targetArn,
"IntegrationName", integrationName);
if (missing != null) {
return missing;
}
Integration integration = integrationService.createIntegration(new RdsIntegrationService.CreateRequest(
integrationName, sourceArn, targetArn, params.getFirst("KMSKeyId"),
encryptionContext(params), parseTags(params), params.getFirst("DataFilter"),
params.getFirst("Description")), region);
return Response.ok(AwsQueryResponse.envelope("CreateIntegration", AwsNamespaces.RDS,
integrationXml(integration))).build();
}
private Response handleDescribeIntegrations(MultivaluedMap<String, String> params, String region) {
int limit = recordPageLimit(params);
Map<String, List<String>> filters = new LinkedHashMap<>();
for (int i = 1; params.getFirst("Filters.Filter." + i + ".Name") != null; i++) {
String name = params.getFirst("Filters.Filter." + i + ".Name");
filters.put(name, extractRdsFilterValues(params, name));
}
List<Integration> all = integrationService.describeIntegrations(
params.getFirst("IntegrationIdentifier"), filters, region);
PaginatedResult<Integration> page = recordPage(all, parseMarker(params.getFirst("Marker")), limit);
XmlBuilder xml = new XmlBuilder().start("Integrations");
for (Integration integration : page.items()) {
xml.start("Integration").raw(integrationXml(integration)).end("Integration");
}
xml.end("Integrations");
if (page.nextToken() != null) {
xml.elem("Marker", page.nextToken());
}
return Response.ok(AwsQueryResponse.envelope("DescribeIntegrations", AwsNamespaces.RDS, xml.build())).build();
}
private Response handleModifyIntegration(MultivaluedMap<String, String> params, String region) {
String identifier = params.getFirst("IntegrationIdentifier");
Response missing = firstMissingParam("IntegrationIdentifier", identifier);
if (missing != null) {
return missing;
}
Integration integration = integrationService.modifyIntegration(identifier,
params.getFirst("IntegrationName"), params.getFirst("DataFilter"),
params.getFirst("Description"), region);
return Response.ok(AwsQueryResponse.envelope("ModifyIntegration", AwsNamespaces.RDS,
integrationXml(integration))).build();
}
private Response handleDeleteIntegration(MultivaluedMap<String, String> params, String region) {
String identifier = params.getFirst("IntegrationIdentifier");
Response missing = firstMissingParam("IntegrationIdentifier", identifier);
if (missing != null) {
return missing;
}
Integration integration = integrationService.deleteIntegration(identifier, region);
return Response.ok(AwsQueryResponse.envelope("DeleteIntegration", AwsNamespaces.RDS,
integrationXml(integration))).build();
}
/** Reads an {@code AdditionalEncryptionContext.entry.N.key} / {@code .value} map. */
private static Map<String, String> encryptionContext(MultivaluedMap<String, String> params) {
Map<String, String> context = new LinkedHashMap<>();
for (int i = 1; ; i++) {
String key = params.getFirst("AdditionalEncryptionContext.entry." + i + ".key");
String value = params.getFirst("AdditionalEncryptionContext.entry." + i + ".value");
if (key == null && value == null) {
break;
}
if (key == null) {
throw new AwsException("InvalidParameterValue",
"AdditionalEncryptionContext.entry." + i + ".key is required.", 400);
}
if (value == null) {
throw new AwsException("InvalidParameterValue",
"AdditionalEncryptionContext.entry." + i + ".value is required.", 400);
}
context.put(key, value);
}
return context;
}
static String integrationXml(Integration integration) {
XmlBuilder xml = new XmlBuilder()
.elem("SourceArn", integration.getSourceArn())
.elem("TargetArn", integration.getTargetArn())
.elem("IntegrationName", integration.getIntegrationName())
.elem("IntegrationArn", integration.getIntegrationArn())
.elem("KMSKeyId", integration.getKmsKeyId());
if (!integration.getAdditionalEncryptionContext().isEmpty()) {
xml.start("AdditionalEncryptionContext");
integration.getAdditionalEncryptionContext().forEach((key, value) -> xml.start("entry")
.elem("key", key)
.elem("value", value)
.end("entry"));
xml.end("AdditionalEncryptionContext");
}
xml.elem("Status", integration.getStatus()).start("Tags");
writeTags(xml, integration.getTags());
xml.end("Tags")
.elem("DataFilter", integration.getDataFilter())
.elem("Description", integration.getDescription())
.elem("CreateTime", integration.getCreateTime() != null
? integration.getCreateTime().toString() : null)
.start("Errors");
for (Integration.IntegrationError error : integration.getErrors()) {
xml.start("IntegrationError")
.elem("ErrorCode", error.getErrorCode())
.elem("ErrorMessage", error.getErrorMessage())
.end("IntegrationError");
}
xml.end("Errors");
return xml.build();
}
private Response handleDescribeDbSnapshots(MultivaluedMap<String, String> params, String region) {
String snapshotId = params.getFirst("DBSnapshotIdentifier");
String instanceId = params.getFirst("DBInstanceIdentifier");
@@ -0,0 +1,179 @@
package io.floci.aws.services.rds.integration;
import io.floci.aws.core.common.AwsException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* The {@code DataFilter} of a zero-ETL integration from a PostgreSQL source: a comma-separated list
* of {@code include: database.schema.table} and {@code exclude: database.schema.table} entries in
* Maxwell filter syntax. A schema or table part may be {@code *} or a {@code /regex/}; the database
* part has to be a literal or {@code *}, since RDS takes no regular expression there.
*
* <p>RDS requires a PostgreSQL integration to name at least one database it includes, at most 99
* patterns, and no pattern longer than 256 characters.
*/
public record IntegrationDataFilter(List<Rule> rules) {
static final int MAX_LENGTH = 25_600;
static final int MAX_PATTERNS = 99;
static final int MAX_PATTERN_LENGTH = 256;
// The DataFilter shape's modelled pattern.
private static final Pattern MODELLED = Pattern.compile("[a-zA-Z0-9_ \"\\\\\\-$,*.:?+/]*");
private static final int POSTGRES_PARTS = 3;
/** One {@code include:} or {@code exclude:} entry, split into its database, schema and table parts. */
public record Rule(boolean include, List<String> parts) {
public String database() {
return parts.getFirst();
}
static boolean isWildcard(String part) {
return "*".equals(part);
}
static boolean isRegex(String part) {
return part.length() >= 2 && part.startsWith("/") && part.endsWith("/");
}
}
public IntegrationDataFilter {
rules = List.copyOf(rules);
}
/** Parses and validates a PostgreSQL integration's filter, refusing a missing one. */
public static IntegrationDataFilter parsePostgres(String dataFilter) {
if (dataFilter == null || dataFilter.isBlank()) {
throw invalid("A data filter that includes at least one database (database-name.*.*) is required "
+ "for a PostgreSQL source.");
}
if (dataFilter.length() > MAX_LENGTH || !MODELLED.matcher(dataFilter).matches()) {
throw invalid("The data filter " + dataFilter + " is not valid.");
}
List<Rule> rules = new ArrayList<>();
for (String entry : splitOutsideRegex(dataFilter, ',')) {
rules.add(parseRule(entry.trim(), dataFilter));
}
if (rules.size() > MAX_PATTERNS) {
throw invalid("A data filter can have at most " + MAX_PATTERNS + " patterns.");
}
IntegrationDataFilter filter = new IntegrationDataFilter(rules);
if (filter.includedDatabases().isEmpty()) {
throw invalid("The data filter must include at least one database (database-name.*.*) "
+ "for a PostgreSQL source.");
}
return filter;
}
/** The databases an {@code include:} entry names literally, in the order they first appear. */
public Set<String> includedDatabases() {
Set<String> databases = new LinkedHashSet<>();
for (Rule rule : rules) {
if (rule.include() && !Rule.isWildcard(rule.database())) {
databases.add(rule.database());
}
}
return databases;
}
private static Rule parseRule(String entry, String dataFilter) {
int colon = entry.indexOf(':');
if (colon < 0) {
throw invalid("The data filter " + dataFilter + " is not valid: each pattern must start with "
+ "include: or exclude:.");
}
String type = entry.substring(0, colon).trim().toLowerCase(Locale.ROOT);
String pattern = entry.substring(colon + 1).trim();
boolean include = switch (type) {
case "include" -> true;
case "exclude" -> false;
default -> throw invalid("The data filter " + dataFilter + " is not valid: each pattern must start "
+ "with include: or exclude:.");
};
if (pattern.length() > MAX_PATTERN_LENGTH) {
throw invalid("A data filter pattern can be at most " + MAX_PATTERN_LENGTH + " characters.");
}
List<String> parts = splitOutsideRegex(pattern, '.');
if (parts.size() != POSTGRES_PARTS || parts.stream().anyMatch(String::isBlank)) {
throw invalid("The data filter pattern " + pattern + " is not valid: a PostgreSQL pattern has the "
+ "form database.schema.table.");
}
if (Rule.isRegex(parts.getFirst())) {
throw invalid("The data filter pattern " + pattern + " is not valid: the database name of a "
+ "PostgreSQL pattern can't be a regular expression.");
}
for (String part : parts) {
if (Rule.isRegex(part)) {
String regex = part.substring(1, part.length() - 1);
if (regex.isEmpty() || hasUnescapedSlash(regex)) {
throw invalid("The data filter pattern " + pattern + " is not valid: " + part
+ " is not a valid regular expression.");
}
try {
Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw invalid("The data filter pattern " + pattern + " is not valid: " + part
+ " is not a valid regular expression.");
}
} else if (part.chars().anyMatch(Character::isWhitespace)) {
throw invalid("The data filter pattern " + pattern + " is not valid: a PostgreSQL pattern has the "
+ "form database.schema.table.");
} else if (part.indexOf('/') >= 0) {
throw invalid("The data filter pattern " + pattern + " is not valid: " + part
+ " has an unexpected '/'.");
}
}
return new Rule(include, parts);
}
private static boolean hasUnescapedSlash(String regex) {
for (int i = 0; i < regex.length(); i++) {
char c = regex.charAt(i);
if (c == '\\' && i + 1 < regex.length()) {
i++;
} else if (c == '/') {
return true;
}
}
return false;
}
/** Splits on {@code separator}, leaving alone what a {@code /regex/} part encloses. */
private static List<String> splitOutsideRegex(String value, char separator) {
List<String> pieces = new ArrayList<>();
StringBuilder current = new StringBuilder();
boolean inRegex = false;
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c == '\\' && inRegex && i + 1 < value.length()) {
current.append(c).append(value.charAt(++i));
continue;
}
if (c == '/') {
inRegex = !inRegex;
}
if (c == separator && !inRegex) {
pieces.add(current.toString());
current.setLength(0);
} else {
current.append(c);
}
}
if (inRegex) {
throw invalid("The data filter " + value + " is not valid: a regular expression is not closed.");
}
pieces.add(current.toString());
return pieces;
}
private static AwsException invalid(String message) {
return new AwsException("InvalidParameterValue", message, 400);
}
}
@@ -0,0 +1,408 @@
package io.floci.aws.services.rds.integration;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.Resettable;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.rds.RdsService;
import io.floci.aws.services.rds.model.DatabaseEngine;
import io.floci.aws.services.rds.model.DbCluster;
import io.floci.aws.services.rds.model.DbInstance;
import io.floci.aws.services.rds.model.Integration;
import io.floci.aws.services.redshift.RedshiftService;
import io.floci.aws.services.redshift.RedshiftZeroEtlEndpoints;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Clock;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;
/**
* RDS zero-ETL integrations into Amazon Redshift: {@code CreateIntegration},
* {@code DescribeIntegrations}, {@code ModifyIntegration} and {@code DeleteIntegration}, from an
* Aurora PostgreSQL cluster or an RDS for PostgreSQL instance into a Redshift Serverless namespace
* or a provisioned Redshift cluster.
*
* <p>The record, its validation and its lifecycle are kept here. Nothing is copied into the target
* yet: a created integration reports {@code creating} and is {@code active} on the next read, and a
* modified one reports {@code modifying} and is {@code active} again on the next read. Deviations
* are documented in {@code docs/services/rds.md}.
*/
@ApplicationScoped
public class RdsIntegrationService implements Resettable {
private static final Logger LOG = Logger.getLogger(RdsIntegrationService.class);
private static final String KEY_PREFIX = "integration::";
// The IntegrationName shape's modelled pattern and length.
private static final Pattern NAME = Pattern.compile("[a-zA-Z](?:-?[a-zA-Z0-9]+)*");
private static final int NAME_MAX_LENGTH = 63;
private static final int DESCRIPTION_MAX_LENGTH = 1000;
private static final String AURORA_POSTGRESQL = "aurora-postgresql";
private static final String POSTGRES = "postgres";
private static final Set<String> FILTER_NAMES =
Set.of("integration-identifier", "integration-name", "source-arn", "target-arn", "status");
private final StorageBackend<String, Integration> integrations;
private final RdsService rdsService;
private final RedshiftService redshiftService;
private final RedshiftServerlessService redshiftServerlessService;
private final RegionResolver regionResolver;
private final Clock clock;
private final Object lock = new Object();
@Inject
public RdsIntegrationService(StorageFactory storageFactory, RdsService rdsService,
RedshiftService redshiftService, RedshiftServerlessService redshiftServerlessService,
RegionResolver regionResolver, Clock clock) {
this(storageFactory.create("rds", "rds-integrations.json",
new TypeReference<Map<String, Integration>>() {}),
rdsService, redshiftService, redshiftServerlessService, regionResolver, clock);
}
RdsIntegrationService(StorageBackend<String, Integration> integrations, RdsService rdsService,
RedshiftService redshiftService, RedshiftServerlessService redshiftServerlessService,
RegionResolver regionResolver, Clock clock) {
this.integrations = integrations;
this.rdsService = rdsService;
this.redshiftService = redshiftService;
this.redshiftServerlessService = redshiftServerlessService;
this.regionResolver = regionResolver;
this.clock = clock;
}
public record CreateRequest(String integrationName, String sourceArn, String targetArn, String kmsKeyId,
Map<String, String> additionalEncryptionContext, Map<String, String> tags,
String dataFilter, String description) {}
public Integration createIntegration(CreateRequest request, String region) {
String effectiveRegion = effectiveRegion(region);
String accountId = regionResolver.getAccountId();
requireValidName(request.integrationName());
requireValidDescription(request.description());
requireSource(request.sourceArn(), effectiveRegion, accountId);
requireTarget(request.targetArn(), effectiveRegion, accountId);
IntegrationDataFilter.parsePostgres(request.dataFilter());
Map<String, String> encryptionContext = request.additionalEncryptionContext() != null
? request.additionalEncryptionContext() : Map.of();
if (!encryptionContext.isEmpty() && (request.kmsKeyId() == null || request.kmsKeyId().isBlank())) {
throw new AwsException("InvalidParameterValue",
"AdditionalEncryptionContext can only be specified together with KMSKeyId.", 400);
}
Integration integration = new Integration();
integration.setIntegrationArn(regionResolver.buildArn("rds", effectiveRegion, accountId,
"integration:" + UUID.randomUUID()));
integration.setIntegrationName(request.integrationName());
integration.setSourceArn(request.sourceArn());
integration.setTargetArn(request.targetArn());
integration.setKmsKeyId(blankToNull(request.kmsKeyId()));
integration.setAdditionalEncryptionContext(encryptionContext);
integration.setTags(request.tags());
integration.setDataFilter(request.dataFilter());
integration.setDescription(request.description());
integration.setCreateTime(Instant.now(clock));
integration.setRegion(effectiveRegion);
integration.setAccountId(accountId);
// Nothing is copied yet, so there is no setup to wait for: the record is active, and only the
// create response reports the creating status AWS returns.
integration.setStatus(Integration.STATUS_ACTIVE);
synchronized (lock) {
if (findByName(effectiveRegion, request.integrationName()).isPresent()) {
throw alreadyExists(request.integrationName());
}
if (findBySourceAndTarget(effectiveRegion, request.sourceArn(), request.targetArn()).isPresent()) {
throw new AwsException("IntegrationAlreadyExistsFault",
"An integration between source " + request.sourceArn() + " and target "
+ request.targetArn() + " already exists.", 400);
}
integrations.put(key(effectiveRegion, integration.integrationId()), integration);
}
LOG.infov("Created RDS integration {0} from {1} to {2}", integration.getIntegrationArn(),
integration.getSourceArn(), integration.getTargetArn());
return withStatus(integration, Integration.STATUS_CREATING);
}
/** The Region's integrations, oldest first, narrowed by an identifier and the filters. */
public List<Integration> describeIntegrations(String integrationIdentifier, Map<String, List<String>> filters,
String region) {
String effectiveRegion = effectiveRegion(region);
for (String name : filters.keySet()) {
if (!FILTER_NAMES.contains(name)) {
throw new AwsException("InvalidParameterValue", "Unrecognized filter name: " + name, 400);
}
}
if (integrationIdentifier != null && !integrationIdentifier.isBlank()) {
Integration found = requireIntegration(effectiveRegion, integrationIdentifier);
return matchesFilters(found, filters) ? List.of(new Integration(found)) : List.of();
}
return regionIntegrations(effectiveRegion).stream()
.filter(integration -> matchesFilters(integration, filters))
.map(Integration::new)
.toList();
}
public Integration modifyIntegration(String integrationIdentifier, String integrationName, String dataFilter,
String description, String region) {
String effectiveRegion = effectiveRegion(region);
if (integrationName != null) {
requireValidName(integrationName);
}
requireValidDescription(description);
if (dataFilter != null) {
IntegrationDataFilter.parsePostgres(dataFilter);
}
synchronized (lock) {
Integration integration = requireIntegration(effectiveRegion, integrationIdentifier);
if (!Integration.STATUS_ACTIVE.equals(integration.getStatus())) {
throw new AwsException("InvalidIntegrationStateFault", "The integration "
+ integration.getIntegrationName() + " can't be modified because its status is "
+ integration.getStatus() + ".", 400);
}
Integration updated = new Integration(integration);
if (integrationName != null && !integrationName.equals(updated.getIntegrationName())) {
if (findByName(effectiveRegion, integrationName).isPresent()) {
throw alreadyExists(integrationName);
}
updated.setIntegrationName(integrationName);
}
if (dataFilter != null) {
updated.setDataFilter(dataFilter);
}
if (description != null) {
updated.setDescription(description);
}
integrations.put(key(effectiveRegion, updated.integrationId()), updated);
LOG.infov("Modified RDS integration {0}", updated.getIntegrationArn());
return withStatus(updated, Integration.STATUS_MODIFYING);
}
}
public Integration deleteIntegration(String integrationIdentifier, String region) {
String effectiveRegion = effectiveRegion(region);
synchronized (lock) {
Integration integration = requireIntegration(effectiveRegion, integrationIdentifier);
integrations.delete(key(effectiveRegion, integration.integrationId()));
LOG.infov("Deleted RDS integration {0}", integration.getIntegrationArn());
return withStatus(integration, Integration.STATUS_DELETING);
}
}
private void requireSource(String sourceArn, String region, String accountId) {
AwsArnUtils.Arn arn = parseArn(sourceArn, "SourceArn");
String resource = arn.resource();
int separator = resource.indexOf(':');
if (!"rds".equals(arn.service()) || separator < 0) {
throw invalidSource();
}
requireInScope(arn, region, accountId, "SourceArn");
String type = resource.substring(0, separator);
String identifier = resource.substring(separator + 1);
if (identifier.isBlank()) {
throw invalidSource();
}
switch (type) {
case "cluster" -> requireClusterSource(rdsService.getDbCluster(identifier, region));
case "db" -> requireInstanceSource(rdsService.getDbInstance(identifier, region));
default -> throw invalidSource();
}
}
private static AwsException invalidSource() {
return new AwsException("InvalidParameterValue",
"SourceArn must identify an RDS DB instance or an Aurora DB cluster.", 400);
}
private static void requireClusterSource(DbCluster cluster) {
String engine = engineName(cluster.getEngineIdentifier(), cluster.getEngine(), AURORA_POSTGRESQL);
if (!AURORA_POSTGRESQL.equals(engine)) {
throw unsupportedSource("DB cluster " + cluster.getDbClusterIdentifier(), engine);
}
}
private static void requireInstanceSource(DbInstance instance) {
if (instance.getDbClusterIdentifier() != null && !instance.getDbClusterIdentifier().isBlank()) {
throw new AwsException("InvalidParameterValue", "DB instance " + instance.getDbInstanceIdentifier()
+ " is a member of DB cluster " + instance.getDbClusterIdentifier()
+ ": use the DB cluster ARN as the SourceArn.", 400);
}
String engine = engineName(instance.getEngineIdentifier(), instance.getEngine(), POSTGRES);
if (!POSTGRES.equals(engine)) {
throw unsupportedSource("DB instance " + instance.getDbInstanceIdentifier(), engine);
}
}
/**
* The engine name the resource was created with. A record persisted before the name was kept
* only has the enum, and a PostgreSQL one is taken to be the engine this source type allows.
*/
private static String engineName(String engineIdentifier, DatabaseEngine engine, String postgresName) {
if (engineIdentifier != null && !engineIdentifier.isBlank()) {
return engineIdentifier.toLowerCase(Locale.ROOT);
}
if (engine == DatabaseEngine.POSTGRES) {
return postgresName;
}
return engine != null ? engine.name().toLowerCase(Locale.ROOT) : "";
}
private static AwsException unsupportedSource(String source, String engine) {
return new AwsException("InvalidParameterValue", source + " uses engine " + engine
+ ", which is not a supported zero-ETL source: use an aurora-postgresql DB cluster"
+ " or a postgres DB instance.", 400);
}
private void requireTarget(String targetArn, String region, String accountId) {
AwsArnUtils.Arn arn = parseArn(targetArn, "TargetArn");
boolean namespace = RedshiftZeroEtlEndpoints.isNamespaceArn(targetArn);
boolean cluster = "redshift".equals(arn.service()) && arn.resource().startsWith("cluster:");
if (!namespace && !cluster) {
throw new AwsException("InvalidParameterValue",
"TargetArn must identify a Redshift Serverless namespace or a provisioned Redshift cluster.", 400);
}
requireInScope(arn, region, accountId, "TargetArn");
boolean found = namespace
? redshiftServerlessService.findNamespaceByArn(targetArn, region).isPresent()
: redshiftService.findClusterByArn(targetArn, region).isPresent();
if (!found) {
throw new AwsException("InvalidParameterValue",
"The integration target " + targetArn + " can't be found.", 400);
}
}
private void requireInScope(AwsArnUtils.Arn arn, String region, String accountId, String parameter) {
if (!region.equals(arn.region()) || !accountId.equals(arn.accountId())
|| !regionResolver.partitionForRegion(region).equals(arn.partition())) {
throw new AwsException("InvalidParameterValue", parameter + " " + arn
+ " must be in the integration's account and Region.", 400);
}
}
private static AwsArnUtils.Arn parseArn(String value, String parameter) {
if (value == null || value.isBlank()) {
throw new AwsException("InvalidParameterValue", parameter + " is required.", 400);
}
try {
return AwsArnUtils.parse(value);
} catch (IllegalArgumentException e) {
throw new AwsException("InvalidParameterValue", parameter + " " + value + " is not a valid ARN.", 400);
}
}
private static void requireValidName(String integrationName) {
if (integrationName == null || integrationName.isBlank()) {
throw new AwsException("InvalidParameterValue", "IntegrationName is required.", 400);
}
if (integrationName.length() > NAME_MAX_LENGTH || !NAME.matcher(integrationName).matches()) {
throw new AwsException("InvalidParameterValue", "The integration name " + integrationName
+ " is not valid: use 1 to 63 letters, digits or single hyphens, starting with a letter"
+ " and not ending with a hyphen.", 400);
}
}
private static void requireValidDescription(String description) {
if (description != null && description.length() > DESCRIPTION_MAX_LENGTH) {
throw new AwsException("InvalidParameterValue",
"Description can be at most " + DESCRIPTION_MAX_LENGTH + " characters.", 400);
}
}
/** An integration by its ARN, the id at the end of its ARN, or its name. */
private Integration requireIntegration(String region, String identifier) {
if (identifier == null || identifier.isBlank()) {
throw new AwsException("InvalidParameterValue", "IntegrationIdentifier is required.", 400);
}
List<Integration> all = regionIntegrations(region);
return all.stream().filter(integration -> identifier.equals(integration.getIntegrationArn())).findFirst()
.or(() -> all.stream().filter(integration -> identifier.equals(integration.integrationId())).findFirst())
.or(() -> all.stream()
.filter(integration -> identifier.equals(integration.getIntegrationName())).findFirst())
.orElseThrow(() -> new AwsException("IntegrationNotFoundFault",
"Integration " + identifier + " not found.", 404));
}
private Optional<Integration> findByName(String region, String integrationName) {
return regionIntegrations(region).stream()
.filter(integration -> integrationName.equals(integration.getIntegrationName()))
.findFirst();
}
private Optional<Integration> findBySourceAndTarget(String region, String sourceArn, String targetArn) {
return regionIntegrations(region).stream()
.filter(integration -> sourceArn.equals(integration.getSourceArn())
&& targetArn.equals(integration.getTargetArn()))
.findFirst();
}
private List<Integration> regionIntegrations(String region) {
return integrations.scan(key -> key.startsWith(KEY_PREFIX + region + "::")).stream()
.sorted(Comparator.comparing(Integration::getCreateTime)
.thenComparing(Integration::getIntegrationArn))
.toList();
}
private static boolean matchesFilters(Integration integration, Map<String, List<String>> filters) {
for (Map.Entry<String, List<String>> filter : filters.entrySet()) {
List<String> values = filter.getValue();
if (values.isEmpty()) {
continue;
}
boolean matched = switch (filter.getKey()) {
case "integration-identifier" -> values.contains(integration.getIntegrationArn())
|| values.contains(integration.integrationId());
case "integration-name" -> values.contains(integration.getIntegrationName());
case "source-arn" -> values.contains(integration.getSourceArn());
case "target-arn" -> values.contains(integration.getTargetArn());
case "status" -> values.contains(integration.getStatus());
default -> throw new IllegalStateException("Unvalidated filter name: " + filter.getKey());
};
if (!matched) {
return false;
}
}
return true;
}
private static Integration withStatus(Integration integration, String status) {
Integration reported = new Integration(integration);
reported.setStatus(status);
return reported;
}
private static AwsException alreadyExists(String integrationName) {
return new AwsException("IntegrationAlreadyExistsFault",
"An integration named " + integrationName + " already exists.", 400);
}
private static String blankToNull(String value) {
return value == null || value.isBlank() ? null : value;
}
private String effectiveRegion(String region) {
return region != null && !region.isBlank() ? region : regionResolver.getDefaultRegion();
}
private static String key(String region, String integrationId) {
return KEY_PREFIX + region + "::" + integrationId;
}
@Override
public void clear() {
integrations.clear();
LOG.info("Cleared all RDS integrations");
}
}
@@ -0,0 +1,166 @@
package io.floci.aws.services.rds.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* A zero-ETL integration from an RDS or Aurora database into Amazon Redshift, as
* {@code CreateIntegration} and {@code DescribeIntegrations} describe it. {@code KMSKeyId} and
* {@code AdditionalEncryptionContext} are kept as given: Floci encrypts nothing with them.
*/
@RegisterForReflection
public class Integration {
public static final String STATUS_CREATING = "creating";
public static final String STATUS_ACTIVE = "active";
public static final String STATUS_MODIFYING = "modifying";
public static final String STATUS_FAILED = "failed";
public static final String STATUS_DELETING = "deleting";
public static final String STATUS_SYNCING = "syncing";
public static final String STATUS_NEEDS_ATTENTION = "needs_attention";
@JsonProperty("IntegrationArn")
private String integrationArn;
@JsonProperty("IntegrationName")
private String integrationName;
@JsonProperty("SourceArn")
private String sourceArn;
@JsonProperty("TargetArn")
private String targetArn;
@JsonProperty("KMSKeyId")
private String kmsKeyId;
@JsonProperty("AdditionalEncryptionContext")
private Map<String, String> additionalEncryptionContext = new LinkedHashMap<>();
@JsonProperty("Status")
private String status;
@JsonProperty("Tags")
private Map<String, String> tags = new LinkedHashMap<>();
@JsonProperty("DataFilter")
private String dataFilter;
@JsonProperty("Description")
private String description;
@JsonProperty("CreateTime")
private Instant createTime;
@JsonProperty("Errors")
private List<IntegrationError> errors = new ArrayList<>();
@JsonProperty("Region")
private String region;
@JsonProperty("AccountId")
private String accountId;
public Integration() {}
public Integration(Integration other) {
this.integrationArn = other.integrationArn;
this.integrationName = other.integrationName;
this.sourceArn = other.sourceArn;
this.targetArn = other.targetArn;
this.kmsKeyId = other.kmsKeyId;
this.additionalEncryptionContext = new LinkedHashMap<>(other.additionalEncryptionContext);
this.status = other.status;
this.tags = new LinkedHashMap<>(other.tags);
this.dataFilter = other.dataFilter;
this.description = other.description;
this.createTime = other.createTime;
this.errors = new ArrayList<>(other.errors);
this.region = other.region;
this.accountId = other.accountId;
}
/** The id AWS mints for the integration: the last part of its ARN. */
public String integrationId() {
return integrationArn.substring(integrationArn.lastIndexOf(':') + 1);
}
public String getIntegrationArn() { return integrationArn; }
public void setIntegrationArn(String integrationArn) { this.integrationArn = integrationArn; }
public String getIntegrationName() { return integrationName; }
public void setIntegrationName(String integrationName) { this.integrationName = integrationName; }
public String getSourceArn() { return sourceArn; }
public void setSourceArn(String sourceArn) { this.sourceArn = sourceArn; }
public String getTargetArn() { return targetArn; }
public void setTargetArn(String targetArn) { this.targetArn = targetArn; }
public String getKmsKeyId() { return kmsKeyId; }
public void setKmsKeyId(String kmsKeyId) { this.kmsKeyId = kmsKeyId; }
public Map<String, String> getAdditionalEncryptionContext() { return additionalEncryptionContext; }
public void setAdditionalEncryptionContext(Map<String, String> additionalEncryptionContext) {
this.additionalEncryptionContext = additionalEncryptionContext != null
? new LinkedHashMap<>(additionalEncryptionContext) : new LinkedHashMap<>();
}
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) {
this.tags = tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>();
}
public String getDataFilter() { return dataFilter; }
public void setDataFilter(String dataFilter) { this.dataFilter = dataFilter; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public Instant getCreateTime() { return createTime; }
public void setCreateTime(Instant createTime) { this.createTime = createTime; }
public List<IntegrationError> getErrors() { return errors; }
public void setErrors(List<IntegrationError> errors) {
this.errors = errors != null ? new ArrayList<>(errors) : new ArrayList<>();
}
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public String getAccountId() { return accountId; }
public void setAccountId(String accountId) { this.accountId = accountId; }
/** One entry of an integration's {@code Errors}. */
@RegisterForReflection
public static class IntegrationError {
@JsonProperty("ErrorCode")
private String errorCode;
@JsonProperty("ErrorMessage")
private String errorMessage;
public IntegrationError() {}
public IntegrationError(String errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public String getErrorCode() { return errorCode; }
public void setErrorCode(String errorCode) { this.errorCode = errorCode; }
public String getErrorMessage() { return errorMessage; }
public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; }
}
}
@@ -1207,6 +1207,11 @@ public class RedshiftService implements ManagedSecretRotator {
/** The caller's cluster an ARN names, when the ARN is exactly that cluster's in this Region. */
public Optional<Cluster> findClusterByArn(String clusterArn) {
return findClusterByArn(clusterArn, regionResolver.getRegion());
}
/** The caller's cluster an ARN names, when the ARN is exactly that cluster's in {@code region}. */
public Optional<Cluster> findClusterByArn(String clusterArn, String region) {
if (!AwsArnUtils.looksLikeArn(clusterArn)) {
return Optional.empty();
}
@@ -1214,8 +1219,12 @@ public class RedshiftService implements ManagedSecretRotator {
if (!"redshift".equals(arn.service()) || !arn.resource().startsWith("cluster:")) {
return Optional.empty();
}
String effectiveRegion = region != null && !region.isBlank() ? region : regionResolver.getRegion();
String identifier = arn.resource().substring("cluster:".length());
return regionalCluster(identifier).filter(cluster -> clusterArn.equals(clusterArn(identifier)));
String expectedArn = regionResolver.buildArn("redshift", effectiveRegion, "cluster:" + identifier);
return clusters.get(identifier)
.filter(cluster -> clusterRegion(cluster).equals(effectiveRegion))
.filter(cluster -> clusterArn.equals(expectedArn));
}
/** Sets, or with {@code null} removes, the resource policy of the caller's cluster an ARN names. */
@@ -0,0 +1,218 @@
package io.floci.aws.services.rds;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.RdsMockProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.CreateIntegrationResponse;
import software.amazon.awssdk.services.rds.model.DbClusterNotFoundException;
import software.amazon.awssdk.services.rds.model.DbInstanceNotFoundException;
import software.amazon.awssdk.services.rds.model.DeleteIntegrationResponse;
import software.amazon.awssdk.services.rds.model.DescribeIntegrationsResponse;
import software.amazon.awssdk.services.rds.model.Integration;
import software.amazon.awssdk.services.rds.model.IntegrationAlreadyExistsException;
import software.amazon.awssdk.services.rds.model.IntegrationNotFoundException;
import software.amazon.awssdk.services.rds.model.IntegrationStatus;
import software.amazon.awssdk.services.rds.model.ModifyIntegrationResponse;
import software.amazon.awssdk.services.rds.model.Tag;
import software.amazon.awssdk.services.redshiftserverless.RedshiftServerlessClient;
import software.amazon.awssdk.services.redshiftserverless.model.Namespace;
import software.amazon.awssdk.services.redshiftserverless.model.ResourceNotFoundException;
import java.util.List;
import java.util.Map;
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
import static io.floci.aws.testing.RdsRequests.rdsClient;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* The RDS zero-ETL integration control plane through the SDK: an Aurora PostgreSQL cluster as the
* source and a Redshift Serverless namespace as the target, created, described, modified and deleted,
* and a missing source or target refused.
*/
@QuarkusTest
@TestProfile(RdsMockProfile.class)
class RdsIntegrationIntegrationTest {
private static final String ACCOUNT = "246813579024";
private static final String CLUSTER = "zetl-orders-src";
private static final String INSTANCE = "zetl-orders-db";
private static final String NAMESPACE = "zetl-orders-dest";
private static final String FILTER = "include: orders.*.*";
@AfterEach
void cleanUp() {
try (RdsClient rds = rdsClient("us-east-1", ACCOUNT);
RedshiftServerlessClient serverless = serverlessClient()) {
for (Integration integration : rds.describeIntegrations(request -> {}).integrations()) {
rds.deleteIntegration(request -> request.integrationIdentifier(integration.integrationArn()));
}
try {
rds.deleteDBCluster(request -> request.dbClusterIdentifier(CLUSTER).skipFinalSnapshot(true));
} catch (DbClusterNotFoundException ignored) {
// the test failed before it created the cluster
}
try {
rds.deleteDBInstance(request -> request.dbInstanceIdentifier(INSTANCE).skipFinalSnapshot(true));
} catch (DbInstanceNotFoundException ignored) {
// the test did not create the standalone instance
}
for (Namespace namespace : serverless.listNamespaces(request -> {}).namespaces()) {
try {
serverless.deleteNamespace(request -> request.namespaceName(namespace.namespaceName()));
} catch (ResourceNotFoundException ignored) {
// already removed
}
}
}
}
private static RedshiftServerlessClient serverlessClient() {
return AwsTestClients.create(RedshiftServerlessClient.builder(), ACCOUNT, Region.US_EAST_1);
}
private static String createSource(RdsClient rds) {
return rds.createDBCluster(request -> request.dbClusterIdentifier(CLUSTER).engine("aurora-postgresql")
.masterUsername("postgres").masterUserPassword("Secret123")).dbCluster().dbClusterArn();
}
private static String createTarget(RedshiftServerlessClient serverless) {
return serverless.createNamespace(request -> request.namespaceName(NAMESPACE)).namespace().namespaceArn();
}
@Test
void integrationLifecycleThroughTheSdk() {
try (RdsClient rds = rdsClient("us-east-1", ACCOUNT);
RedshiftServerlessClient serverless = serverlessClient()) {
String sourceArn = createSource(rds);
String targetArn = createTarget(serverless);
CreateIntegrationResponse created = rds.createIntegration(request -> request
.integrationName("orders-zero-etl").sourceArn(sourceArn).targetArn(targetArn)
.dataFilter(FILTER).description("orders into Redshift")
.kmsKeyId("alias/orders").additionalEncryptionContext(Map.of("purpose", "analytics"))
.tags(Tag.builder().key("team").value("data").build()));
assertThat(created.status(), equalTo(IntegrationStatus.CREATING));
assertThat(created.integrationArn(), matchesPattern(
"arn:aws:rds:us-east-1:" + ACCOUNT + ":integration:[0-9a-f-]{36}"));
assertThat(created.sourceArn(), equalTo(sourceArn));
assertThat(created.targetArn(), equalTo(targetArn));
assertThat(created.dataFilter(), equalTo(FILTER));
assertThat(created.kmsKeyId(), equalTo("alias/orders"));
assertThat(created.additionalEncryptionContext(), equalTo(Map.of("purpose", "analytics")));
assertThat(created.tags(), contains(Tag.builder().key("team").value("data").build()));
assertThat(created.createTime(), notNullValue());
assertThat(created.errors(), empty());
Integration described = rds.describeIntegrations(request -> request
.integrationIdentifier(created.integrationArn())).integrations().getFirst();
assertThat(described.status(), equalTo(IntegrationStatus.ACTIVE));
assertThat(described.integrationName(), equalTo("orders-zero-etl"));
assertThat(described.description(), equalTo("orders into Redshift"));
assertThrows(IntegrationAlreadyExistsException.class, () -> rds.createIntegration(request -> request
.integrationName("orders-zero-etl").sourceArn(sourceArn).targetArn(targetArn)
.dataFilter(FILTER)));
ModifyIntegrationResponse modified = rds.modifyIntegration(request -> request
.integrationIdentifier("orders-zero-etl").integrationName("orders-renamed")
.dataFilter("include: orders.public.*").description("renamed"));
assertThat(modified.status(), equalTo(IntegrationStatus.MODIFYING));
assertThat(modified.integrationName(), equalTo("orders-renamed"));
List<Integration> byFilter = rds.describeIntegrations(request -> request.filters(filter -> filter
.name("source-arn").values(sourceArn))).integrations();
assertThat(byFilter.stream().map(Integration::dataFilter).toList(),
contains("include: orders.public.*"));
DeleteIntegrationResponse deleted = rds.deleteIntegration(request -> request
.integrationIdentifier(created.integrationArn()));
assertThat(deleted.status(), equalTo(IntegrationStatus.DELETING));
assertThat(rds.describeIntegrations(request -> {}).integrations(), empty());
assertThrows(IntegrationNotFoundException.class, () -> rds.describeIntegrations(request -> request
.integrationIdentifier(created.integrationArn())));
}
}
@Test
void createIntegrationRefusesAMissingSourceOrTarget() {
try (RdsClient rds = rdsClient("us-east-1", ACCOUNT);
RedshiftServerlessClient serverless = serverlessClient()) {
String targetArn = createTarget(serverless);
assertAwsError("DBClusterNotFoundFault", 404, () -> rds.createIntegration(request -> request
.integrationName("orders-zero-etl")
.sourceArn("arn:aws:rds:us-east-1:" + ACCOUNT + ":cluster:missing")
.targetArn(targetArn).dataFilter(FILTER)));
String sourceArn = createSource(rds);
assertAwsError("InvalidParameterValue", 400, () -> rds.createIntegration(request -> request
.integrationName("orders-zero-etl").sourceArn(sourceArn)
.targetArn("arn:aws:redshift-serverless:us-east-1:" + ACCOUNT
+ ":namespace/00000000-0000-0000-0000-000000000000")
.dataFilter(FILTER)));
assertAwsError("InvalidParameterValue", 400, () -> rds.createIntegration(request -> request
.integrationName("orders-zero-etl").sourceArn(sourceArn).targetArn(targetArn)));
assertThat(rds.describeIntegrations(request -> {}).integrations(), empty());
}
}
@Test
void standalonePostgresInstanceIntegrationThroughTheSdk() {
try (RdsClient rds = rdsClient("us-east-1", ACCOUNT);
RedshiftServerlessClient serverless = serverlessClient()) {
String sourceArn = rds.createDBInstance(request -> request.dbInstanceIdentifier(INSTANCE)
.dbInstanceClass("db.t3.micro").engine("postgres")
.masterUsername("postgres").masterUserPassword("Secret123")).dbInstance().dbInstanceArn();
String targetArn = createTarget(serverless);
CreateIntegrationResponse created = rds.createIntegration(request -> request
.integrationName("orders-from-instance").sourceArn(sourceArn).targetArn(targetArn)
.dataFilter(FILTER));
assertThat(created.status(), equalTo(IntegrationStatus.CREATING));
assertThat(created.sourceArn(), equalTo(sourceArn));
assertThat(created.targetArn(), equalTo(targetArn));
Integration described = rds.describeIntegrations(request -> request
.integrationIdentifier(created.integrationArn())).integrations().getFirst();
assertThat(described.status(), equalTo(IntegrationStatus.ACTIVE));
}
}
@Test
void describeIntegrationsPaginatesWithMaxRecordsAndMarker() {
try (RdsClient rds = rdsClient("us-east-1", ACCOUNT);
RedshiftServerlessClient serverless = serverlessClient()) {
String sourceArn = createSource(rds);
for (int i = 0; i < 21; i++) {
String nsName = "zetl-page-" + i;
String targetArn = serverless.createNamespace(request -> request.namespaceName(nsName))
.namespace().namespaceArn();
String integrationName = "orders-page-" + i;
rds.createIntegration(request -> request.integrationName(integrationName)
.sourceArn(sourceArn).targetArn(targetArn).dataFilter(FILTER));
}
DescribeIntegrationsResponse firstPage = rds.describeIntegrations(request -> request.maxRecords(20));
assertThat(firstPage.integrations(), hasSize(20));
assertThat(firstPage.marker(), notNullValue());
DescribeIntegrationsResponse secondPage = rds.describeIntegrations(request -> request
.maxRecords(20).marker(firstPage.marker()));
assertThat(secondPage.integrations(), hasSize(1));
assertThat(secondPage.marker(), nullValue());
}
}
}
@@ -9,6 +9,7 @@ import io.floci.aws.services.docdb.DocDbQueryHandler;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.neptune.NeptuneQueryHandler;
import io.floci.aws.services.rds.export.RdsExportTaskService;
import io.floci.aws.services.rds.integration.RdsIntegrationService;
import io.floci.aws.services.rds.model.DatabaseEngine;
import io.floci.aws.services.rds.model.DbCluster;
import io.floci.aws.services.rds.model.DbClusterParameterGroup;
@@ -60,6 +61,7 @@ class RdsQueryHandlerTest {
private RdsService service;
private RdsExportTaskService exportTaskService;
private RdsIntegrationService integrationService;
private DocDbQueryHandler docDbHandler;
private NeptuneQueryHandler neptuneHandler;
private RdsQueryHandler handler;
@@ -82,8 +84,9 @@ class RdsQueryHandlerTest {
docDbHandler = mock(DocDbQueryHandler.class);
neptuneHandler = mock(NeptuneQueryHandler.class);
exportTaskService = mock(RdsExportTaskService.class);
handler = new RdsQueryHandler(service, exportTaskService, config, regionResolver, docDbHandler,
neptuneHandler);
integrationService = mock(RdsIntegrationService.class);
handler = new RdsQueryHandler(service, exportTaskService, integrationService, config,
regionResolver, docDbHandler, neptuneHandler);
}
@ParameterizedTest
@@ -4037,4 +4040,31 @@ class RdsQueryHandlerTest {
assertTrue(body.contains("<Code>InternalFailure</Code>"), body);
assertTrue(body.contains("<Message>Unexpected error: Docker daemon connection failed</Message>"), body);
}
@Test
void createIntegration_rejectsIncompleteEncryptionContextEntry() {
MultivaluedMap<String, String> missingValue = params();
missingValue.add("IntegrationName", "orders-zero-etl");
missingValue.add("SourceArn", "arn:aws:rds:us-east-1:000000000000:cluster:orders-src");
missingValue.add("TargetArn", "arn:aws:redshift-serverless:us-east-1:000000000000:namespace/ns-1");
missingValue.add("KMSKeyId", "alias/orders");
missingValue.add("AdditionalEncryptionContext.entry.1.key", "purpose");
Response missingValueResponse = handler.handle("CreateIntegration", missingValue);
assertEquals(400, missingValueResponse.getStatus());
assertTrue(((String) missingValueResponse.getEntity()).contains("<Code>InvalidParameterValue</Code>"));
MultivaluedMap<String, String> missingKey = params();
missingKey.add("IntegrationName", "orders-zero-etl");
missingKey.add("SourceArn", "arn:aws:rds:us-east-1:000000000000:cluster:orders-src");
missingKey.add("TargetArn", "arn:aws:redshift-serverless:us-east-1:000000000000:namespace/ns-1");
missingKey.add("KMSKeyId", "alias/orders");
missingKey.add("AdditionalEncryptionContext.entry.1.value", "analytics");
Response missingKeyResponse = handler.handle("CreateIntegration", missingKey);
assertEquals(400, missingKeyResponse.getStatus());
assertTrue(((String) missingKeyResponse.getEntity()).contains("<Code>InvalidParameterValue</Code>"));
verifyNoInteractions(integrationService);
}
}
@@ -0,0 +1,89 @@
package io.floci.aws.services.rds.integration;
import io.floci.aws.core.common.AwsException;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** The PostgreSQL data filter forms the RDS documentation shows, and the ones it refuses. */
class IntegrationDataFilterTest {
@Test
void parsesTheDocumentedPostgresExamples() {
for (String filter : List.of(
"include: books.*.*",
"include: books.*.*, exclude: books.*.mystery",
"include: books.mystery.stephen_king, include: employee.finance.benefits",
"include: books.science_fiction.*, exclude: books.*./.*king.*/",
"include: books.*.*, exclude: books./sci.*/.*",
"include: books.*./table_.*/, exclude: books.*.table_stephen_king",
"include: mydb.myschema./table_\\d+/",
"include: mydb./sales team/.*")) {
IntegrationDataFilter parsed = IntegrationDataFilter.parsePostgres(filter);
assertFalse(parsed.rules().isEmpty(), filter);
}
}
@Test
void keepsEachRuleWithItsTypeAndParts() {
IntegrationDataFilter parsed = IntegrationDataFilter.parsePostgres(
"Include: books.*.*, EXCLUDE: books.*./.*king.*/, include: employee.finance.benefits");
assertThat(parsed.rules(), hasSize(3));
assertTrue(parsed.rules().get(0).include());
assertFalse(parsed.rules().get(1).include());
assertThat(parsed.rules().get(1).parts(), contains("books", "*", "/.*king.*/"));
assertThat(parsed.includedDatabases(), contains("books", "employee"));
}
@Test
void requiresAFilterThatIncludesADatabase() {
assertInvalid(null);
assertInvalid(" ");
assertInvalid("include: *.*.*");
assertInvalid("exclude: books.*.*");
}
@Test
void refusesWhatIsNotAPostgresPattern() {
assertInvalid("books.*.*");
assertInvalid("keep: books.*.*");
assertInvalid("include: books.*");
assertInvalid("include: books.a.b.c");
assertInvalid("include: /bo.*/.*.*");
assertInvalid("include: books.*./unclosed");
assertInvalid("include: books.*.{x}");
assertInvalid("include: books.*./*/");
assertInvalid("include: books.*./+/");
assertInvalid("include: books.*.//");
assertInvalid("include: books.public.a/b/c");
assertInvalid("include: books.*./a/b/c/");
assertInvalid("include: books.public.bad table");
assertInvalid("include: books. /sales team/.*");
}
@Test
void refusesMoreThanTheAllowedPatternsOrAPatternTooLong() {
String many = String.join(", ", Collections.nCopies(100, "include: books.*.*"));
AwsException tooMany = assertInvalid(many);
assertThat(tooMany.getMessage(), containsString("99"));
assertInvalid("include: books.*." + "t".repeat(260));
}
private static AwsException assertInvalid(String filter) {
AwsException error = assertThrows(AwsException.class, () -> IntegrationDataFilter.parsePostgres(filter));
assertEquals("InvalidParameterValue", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
return error;
}
}
@@ -0,0 +1,359 @@
package io.floci.aws.services.rds.integration;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.services.rds.RdsService;
import io.floci.aws.services.rds.model.DatabaseEngine;
import io.floci.aws.services.rds.model.DbCluster;
import io.floci.aws.services.rds.model.DbInstance;
import io.floci.aws.services.rds.model.Integration;
import io.floci.aws.services.redshift.RedshiftService;
import io.floci.aws.services.redshift.model.Cluster;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
import io.floci.aws.services.redshiftserverless.model.Namespace;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.matchesPattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* The integration record and its checks, with the RDS source and the Redshift target looked up
* through mocks: the statuses each call reports, the source and target checks, and the identifier
* forms a describe, modify or delete accepts.
*/
class RdsIntegrationServiceTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
private static final String CLUSTER_ARN = "arn:aws:rds:us-east-1:000000000000:cluster:orders-src";
private static final String INSTANCE_ARN = "arn:aws:rds:us-east-1:000000000000:db:orders-db";
private static final String NAMESPACE_ARN = "arn:aws:redshift-serverless:us-east-1:000000000000:"
+ "namespace/4b2f2f9c-7d1e-4f55-9a77-1a2b3c4d5e6f";
private static final String REDSHIFT_CLUSTER_ARN = "arn:aws:redshift:us-east-1:000000000000:cluster:orders-dw";
private static final String FILTER = "include: orders.*.*";
private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-11-24T09:00:00Z"), ZoneOffset.UTC);
private InMemoryStorage<String, Integration> storage;
private RdsService rdsService;
private RedshiftService redshiftService;
private RedshiftServerlessService serverless;
private RdsIntegrationService service;
@BeforeEach
void setUp() {
storage = new InMemoryStorage<>();
rdsService = mock(RdsService.class);
redshiftService = mock(RedshiftService.class);
serverless = mock(RedshiftServerlessService.class);
when(rdsService.getDbCluster("orders-src", REGION)).thenReturn(cluster("orders-src", "aurora-postgresql"));
when(rdsService.getDbCluster("missing", REGION)).thenThrow(
new AwsException("DBClusterNotFoundFault", "DB cluster missing not found.", 404));
when(serverless.findNamespaceByArn(anyString(), anyString())).thenReturn(Optional.empty());
when(serverless.findNamespaceByArn(NAMESPACE_ARN, REGION)).thenReturn(Optional.of(new Namespace()));
when(redshiftService.findClusterByArn(anyString(), anyString())).thenReturn(Optional.empty());
when(redshiftService.findClusterByArn(REDSHIFT_CLUSTER_ARN, REGION)).thenReturn(Optional.of(new Cluster()));
service = new RdsIntegrationService(storage, rdsService, redshiftService, serverless,
new RegionResolver(REGION, ACCOUNT), CLOCK);
}
private static DbCluster cluster(String id, String engine) {
DbCluster cluster = new DbCluster();
cluster.setDbClusterIdentifier(id);
cluster.setEngine(engine.contains("postgres") ? DatabaseEngine.POSTGRES : DatabaseEngine.MYSQL);
cluster.setEngineIdentifier(engine);
return cluster;
}
private static DbInstance instance(String id, String engine, String clusterId) {
DbInstance instance = new DbInstance();
instance.setDbInstanceIdentifier(id);
instance.setEngine(engine.contains("postgres") ? DatabaseEngine.POSTGRES : DatabaseEngine.MYSQL);
instance.setEngineIdentifier(engine);
instance.setDbClusterIdentifier(clusterId);
return instance;
}
private static RdsIntegrationService.CreateRequest request(String name, String sourceArn, String targetArn) {
return new RdsIntegrationService.CreateRequest(name, sourceArn, targetArn, null, Map.of(),
Map.of("team", "data"), FILTER, "orders into Redshift");
}
private Integration create(String name) {
return service.createIntegration(request(name, CLUSTER_ARN, NAMESPACE_ARN), REGION);
}
private static void assertError(String code, int status, Runnable call) {
AwsException error = assertThrows(AwsException.class, call::run);
assertEquals(code, error.getErrorCode(), error.getMessage());
assertEquals(status, error.getHttpStatus());
}
@Test
void createIntegration_reportsCreatingAndIsActiveWhenReadBack() {
Integration created = create("orders-zero-etl");
assertThat(created.getStatus(), equalTo("creating"));
assertThat(created.getIntegrationArn(), matchesPattern(
"arn:aws:rds:us-east-1:000000000000:integration:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-"
+ "[0-9a-f]{12}"));
assertThat(created.getSourceArn(), equalTo(CLUSTER_ARN));
assertThat(created.getTargetArn(), equalTo(NAMESPACE_ARN));
assertThat(created.getDataFilter(), equalTo(FILTER));
assertThat(created.getDescription(), equalTo("orders into Redshift"));
assertThat(created.getTags(), equalTo(Map.of("team", "data")));
assertThat(created.getCreateTime(), equalTo(CLOCK.instant()));
assertThat(created.getErrors(), empty());
Integration described = service.describeIntegrations(null, Map.of(), REGION).getFirst();
assertThat(described.getStatus(), equalTo("active"));
assertThat(described.getIntegrationArn(), equalTo(created.getIntegrationArn()));
}
@Test
void createIntegration_takesAPostgresInstanceAndAProvisionedCluster() {
when(rdsService.getDbInstance("orders-db", REGION)).thenReturn(instance("orders-db", "postgres", null));
Integration created = service.createIntegration(
request("orders-from-instance", INSTANCE_ARN, REDSHIFT_CLUSTER_ARN), REGION);
assertThat(created.getSourceArn(), equalTo(INSTANCE_ARN));
assertThat(created.getTargetArn(), equalTo(REDSHIFT_CLUSTER_ARN));
}
@Test
void createIntegration_refusesASourceThatDoesNotExist() {
assertError("DBClusterNotFoundFault", 404, () -> service.createIntegration(
request("orders", "arn:aws:rds:us-east-1:000000000000:cluster:missing", NAMESPACE_ARN), REGION));
when(rdsService.getDbInstance("gone", REGION)).thenThrow(
new AwsException("DBInstanceNotFound", "DB instance gone not found.", 404));
assertError("DBInstanceNotFound", 404, () -> service.createIntegration(
request("orders", "arn:aws:rds:us-east-1:000000000000:db:gone", NAMESPACE_ARN), REGION));
}
@Test
void createIntegration_refusesATargetThatDoesNotExist() {
assertError("InvalidParameterValue", 400, () -> service.createIntegration(request("orders", CLUSTER_ARN,
"arn:aws:redshift-serverless:us-east-1:000000000000:namespace/missing"), REGION));
assertError("InvalidParameterValue", 400, () -> service.createIntegration(request("orders", CLUSTER_ARN,
"arn:aws:redshift:us-east-1:000000000000:cluster:missing"), REGION));
}
@Test
void createIntegration_refusesASourceOrTargetOfAnotherKind() {
assertError("InvalidParameterValue", 400, () -> service.createIntegration(request("orders",
"arn:aws:rds:us-east-1:000000000000:snapshot:orders", NAMESPACE_ARN), REGION));
assertError("InvalidParameterValue", 400, () -> service.createIntegration(request("orders",
"arn:aws:rds:us-east-1:000000000000:cluster:", NAMESPACE_ARN), REGION));
assertError("InvalidParameterValue", 400, () -> service.createIntegration(request("orders",
"arn:aws:rds:us-east-1:000000000000:db:", NAMESPACE_ARN), REGION));
assertError("InvalidParameterValue", 400, () -> service.createIntegration(request("orders",
CLUSTER_ARN, "arn:aws:s3:::orders"), REGION));
assertError("InvalidParameterValue", 400, () -> service.createIntegration(request("orders",
"not-an-arn", NAMESPACE_ARN), REGION));
}
@Test
void createIntegration_refusesASourceInAnotherRegionOrAccount() {
assertError("InvalidParameterValue", 400, () -> service.createIntegration(request("orders",
"arn:aws:rds:us-west-2:000000000000:cluster:orders-src", NAMESPACE_ARN), REGION));
assertError("InvalidParameterValue", 400, () -> service.createIntegration(request("orders",
"arn:aws:rds:us-east-1:111111111111:cluster:orders-src", NAMESPACE_ARN), REGION));
}
@Test
void createIntegration_refusesAnEngineThatIsNotPostgres() {
when(rdsService.getDbCluster("mysql-src", REGION)).thenReturn(cluster("mysql-src", "aurora-mysql"));
when(rdsService.getDbCluster("multi-az", REGION)).thenReturn(cluster("multi-az", "postgres"));
when(rdsService.getDbInstance("mysql-db", REGION)).thenReturn(instance("mysql-db", "mysql", null));
assertError("InvalidParameterValue", 400, () -> service.createIntegration(request("orders",
"arn:aws:rds:us-east-1:000000000000:cluster:mysql-src", NAMESPACE_ARN), REGION));
assertError("InvalidParameterValue", 400, () -> service.createIntegration(request("orders",
"arn:aws:rds:us-east-1:000000000000:cluster:multi-az", NAMESPACE_ARN), REGION));
assertError("InvalidParameterValue", 400, () -> service.createIntegration(request("orders",
"arn:aws:rds:us-east-1:000000000000:db:mysql-db", NAMESPACE_ARN), REGION));
}
@Test
void createIntegration_refusesAnAuroraMemberInstance() {
when(rdsService.getDbInstance("orders-src-1", REGION))
.thenReturn(instance("orders-src-1", "aurora-postgresql", "orders-src"));
AwsException error = assertThrows(AwsException.class, () -> service.createIntegration(request("orders",
"arn:aws:rds:us-east-1:000000000000:db:orders-src-1", NAMESPACE_ARN), REGION));
assertThat(error.getMessage(), containsString("DB cluster ARN"));
}
@Test
void createIntegration_refusesAnInvalidName() {
assertError("InvalidParameterValue", 400, () -> create("1orders"));
assertError("InvalidParameterValue", 400, () -> create("orders-"));
assertError("InvalidParameterValue", 400, () -> create("orders--etl"));
assertError("InvalidParameterValue", 400, () -> create("a".repeat(64)));
}
@Test
void createIntegration_refusesANameAlreadyTaken() {
create("orders-zero-etl");
assertError("IntegrationAlreadyExistsFault", 400, () -> create("orders-zero-etl"));
}
@Test
void createIntegration_refusesADuplicateSourceAndTargetPair() {
create("orders-zero-etl");
assertError("IntegrationAlreadyExistsFault", 400, () -> service.createIntegration(
request("orders-second-name", CLUSTER_ARN, NAMESPACE_ARN), REGION));
}
@Test
void createIntegration_requiresADataFilterNamingADatabase() {
assertError("InvalidParameterValue", 400, () -> service.createIntegration(
new RdsIntegrationService.CreateRequest("orders", CLUSTER_ARN, NAMESPACE_ARN, null, Map.of(),
Map.of(), null, null), REGION));
}
@Test
void createIntegration_takesAnEncryptionContextOnlyWithAKey() {
assertError("InvalidParameterValue", 400, () -> service.createIntegration(
new RdsIntegrationService.CreateRequest("orders", CLUSTER_ARN, NAMESPACE_ARN, null,
Map.of("purpose", "analytics"), Map.of(), FILTER, null), REGION));
Integration created = service.createIntegration(new RdsIntegrationService.CreateRequest("orders",
CLUSTER_ARN, NAMESPACE_ARN, "alias/orders", Map.of("purpose", "analytics"), Map.of(), FILTER,
null), REGION);
assertThat(created.getKmsKeyId(), equalTo("alias/orders"));
assertThat(created.getAdditionalEncryptionContext(), equalTo(Map.of("purpose", "analytics")));
}
@Test
void describeIntegrations_findsAnIntegrationByArnIdOrName() {
Integration created = create("orders-zero-etl");
service.createIntegration(request("other-zero-etl", CLUSTER_ARN, REDSHIFT_CLUSTER_ARN), REGION);
for (String identifier : List.of(created.getIntegrationArn(), created.integrationId(), "orders-zero-etl")) {
List<Integration> found = service.describeIntegrations(identifier, Map.of(), REGION);
assertThat(found.stream().map(Integration::getIntegrationArn).toList(),
contains(created.getIntegrationArn()));
}
assertThat(service.describeIntegrations(created.getIntegrationArn(),
Map.of("status", List.of("active")), REGION).stream().map(Integration::getIntegrationArn).toList(),
contains(created.getIntegrationArn()));
assertThat(service.describeIntegrations(created.getIntegrationArn(),
Map.of("status", List.of("failed")), REGION), empty());
assertError("IntegrationNotFoundFault", 404,
() -> service.describeIntegrations("missing", Map.of(), REGION));
}
@Test
void describeIntegrations_prefersIdMatchOverAnotherIntegrationsName() {
Integration first = create("orders-zero-etl");
Integration second = service.createIntegration(
request("other-zero-etl", CLUSTER_ARN, REDSHIFT_CLUSTER_ARN), REGION);
String secondId = second.integrationId();
String firstKey = "integration::" + REGION + "::" + first.integrationId();
Integration renamed = new Integration(storage.get(firstKey).orElseThrow());
renamed.setIntegrationName(secondId);
storage.put(firstKey, renamed);
List<Integration> found = service.describeIntegrations(secondId, Map.of(), REGION);
assertThat(found.stream().map(Integration::getIntegrationArn).toList(),
contains(second.getIntegrationArn()));
}
@Test
void describeIntegrations_isScopedToTheRegionAndFiltered() {
Integration orders = create("orders-zero-etl");
service.createIntegration(request("other-zero-etl", CLUSTER_ARN, REDSHIFT_CLUSTER_ARN), REGION);
assertThat(service.describeIntegrations(null, Map.of(), "us-west-2"), empty());
assertThat(service.describeIntegrations(null, Map.of("integration-name", List.of("orders-zero-etl")),
REGION).stream().map(Integration::getIntegrationArn).toList(), contains(orders.getIntegrationArn()));
assertThat(service.describeIntegrations(null, Map.of("status", List.of("failed")), REGION), empty());
assertError("InvalidParameterValue", 400,
() -> service.describeIntegrations(null, Map.of("engine", List.of("postgres")), REGION));
}
@Test
void modifyIntegration_reportsModifyingAndKeepsTheChanges() {
Integration created = create("orders-zero-etl");
Integration modified = service.modifyIntegration(created.getIntegrationArn(), "orders-renamed",
"include: orders.public.*", "renamed", REGION);
assertThat(modified.getStatus(), equalTo("modifying"));
Integration described = service.describeIntegrations(created.getIntegrationArn(), Map.of(), REGION)
.getFirst();
assertThat(described.getStatus(), equalTo("active"));
assertThat(described.getIntegrationName(), equalTo("orders-renamed"));
assertThat(described.getDataFilter(), equalTo("include: orders.public.*"));
assertThat(described.getDescription(), equalTo("renamed"));
}
@Test
void modifyIntegration_refusesATakenNameAnInvalidFilterAndAnUnknownIntegration() {
Integration created = create("orders-zero-etl");
service.createIntegration(request("other-zero-etl", CLUSTER_ARN, REDSHIFT_CLUSTER_ARN), REGION);
assertError("IntegrationAlreadyExistsFault", 400, () -> service.modifyIntegration(
created.getIntegrationArn(), "other-zero-etl", null, null, REGION));
assertError("InvalidParameterValue", 400, () -> service.modifyIntegration(
created.getIntegrationArn(), null, "include: orders.items", null, REGION));
assertError("IntegrationNotFoundFault", 404, () -> service.modifyIntegration(
"missing", null, null, "changed", REGION));
}
@Test
void modifyIntegration_refusesAnIntegrationThatIsNotActive() {
Integration created = create("orders-zero-etl");
String key = "integration::" + REGION + "::" + created.integrationId();
Integration stored = new Integration(storage.get(key).orElseThrow());
stored.setStatus(Integration.STATUS_CREATING);
storage.put(key, stored);
assertError("InvalidIntegrationStateFault", 400, () -> service.modifyIntegration(
created.getIntegrationArn(), null, null, "changed", REGION));
}
@Test
void deleteIntegration_reportsDeletingAndRemovesTheRecord() {
Integration created = create("orders-zero-etl");
Integration deleted = service.deleteIntegration(created.getIntegrationArn(), REGION);
assertThat(deleted.getStatus(), equalTo("deleting"));
assertThat(service.describeIntegrations(null, Map.of(), REGION), empty());
assertError("IntegrationNotFoundFault", 404,
() -> service.deleteIntegration(created.getIntegrationArn(), REGION));
// The name is free again once the integration is gone.
create("orders-zero-etl");
}
@Test
void clear_removesEveryIntegration() {
create("orders-zero-etl");
service.clear();
assertThat(service.describeIntegrations(null, Map.of(), REGION), empty());
}
}
@@ -365,6 +365,8 @@ class RedshiftServiceTest {
String arn = "arn:aws:redshift:us-east-1:111111111111:cluster:warehouse";
assertTrue(service.findClusterByArn(arn).isPresent());
assertTrue(service.findClusterByArn(arn, "us-east-1").isPresent());
assertTrue(service.findClusterByArn(arn, "eu-west-1").isEmpty());
for (String other : List.of("arn:aws:redshift:us-east-1:222222222222:cluster:warehouse",
"arn:aws:redshift:eu-west-1:111111111111:cluster:warehouse",
"arn:aws:redshift:us-east-1:111111111111:snapshot:warehouse/nightly")) {