diff --git a/docs/services/rds.md b/docs/services/rds.md index f399ba5d64..fb53e6d463 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -1181,10 +1181,56 @@ or by its name. `DeleteIntegration` reports `deleting`, as on AWS. `ModifyIntegration` only accepts an `active` integration, otherwise it fails with `InvalidIntegrationStateFault`. +### Initial load into a destination database + +An integration reads back as `active` once created. Its data lands in Redshift once a database is +created from it on the target, as on AWS. Connect to the cluster or workgroup and run: + +```sql +CREATE DATABASE orders_dw FROM INTEGRATION '' DATABASE 'orders'; +``` + +`` is the last part of the integration ARN. `DATABASE` names the source database, +which a PostgreSQL source requires and its `DataFilter` must include. The integration then reports +`syncing` while Floci copies the source database in, and `active` again once the copy is done. +Floci copies each table that the filter includes and that has a primary key into a table of the same +schema and name. As on RDS, the filter's entries apply in order, the last matching entry decides, and +a table that no entry matches is not copied. Column types follow the +[Aurora PostgreSQL to Redshift mapping](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/zero-etl.querying.html): +`text` becomes `VARCHAR(65535)`, `numeric(p,s)` becomes `DECIMAL(p,s)`, `json`, `jsonb` and arrays +become `SUPER`, `bytea` becomes `VARBYTE`, and so on. + +The statement fails with: + +- SQLSTATE `42704` when the integration does not exist or replicates into another cluster or + workgroup, and `0A000` for a DynamoDB integration's id. +- `42601` without `DATABASE`, and `22023` for a source database the filter does not include. +- `42P04` when a database created from that source database still exists on the target. Once that + database is dropped, or after its load failed, the statement loads it again (reusing the existing + database when retrying a failed load with the same name). +- `25001` inside a transaction block. + +Databases from several source databases of one integration can be created one after the other, +also while an earlier one is still loading. The `SET` and `WITH` options are accepted and ignored. +A load that a restart interrupts starts again from the beginning. A table that cannot be loaded, for +example because a value is longer than its Redshift column, is logged as a warning while the other +tables still load, and the integration finishes `failed` with `InitialLoadFailed`. When the source +or the target cannot be reached, Floci tries the load again a few times, then leaves the integration +`failed`, with the cause under `Errors` (`InitialLoadFailed`). + 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 the initial load is copied. Changes made to the source after it are not replicated. +- A table without a primary key, or with a column type AWS does not replicate (an enum, a domain, a + range, a type from an extension, `numeric` without a precision), is skipped and logged as a + warning. Floci also skips `bit` and `bit varying` columns. The table states of + `SVV_INTEGRATION_TABLE_STATE` are not reported. +- With `FLOCI_SERVICES_RDS_MOCK=true` there is no source database, so the destination database is + created empty and the integration goes back to `active`. +- On Redshift Serverless the Data API only reaches the namespace's own database, so query the + destination database over the workgroup's PostgreSQL endpoint. A provisioned cluster serves it + through both. +- Changing `DataFilter` with `ModifyIntegration` does not load or drop tables. - 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 diff --git a/docs/services/redshift.md b/docs/services/redshift.md index f9fbce1018..1e87aedb71 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -646,8 +646,10 @@ 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. -`CREATE DATABASE ... FROM INTEGRATION`, history mode and `SVV_INTEGRATION*` views are not -supported, and a provisioned cluster's namespace ARN (`arn:aws:redshift:::namespace:`) +`CREATE DATABASE ... FROM INTEGRATION` is supported for RDS and Aurora PostgreSQL integrations only; +see [Zero-ETL integrations with Amazon Redshift](rds.md#zero-etl-integrations-with-amazon-redshift). +For a DynamoDB integration it fails with SQLSTATE `0A000`. History mode and `SVV_INTEGRATION*` views +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/floci/aws/lifecycle/EmulatorLifecycle.java b/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java index ab6bfd1961..acd1f73f0c 100644 --- a/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/floci/aws/lifecycle/EmulatorLifecycle.java @@ -44,6 +44,7 @@ import io.floci.aws.services.opensearch.OpenSearchService; import io.floci.aws.services.pipes.PipesService; import io.floci.aws.services.rds.RdsService; import io.floci.aws.services.rds.container.RdsContainerManager; +import io.floci.aws.services.rds.integration.RdsIntegrationLoader; import io.floci.aws.services.rds.proxy.RdsProxyManager; import io.floci.aws.services.redshift.RedshiftDynamoDbZeroEtlConsumer; import io.floci.aws.services.sagemaker.SageMakerService; @@ -135,6 +136,7 @@ public class EmulatorLifecycle { private final CloudWatchMetricsService cloudWatchMetricsService; private final DynamoDbRuntime dynamoDbRuntime; private final RedshiftDynamoDbZeroEtlConsumer redshiftZeroEtlConsumer; + private final RdsIntegrationLoader rdsIntegrationLoader; // Set on the boot thread, read by the async HttpServerStart observer. private volatile CompletableFuture metadataServerStarted = CompletableFuture.completedFuture(null); @@ -185,7 +187,8 @@ public class EmulatorLifecycle { RedshiftDynamoDbZeroEtlConsumer redshiftZeroEtlConsumer, EksService eksService, CodeArtifactService codeArtifactService, - CloudWatchMetricsService cloudWatchMetricsService) { + CloudWatchMetricsService cloudWatchMetricsService, + RdsIntegrationLoader rdsIntegrationLoader) { this.storageFactory = storageFactory; this.serviceRegistry = serviceRegistry; this.config = config; @@ -234,6 +237,7 @@ public class EmulatorLifecycle { this.cloudWatchMetricsService = cloudWatchMetricsService; this.dynamoDbRuntime = dynamoDbRuntime; this.redshiftZeroEtlConsumer = redshiftZeroEtlConsumer; + this.rdsIntegrationLoader = rdsIntegrationLoader; } void onStart(@Observes StartupEvent ignored) { @@ -291,6 +295,7 @@ public class EmulatorLifecycle { pipesService.startPersistedPollers(); redshiftZeroEtlConsumer.startPersistedIntegrations(); rdsService.restorePersistedRuntime(); + rdsIntegrationLoader.resumeInterruptedLoads(); if (config.services().memorydb().enabled()) { memoryDbService.restorePersistedRuntime().exceptionally(ex -> { LOG.warnv(ex, "MemoryDB runtime restoration failed"); diff --git a/src/main/java/io/floci/aws/services/rds/integration/IntegrationDataFilter.java b/src/main/java/io/floci/aws/services/rds/integration/IntegrationDataFilter.java index d1f2174ef9..00d1c0a90b 100644 --- a/src/main/java/io/floci/aws/services/rds/integration/IntegrationDataFilter.java +++ b/src/main/java/io/floci/aws/services/rds/integration/IntegrationDataFilter.java @@ -83,6 +83,41 @@ public record IntegrationDataFilter(List rules) { return databases; } + /** Whether some {@code include:} entry can match a table of {@code database}. */ + public boolean includesDatabase(String database) { + return rules.stream().anyMatch(rule -> rule.include() && matches(rule.database(), database)); + } + + /** + * Whether the filter replicates the table. As on RDS, the entries are applied in order and the + * last one that matches decides; a table no entry matches is not replicated, since a filter + * switches the default from {@code include: *.*.*} to {@code exclude: *.*.*}. + */ + public boolean includes(String database, String schema, String table) { + boolean included = false; + for (Rule rule : rules) { + List parts = rule.parts(); + if (matches(parts.get(0), database) && matches(parts.get(1), schema) && matches(parts.get(2), table)) { + included = rule.include(); + } + } + return included; + } + + /** A {@code *}, a {@code /regex/} matching the whole name, or a name, which may be double-quoted. */ + private static boolean matches(String part, String name) { + if (Rule.isWildcard(part)) { + return true; + } + if (Rule.isRegex(part)) { + return Pattern.compile(part.substring(1, part.length() - 1)).matcher(name).matches(); + } + if (part.length() >= 2 && part.startsWith("\"") && part.endsWith("\"")) { + return part.substring(1, part.length() - 1).replace("\"\"", "\"").equals(name); + } + return part.equals(name); + } + private static Rule parseRule(String entry, String dataFilter) { int colon = entry.indexOf(':'); if (colon < 0) { diff --git a/src/main/java/io/floci/aws/services/rds/integration/PostgresRedshiftTypes.java b/src/main/java/io/floci/aws/services/rds/integration/PostgresRedshiftTypes.java new file mode 100644 index 0000000000..5f70fefd00 --- /dev/null +++ b/src/main/java/io/floci/aws/services/rds/integration/PostgresRedshiftTypes.java @@ -0,0 +1,155 @@ +package io.floci.aws.services.rds.integration; + +import io.floci.aws.core.common.PostgresWire; + +import java.util.Map; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * The Amazon Redshift type a zero-ETL integration gives a PostgreSQL column, following the table + * AWS publishes for Aurora PostgreSQL sources, and the expression that reads the column out of the + * source in a form the Redshift column takes from CSV. + * + *

A type AWS does not replicate maps to nothing: an enum, a domain, a composite, a range, a type + * an extension or a user created, an array of any of those, and a {@code numeric} without its + * precision. A table with such a column is not replicated. + */ +final class PostgresRedshiftTypes { + + /** A source column as the catalog describes it. {@code element*} describe an array's element type. */ + record SourceColumn(String name, String typeName, String typeType, String category, boolean builtin, + String elementTypeName, String elementTypeType, boolean elementBuiltin, + String formattedType) {} + + /** A column of the replicated table: its Redshift type and how the source column is read out. */ + record MappedColumn(String name, String redshiftType, String selectExpression) {} + + private static final String SUPER = "pg_catalog.super"; + private static final String VARBYTE = "pg_catalog.varbyte"; + private static final String LONG_VARCHAR = "VARCHAR(65535)"; + private static final int MAX_DECIMAL_PRECISION = 38; + private static final int MAX_CHAR_LENGTH = 65535; + private static final Pattern NUMERIC = Pattern.compile("numeric\\((\\d+),(-?\\d+)\\)"); + private static final Pattern CHARACTER = Pattern.compile("character\\((\\d+)\\)"); + + /** Types read out as they are, by {@code pg_type.typname}. */ + private static final Map AS_IS = Map.ofEntries( + Map.entry("int2", "SMALLINT"), + Map.entry("int4", "INTEGER"), + Map.entry("int8", "BIGINT"), + Map.entry("bool", "BOOLEAN"), + Map.entry("float4", "REAL"), + Map.entry("float8", "DOUBLE PRECISION"), + Map.entry("date", "DATE"), + Map.entry("timestamp", "TIMESTAMP"), + Map.entry("timestamptz", "TIMESTAMPTZ"), + Map.entry("interval", "INTERVAL"), + Map.entry("bytea", VARBYTE)); + + /** Types read out as their text, by {@code pg_type.typname}. */ + private static final Map AS_TEXT = Map.ofEntries( + Map.entry("text", LONG_VARCHAR), + Map.entry("varchar", LONG_VARCHAR), + Map.entry("name", "VARCHAR(64)"), + Map.entry("uuid", "VARCHAR(36)"), + Map.entry("time", "VARCHAR(19)"), + Map.entry("timetz", "VARCHAR(22)"), + Map.entry("inet", "VARCHAR(19)"), + Map.entry("cidr", "VARCHAR(19)"), + Map.entry("macaddr", "VARCHAR(17)"), + Map.entry("macaddr8", "VARCHAR(23)"), + Map.entry("pg_lsn", "VARCHAR(17)"), + Map.entry("tid", "VARCHAR(23)"), + Map.entry("xml", LONG_VARCHAR), + Map.entry("jsonpath", LONG_VARCHAR), + Map.entry("tsvector", LONG_VARCHAR), + Map.entry("tsquery", LONG_VARCHAR), + Map.entry("gtsvector", LONG_VARCHAR), + Map.entry("refcursor", LONG_VARCHAR), + Map.entry("txid_snapshot", LONG_VARCHAR), + Map.entry("pg_snapshot", LONG_VARCHAR), + Map.entry("pg_node_tree", LONG_VARCHAR), + Map.entry("pg_ndistinct", LONG_VARCHAR), + Map.entry("pg_dependencies", LONG_VARCHAR), + Map.entry("pg_mcv_list", LONG_VARCHAR), + Map.entry("pg_brin_bloom_summary", LONG_VARCHAR)); + + private PostgresRedshiftTypes() {} + + static Optional map(SourceColumn column) { + String quoted = PostgresWire.quoteIdentifier(column.name()); + if (!column.builtin()) { + return Optional.empty(); + } + String typeName = column.typeName(); + switch (typeName) { + case "int2vector" -> { + return mapped(column, SUPER, "to_jsonb(" + quoted + "::int2[])"); + } + case "oidvector" -> { + return mapped(column, SUPER, "to_jsonb(" + quoted + "::oid[])"); + } + default -> { } + } + if ("A".equals(column.category())) { + String formatted = column.formattedType(); + SourceColumn element = new SourceColumn(column.name(), column.elementTypeName(), + column.elementTypeType(), "", column.elementBuiltin(), null, null, false, + formatted.endsWith("[]") ? formatted.substring(0, formatted.length() - 2) : formatted); + return column.elementTypeName() != null && map(element).isPresent() + ? mapped(column, SUPER, "to_jsonb(" + quoted + ")") : Optional.empty(); + } + if (!"b".equals(column.typeType())) { + return Optional.empty(); + } + String asIs = AS_IS.get(typeName); + if (asIs != null) { + return mapped(column, asIs, quoted); + } + String asText = AS_TEXT.get(typeName); + if (asText != null) { + return mapped(column, asText, quoted + "::text"); + } + return switch (typeName) { + case "json", "jsonb" -> mapped(column, SUPER, quoted + "::jsonb"); + case "money" -> mapped(column, "DECIMAL(20,3)", quoted + "::numeric"); + case "oid", "xid", "cid" -> mapped(column, "BIGINT", quoted + "::text::bigint"); + case "xid8" -> mapped(column, "DECIMAL(20,0)", quoted + "::text::numeric"); + case "numeric" -> numeric(column, quoted); + case "bpchar" -> character(column, quoted); + default -> Optional.empty(); + }; + } + + private static Optional numeric(SourceColumn column, String quoted) { + Matcher matcher = NUMERIC.matcher(column.formattedType()); + if (!matcher.matches()) { + return Optional.empty(); + } + int precision = Integer.parseInt(matcher.group(1)); + int scale = Integer.parseInt(matcher.group(2)); + if (precision > MAX_DECIMAL_PRECISION || scale < 0 || scale > precision) { + return Optional.empty(); + } + return mapped(column, "DECIMAL(" + precision + "," + scale + ")", quoted); + } + + private static Optional character(SourceColumn column, String quoted) { + Matcher matcher = CHARACTER.matcher(column.formattedType()); + if (!matcher.matches()) { + // A bpchar without a length takes any length, so it is read as text. + return mapped(column, LONG_VARCHAR, quoted + "::text"); + } + int length = Integer.parseInt(matcher.group(1)); + if (length > MAX_CHAR_LENGTH) { + return Optional.empty(); + } + return mapped(column, "CHAR(" + length + ")", quoted); + } + + private static Optional mapped(SourceColumn column, String redshiftType, String expression) { + return Optional.of(new MappedColumn(column.name(), redshiftType, expression)); + } +} diff --git a/src/main/java/io/floci/aws/services/rds/integration/RdsIntegrationDatabases.java b/src/main/java/io/floci/aws/services/rds/integration/RdsIntegrationDatabases.java new file mode 100644 index 0000000000..2208a508c0 --- /dev/null +++ b/src/main/java/io/floci/aws/services/rds/integration/RdsIntegrationDatabases.java @@ -0,0 +1,168 @@ +package io.floci.aws.services.rds.integration; + +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.PostgresWire; +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.redshift.spectrum.BackendSql; +import io.floci.aws.services.redshift.spectrum.ExternalStatement; +import io.floci.aws.services.redshift.spectrum.IntegrationDatabaseCreator; +import io.floci.aws.services.redshift.spectrum.SpectrumSession; +import io.floci.aws.services.redshift.spectrum.SpectrumSqlException; +import io.floci.aws.services.redshiftserverless.RedshiftServerlessRuntime; +import io.floci.aws.services.redshiftserverless.RedshiftServerlessService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; + +/** + * {@code CREATE DATABASE FROM INTEGRATION '' DATABASE } on the Redshift cluster or + * workgroup an RDS zero-ETL integration replicates into: creates the database and starts the initial + * load of the source database into it. + */ +@ApplicationScoped +public class RdsIntegrationDatabases implements IntegrationDatabaseCreator { + + private static final String UNDEFINED_OBJECT = "42704"; + private static final String SYNTAX_ERROR = "42601"; + private static final String INVALID_PARAMETER_VALUE = "22023"; + private static final String DUPLICATE_DATABASE = "42P04"; + private static final String NOT_IN_PREREQUISITE_STATE = "55000"; + private static final String FEATURE_NOT_SUPPORTED = "0A000"; + + private final RdsIntegrationService integrations; + private final RdsIntegrationLoader loader; + private final RedshiftService redshiftService; + private final RedshiftServerlessService serverlessService; + + @Inject + public RdsIntegrationDatabases(RdsIntegrationService integrations, RdsIntegrationLoader loader, + RedshiftService redshiftService, RedshiftServerlessService serverlessService) { + this.integrations = integrations; + this.loader = loader; + this.redshiftService = redshiftService; + this.serverlessService = serverlessService; + } + + @Override + public void create(ExternalStatement.CreateIntegrationDatabase statement, SpectrumSession session, + BackendSql backend) { + String integrationId = statement.integrationId(); + Integration integration = integrations.findById(integrationId) + .filter(found -> replicatesInto(found, session)) + .orElseThrow(() -> notFound(integrationId, session)); + String sourceDatabase = statement.sourceDatabase(); + if (sourceDatabase == null || sourceDatabase.isBlank()) { + throw new SpectrumSqlException(SYNTAX_ERROR, "Integration " + integrationId + + " replicates a PostgreSQL source, so CREATE DATABASE must name the source database with" + + " DATABASE ''"); + } + if (!IntegrationDataFilter.parsePostgres(integration.getDataFilter()).includesDatabase(sourceDatabase)) { + throw new SpectrumSqlException(INVALID_PARAMETER_VALUE, "Source database \"" + sourceDatabase + + "\" is not included in the data filter of integration " + integrationId); + } + Optional existing = integration.destinationFor(sourceDatabase); + boolean previousGone = existing + .filter(destination -> !Integration.Destination.STATE_CREATING.equals(destination.getState())) + .map(destination -> previousDatabaseGone(destination, backend)) + .orElse(false); + boolean reuseFailedDatabase = existing.isPresent() + && Integration.Destination.STATE_FAILED.equals(existing.get().getState()) + && statement.databaseName().equals(existing.get().getDatabaseName()) + && !previousGone; + List previousErrors = integration.getErrors().stream() + .filter(error -> RdsIntegrationService.isErrorForSourceDatabase(error, sourceDatabase)) + .toList(); + if (reuseFailedDatabase) { + Integration syncing = runDestinationRegistration( + () -> integrations.addDestination(integration, statement.databaseName(), sourceDatabase, false)); + String loadId = syncing.destinationFor(sourceDatabase) + .map(Integration.Destination::getLoadId) + .orElse(null); + loader.submit(syncing, sourceDatabase, statement.databaseName(), loadId); + return; + } + String droppedDatabaseName = previousGone ? existing.get().getDatabaseName() : null; + String droppedLoadId = previousGone ? existing.get().getLoadId() : null; + Integration reserved = runDestinationRegistration( + () -> integrations.reserveDestination(integration, statement.databaseName(), sourceDatabase, + droppedDatabaseName, droppedLoadId)); + String loadId = reserved.destinationFor(sourceDatabase) + .map(Integration.Destination::getLoadId) + .orElse(null); + try { + backend.execute("CREATE DATABASE " + PostgresWire.quoteIdentifier(statement.databaseName())); + } catch (RuntimeException e) { + if (existing.isPresent()) { + integrations.restoreDestination(integration, sourceDatabase, loadId, existing.get(), previousErrors); + } else { + integrations.removeDestination(integration, sourceDatabase, loadId); + } + throw e; + } + Integration syncing = runDestinationRegistration( + () -> integrations.startDestinationSync(reserved, sourceDatabase, loadId)); + loader.submit(syncing, sourceDatabase, statement.databaseName(), loadId); + } + + private static Integration runDestinationRegistration(Supplier action) { + try { + return action.get(); + } catch (AwsException e) { + String state = switch (e.getErrorCode()) { + case "IntegrationAlreadyExistsFault" -> DUPLICATE_DATABASE; + case "IntegrationNotFoundFault" -> UNDEFINED_OBJECT; + default -> NOT_IN_PREREQUISITE_STATE; + }; + throw new SpectrumSqlException(state, e.getMessage()); + } + } + + /** + * Whether a database was created from {@code sourceDatabase} before and has since been dropped on the target, + * so that it can be created and loaded again. + */ + private static boolean previousDatabaseGone(Integration.Destination destination, BackendSql backend) { + return backend.queryString("SELECT 1 FROM pg_catalog.pg_database WHERE datname = '" + + destination.getDatabaseName().replace("'", "''") + "'").isEmpty(); + } + + /** Whether the integration's target is the provisioned cluster or the workgroup the session runs on. */ + private boolean replicatesInto(Integration integration, SpectrumSession session) { + String sessionTarget = session.clusterIdentifier(); + if (sessionTarget == null || !session.accountId().equals(integration.getAccountId())) { + return false; + } + String targetArn = integration.getTargetArn(); + if (RedshiftZeroEtlEndpoints.isNamespaceArn(targetArn)) { + try { + RedshiftServerlessService.WorkgroupTarget workgroup = + serverlessService.getNamespaceWorkgroupTarget(targetArn, integration.getRegion()); + return sessionTarget.equals( + RedshiftServerlessRuntime.backendId(integration.getRegion(), workgroup.workgroupName())); + } catch (AwsException expected) { + // A namespace without a workgroup serves no session, so no session's statement can name it. + return false; + } + } + String clusterIdentifier = AwsArnUtils.parse(targetArn).resource().substring("cluster:".length()); + return sessionTarget.equals(clusterIdentifier) + && redshiftService.clusterRegion(session.accountId(), clusterIdentifier) + .map(integration.getRegion()::equals).orElse(false); + } + + private SpectrumSqlException notFound(String integrationId, SpectrumSession session) { + if (redshiftService.integrationExists(session.accountId(), integrationId)) { + return new SpectrumSqlException(FEATURE_NOT_SUPPORTED, "CREATE DATABASE ... FROM INTEGRATION is only " + + "supported for integrations from RDS and Aurora PostgreSQL; integration " + integrationId + + " replicates another source"); + } + return new SpectrumSqlException(UNDEFINED_OBJECT, "Integration " + integrationId + + " does not exist or does not replicate into this database"); + } +} diff --git a/src/main/java/io/floci/aws/services/rds/integration/RdsIntegrationLoader.java b/src/main/java/io/floci/aws/services/rds/integration/RdsIntegrationLoader.java new file mode 100644 index 0000000000..6a49687054 --- /dev/null +++ b/src/main/java/io/floci/aws/services/rds/integration/RdsIntegrationLoader.java @@ -0,0 +1,396 @@ +package io.floci.aws.services.rds.integration; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.PostgresWire; +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.core.common.Resettable; +import io.floci.aws.services.rds.RdsService; +import io.floci.aws.services.rds.container.RdsContainerManager; +import io.floci.aws.services.rds.integration.PostgresRedshiftTypes.MappedColumn; +import io.floci.aws.services.rds.integration.PostgresRedshiftTypes.SourceColumn; +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.redshiftdata.RedshiftZeroEtlWriter; +import io.floci.aws.services.redshiftdata.RedshiftZeroEtlWriter.ReplicatedTable; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalLong; +import java.util.TreeMap; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicLong; + +/** + * The initial load of an RDS zero-ETL integration: copies the tables of one source database into the + * Redshift database created from the integration with {@code CREATE DATABASE ... FROM INTEGRATION}. + * + *

Each table the integration's {@code DataFilter} includes and that has a primary key is read out + * of the source's PostgreSQL container with {@code COPY ... TO STDOUT}, staged in a temporary file and + * copied into a table of the same schema and name on the target, with the column types AWS gives a + * PostgreSQL source. A table with a column type AWS does not replicate is skipped, as AWS leaves such a + * table out. Loading a table replaces it, so a load a restart interrupted runs again from the start. + * Changes made to the source after the load are not replicated. + */ +@ApplicationScoped +public class RdsIntegrationLoader implements Resettable { + + private static final Logger LOG = Logger.getLogger(RdsIntegrationLoader.class); + + // Ordinary and partitioned tables, but not a partition on its own, since reading the parent reads + // its partitions. Temporary and unlogged tables are skipped, as for a snapshot export. "key" is the + // column's position in the primary key, 0 when it is not part of one. + static final String CATALOG_SQL = "SELECT json_build_object('schema', n.nspname, 'table', c.relname, " + + "'column', a.attname, 'type', t.typname, 'typtype', t.typtype, 'category', t.typcategory, " + + "'builtin', t.typnamespace = 'pg_catalog'::regnamespace, " + + "'element', e.typname, 'elementtype', e.typtype, " + + "'elementbuiltin', COALESCE(e.typnamespace = 'pg_catalog'::regnamespace, false), " + + "'formatted', format_type(a.atttypid, a.atttypmod), " + // indkey is an int2vector, whose subscripts start at 0, so the position is counted rather than read + // off the subscript. Limit to indnkeyatts so INCLUDE columns are not treated as primary-key columns. + + "'key', COALESCE((SELECT k.n FROM unnest(i.indkey::int2[]) WITH ORDINALITY AS k(att, n) " + + "WHERE k.att = a.attnum AND k.n <= i.indnkeyatts), 0)) " + + "FROM pg_class c " + + "JOIN pg_namespace n ON n.oid = c.relnamespace " + + "JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped " + + "JOIN pg_type t ON t.oid = a.atttypid " + + "LEFT JOIN pg_type e ON e.oid = t.typelem AND t.typcategory = 'A' " + + "LEFT JOIN pg_index i ON i.indrelid = c.oid AND i.indisprimary " + + "WHERE c.relkind IN ('r', 'p') AND NOT c.relispartition AND c.relpersistence = 'p' " + + "AND n.nspname <> 'information_schema' AND n.nspname NOT LIKE 'pg\\_%' " + + "ORDER BY n.nspname, c.relname, a.attnum"; + + // How long one table may take to read out of the source. + static final int TABLE_READ_TIMEOUT_SECONDS = 3600; + private static final int LOAD_ATTEMPTS = 5; + private static final Duration RETRY_DELAY = Duration.ofSeconds(5); + + private final RdsIntegrationService integrations; + private final RdsService rdsService; + private final RdsContainerManager containerManager; + private final RedshiftZeroEtlWriter writer; + private final ObjectMapper objectMapper; + private final boolean mock; + private final Executor workers; + private final int attempts; + private final Duration retryDelay; + /** Bumped by a reset, so a load started before it stops writing. */ + private final AtomicLong generation = new AtomicLong(); + + @Inject + public RdsIntegrationLoader(RdsIntegrationService integrations, RdsService rdsService, + RdsContainerManager containerManager, RedshiftZeroEtlWriter writer, + ObjectMapper objectMapper, EmulatorConfig config) { + this(integrations, rdsService, containerManager, writer, objectMapper, config.services().rds().mock(), + task -> Thread.ofVirtual().name("rds-integration-load").start(task), LOAD_ATTEMPTS, RETRY_DELAY); + } + + RdsIntegrationLoader(RdsIntegrationService integrations, RdsService rdsService, + RdsContainerManager containerManager, RedshiftZeroEtlWriter writer, + ObjectMapper objectMapper, boolean mock, Executor workers, int attempts, + Duration retryDelay) { + this.integrations = integrations; + this.rdsService = rdsService; + this.containerManager = containerManager; + this.writer = writer; + this.objectMapper = objectMapper; + this.mock = mock; + this.workers = workers; + this.attempts = attempts; + this.retryDelay = retryDelay; + } + + /** + * Starts loading {@code sourceDatabase} of the integration into {@code databaseName} in the background + * under the load identity {@code loadId}. + */ + public void submit(Integration integration, String sourceDatabase, String databaseName, String loadId) { + long startedIn = generation.get(); + String accountId = integration.getAccountId(); + workers.execute(() -> RequestScopes.runAs(accountId, integration.getRegion(), + () -> load(integration, sourceDatabase, databaseName, loadId, startedIn))); + } + + /** Starts again the loads a restart interrupted, and reconciles creations left mid-flight. */ + public void resumeInterruptedLoads() { + integrations.reconcileInterruptedCreations(); + for (Integration integration : integrations.integrationsWithLoadsInProgress()) { + for (Integration.Destination destination : integration.getDestinations()) { + if (Integration.Destination.STATE_SYNCING.equals(destination.getState())) { + LOG.infov("Restarting the initial load of {0} into {1} for integration {2}", + destination.getSourceDatabase(), destination.getDatabaseName(), + integration.getIntegrationArn()); + submit(integration, destination.getSourceDatabase(), destination.getDatabaseName(), + destination.getLoadId()); + } + } + } + } + + /** + * Loads the destination, trying again a few times when the source or the target cannot be reached: a load + * resumed at startup may start before the containers it reads and writes are back, and loading replaces each + * table, so a retry leaves the same rows. + */ + void load(Integration integration, String sourceDatabase, String databaseName, String loadId, long startedIn) { + if (mock) { + LOG.infov("RDS runs without database containers, so integration {0} copies no rows into {1}", + integration.getIntegrationArn(), databaseName); + finish(integration, sourceDatabase, databaseName, loadId, startedIn, null); + return; + } + String failure = null; + for (int attempt = 1; attempt <= attempts; attempt++) { + try { + Optional> result = copyTables(integration, sourceDatabase, databaseName, loadId, + startedIn); + if (result.isEmpty()) { + return; + } + List failedTables = result.get(); + if (!failedTables.isEmpty()) { + failure = "Could not load " + failedTables.size() + " table(s): " + + String.join(", ", failedTables); + } else { + failure = null; + } + break; + } catch (RuntimeException e) { + LOG.warnv(e, "Attempt {0} of {1} at the initial load of {2} into {3} for integration {4} failed", + attempt, attempts, sourceDatabase, databaseName, integration.getIntegrationArn()); + failure = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName(); + } + if (attempt < attempts && !waitBeforeRetry(integration, sourceDatabase, databaseName, loadId, startedIn)) { + return; + } + } + finish(integration, sourceDatabase, databaseName, loadId, startedIn, failure); + } + + /** Waits before the next attempt; false when the load should stop instead. */ + private boolean waitBeforeRetry(Integration integration, String sourceDatabase, String databaseName, + String loadId, long startedIn) { + try { + Thread.sleep(retryDelay); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + return isCurrentLoad(integration, sourceDatabase, databaseName, loadId, startedIn); + } + + private boolean isCurrentLoad(Integration integration, String sourceDatabase, String databaseName, + String loadId, long startedIn) { + return generation.get() == startedIn + && integrations.isLoading(integration, sourceDatabase, databaseName, loadId); + } + + private void finish(Integration integration, String sourceDatabase, String databaseName, String loadId, + long startedIn, String failure) { + if (generation.get() == startedIn) { + integrations.finishDestination(integration, sourceDatabase, databaseName, loadId, failure); + } + } + + /** Returns empty when the load was stopped or superseded while running. */ + private Optional> copyTables(Integration integration, String sourceDatabase, String databaseName, + String loadId, long startedIn) { + Source source = source(integration); + IntegrationDataFilter filter = IntegrationDataFilter.parsePostgres(integration.getDataFilter()); + List failedTables = new ArrayList<>(); + for (SourceTable table : catalog(source, sourceDatabase)) { + if (!isCurrentLoad(integration, sourceDatabase, databaseName, loadId, startedIn)) { + LOG.infov("Integration {0} stopped loading {1}", integration.getIntegrationArn(), sourceDatabase); + return Optional.empty(); + } + if (!filter.includes(sourceDatabase, table.schema(), table.table())) { + continue; + } + Optional> columns = mappedColumns(table); + if (table.primaryKey().isEmpty()) { + LOG.warnv("Integration {0} skips table {1}.{2}.{3}: it has no primary key", + integration.getIntegrationArn(), sourceDatabase, table.schema(), table.table()); + } else if (columns.isEmpty()) { + LOG.warnv("Integration {0} skips table {1}.{2}.{3}: a column has a type zero-ETL does not " + + "replicate", integration.getIntegrationArn(), sourceDatabase, table.schema(), + table.table()); + } else { + try { + OptionalLong rows = copyTable(integration, source, sourceDatabase, databaseName, loadId, + startedIn, table, columns.get()); + if (rows.isEmpty()) { + LOG.infov("Integration {0} stopped loading {1}", integration.getIntegrationArn(), + sourceDatabase); + return Optional.empty(); + } + LOG.infov("Integration {0} loaded {1} rows of {2}.{3}.{4} into {5}", + integration.getIntegrationArn(), rows.getAsLong(), sourceDatabase, table.schema(), + table.table(), databaseName); + } catch (RedshiftZeroEtlWriter.TargetUnavailableException | SourceUnavailableException e) { + throw e; + } catch (RuntimeException e) { + // Continue copying remaining tables, then report the destination as failed. + LOG.warnv(e, "Integration {0} could not load table {1}.{2}.{3}", integration.getIntegrationArn(), + sourceDatabase, table.schema(), table.table()); + failedTables.add(table.schema() + "." + table.table()); + } + } + } + return Optional.of(failedTables); + } + + /** Returns empty when the load was stopped or superseded during the source export, before writing. */ + private OptionalLong copyTable(Integration integration, Source source, String sourceDatabase, String databaseName, + String loadId, long startedIn, SourceTable table, List columns) { + StringBuilder select = new StringBuilder("COPY (SELECT "); + List replicated = new ArrayList<>(); + for (int i = 0; i < columns.size(); i++) { + MappedColumn column = columns.get(i); + select.append(i > 0 ? ", " : "").append(column.selectExpression()); + replicated.add(new ReplicatedTable.Column(column.name(), column.redshiftType())); + } + select.append(" FROM ").append(PostgresWire.quoteIdentifier(table.schema())).append('.') + .append(PostgresWire.quoteIdentifier(table.table())) + .append(") TO STDOUT WITH (FORMAT csv)"); + ReplicatedTable target = new ReplicatedTable(table.schema(), table.table(), replicated, table.primaryKey()); + Path staged = null; + try { + staged = Files.createTempFile("floci-rds-integration-", ".csv"); + try (OutputStream out = Files.newOutputStream(staged)) { + try { + containerManager.queryPostgres(source.containerId(), source.masterUsername(), sourceDatabase, + select.toString(), out, TABLE_READ_TIMEOUT_SECONDS); + } catch (RuntimeException e) { + throw new SourceUnavailableException("Could not read table " + table.schema() + "." + + table.table() + " from source: " + e.getMessage(), e); + } + } + if (!isCurrentLoad(integration, sourceDatabase, databaseName, loadId, startedIn)) { + return OptionalLong.empty(); + } + try (InputStream in = Files.newInputStream(staged)) { + return OptionalLong.of(writer.loadTable(integration.getAccountId(), integration.getTargetArn(), + databaseName, target, in)); + } + } catch (IOException e) { + throw new UncheckedIOException("Could not stage the rows of " + table.schema() + "." + table.table(), e); + } finally { + deleteStaged(staged); + } + } + + private static final class SourceUnavailableException extends RuntimeException { + private SourceUnavailableException(String message, Throwable cause) { + super(message, cause); + } + } + + private static void deleteStaged(Path staged) { + if (staged == null) { + return; + } + try { + Files.deleteIfExists(staged); + } catch (IOException e) { + LOG.warnv(e, "Could not delete the staged rows in {0}", staged); + } + } + + private static Optional> mappedColumns(SourceTable table) { + List mapped = new ArrayList<>(); + for (SourceColumn column : table.columns()) { + Optional one = PostgresRedshiftTypes.map(column); + if (one.isEmpty()) { + return Optional.empty(); + } + mapped.add(one.get()); + } + return Optional.of(mapped); + } + + /** The source's tables, in schema and table order, each with its columns and its primary key in key order. */ + List catalog(Source source, String sourceDatabase) { + String output = containerManager.queryPostgres(source.containerId(), source.masterUsername(), + sourceDatabase, CATALOG_SQL); + Map tables = new LinkedHashMap<>(); + Map> keys = new LinkedHashMap<>(); + for (String line : output.split("\r?\n")) { + if (line.isBlank()) { + continue; + } + JsonNode row = parse(line); + String schema = row.path("schema").asText(); + String name = row.path("table").asText(); + String tableKey = schema + "\u0000" + name; + SourceTable table = tables.computeIfAbsent(tableKey, + ignored -> new SourceTable(schema, name, new ArrayList<>(), new ArrayList<>())); + String column = row.path("column").asText(); + table.columns().add(new SourceColumn(column, row.path("type").asText(), row.path("typtype").asText(), + row.path("category").asText(), row.path("builtin").asBoolean(), + row.path("element").isNull() ? null : row.path("element").asText(null), + row.path("elementtype").asText(null), row.path("elementbuiltin").asBoolean(), + row.path("formatted").asText())); + int keyPosition = row.path("key").asInt(); + if (keyPosition > 0) { + keys.computeIfAbsent(tableKey, ignored -> new TreeMap<>()).put(keyPosition, column); + } + } + keys.forEach((tableKey, positions) -> tables.get(tableKey).primaryKey().addAll(positions.values())); + return new ArrayList<>(tables.values()); + } + + private JsonNode parse(String line) { + try { + return objectMapper.readTree(line); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Could not read the source's catalog: " + e.getOriginalMessage(), e); + } + } + + /** The source's running database, started first when it was recorded without one. */ + private Source source(Integration integration) { + AwsArnUtils.Arn arn = AwsArnUtils.parse(integration.getSourceArn()); + String resource = arn.resource(); + String identifier = resource.substring(resource.indexOf(':') + 1); + if (resource.startsWith("cluster:")) { + DbCluster cluster = rdsService.ensureClusterBackend(identifier, arn.region()); + return requireRunning(cluster.getContainerId(), cluster.getMasterUsername(), integration); + } + DbInstance instance = rdsService.ensureInstanceBackend(identifier, arn.region()); + return requireRunning(instance.getContainerId(), instance.getMasterUsername(), integration); + } + + private static Source requireRunning(String containerId, String masterUsername, Integration integration) { + if (containerId == null || containerId.isBlank()) { + throw new IllegalStateException("The source " + integration.getSourceArn() + + " has no running database to copy from."); + } + return new Source(containerId, masterUsername); + } + + record Source(String containerId, String masterUsername) {} + + record SourceTable(String schema, String table, List columns, List primaryKey) {} + + @Override + public void clear() { + generation.incrementAndGet(); + } +} diff --git a/src/main/java/io/floci/aws/services/rds/integration/RdsIntegrationService.java b/src/main/java/io/floci/aws/services/rds/integration/RdsIntegrationService.java index 13d2e47ce7..54a13d516f 100644 --- a/src/main/java/io/floci/aws/services/rds/integration/RdsIntegrationService.java +++ b/src/main/java/io/floci/aws/services/rds/integration/RdsIntegrationService.java @@ -4,7 +4,9 @@ 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.RequestScopes; import io.floci.aws.core.common.Resettable; +import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.rds.RdsService; @@ -25,6 +27,7 @@ import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; @@ -36,10 +39,12 @@ import java.util.regex.Pattern; * Aurora PostgreSQL cluster or an RDS for PostgreSQL instance into a Redshift Serverless namespace * or a provisioned Redshift cluster. * - *

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}. + *

The record, its validation and its lifecycle are kept here. 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. Each database created on the + * target with {@code CREATE DATABASE ... FROM INTEGRATION} is a destination of the integration, + * which is {@code syncing} while {@link RdsIntegrationLoader} copies its source database in. + * Deviations are documented in {@code docs/services/rds.md}. */ @ApplicationScoped public class RdsIntegrationService implements Resettable { @@ -47,6 +52,7 @@ public class RdsIntegrationService implements Resettable { private static final Logger LOG = Logger.getLogger(RdsIntegrationService.class); private static final String KEY_PREFIX = "integration::"; + static final String INITIAL_LOAD_FAILED = "InitialLoadFailed"; // 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; @@ -117,8 +123,8 @@ public class RdsIntegrationService implements Resettable { 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. + // There is no setup to wait for: the record is active, ready for a database to be created from + // it, and only the create response reports the creating status AWS returns. integration.setStatus(Integration.STATUS_ACTIVE); synchronized (lock) { @@ -202,6 +208,281 @@ public class RdsIntegrationService implements Resettable { } } + /** The caller's integration whose ARN ends in {@code integrationId}, in any Region. */ + public Optional findById(String integrationId) { + if (integrationId == null || integrationId.isBlank()) { + return Optional.empty(); + } + return integrations.scan(key -> key.startsWith(KEY_PREFIX) && key.endsWith("::" + integrationId)).stream() + .filter(integration -> integrationId.equals(integration.integrationId())) + .findFirst() + .map(Integration::new); + } + + /** + * Records that {@code databaseName} is being created on the target from {@code sourceDatabase}, which + * puts the integration in {@code syncing} until its initial load ends. An {@code active}, {@code syncing} + * or {@code failed} integration takes a new destination, one for each source database. The destination + * already recorded for that source database is replaced when its load failed, or when the caller found + * that its database no longer exists ({@code previousDatabaseGone}); otherwise it is refused. + * + * @return the integration as it now is + */ + public Integration addDestination(Integration integration, String databaseName, String sourceDatabase, + boolean previousDatabaseGone) { + return registerDestination(integration, databaseName, sourceDatabase, + Integration.Destination.STATE_SYNCING, previousDatabaseGone, null, null); + } + + /** + * Reserves a destination in {@code Creating} while {@code CREATE DATABASE} runs on the target, so a + * concurrent request for the same source database cannot treat the not-yet-created database as dropped and + * overwrite this registration. + */ + public Integration reserveDestination(Integration integration, String databaseName, String sourceDatabase, + String droppedDatabaseName, String droppedLoadId) { + return registerDestination(integration, databaseName, sourceDatabase, + Integration.Destination.STATE_CREATING, droppedDatabaseName != null, droppedDatabaseName, + droppedLoadId); + } + + /** + * Promotes a reserved destination from {@code Creating} to {@code Syncing} once its database exists on + * the target. No-op when the integration or reservation is no longer present under {@code loadId}. + */ + public Integration startDestinationSync(Integration integration, String sourceDatabase, String loadId) { + synchronized (lock) { + Integration current = findCurrent(integration).orElseThrow(() -> new AwsException( + "IntegrationNotFoundFault", "Integration " + integration.integrationId() + " not found.", 404)); + Integration.Destination destination = current.destinationFor(sourceDatabase) + .filter(candidate -> Objects.equals(loadId, candidate.getLoadId())) + .orElseThrow(() -> new AwsException("InvalidIntegrationStateFault", + "Destination for source database " + sourceDatabase + " of integration " + + current.integrationId() + " is no longer active.", 400)); + destination.setState(Integration.Destination.STATE_SYNCING); + refreshStatus(current); + integrations.put(key(current.getRegion(), current.integrationId()), current); + return new Integration(current); + } + } + + private Integration registerDestination(Integration integration, String databaseName, String sourceDatabase, + String initialState, boolean previousDatabaseGone, + String droppedDatabaseName, String droppedLoadId) { + synchronized (lock) { + Integration current = findCurrent(integration).orElseThrow(() -> new AwsException( + "IntegrationNotFoundFault", "Integration " + integration.integrationId() + " not found.", 404)); + if (!Set.of(Integration.STATUS_ACTIVE, Integration.STATUS_SYNCING, Integration.STATUS_FAILED) + .contains(current.getStatus())) { + throw new AwsException("InvalidIntegrationStateFault", "Integration " + current.integrationId() + + " can't take a database because its status is " + current.getStatus() + ".", 400); + } + Optional previous = current.destinationFor(sourceDatabase); + if (previous.isPresent()) { + Integration.Destination existing = previous.get(); + // A destination currently being created is never replaceable: its database does not exist yet. + boolean beingCreated = Integration.Destination.STATE_CREATING.equals(existing.getState()); + boolean droppedMatches = previousDatabaseGone + && (droppedDatabaseName == null + || (droppedDatabaseName.equals(existing.getDatabaseName()) + && Objects.equals(droppedLoadId, existing.getLoadId()))); + boolean replaceable = !beingCreated + && (droppedMatches || Integration.Destination.STATE_FAILED.equals(existing.getState())); + if (!replaceable) { + throw new AwsException("IntegrationAlreadyExistsFault", "Database " + + existing.getDatabaseName() + " was already created from source database " + + sourceDatabase + " of integration " + current.integrationId() + ".", 400); + } + current.getDestinations().remove(existing); + } + String loadId = UUID.randomUUID().toString(); + current.getDestinations().add(new Integration.Destination(databaseName, sourceDatabase, + initialState, Instant.now(clock), loadId)); + current.getErrors().removeIf(error -> isErrorForSourceDatabase(error, sourceDatabase)); + refreshStatus(current); + integrations.put(key(current.getRegion(), current.integrationId()), current); + LOG.infov("Integration {0} syncs source database {1} into Redshift database {2}", + current.getIntegrationArn(), sourceDatabase, databaseName); + return new Integration(current); + } + } + + /** + * Forgets a destination owned by {@code expectedLoadId} whose database could not be created, as if it had + * never been asked for. + */ + public void removeDestination(Integration integration, String sourceDatabase, String expectedLoadId) { + restoreDestination(integration, sourceDatabase, expectedLoadId, null, List.of()); + } + + /** + * Reverts a destination registration owned by {@code expectedLoadId} when creating its database on the target + * failed, restoring any replaced destination and its errors rather than clearing a prior failure. Another + * caller's registration is left untouched. + */ + public void restoreDestination(Integration integration, String sourceDatabase, String expectedLoadId, + Integration.Destination previousDestination, + List previousErrors) { + synchronized (lock) { + findCurrent(integration).ifPresent(current -> { + Optional existing = current.destinationFor(sourceDatabase); + if (existing.filter(destination -> Objects.equals(expectedLoadId, destination.getLoadId())) + .isEmpty()) { + return; + } + current.getDestinations().removeIf( + destination -> sourceDatabase.equals(destination.getSourceDatabase())); + if (previousDestination != null) { + current.getDestinations().add(new Integration.Destination(previousDestination)); + } + if (previousErrors != null && !previousErrors.isEmpty()) { + current.getErrors().removeIf(error -> isErrorForSourceDatabase(error, sourceDatabase)); + for (Integration.IntegrationError error : previousErrors) { + current.getErrors().add(new Integration.IntegrationError( + error.getErrorCode(), error.getErrorMessage())); + } + } + refreshStatus(current); + integrations.put(key(current.getRegion(), current.integrationId()), current); + }); + } + } + + static boolean isErrorForSourceDatabase(Integration.IntegrationError error, String sourceDatabase) { + return error != null && error.getErrorMessage() != null + && error.getErrorMessage().startsWith("The initial load of source database " + sourceDatabase + " "); + } + + /** + * Whether the integration still exists and is still running the specific load identified by {@code loadId} + * for {@code sourceDatabase} into {@code databaseName}. + */ + public boolean isLoading(Integration integration, String sourceDatabase, String databaseName, String loadId) { + return findCurrent(integration) + .flatMap(current -> current.destinationFor(sourceDatabase)) + .filter(destination -> databaseName.equals(destination.getDatabaseName())) + .filter(destination -> Objects.equals(loadId, destination.getLoadId())) + .filter(destination -> Integration.Destination.STATE_SYNCING.equals(destination.getState())) + .isPresent(); + } + + /** + * Ends the initial load identified by {@code loadId}: {@code Synced}, or {@code Failed} with {@code failure} + * as the integration's error. The integration is {@code active} again once no destination is syncing, or + * {@code failed} when a load failed. A stale completion, whose load was replaced or already ended or whose + * integration was deleted meanwhile, is ignored. + */ + public void finishDestination(Integration integration, String sourceDatabase, String databaseName, + String loadId, String failure) { + synchronized (lock) { + Optional found = findCurrent(integration); + Optional destination = found + .flatMap(current -> current.destinationFor(sourceDatabase)) + .filter(candidate -> databaseName.equals(candidate.getDatabaseName())) + .filter(candidate -> Objects.equals(loadId, candidate.getLoadId())) + .filter(candidate -> Integration.Destination.STATE_SYNCING.equals(candidate.getState())); + if (destination.isEmpty()) { + return; + } + Integration current = found.get(); + destination.get().setState(failure == null + ? Integration.Destination.STATE_SYNCED : Integration.Destination.STATE_FAILED); + if (failure != null) { + current.getErrors().add(new Integration.IntegrationError(INITIAL_LOAD_FAILED, + "The initial load of source database " + sourceDatabase + " into " + databaseName + + " failed: " + failure)); + } + refreshStatus(current); + integrations.put(key(current.getRegion(), current.integrationId()), current); + LOG.infov("Integration {0} finished loading {1} into {2}: {3}", current.getIntegrationArn(), + sourceDatabase, databaseName, destination.get().getState()); + } + } + + /** + * Marks any destination left in {@code Creating} by a restart as {@code Failed} so the integration is + * not stuck syncing and a subsequent {@code CREATE DATABASE ... FROM INTEGRATION} can retry or reuse + * the database if it was created before the restart. + */ + public void reconcileInterruptedCreations() { + synchronized (lock) { + for (Integration integration : integrationsWithState(Integration.Destination.STATE_CREATING)) { + RequestScopes.runAs(integration.getAccountId(), integration.getRegion(), () -> + findCurrent(integration).ifPresent(current -> { + boolean changed = false; + for (Integration.Destination destination : current.getDestinations()) { + if (Integration.Destination.STATE_CREATING.equals(destination.getState())) { + destination.setState(Integration.Destination.STATE_FAILED); + current.getErrors().add(new Integration.IntegrationError(INITIAL_LOAD_FAILED, + "The initial load of source database " + destination.getSourceDatabase() + + " into " + destination.getDatabaseName() + + " failed: interrupted while creating the destination database.")); + changed = true; + } + } + if (changed) { + refreshStatus(current); + integrations.put(key(current.getRegion(), current.integrationId()), current); + LOG.warnv("Marked interrupted Creating destination(s) of integration {0} as Failed", + current.getIntegrationArn()); + } + })); + } + } + } + + /** + * The integrations of every account with a destination still syncing, as a restart left them. Each + * carries its account id, since no request scope is active at startup. + */ + public List integrationsWithLoadsInProgress() { + return integrationsWithState(Integration.Destination.STATE_SYNCING); + } + + private List integrationsWithState(String state) { + if (!(integrations instanceof AccountAwareStorageBackend accountIntegrations)) { + return integrations.scan(key -> key.startsWith(KEY_PREFIX)).stream() + .filter(integration -> hasDestinationInState(integration, state)) + .map(Integration::new) + .toList(); + } + return accountIntegrations.scanAllAccountEntries(key -> key.startsWith(KEY_PREFIX)).stream() + .filter(entry -> hasDestinationInState(entry.value(), state)) + .map(entry -> { + Integration integration = new Integration(entry.value()); + integration.setAccountId(entry.accountId()); + return integration; + }) + .toList(); + } + + private static boolean hasDestinationInState(Integration integration, String state) { + return integration.getDestinations().stream() + .anyMatch(destination -> state.equals(destination.getState())); + } + + /** The stored copy of the integration, when it still exists under the same ARN. */ + private Optional findCurrent(Integration integration) { + return integrations.get(key(integration.getRegion(), integration.integrationId())) + .filter(current -> integration.getIntegrationArn().equals(current.getIntegrationArn())) + .map(Integration::new); + } + + private static void refreshStatus(Integration integration) { + List destinations = integration.getDestinations(); + if (destinations.stream().anyMatch(destination -> + Integration.Destination.STATE_SYNCING.equals(destination.getState()) + || Integration.Destination.STATE_CREATING.equals(destination.getState()))) { + integration.setStatus(Integration.STATUS_SYNCING); + } else if (destinations.stream().anyMatch(destination -> + Integration.Destination.STATE_FAILED.equals(destination.getState()))) { + integration.setStatus(Integration.STATUS_FAILED); + } else { + integration.setStatus(Integration.STATUS_ACTIVE); + integration.setErrors(List.of()); + } + } + private void requireSource(String sourceArn, String region, String accountId) { AwsArnUtils.Arn arn = parseArn(sourceArn, "SourceArn"); String resource = arn.resource(); diff --git a/src/main/java/io/floci/aws/services/rds/model/Integration.java b/src/main/java/io/floci/aws/services/rds/model/Integration.java index d64c36350b..5ca9db9208 100644 --- a/src/main/java/io/floci/aws/services/rds/model/Integration.java +++ b/src/main/java/io/floci/aws/services/rds/model/Integration.java @@ -8,6 +8,7 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; /** * A zero-ETL integration from an RDS or Aurora database into Amazon Redshift, as @@ -67,6 +68,10 @@ public class Integration { @JsonProperty("AccountId") private String accountId; + /** The Redshift databases created from the integration; Floci's own state, not part of the AWS shape. */ + @JsonProperty("Destinations") + private List destinations = new ArrayList<>(); + public Integration() {} public Integration(Integration other) { @@ -84,6 +89,10 @@ public class Integration { this.errors = new ArrayList<>(other.errors); this.region = other.region; this.accountId = other.accountId; + this.destinations = new ArrayList<>(); + for (Destination destination : other.destinations) { + this.destinations.add(new Destination(destination)); + } } /** The id AWS mints for the integration: the last part of its ARN. */ @@ -140,6 +149,80 @@ public class Integration { public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } + public List getDestinations() { return destinations; } + public void setDestinations(List destinations) { + this.destinations = destinations != null ? new ArrayList<>(destinations) : new ArrayList<>(); + } + + /** The destination created from {@code sourceDatabase}, if there is one. */ + public Optional destinationFor(String sourceDatabase) { + return destinations.stream() + .filter(destination -> destination.getSourceDatabase().equals(sourceDatabase)) + .findFirst(); + } + + /** + * A database {@code CREATE DATABASE ... FROM INTEGRATION} created on the target, and how far the initial + * load of its source database has got. + */ + @RegisterForReflection + public static class Destination { + + public static final String STATE_CREATING = "Creating"; + public static final String STATE_SYNCING = "Syncing"; + public static final String STATE_SYNCED = "Synced"; + public static final String STATE_FAILED = "Failed"; + + @JsonProperty("DatabaseName") + private String databaseName; + + @JsonProperty("SourceDatabase") + private String sourceDatabase; + + @JsonProperty("State") + private String state; + + @JsonProperty("CreateTime") + private Instant createTime; + + @JsonProperty("LoadId") + private String loadId; + + public Destination() {} + + public Destination(String databaseName, String sourceDatabase, String state, Instant createTime) { + this(databaseName, sourceDatabase, state, createTime, null); + } + + public Destination(String databaseName, String sourceDatabase, String state, Instant createTime, + String loadId) { + this.databaseName = databaseName; + this.sourceDatabase = sourceDatabase; + this.state = state; + this.createTime = createTime; + this.loadId = loadId; + } + + public Destination(Destination other) { + this(other.databaseName, other.sourceDatabase, other.state, other.createTime, other.loadId); + } + + public String getDatabaseName() { return databaseName; } + public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } + + public String getSourceDatabase() { return sourceDatabase; } + public void setSourceDatabase(String sourceDatabase) { this.sourceDatabase = sourceDatabase; } + + public String getState() { return state; } + public void setState(String state) { this.state = state; } + + public Instant getCreateTime() { return createTime; } + public void setCreateTime(Instant createTime) { this.createTime = createTime; } + + public String getLoadId() { return loadId; } + public void setLoadId(String loadId) { this.loadId = loadId; } + } + /** One entry of an integration's {@code Errors}. */ @RegisterForReflection public static class IntegrationError { diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatement.java b/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatement.java index 7189a405ec..4148efbead 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatement.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatement.java @@ -9,7 +9,7 @@ public sealed interface ExternalStatement permits ExternalStatement.CreateSchema ExternalStatement.CreateMskSchema, ExternalStatement.CreateTable, ExternalStatement.AddPartitions, ExternalStatement.DropSchema, ExternalStatement.DropTable, ExternalStatement.CreateStreamingView, ExternalStatement.RefreshView, ExternalStatement.DropView, ExternalStatement.CreateFunction, - ExternalStatement.DropFunction { + ExternalStatement.DropFunction, ExternalStatement.CreateIntegrationDatabase { /** Read-only copy that keeps statement order, so Glue payloads are stable across runs. */ private static Map ordered(Map source) { return Collections.unmodifiableMap(new LinkedHashMap<>(source)); @@ -73,4 +73,10 @@ public sealed interface ExternalStatement permits ExternalStatement.CreateSchema boolean cascade) implements ExternalStatement { public DropFunction { argumentTypes = List.copyOf(argumentTypes); } } + /** + * {@code CREATE DATABASE FROM INTEGRATION '' [DATABASE ]}. {@code sourceDatabase} is null + * when the statement names none; the {@code SET} and {@code WITH} options are accepted and not kept. + */ + record CreateIntegrationDatabase(String databaseName, String integrationId, + String sourceDatabase) implements ExternalStatement { } } diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatementParser.java b/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatementParser.java index df48e4d2a9..7dd2a91944 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatementParser.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalStatementParser.java @@ -28,6 +28,11 @@ public class ExternalStatementParser { private static final Pattern DROP_FUNCTION = Pattern.compile( "(?is)^\\s*DROP\\s+FUNCTION\\s+(IF\\s+EXISTS\\s+)?" + NAME + "(?:\\s*\\.\\s*" + NAME + ")?\\s*\\((.*)\\)" + "(?:\\s+(CASCADE|RESTRICT))?\\s*;?\\s*$"); + private static final Pattern CREATE_INTEGRATION_DATABASE = Pattern.compile( + "(?is)^\\s*CREATE\\s+DATABASE\\s+" + NAME + "\\s+FROM\\s+INTEGRATION\\s+'((?:''|[^'])*)'" + + "(?:\\s+DATABASE\\s+('(?:''|[^'])*'|" + NAME + "))?" + + "(?:\\s+(?:SET|WITH|ACCEPTINVCHARS|QUERY_ALL_STATES|REFRESH_INTERVAL|TRUNCATECOLUMNS|HISTORY_MODE" + + "|AUTO_REMEDIATION|OWNER|CONNECTION|COLLATE|ISOLATION)\\b.*?)?\\s*;?\\s*$"); private static final Set FUNCTION_CLAUSES = Set.of("VOLATILE", "STABLE", "IMMUTABLE", "LAMBDA", "IAM_ROLE", "RETRY_TIMEOUT", "MAX_BATCH_ROWS", "MAX_BATCH_SIZE"); private static final long DEFAULT_RETRY_TIMEOUT_MILLIS = 20_000L; @@ -83,6 +88,17 @@ public class ExternalStatementParser { if (dropFunction.matches()) { return parseDropFunction(dropFunction); } + Matcher integrationDatabase = CREATE_INTEGRATION_DATABASE.matcher(viewText); + if (integrationDatabase.matches()) { + if (hasStatementSeparator(viewText.replaceFirst("[\\s;]+$", ""))) { + throw new SpectrumSqlException("42601", + "CREATE DATABASE ... FROM INTEGRATION must be a single statement"); + } + String source = integrationDatabase.group(3); + return Optional.of(new ExternalStatement.CreateIntegrationDatabase(identifier(integrationDatabase.group(1)), + integrationDatabase.group(2).replace("''", "'"), + source == null ? null : source.startsWith("'") ? unquote(source) : identifier(source))); + } Matcher createView = CREATE_VIEW.matcher(viewText); if (createView.matches()) { if (hasStatementSeparator(createView.group(4))) { diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/IntegrationDatabaseCreator.java b/src/main/java/io/floci/aws/services/redshift/spectrum/IntegrationDatabaseCreator.java new file mode 100644 index 0000000000..66869d2bb1 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/IntegrationDatabaseCreator.java @@ -0,0 +1,12 @@ +package io.floci.aws.services.redshift.spectrum; + +/** + * Runs {@code CREATE DATABASE ... FROM INTEGRATION} for the integration the statement names: checks that the + * integration replicates into the session's cluster or workgroup, creates the database on {@code backend}, and + * starts copying the source into it. It fails with a {@link SpectrumSqlException} carrying the SQLSTATE the + * client sees. + */ +public interface IntegrationDatabaseCreator { + + void create(ExternalStatement.CreateIntegrationDatabase statement, SpectrumSession session, BackendSql backend); +} diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java b/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java index d1b9323f29..7025a59cb1 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java @@ -57,6 +57,7 @@ public class SpectrumQueryPreparation { private final ExternalCatalogLocks catalogLocks; /** The Region of an account's cluster, by its identifier; null when it isn't known. */ private final BiFunction clusterRegion; + private final IntegrationDatabaseCreator integrationDatabases; /** What to bind once the statement that created each schema has committed, by backend. */ private final Map> pendingBindings = new ConcurrentHashMap<>(); @@ -79,10 +80,12 @@ public class SpectrumQueryPreparation { ExternalTableMaterializer materializer, ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks, KinesisStreamingViews views, - MskStreamingViews mskViews, Instance redshift) { + MskStreamingViews mskViews, Instance redshift, + Instance integrationDatabases) { this(registry, kinesisSchemas, mskSchemas, functions, udfEvaluator, materializer, parser, glue, metadata, catalogLocks, views, mskViews, - (accountId, clusterIdentifier) -> redshift.get().clusterRegion(accountId, clusterIdentifier).orElse(null)); + (accountId, clusterIdentifier) -> redshift.get().clusterRegion(accountId, clusterIdentifier).orElse(null), + (statement, session, backend) -> integrationDatabases.get().create(statement, session, backend)); } SpectrumQueryPreparation(ExternalCatalogRegistry registry, ExternalTableMaterializer materializer, @@ -152,6 +155,21 @@ public class SpectrumQueryPreparation { GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks, KinesisStreamingViews views, MskStreamingViews mskViews, BiFunction clusterRegion) { + this(registry, kinesisSchemas, mskSchemas, functions, udfEvaluator, materializer, parser, glue, metadata, + catalogLocks, views, mskViews, clusterRegion, (statement, session, backend) -> { + throw new SpectrumSqlException("0A000", "CREATE DATABASE ... FROM INTEGRATION is not supported"); + }); + } + + SpectrumQueryPreparation(ExternalCatalogRegistry registry, KinesisSchemaRegistry kinesisSchemas, + MskSchemaRegistry mskSchemas, ExternalFunctionRegistry functions, + LambdaUdfEvaluator udfEvaluator, + ExternalTableMaterializer materializer, ExternalStatementParser parser, + GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks, + KinesisStreamingViews views, MskStreamingViews mskViews, + BiFunction clusterRegion, + IntegrationDatabaseCreator integrationDatabases) { + this.integrationDatabases = integrationDatabases; this.functions = functions; this.udfEvaluator = Objects.requireNonNull(udfEvaluator, "udfEvaluator must not be null"); this.views = views; @@ -270,6 +288,7 @@ public class SpectrumQueryPreparation { case ExternalStatement.CreateKinesisSchema ignored -> true; case ExternalStatement.CreateMskSchema ignored -> true; case ExternalStatement.CreateFunction ignored -> true; + case ExternalStatement.CreateIntegrationDatabase ignored -> true; case ExternalStatement.DropFunction function -> findFunctionToDrop(function, session, backend).isPresent(); case ExternalStatement.CreateTable table -> session.inTransaction() || bindingsOf(registry, session).containsKey(table.schemaName()) @@ -303,6 +322,7 @@ public class SpectrumQueryPreparation { case ExternalStatement.DropView ignored -> "DROP MATERIALIZED VIEW"; case ExternalStatement.CreateFunction ignored -> "CREATE FUNCTION"; case ExternalStatement.DropFunction ignored -> "DROP FUNCTION"; + case ExternalStatement.CreateIntegrationDatabase ignored -> "CREATE DATABASE"; case null, default -> "CREATE EXTERNAL"; }; } @@ -325,6 +345,13 @@ public class SpectrumQueryPreparation { if (statement.orElse(null) instanceof ExternalStatement.DropFunction function) { return dropFunction(function, session, backend); } + if (statement.orElse(null) instanceof ExternalStatement.CreateIntegrationDatabase database) { + if (session.inTransaction()) { + throw new SpectrumSqlException("25001", "CREATE DATABASE cannot run inside a transaction block"); + } + integrationDatabases.create(database, session, backend); + return true; + } Map kinesis = bindingsOf(kinesisSchemas, session); Map msk = bindingsOf(mskSchemas, session); if (statement.orElse(null) instanceof ExternalStatement.DropSchema schema diff --git a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftZeroEtlWriter.java b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftZeroEtlWriter.java index ce872ade41..f90f41f5be 100644 --- a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftZeroEtlWriter.java +++ b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftZeroEtlWriter.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.PostgresWire; import io.floci.aws.services.redshift.RedshiftService; import io.floci.aws.services.redshift.RedshiftZeroEtlEndpoints; import io.floci.aws.services.redshift.model.Cluster; @@ -12,7 +13,11 @@ import io.floci.aws.services.redshiftserverless.RedshiftServerlessService; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import org.postgresql.PGConnection; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -289,15 +294,112 @@ public class RedshiftZeroEtlWriter { } } + /** The Redshift target could not be resolved or reached, so the caller may retry once it is back. */ + public static final class TargetUnavailableException extends RuntimeException { + public TargetUnavailableException(String message, Throwable cause) { + super(message, cause); + } + } + + /** A table an RDS zero-ETL integration replicates: its columns' Redshift types and its primary key. */ + public record ReplicatedTable(String schema, String table, List columns, List primaryKey) { + public ReplicatedTable { + columns = List.copyOf(columns); + primaryKey = List.copyOf(primaryKey); + } + + public record Column(String name, String type) {} + + String qualifiedName() { + return PostgresWire.quoteIdentifier(schema) + "." + PostgresWire.quoteIdentifier(table); + } + + String ddl() { + StringBuilder ddl = new StringBuilder("CREATE TABLE ").append(qualifiedName()).append(" ("); + for (Column column : columns) { + ddl.append(PostgresWire.quoteIdentifier(column.name())).append(' ').append(column.type()).append(", "); + } + ddl.append("PRIMARY KEY ("); + for (int i = 0; i < primaryKey.size(); i++) { + ddl.append(i > 0 ? ", " : "").append(PostgresWire.quoteIdentifier(primaryKey.get(i))); + } + return ddl.append("))").toString(); + } + } + + /** + * Replaces the table in {@code database} of the target with the rows of {@code csv}, in one transaction: + * its schema is created when missing, a table of that name is dropped and created again with the given + * columns, and the rows are copied in. Loading a table again so leaves the same rows. + * + * @return the number of rows loaded + */ + public long loadTable(String accountId, String targetArn, String database, ReplicatedTable table, + InputStream csv) { + RedshiftDataResourceResolver.DatabaseTarget resolved; + try { + resolved = target(accountId, targetArn, database); + } catch (RuntimeException e) { + throw new TargetUnavailableException("Could not resolve Redshift target " + targetArn + + ": " + e.getMessage(), e); + } + Connection opened; + try { + opened = connectionFactory.open(resolved); + } catch (SQLException e) { + throw new TargetUnavailableException("Could not connect to Redshift database " + database + + ": " + e.getMessage(), e); + } + try (Connection connection = opened) { + connection.setAutoCommit(false); + try (Statement statement = connection.createStatement()) { + statement.executeUpdate("CREATE SCHEMA IF NOT EXISTS " + PostgresWire.quoteIdentifier(table.schema())); + statement.executeUpdate("DROP TABLE IF EXISTS " + table.qualifiedName()); + statement.executeUpdate(table.ddl()); + long rows = connection.unwrap(PGConnection.class).getCopyAPI() + .copyIn("COPY " + table.qualifiedName() + " FROM STDIN WITH (FORMAT csv)", csv); + connection.commit(); + return rows; + } catch (SQLException | IOException | RuntimeException e) { + try { + connection.rollback(); + } catch (SQLException rollbackFailure) { + e.addSuppressed(rollbackFailure); + } + throw e; + } + } catch (SQLException e) { + if (isConnectionFailure(e)) { + throw new TargetUnavailableException("Connection to Redshift database " + database + + " failed while loading " + table.qualifiedName() + ": " + e.getMessage(), e); + } + LOG.warnv(e, "Could not load zero-ETL table {0} into database {1}", table.qualifiedName(), database); + throw new AwsException("InternalFailure", "Could not load table " + table.qualifiedName() + + " into database " + database + ": " + e.getMessage(), 500); + } catch (IOException e) { + throw new UncheckedIOException("Could not read the rows of table " + table.qualifiedName(), e); + } + } + + private static boolean isConnectionFailure(SQLException e) { + String state = e.getSQLState(); + return state != null && (state.startsWith("08") || state.startsWith("57P")); + } + + private RedshiftDataResourceResolver.DatabaseTarget target(String accountId, String targetArn) { + return target(accountId, targetArn, null); + } + /** * A namespace is written through its workgroup, into the namespace's database as its admin user, the - * same identity a cluster target is written with. + * same identity a cluster target is written with. A null {@code database} is the target's default one. */ - private RedshiftDataResourceResolver.DatabaseTarget target(String accountId, String targetArn) { + private RedshiftDataResourceResolver.DatabaseTarget target(String accountId, String targetArn, String database) { if (RedshiftZeroEtlEndpoints.isNamespaceArn(targetArn)) { RedshiftServerlessService.WorkgroupTarget workgroup = endpoints.targetWorkgroup(accountId, targetArn); return new RedshiftDataResourceResolver.DatabaseTarget(workgroup.arn(), workgroup.host(), - workgroup.port(), workgroup.database(), workgroup.masterUsername(), workgroup.masterPassword()); + workgroup.port(), database != null ? database : workgroup.database(), + workgroup.masterUsername(), workgroup.masterPassword()); } String clusterIdentifier = AwsArnUtils.parse(targetArn).resource().substring("cluster:".length()); Cluster cluster; @@ -315,7 +417,7 @@ public class RedshiftZeroEtlWriter { "cluster:" + clusterIdentifier, cluster.getContainerHost(), cluster.getContainerPort(), - "dev", + database != null ? database : "dev", cluster.getMasterUsername(), cluster.getMasterPassword()); } diff --git a/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java index eb58a7c6b3..e24463a6a0 100644 --- a/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java +++ b/src/test/java/io/floci/aws/lifecycle/EmulatorLifecycleTest.java @@ -43,6 +43,7 @@ import io.floci.aws.services.opensearch.OpenSearchService; import io.floci.aws.services.pipes.PipesService; import io.floci.aws.services.rds.RdsService; import io.floci.aws.services.rds.container.RdsContainerManager; +import io.floci.aws.services.rds.integration.RdsIntegrationLoader; import io.floci.aws.services.rds.proxy.RdsProxyManager; import io.floci.aws.services.redshift.RedshiftDynamoDbZeroEtlConsumer; import io.floci.aws.services.sagemaker.SageMakerService; @@ -155,6 +156,7 @@ class EmulatorLifecycleTest { @Mock private Instance containerTeardowns; @Mock private DynamoDbRuntime dynamoDbRuntime; @Mock private RedshiftDynamoDbZeroEtlConsumer redshiftZeroEtlConsumer; + @Mock private RdsIntegrationLoader rdsIntegrationLoader; private EmulatorLifecycle emulatorLifecycle; @@ -212,7 +214,7 @@ class EmulatorLifecycleTest { schemaCreationWorker, stepFunctionsService, durableExecutionService, containerTeardowns, persistentPathValidator, dynamoDbRuntime, redshiftZeroEtlConsumer, eksService, codeArtifactService, - cloudWatchMetricsService); + cloudWatchMetricsService, rdsIntegrationLoader); Mockito.lenient().when(containerTeardowns.iterator()) .thenReturn(Collections.emptyIterator()); } diff --git a/src/test/java/io/floci/aws/services/rds/RdsZeroEtlInitialLoadIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsZeroEtlInitialLoadIntegrationTest.java new file mode 100644 index 0000000000..dccc80d326 --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/RdsZeroEtlInitialLoadIntegrationTest.java @@ -0,0 +1,201 @@ +package io.floci.aws.services.rds; + +import io.floci.aws.services.redshiftserverless.RedshiftServerlessService; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import jakarta.inject.Inject; +import org.awaitility.Awaitility; +import org.jboss.logging.Logger; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.postgresql.Driver; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.UUID; + +import static io.floci.aws.testing.RdsRequests.assumeDocker; +import static io.floci.aws.testing.RdsRequests.createPostgresInstance; +import static io.floci.aws.testing.RdsRequests.deleteInstance; +import static io.floci.aws.testing.RdsRequests.rds; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * The initial load of an RDS zero-ETL integration end to end: a PostgreSQL instance as the source, a + * Redshift Serverless workgroup as the target, and the destination database created over the + * workgroup's PostgreSQL endpoint with {@code CREATE DATABASE ... FROM INTEGRATION}. Needs Docker. + */ +@QuarkusTest +class RdsZeroEtlInitialLoadIntegrationTest { + + private static final Logger LOG = Logger.getLogger(RdsZeroEtlInitialLoadIntegrationTest.class); + private static final String MASTER_USER = "master"; + private static final String MASTER_PASSWORD = "Master123!"; + private static final String ADMIN_PASSWORD = "Secret123"; + private static final String REGION = "us-east-1"; + + @Inject + RedshiftServerlessService serverless; + + @BeforeEach + void requireDocker() throws InterruptedException { + assumeDocker(); + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void theIncludedTablesWithAPrimaryKeyAreCopiedIntoTheDestinationDatabase() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String dbId = "zetl-src-" + suffix; + String namespace = "zetl-ns-" + suffix; + String workgroup = "zetl-wg-" + suffix; + int sourcePort = createPostgresInstance(dbId, MASTER_USER, MASTER_PASSWORD, false); + String integrationArn = null; + boolean namespaceCreated = false; + boolean workgroupCreated = false; + try { + execute(sourcePort, "appdb", MASTER_USER, MASTER_PASSWORD, + "CREATE SCHEMA sales", + "CREATE TABLE sales.orders (id int8, line int4, note text, total numeric(10,2), " + + "attrs jsonb, PRIMARY KEY (id, line))", + "INSERT INTO sales.orders VALUES (1, 1, 'first', 12.30, '{\"rush\": true}'), " + + "(1, 2, NULL, 0.50, NULL)", + "CREATE TABLE customers (id serial, name text, payload text, PRIMARY KEY (id) INCLUDE (payload))", + "INSERT INTO customers (name, payload) VALUES ('ada', 'vip'), ('grace', NULL)", + "CREATE TABLE no_key (id int)", + "CREATE TABLE left_out (id int PRIMARY KEY)"); + + Response namespaceResponse = RestAssuredJsonUtils.awsAction("RedshiftServerless", "CreateNamespace", """ + {"namespaceName":"%s","adminUsername":"admin","adminUserPassword":"%s"} + """.formatted(namespace, ADMIN_PASSWORD)); + namespaceCreated = namespaceResponse.statusCode() < 300; + String namespaceArn = namespaceResponse.then().statusCode(200) + .extract().path("namespace.namespaceArn"); + + Response workgroupResponse = RestAssuredJsonUtils.awsAction("RedshiftServerless", "CreateWorkgroup", """ + {"workgroupName":"%s","namespaceName":"%s"} + """.formatted(workgroup, namespace)); + workgroupCreated = workgroupResponse.statusCode() < 300; + int workgroupPort = workgroupResponse.then().statusCode(200) + .extract().path("workgroup.endpoint.port"); + + integrationArn = rds("CreateIntegration") + .formParam("IntegrationName", "zetl-" + suffix) + .formParam("SourceArn", "arn:aws:rds:us-east-1:000000000000:db:" + dbId) + .formParam("TargetArn", namespaceArn) + .formParam("DataFilter", "include: appdb.*.*, exclude: appdb.public.left_out") + .when().post("/").then().statusCode(200) + .body(containsString("creating")) + .extract().xmlPath().getString("CreateIntegrationResponse.CreateIntegrationResult.IntegrationArn"); + String integrationId = integrationArn.substring(integrationArn.lastIndexOf(':') + 1); + + execute(workgroupPort, "dev", "admin", ADMIN_PASSWORD, + "CREATE DATABASE appdb_dw FROM INTEGRATION '" + integrationId + "' DATABASE 'appdb'"); + + String arn = integrationArn; + Awaitility.await().atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofMillis(500)) + .until(() -> { + String body = rds("DescribeIntegrations").formParam("IntegrationIdentifier", arn) + .when().post("/").then().statusCode(200).extract().asString(); + assertThat("the load failed: " + body, body, + not(containsString("failed"))); + return body.contains("active"); + }); + + assertThat(query(workgroupPort, "appdb_dw", + "SELECT id || ':' || line || ':' || COALESCE(note, '-') || ':' || total || ':' " + + "|| COALESCE(attrs::text, '-') FROM sales.orders ORDER BY id, line"), + contains("1:1:first:12.30:{\"rush\": true}", "1:2:-:0.50:-")); + assertThat(query(workgroupPort, "appdb_dw", + "SELECT string_agg(table_schema || '.' || table_name, ',' ORDER BY table_name) " + + "FROM information_schema.tables WHERE table_schema IN ('public', 'sales')"), + contains("public.customers,sales.orders")); + assertThat(query(workgroupPort, "appdb_dw", + "SELECT name || ':' || COALESCE(payload, '-') FROM public.customers ORDER BY id"), + contains("ada:vip", "grace:-")); + assertThat(query(workgroupPort, "appdb_dw", + "SELECT k.table_name || ':' || string_agg(k.column_name, ',' ORDER BY k.ordinal_position) " + + "FROM information_schema.table_constraints c " + + "JOIN information_schema.key_column_usage k " + + "ON k.constraint_name = c.constraint_name AND k.table_schema = c.table_schema " + + "WHERE c.constraint_type = 'PRIMARY KEY' " + + "AND c.table_schema IN ('public', 'sales') " + + "GROUP BY k.table_name ORDER BY k.table_name"), + contains("customers:id", "orders:id,line")); + assertThat(query(workgroupPort, "appdb_dw", + "SELECT data_type FROM information_schema.columns " + + "WHERE table_name = 'orders' AND column_name = 'note'"), + contains("character varying")); + + SQLException again = assertThrows(SQLException.class, + () -> execute(workgroupPort, "dev", "admin", ADMIN_PASSWORD, + "CREATE DATABASE appdb_dw2 FROM INTEGRATION '" + integrationId + "' DATABASE 'appdb'")); + assertThat(again.getSQLState(), equalTo("42P04")); + } finally { + String arnToDelete = integrationArn; + if (arnToDelete != null) { + cleanUpStep("DeleteIntegration " + arnToDelete, () -> rds("DeleteIntegration") + .formParam("IntegrationIdentifier", arnToDelete).when().post("/")); + } + if (workgroupCreated) { + cleanUpStep("deleteWorkgroup " + workgroup, () -> serverless.deleteWorkgroup(workgroup, REGION)); + } + if (namespaceCreated) { + cleanUpStep("deleteNamespace " + namespace, () -> serverless.deleteNamespace(namespace, REGION)); + } + cleanUpStep("deleteInstance " + dbId, () -> deleteInstance(dbId)); + } + } + + private static void cleanUpStep(String description, Runnable step) { + try { + step.run(); + } catch (RuntimeException e) { + LOG.warnv(e, "Teardown step failed: {0}", description); + } + } + + private static Connection connect(int port, String database, String user, String password) throws SQLException { + Properties properties = new Properties(); + properties.setProperty("user", user); + properties.setProperty("password", password); + properties.setProperty("sslmode", "disable"); + // 127.0.0.1 rather than the advertised address, which CI sets to a name the test JVM cannot resolve; + // the driver itself rather than DriverManager, which may not see it from a test profile's class loader. + return new Driver().connect("jdbc:postgresql://127.0.0.1:" + port + "/" + database, properties); + } + + private static void execute(int port, String database, String user, String password, String... statements) + throws SQLException { + try (Connection connection = connect(port, database, user, password); + Statement statement = connection.createStatement()) { + for (String sql : statements) { + statement.execute(sql); + } + } + } + + private static List query(int port, String database, String sql) throws SQLException { + List values = new ArrayList<>(); + try (Connection connection = connect(port, database, "admin", ADMIN_PASSWORD); + Statement statement = connection.createStatement(); + ResultSet rows = statement.executeQuery(sql)) { + while (rows.next()) { + values.add(rows.getString(1)); + } + } + return values; + } +} diff --git a/src/test/java/io/floci/aws/services/rds/integration/IntegrationDataFilterTest.java b/src/test/java/io/floci/aws/services/rds/integration/IntegrationDataFilterTest.java index d28b4b3c1b..aaaf3fe259 100644 --- a/src/test/java/io/floci/aws/services/rds/integration/IntegrationDataFilterTest.java +++ b/src/test/java/io/floci/aws/services/rds/integration/IntegrationDataFilterTest.java @@ -86,4 +86,45 @@ class IntegrationDataFilterTest { assertEquals(400, error.getHttpStatus()); return error; } + + @Test + void includes_appliesTheLastMatchingEntry() { + IntegrationDataFilter filter = IntegrationDataFilter.parsePostgres( + "include: books.*.*, exclude: books.*./.*king.*/, include: books.horror.stephen_king"); + assertTrue(filter.includes("books", "public", "authors")); + assertFalse(filter.includes("books", "public", "stephen_king")); + assertTrue(filter.includes("books", "horror", "stephen_king")); + } + + @Test + void includes_leavesOutWhatNoEntryMatches() { + IntegrationDataFilter filter = IntegrationDataFilter.parsePostgres("include: books.sales.*"); + assertTrue(filter.includes("books", "sales", "orders")); + assertFalse(filter.includes("books", "public", "orders")); + assertFalse(filter.includes("employees", "sales", "orders")); + } + + @Test + void includes_matchesARegexAgainstTheWholeName() { + IntegrationDataFilter filter = IntegrationDataFilter.parsePostgres("include: mydb.public./table_\\d+/"); + assertTrue(filter.includes("mydb", "public", "table_12")); + assertFalse(filter.includes("mydb", "public", "table_12_old")); + } + + @Test + void includes_matchesAQuotedNameExactly() { + IntegrationDataFilter filter = IntegrationDataFilter.parsePostgres("include: mydb.public.\"Orders\""); + assertTrue(filter.includes("mydb", "public", "Orders")); + assertFalse(filter.includes("mydb", "public", "orders")); + } + + @Test + void includesDatabase_needsAnIncludeEntryForIt() { + IntegrationDataFilter filter = IntegrationDataFilter.parsePostgres( + "include: books.*.*, exclude: employees.*.*"); + assertTrue(filter.includesDatabase("books")); + assertFalse(filter.includesDatabase("employees")); + assertTrue(IntegrationDataFilter.parsePostgres("include: books.*.*, include: *.sales.*") + .includesDatabase("employees")); + } } diff --git a/src/test/java/io/floci/aws/services/rds/integration/PostgresRedshiftTypesTest.java b/src/test/java/io/floci/aws/services/rds/integration/PostgresRedshiftTypesTest.java new file mode 100644 index 0000000000..b25d5a5f18 --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/integration/PostgresRedshiftTypesTest.java @@ -0,0 +1,83 @@ +package io.floci.aws.services.rds.integration; + +import io.floci.aws.services.rds.integration.PostgresRedshiftTypes.MappedColumn; +import io.floci.aws.services.rds.integration.PostgresRedshiftTypes.SourceColumn; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** The Redshift types AWS documents for an Aurora PostgreSQL source, and the types it does not replicate. */ +class PostgresRedshiftTypesTest { + + private static SourceColumn base(String typeName, String formatted) { + return new SourceColumn("c", typeName, "b", "N", true, null, null, false, formatted); + } + + private static MappedColumn mapped(SourceColumn column) { + return PostgresRedshiftTypes.map(column).orElseThrow(); + } + + @Test + void keepsNumericAndTemporalTypes() { + assertEquals("SMALLINT", mapped(base("int2", "smallint")).redshiftType()); + assertEquals("INTEGER", mapped(base("int4", "integer")).redshiftType()); + assertEquals("BIGINT", mapped(base("int8", "bigint")).redshiftType()); + assertEquals("DOUBLE PRECISION", mapped(base("float8", "double precision")).redshiftType()); + assertEquals("TIMESTAMPTZ", mapped(base("timestamptz", "timestamp with time zone")).redshiftType()); + assertEquals("\"c\"", mapped(base("int4", "integer")).selectExpression()); + } + + @Test + void mapsNumericWithItsPrecisionAndRefusesOneWithout() { + assertEquals("DECIMAL(10,2)", mapped(base("numeric", "numeric(10,2)")).redshiftType()); + assertTrue(PostgresRedshiftTypes.map(base("numeric", "numeric")).isEmpty()); + assertTrue(PostgresRedshiftTypes.map(base("numeric", "numeric(40,2)")).isEmpty()); + } + + @Test + void readsTextTypesAsText() { + MappedColumn text = mapped(base("text", "text")); + assertEquals("VARCHAR(65535)", text.redshiftType()); + assertEquals("\"c\"::text", text.selectExpression()); + assertEquals("VARCHAR(65535)", mapped(base("varchar", "character varying(20)")).redshiftType()); + assertEquals("VARCHAR(36)", mapped(base("uuid", "uuid")).redshiftType()); + assertEquals("VARCHAR(19)", mapped(base("time", "time without time zone")).redshiftType()); + assertEquals("CHAR(3)", mapped(base("bpchar", "character(3)")).redshiftType()); + } + + @Test + void mapsJsonAndArraysToSuper() { + MappedColumn jsonb = mapped(base("jsonb", "jsonb")); + assertEquals("pg_catalog.super", jsonb.redshiftType()); + assertEquals("\"c\"::jsonb", jsonb.selectExpression()); + MappedColumn array = mapped(new SourceColumn("tags", "_text", "b", "A", true, "text", "b", true, "text[]")); + assertEquals("pg_catalog.super", array.redshiftType()); + assertEquals("to_jsonb(\"tags\")", array.selectExpression()); + assertEquals("DECIMAL(20,3)", mapped(base("money", "money")).redshiftType()); + assertEquals("pg_catalog.varbyte", mapped(base("bytea", "bytea")).redshiftType()); + } + + @Test + void refusesTypesAwsDoesNotReplicate() { + Optional enumColumn = PostgresRedshiftTypes.map( + new SourceColumn("mood", "mood", "e", "E", false, null, null, false, "mood")); + assertTrue(enumColumn.isEmpty()); + assertTrue(PostgresRedshiftTypes.map( + new SourceColumn("moods", "_mood", "b", "A", false, "mood", "e", false, "mood[]")).isEmpty()); + assertTrue(PostgresRedshiftTypes.map( + new SourceColumn("moods", "_mood", "b", "A", true, "mood", "e", false, "mood[]")).isEmpty()); + assertTrue(PostgresRedshiftTypes.map(base("point", "point")).isEmpty()); + assertTrue(PostgresRedshiftTypes.map( + new SourceColumn("r", "int4range", "r", "R", true, null, null, false, "int4range")).isEmpty()); + } + + @Test + void quotesIdentifiers() { + MappedColumn column = mapped(new SourceColumn("Order \"Items\"", "int4", "b", "N", true, + null, null, false, "integer")); + assertEquals("\"Order \"\"Items\"\"\"", column.selectExpression()); + } +} diff --git a/src/test/java/io/floci/aws/services/rds/integration/RdsIntegrationDatabasesTest.java b/src/test/java/io/floci/aws/services/rds/integration/RdsIntegrationDatabasesTest.java new file mode 100644 index 0000000000..31d0f8a1e8 --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/integration/RdsIntegrationDatabasesTest.java @@ -0,0 +1,278 @@ +package io.floci.aws.services.rds.integration; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.rds.model.Integration; +import io.floci.aws.services.redshift.RedshiftService; +import io.floci.aws.services.redshift.spectrum.BackendSql; +import io.floci.aws.services.redshift.spectrum.ExternalStatement; +import io.floci.aws.services.redshift.spectrum.SpectrumSession; +import io.floci.aws.services.redshift.spectrum.SpectrumSqlException; +import io.floci.aws.services.redshiftserverless.RedshiftServerlessService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.empty; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * {@code CREATE DATABASE ... FROM INTEGRATION} against an RDS integration: the database is created and loaded + * only on the integration's own target, from a source database its filter includes. + */ +class RdsIntegrationDatabasesTest { + + private static final String ACCOUNT = "000000000000"; + private static final String INTEGRATION_ID = "4b2f2f9c-7d1e-4f55-9a77-1a2b3c4d5e6f"; + private static final String NAMESPACE_ARN = "arn:aws:redshift-serverless:us-east-1:000000000000:" + + "namespace/1a2b3c4d-0000-0000-0000-000000000000"; + + private RdsIntegrationService integrations; + private RdsIntegrationLoader loader; + private RedshiftService redshiftService; + private RedshiftServerlessService serverless; + private RdsIntegrationDatabases databases; + private RecordingBackend backend; + private Integration integration; + + @BeforeEach + void setUp() { + integrations = mock(RdsIntegrationService.class); + loader = mock(RdsIntegrationLoader.class); + redshiftService = mock(RedshiftService.class); + serverless = mock(RedshiftServerlessService.class); + databases = new RdsIntegrationDatabases(integrations, loader, redshiftService, serverless); + backend = new RecordingBackend(); + integration = new Integration(); + integration.setIntegrationArn("arn:aws:rds:us-east-1:000000000000:integration:" + INTEGRATION_ID); + integration.setTargetArn("arn:aws:redshift:us-east-1:000000000000:cluster:orders-dw"); + integration.setDataFilter("include: orders.*.*"); + integration.setAccountId(ACCOUNT); + integration.setRegion("us-east-1"); + when(integrations.findById(anyString())).thenReturn(Optional.empty()); + when(integrations.findById(INTEGRATION_ID)).thenReturn(Optional.of(integration)); + when(integrations.addDestination(any(), anyString(), anyString(), anyBoolean())).thenAnswer(invocation -> { + Integration updated = new Integration(integration); + updated.getDestinations().removeIf(d -> invocation.getArgument(2).equals(d.getSourceDatabase())); + updated.getDestinations().add(new Integration.Destination(invocation.getArgument(1), + invocation.getArgument(2), Integration.Destination.STATE_SYNCING, null, "load-1")); + return updated; + }); + when(integrations.reserveDestination(any(), anyString(), anyString(), any(), any())).thenAnswer(invocation -> { + Integration updated = new Integration(integration); + updated.getDestinations().removeIf(d -> invocation.getArgument(2).equals(d.getSourceDatabase())); + updated.getDestinations().add(new Integration.Destination(invocation.getArgument(1), + invocation.getArgument(2), Integration.Destination.STATE_CREATING, null, "load-1")); + return updated; + }); + when(integrations.startDestinationSync(any(), anyString(), any())).thenReturn(integration); + when(redshiftService.clusterRegion(ACCOUNT, "orders-dw")).thenReturn(Optional.of("us-east-1")); + } + + private static SpectrumSession session(String clusterIdentifier) { + return new SpectrumSession(ACCOUNT, ACCOUNT + ":" + clusterIdentifier, "dev", List.of(), false); + } + + private static ExternalStatement.CreateIntegrationDatabase statement(String sourceDatabase) { + return new ExternalStatement.CreateIntegrationDatabase("orders_dw", INTEGRATION_ID, sourceDatabase); + } + + private void assertState(String sqlState, Runnable call) { + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, call::run); + assertEquals(sqlState, error.sqlState(), error.getMessage()); + } + + @Test + void createsTheDatabaseAndStartsTheLoad() { + databases.create(statement("orders"), session("orders-dw"), backend); + + assertThat(backend.statements, contains("CREATE DATABASE \"orders_dw\"")); + verify(integrations).reserveDestination(integration, "orders_dw", "orders", null, null); + verify(integrations).startDestinationSync(any(), eq("orders"), eq("load-1")); + verify(loader).submit(integration, "orders", "orders_dw", "load-1"); + } + + @Test + void acceptsTheWorkgroupOfANamespaceTarget() { + integration.setTargetArn(NAMESPACE_ARN); + when(serverless.getNamespaceWorkgroupTarget(NAMESPACE_ARN, "us-east-1")).thenReturn( + new RedshiftServerlessService.WorkgroupTarget("arn", "orders-wg", "localhost", 5439, "dev", + "admin", "secret", "admin", List.of(), null)); + + databases.create(statement("orders"), session("serverless_us-east-1_orders-wg"), backend); + + verify(loader).submit(integration, "orders", "orders_dw", "load-1"); + } + + @Test + void refusesAnotherClustersSession() { + assertState("42704", () -> databases.create(statement("orders"), session("other-dw"), backend)); + assertThat(backend.statements, empty()); + } + + @Test + void refusesASameNamedClusterInAnotherRegion() { + when(redshiftService.clusterRegion(ACCOUNT, "orders-dw")).thenReturn(Optional.of("eu-west-1")); + assertState("42704", () -> databases.create(statement("orders"), session("orders-dw"), backend)); + } + + @Test + void replacesTheDestinationOfADroppedDatabase() { + integration.getDestinations().add(new Integration.Destination("orders_dw", "orders", + Integration.Destination.STATE_SYNCED, null, "old-load")); + + databases.create(statement("orders"), session("orders-dw"), backend); + + verify(integrations).reserveDestination(integration, "orders_dw", "orders", "orders_dw", "old-load"); + } + + @Test + void keepsTheDestinationOfADatabaseThatStillExists() { + integration.getDestinations().add(new Integration.Destination("orders_dw", "orders", + Integration.Destination.STATE_SYNCED, null, "old-load")); + backend.existingDatabase = true; + + databases.create(statement("orders"), session("orders-dw"), backend); + + verify(integrations).reserveDestination(integration, "orders_dw", "orders", null, null); + } + + @Test + void doesNotTreatACreatingDestinationAsDropped() { + integration.getDestinations().add(new Integration.Destination("orders_dw", "orders", + Integration.Destination.STATE_CREATING, null, "in-flight-load")); + when(integrations.reserveDestination(any(), anyString(), anyString(), isNull(), isNull())).thenThrow( + new AwsException("IntegrationAlreadyExistsFault", "already", 400)); + + assertState("42P04", () -> databases.create( + new ExternalStatement.CreateIntegrationDatabase("orders_dw2", INTEGRATION_ID, "orders"), + session("orders-dw"), backend)); + verify(integrations).reserveDestination(integration, "orders_dw2", "orders", null, null); + assertThat(backend.statements, empty()); + } + + @Test + void mapsAnIntegrationDeletedMeanwhileToUndefinedObject() { + when(integrations.reserveDestination(any(), anyString(), anyString(), any(), any())).thenThrow( + new AwsException("IntegrationNotFoundFault", "gone", 404)); + assertState("42704", () -> databases.create(statement("orders"), session("orders-dw"), backend)); + } + + @Test + void refusesAnUnknownIntegration() { + assertState("42704", () -> databases.create( + new ExternalStatement.CreateIntegrationDatabase("dw", "missing", "orders"), session("orders-dw"), + backend)); + } + + @Test + void refusesADynamoDbIntegrationAsUnsupported() { + when(redshiftService.integrationExists(ACCOUNT, "dynamo")).thenReturn(true); + assertState("0A000", () -> databases.create( + new ExternalStatement.CreateIntegrationDatabase("dw", "dynamo", "orders"), session("orders-dw"), + backend)); + } + + @Test + void requiresTheSourceDatabase() { + assertState("42601", () -> databases.create(statement(null), session("orders-dw"), backend)); + } + + @Test + void refusesASourceDatabaseTheFilterLeavesOut() { + assertState("22023", () -> databases.create(statement("billing"), session("orders-dw"), backend)); + } + + @Test + void mapsADuplicateSourceDatabaseToDuplicateDatabase() { + when(integrations.reserveDestination(any(), anyString(), anyString(), any(), any())).thenThrow( + new AwsException("IntegrationAlreadyExistsFault", "already", 400)); + assertState("42P04", () -> databases.create(statement("orders"), session("orders-dw"), backend)); + assertThat(backend.statements, empty()); + } + + @Test + void forgetsTheDestinationWhenTheDatabaseCannotBeCreated() { + RecordingBackend failing = new RecordingBackend(); + failing.failure = new SpectrumSqlException("42P04", "database \"orders_dw\" already exists"); + + assertState("42P04", () -> databases.create(statement("orders"), session("orders-dw"), failing)); + + verify(integrations).removeDestination(integration, "orders", "load-1"); + verify(loader, never()).submit(any(), anyString(), anyString(), any()); + } + + @Test + void reusesExistingDatabaseWhenRetryingAFailedLoadWithTheSameName() { + integration.getDestinations().add(new Integration.Destination("orders_dw", "orders", + Integration.Destination.STATE_FAILED, null)); + backend.existingDatabase = true; + + databases.create(statement("orders"), session("orders-dw"), backend); + + assertThat(backend.statements, empty()); + verify(integrations).addDestination(integration, "orders_dw", "orders", false); + verify(loader).submit(any(), eq("orders"), eq("orders_dw"), eq("load-1")); + } + + @Test + void restoresPreviousFailedDestinationAndErrorsWhenRetryDatabaseCreationFails() { + Integration.Destination failed = new Integration.Destination("orders_dw", "orders", + Integration.Destination.STATE_FAILED, null); + Integration.IntegrationError error = new Integration.IntegrationError( + RdsIntegrationService.INITIAL_LOAD_FAILED, + "The initial load of source database orders into orders_dw failed: source is down"); + integration.getDestinations().add(failed); + integration.getErrors().add(error); + RecordingBackend failing = new RecordingBackend(); + failing.existingDatabase = true; + failing.failure = new SpectrumSqlException("42P04", "database \"orders_dw_v2\" already exists"); + + assertState("42P04", () -> databases.create( + new ExternalStatement.CreateIntegrationDatabase("orders_dw_v2", INTEGRATION_ID, "orders"), + session("orders-dw"), failing)); + + verify(integrations).restoreDestination(integration, "orders", "load-1", failed, List.of(error)); + verify(integrations, never()).removeDestination(any(), anyString(), any()); + verify(loader, never()).submit(any(), anyString(), anyString(), any()); + } + + private static final class RecordingBackend implements BackendSql { + private final List statements = new ArrayList<>(); + private RuntimeException failure; + private boolean existingDatabase; + + @Override + public Optional queryString(String sql) { + return existingDatabase ? Optional.of("1") : Optional.empty(); + } + + @Override + public void execute(String sql) { + if (failure != null) { + throw failure; + } + statements.add(sql); + } + + @Override + public long copyIn(String copySql, InputStream data) { + throw new UnsupportedOperationException(); + } + } +} diff --git a/src/test/java/io/floci/aws/services/rds/integration/RdsIntegrationLoaderTest.java b/src/test/java/io/floci/aws/services/rds/integration/RdsIntegrationLoaderTest.java new file mode 100644 index 0000000000..01de75f1cd --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/integration/RdsIntegrationLoaderTest.java @@ -0,0 +1,280 @@ +package io.floci.aws.services.rds.integration; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.rds.RdsService; +import io.floci.aws.services.rds.container.RdsContainerManager; +import io.floci.aws.services.rds.model.DbCluster; +import io.floci.aws.services.rds.model.Integration; +import io.floci.aws.services.redshiftdata.RedshiftZeroEtlWriter; +import io.floci.aws.services.redshiftdata.RedshiftZeroEtlWriter.ReplicatedTable; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +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.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.ArgumentMatchers.startsWith; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** + * The initial load with the source's container and the Redshift writer mocked: which tables are copied, the + * columns they get, the COPY that reads them out, and the destination state the load ends in. + */ +class RdsIntegrationLoaderTest { + + private static final String CLUSTER_ARN = "arn:aws:rds:us-east-1:000000000000:cluster:orders-src"; + private static final String TARGET_ARN = "arn:aws:redshift:us-east-1:000000000000:cluster:orders-dw"; + private static final String LOAD_ID = "load-1"; + + private RdsIntegrationService integrations; + private RdsService rdsService; + private RdsContainerManager containers; + private RedshiftZeroEtlWriter writer; + private List loadedRows; + private Integration integration; + + @BeforeEach + void setUp() { + integrations = mock(RdsIntegrationService.class); + rdsService = mock(RdsService.class); + containers = mock(RdsContainerManager.class); + writer = mock(RedshiftZeroEtlWriter.class); + loadedRows = new ArrayList<>(); + DbCluster cluster = new DbCluster(); + cluster.setContainerId("container-1"); + cluster.setMasterUsername("postgres"); + when(rdsService.ensureClusterBackend("orders-src", "us-east-1")).thenReturn(cluster); + when(integrations.isLoading(any(), eq("orders"), eq("orders_dw"), eq(LOAD_ID))).thenReturn(true); + doAnswer(invocation -> { + invocation.getArgument(4).write("1,widget\n".getBytes(StandardCharsets.UTF_8)); + return null; + }).when(containers).queryPostgres(eq("container-1"), eq("postgres"), eq("orders"), startsWith("COPY"), + any(OutputStream.class), anyInt()); + when(writer.loadTable(anyString(), anyString(), anyString(), any(), any())).thenAnswer(invocation -> { + try (InputStream in = invocation.getArgument(4)) { + loadedRows.add(new String(in.readAllBytes(), StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return 1L; + }); + integration = new Integration(); + integration.setIntegrationArn("arn:aws:rds:us-east-1:000000000000:integration:4b2f2f9c"); + integration.setSourceArn(CLUSTER_ARN); + integration.setTargetArn(TARGET_ARN); + integration.setDataFilter("include: orders.*.*, exclude: orders.audit.*"); + integration.setAccountId("000000000000"); + integration.setRegion("us-east-1"); + } + + private RdsIntegrationLoader loader(boolean mock) { + return new RdsIntegrationLoader(integrations, rdsService, containers, writer, new ObjectMapper(), mock, + Runnable::run, 2, Duration.ZERO); + } + + private void catalog(String... rows) { + when(containers.queryPostgres("container-1", "postgres", "orders", RdsIntegrationLoader.CATALOG_SQL)) + .thenReturn(String.join("\n", rows)); + } + + private static String column(String schema, String table, String column, String type, String formatted, + int key) { + return "{\"schema\":\"" + schema + "\",\"table\":\"" + table + "\",\"column\":\"" + column + + "\",\"type\":\"" + type + "\",\"typtype\":\"b\",\"category\":\"N\",\"builtin\":true," + + "\"element\":null,\"elementtype\":null,\"elementbuiltin\":false,\"formatted\":\"" + formatted + + "\",\"key\":" + key + "}"; + } + + @Test + void copiesEachIncludedTableWithAPrimaryKey() { + catalog(column("public", "items", "id", "int4", "integer", 1), + column("public", "items", "name", "text", "text", 0), + column("public", "notes", "body", "text", "text", 0), + column("audit", "events", "id", "int4", "integer", 1)); + + loader(false).submit(integration, "orders", "orders_dw", LOAD_ID); + + ArgumentCaptor table = ArgumentCaptor.forClass(ReplicatedTable.class); + verify(writer, times(1)).loadTable(eq("000000000000"), eq(TARGET_ARN), eq("orders_dw"), table.capture(), + any()); + assertEquals("items", table.getValue().table()); + assertThat(table.getValue().columns(), contains(new ReplicatedTable.Column("id", "INTEGER"), + new ReplicatedTable.Column("name", "VARCHAR(65535)"))); + assertThat(table.getValue().primaryKey(), contains("id")); + assertThat(loadedRows, contains("1,widget\n")); + ArgumentCaptor copy = ArgumentCaptor.forClass(String.class); + verify(containers).queryPostgres(eq("container-1"), eq("postgres"), eq("orders"), copy.capture(), + any(OutputStream.class), anyInt()); + assertEquals("COPY (SELECT \"id\", \"name\"::text FROM \"public\".\"items\") TO STDOUT WITH (FORMAT csv)", + copy.getValue()); + verify(integrations).finishDestination(integration, "orders", "orders_dw", LOAD_ID, null); + } + + @Test + void catalogQueryRestrictsPrimaryKeysToKeyColumnsOnly() { + assertThat(RdsIntegrationLoader.CATALOG_SQL, containsString("k.n <= i.indnkeyatts")); + } + + @Test + void ordersACompositePrimaryKeyByItsKeyPositions() { + catalog(column("public", "lines", "line", "int4", "integer", 2), + column("public", "lines", "order_id", "int8", "bigint", 1)); + + loader(false).submit(integration, "orders", "orders_dw", LOAD_ID); + + ArgumentCaptor table = ArgumentCaptor.forClass(ReplicatedTable.class); + verify(writer).loadTable(anyString(), anyString(), anyString(), table.capture(), any()); + assertThat(table.getValue().primaryKey(), contains("order_id", "line")); + } + + @Test + void skipsATableWithAColumnTypeZeroEtlDoesNotReplicate() { + catalog(column("public", "items", "id", "int4", "integer", 1), + column("public", "items", "price", "numeric", "numeric", 0)); + + loader(false).submit(integration, "orders", "orders_dw", LOAD_ID); + + verify(writer, never()).loadTable(anyString(), anyString(), anyString(), any(), any()); + verify(integrations).finishDestination(integration, "orders", "orders_dw", LOAD_ID, null); + } + + @Test + void carriesOnWithTheOtherTablesWhenOneFailsToLoadAndReportsFailure() { + catalog(column("public", "broken", "id", "int4", "integer", 1), + column("public", "items", "id", "int4", "integer", 1)); + doThrow(new IllegalStateException("value too long")).doReturn(1L).when(writer) + .loadTable(anyString(), anyString(), anyString(), any(), any()); + + loader(false).submit(integration, "orders", "orders_dw", LOAD_ID); + + verify(writer, times(2)).loadTable(anyString(), anyString(), anyString(), any(), any()); + ArgumentCaptor failure = ArgumentCaptor.forClass(String.class); + verify(integrations).finishDestination(eq(integration), eq("orders"), eq("orders_dw"), eq(LOAD_ID), + failure.capture()); + assertThat(failure.getValue(), containsString("public.broken")); + } + + @Test + void retriesWhenTargetIsUnavailableDuringCopy() { + catalog(column("public", "items", "id", "int4", "integer", 1)); + doThrow(new RedshiftZeroEtlWriter.TargetUnavailableException("connection refused", null)) + .doReturn(1L) + .when(writer).loadTable(anyString(), anyString(), anyString(), any(), any()); + + loader(false).submit(integration, "orders", "orders_dw", LOAD_ID); + + verify(writer, times(2)).loadTable(anyString(), anyString(), anyString(), any(), any()); + verify(integrations).finishDestination(integration, "orders", "orders_dw", LOAD_ID, null); + } + + @Test + void retriesWhenSourceFailsDuringCopyAfterCatalogDiscovery() { + catalog(column("public", "items", "id", "int4", "integer", 1)); + doThrow(new IllegalStateException("source container stopped")) + .doAnswer(invocation -> { + invocation.getArgument(4).write("1\n".getBytes(StandardCharsets.UTF_8)); + return null; + }) + .when(containers).queryPostgres(eq("container-1"), eq("postgres"), eq("orders"), + startsWith("COPY"), any(OutputStream.class), anyInt()); + + loader(false).submit(integration, "orders", "orders_dw", LOAD_ID); + + verify(writer, times(1)).loadTable(anyString(), anyString(), anyString(), any(), any()); + verify(integrations).finishDestination(integration, "orders", "orders_dw", LOAD_ID, null); + } + + @Test + void triesAgainWhenTheSourceIsNotBackYet() { + when(containers.queryPostgres("container-1", "postgres", "orders", RdsIntegrationLoader.CATALOG_SQL)) + .thenThrow(new IllegalStateException("container not running")) + .thenReturn(column("public", "items", "id", "int4", "integer", 1)); + + loader(false).submit(integration, "orders", "orders_dw", LOAD_ID); + + verify(writer).loadTable(anyString(), anyString(), anyString(), any(), any()); + verify(integrations).finishDestination(integration, "orders", "orders_dw", LOAD_ID, null); + } + + @Test + void failsTheDestinationWhenTheSourceCannotBeRead() { + when(containers.queryPostgres("container-1", "postgres", "orders", RdsIntegrationLoader.CATALOG_SQL)) + .thenThrow(new IllegalStateException("psql failed: database \"orders\" does not exist")); + + loader(false).submit(integration, "orders", "orders_dw", LOAD_ID); + + ArgumentCaptor failure = ArgumentCaptor.forClass(String.class); + verify(integrations).finishDestination(eq(integration), eq("orders"), eq("orders_dw"), eq(LOAD_ID), + failure.capture()); + assertThat(failure.getValue(), containsString("does not exist")); + } + + @Test + void stopsWhenTheIntegrationIsNoLongerLoading() { + when(integrations.isLoading(any(), eq("orders"), eq("orders_dw"), eq(LOAD_ID))).thenReturn(false); + catalog(column("public", "items", "id", "int4", "integer", 1)); + + loader(false).submit(integration, "orders", "orders_dw", LOAD_ID); + + verify(writer, never()).loadTable(anyString(), anyString(), anyString(), any(), any()); + verify(integrations, never()).finishDestination(any(), anyString(), anyString(), any(), any()); + } + + @Test + void stopsBeforeWritingWhenLoadIsSupersededDuringSourceExport() { + when(integrations.isLoading(any(), eq("orders"), eq("orders_dw"), eq("load-old"))) + .thenReturn(true, false); + catalog(column("public", "items", "id", "int4", "integer", 1)); + + loader(false).submit(integration, "orders", "orders_dw", "load-old"); + + verify(writer, never()).loadTable(anyString(), anyString(), anyString(), any(), any()); + verify(integrations, never()).finishDestination(any(), anyString(), anyString(), any(), any()); + } + + @Test + void inMockModeCopiesNothingAndSyncs() { + loader(true).submit(integration, "orders", "orders_dw", LOAD_ID); + + verifyNoInteractions(containers, writer); + verify(integrations).finishDestination(eq(integration), eq("orders"), eq("orders_dw"), eq(LOAD_ID), isNull()); + } + + @Test + void resumeInterruptedLoads_loadsTheSyncingDestinationsAgain() { + integration.getDestinations().add(new Integration.Destination("orders_dw", "orders", + Integration.Destination.STATE_SYNCING, null, "load-resumed")); + integration.getDestinations().add(new Integration.Destination("done_dw", "done", + Integration.Destination.STATE_SYNCED, null, "load-done")); + when(integrations.integrationsWithLoadsInProgress()).thenReturn(List.of(integration)); + + loader(true).resumeInterruptedLoads(); + + verify(integrations).reconcileInterruptedCreations(); + verify(integrations).finishDestination(any(), eq("orders"), eq("orders_dw"), eq("load-resumed"), isNull()); + verify(integrations, never()).finishDestination(any(), eq("done"), anyString(), any(), any()); + } +} diff --git a/src/test/java/io/floci/aws/services/rds/integration/RdsIntegrationServiceTest.java b/src/test/java/io/floci/aws/services/rds/integration/RdsIntegrationServiceTest.java index 64221afc03..021681c52f 100644 --- a/src/test/java/io/floci/aws/services/rds/integration/RdsIntegrationServiceTest.java +++ b/src/test/java/io/floci/aws/services/rds/integration/RdsIntegrationServiceTest.java @@ -29,7 +29,9 @@ 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.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -356,4 +358,240 @@ class RdsIntegrationServiceTest { assertThat(service.describeIntegrations(null, Map.of(), REGION), empty()); } + + @Test + void addDestination_syncsUntilTheLoadFinishesThenIsActive() { + Integration created = create("orders-zero-etl"); + Integration integration = service.findById(created.integrationId()).orElseThrow(); + + Integration syncing = service.addDestination(integration, "orders_dw", "orders", false); + String loadId = loadId(syncing, "orders"); + assertEquals(Integration.STATUS_SYNCING, syncing.getStatus()); + assertEquals(Integration.STATUS_SYNCING, describe(created).getStatus()); + assertTrue(service.isLoading(integration, "orders", "orders_dw", loadId)); + assertError("InvalidIntegrationStateFault", 400, + () -> service.modifyIntegration(created.getIntegrationArn(), null, null, "x", REGION)); + + service.finishDestination(integration, "orders", "orders_dw", loadId, null); + Integration active = describe(created); + assertEquals(Integration.STATUS_ACTIVE, active.getStatus()); + assertEquals(Integration.Destination.STATE_SYNCED, active.destinationFor("orders").orElseThrow().getState()); + assertFalse(service.isLoading(integration, "orders", "orders_dw", loadId)); + } + + @Test + void addDestination_refusesASecondDatabaseFromTheSameSourceDatabase() { + Integration integration = service.findById(create("orders-zero-etl").integrationId()).orElseThrow(); + Integration syncing = service.addDestination(integration, "orders_dw", "orders", false); + service.finishDestination(integration, "orders", "orders_dw", loadId(syncing, "orders"), null); + + assertError("IntegrationAlreadyExistsFault", 400, + () -> service.addDestination(integration, "orders_dw2", "orders", false)); + } + + @Test + void addDestination_takesAnotherSourceDatabaseWhileSyncing() { + Integration integration = service.findById(create("orders-zero-etl").integrationId()).orElseThrow(); + service.addDestination(integration, "orders_dw", "orders", false); + + Integration both = service.addDestination(integration, "billing_dw", "billing", false); + + assertEquals(2, both.getDestinations().size()); + assertEquals(Integration.STATUS_SYNCING, both.getStatus()); + } + + @Test + void addDestination_replacesAFailedLoadOrADroppedDatabase() { + Integration created = create("orders-zero-etl"); + Integration integration = service.findById(created.integrationId()).orElseThrow(); + Integration first = service.addDestination(integration, "orders_dw", "orders", false); + service.finishDestination(integration, "orders", "orders_dw", loadId(first, "orders"), "source is down"); + + Integration retried = service.addDestination(integration, "orders_dw", "orders", false); + assertEquals(Integration.STATUS_SYNCING, retried.getStatus()); + assertEquals(1, retried.getDestinations().size()); + + service.finishDestination(integration, "orders", "orders_dw", loadId(retried, "orders"), null); + Integration reloaded = service.addDestination(integration, "orders_dw_v2", "orders", true); + assertEquals("orders_dw_v2", reloaded.destinationFor("orders").orElseThrow().getDatabaseName()); + } + + @Test + void finishDestination_withAFailureMarksTheIntegrationFailed() { + Integration created = create("orders-zero-etl"); + Integration integration = service.findById(created.integrationId()).orElseThrow(); + Integration syncing = service.addDestination(integration, "orders_dw", "orders", false); + + service.finishDestination(integration, "orders", "orders_dw", loadId(syncing, "orders"), "source is down"); + + Integration failed = describe(created); + assertEquals(Integration.STATUS_FAILED, failed.getStatus()); + assertEquals(RdsIntegrationService.INITIAL_LOAD_FAILED, failed.getErrors().get(0).getErrorCode()); + assertThat(failed.getErrors().get(0).getErrorMessage(), containsString("source is down")); + } + + @Test + void addDestination_preservesErrorsOfOtherFailedDestinations() { + Integration created = create("orders-zero-etl"); + Integration integration = service.findById(created.integrationId()).orElseThrow(); + Integration orders = service.addDestination(integration, "orders_dw", "orders", false); + service.finishDestination(integration, "orders", "orders_dw", loadId(orders, "orders"), "orders load failed"); + + Integration billing = service.addDestination(integration, "billing_dw", "billing", false); + service.finishDestination(integration, "billing", "billing_dw", loadId(billing, "billing"), null); + + Integration described = describe(created); + assertEquals(Integration.STATUS_FAILED, described.getStatus()); + assertEquals(1, described.getErrors().size()); + assertThat(described.getErrors().get(0).getErrorMessage(), containsString("orders load failed")); + } + + @Test + void restoreDestination_restoresPreviousFailedDestinationAndErrors() { + Integration created = create("orders-zero-etl"); + Integration integration = service.findById(created.integrationId()).orElseThrow(); + Integration first = service.addDestination(integration, "orders_dw", "orders", false); + service.finishDestination(integration, "orders", "orders_dw", loadId(first, "orders"), "source is down"); + Integration failed = describe(created); + Integration.Destination previous = failed.destinationFor("orders").orElseThrow(); + List previousErrors = List.copyOf(failed.getErrors()); + + Integration replacement = service.addDestination(integration, "orders_dw_v2", "orders", false); + service.restoreDestination(integration, "orders", loadId(replacement, "orders"), previous, previousErrors); + + Integration restored = describe(created); + assertEquals(Integration.STATUS_FAILED, restored.getStatus()); + assertEquals("orders_dw", restored.destinationFor("orders").orElseThrow().getDatabaseName()); + assertEquals(Integration.Destination.STATE_FAILED, + restored.destinationFor("orders").orElseThrow().getState()); + assertEquals(1, restored.getErrors().size()); + assertThat(restored.getErrors().get(0).getErrorMessage(), containsString("source is down")); + } + + @Test + void removeDestination_putsTheIntegrationBackToActive() { + Integration created = create("orders-zero-etl"); + Integration integration = service.findById(created.integrationId()).orElseThrow(); + Integration syncing = service.addDestination(integration, "orders_dw", "orders", false); + + service.removeDestination(integration, "orders", loadId(syncing, "orders")); + + assertEquals(Integration.STATUS_ACTIVE, describe(created).getStatus()); + assertThat(describe(created).getDestinations(), empty()); + } + + @Test + void finishDestination_ignoresADeletedIntegration() { + Integration created = create("orders-zero-etl"); + Integration integration = service.findById(created.integrationId()).orElseThrow(); + Integration syncing = service.addDestination(integration, "orders_dw", "orders", false); + service.deleteIntegration(created.getIntegrationArn(), REGION); + + service.finishDestination(integration, "orders", "orders_dw", loadId(syncing, "orders"), null); + + assertThat(storage.scan(key -> true), empty()); + } + + @Test + void integrationsWithLoadsInProgress_listsOnlySyncingOnes() { + Integration first = service.findById(create("orders-zero-etl").integrationId()).orElseThrow(); + service.createIntegration(request("other-zero-etl", CLUSTER_ARN, REDSHIFT_CLUSTER_ARN), REGION); + service.addDestination(first, "orders_dw", "orders", false); + + List pending = service.integrationsWithLoadsInProgress(); + + assertEquals(1, pending.size()); + assertEquals(first.getIntegrationArn(), pending.get(0).getIntegrationArn()); + } + + @Test + void reserveDestination_blocksConcurrentReplacementWhileCreating() { + Integration created = create("orders-zero-etl"); + Integration integration = service.findById(created.integrationId()).orElseThrow(); + Integration reserved = service.reserveDestination(integration, "orders_dw", "orders", null, null); + String loadId = reserved.destinationFor("orders").orElseThrow().getLoadId(); + + assertEquals(Integration.STATUS_SYNCING, reserved.getStatus()); + assertEquals(Integration.Destination.STATE_CREATING, + reserved.destinationFor("orders").orElseThrow().getState()); + assertError("IntegrationAlreadyExistsFault", 400, + () -> service.reserveDestination(integration, "orders_dw2", "orders", "orders_dw", loadId)); + + Integration syncing = service.startDestinationSync(reserved, "orders", loadId); + assertEquals(Integration.Destination.STATE_SYNCING, + syncing.destinationFor("orders").orElseThrow().getState()); + assertTrue(service.isLoading(integration, "orders", "orders_dw", loadId)); + } + + @Test + void restoreDestination_ignoresRollbackWhenLoadIdDoesNotMatch() { + Integration created = create("orders-zero-etl"); + Integration integration = service.findById(created.integrationId()).orElseThrow(); + Integration reserved = service.reserveDestination(integration, "orders_dw", "orders", null, null); + String activeLoadId = reserved.destinationFor("orders").orElseThrow().getLoadId(); + + service.removeDestination(integration, "orders", "stale-load-id"); + + Integration current = describe(created); + assertEquals("orders_dw", current.destinationFor("orders").orElseThrow().getDatabaseName()); + assertEquals(activeLoadId, current.destinationFor("orders").orElseThrow().getLoadId()); + } + + @Test + void finishDestination_ignoresStaleLoadIdAfterSameNameReplacement() { + Integration created = create("orders-zero-etl"); + Integration integration = service.findById(created.integrationId()).orElseThrow(); + Integration first = service.addDestination(integration, "orders_dw", "orders", false); + String firstLoadId = first.destinationFor("orders").orElseThrow().getLoadId(); + + Integration replacement = service.addDestination(integration, "orders_dw", "orders", true); + String secondLoadId = replacement.destinationFor("orders").orElseThrow().getLoadId(); + + assertFalse(service.isLoading(integration, "orders", "orders_dw", firstLoadId)); + assertTrue(service.isLoading(integration, "orders", "orders_dw", secondLoadId)); + + service.finishDestination(integration, "orders", "orders_dw", firstLoadId, null); + + Integration stillSyncing = describe(created); + assertEquals(Integration.STATUS_SYNCING, stillSyncing.getStatus()); + assertEquals(Integration.Destination.STATE_SYNCING, + stillSyncing.destinationFor("orders").orElseThrow().getState()); + assertEquals(secondLoadId, stillSyncing.destinationFor("orders").orElseThrow().getLoadId()); + } + + @Test + void reconcileInterruptedCreations_marksCreatingDestinationsFailedSoTheyCanBeRetried() { + Integration created = create("orders-zero-etl"); + Integration integration = service.findById(created.integrationId()).orElseThrow(); + service.reserveDestination(integration, "orders_dw", "orders", null, null); + assertEquals(Integration.STATUS_SYNCING, describe(created).getStatus()); + + service.reconcileInterruptedCreations(); + + Integration reconciled = describe(created); + assertEquals(Integration.STATUS_FAILED, reconciled.getStatus()); + assertEquals(Integration.Destination.STATE_FAILED, + reconciled.destinationFor("orders").orElseThrow().getState()); + assertEquals(1, reconciled.getErrors().size()); + assertEquals(RdsIntegrationService.INITIAL_LOAD_FAILED, reconciled.getErrors().get(0).getErrorCode()); + + Integration retried = service.reserveDestination(reconciled, "orders_dw", "orders", null, null); + assertEquals(Integration.Destination.STATE_CREATING, + retried.destinationFor("orders").orElseThrow().getState()); + assertThat(retried.getErrors(), empty()); + } + + @Test + void findById_returnsNothingForAnUnknownId() { + create("orders-zero-etl"); + assertEquals(Optional.empty(), service.findById("4b2f2f9c-0000-0000-0000-000000000000")); + } + + private Integration describe(Integration integration) { + return service.describeIntegrations(integration.getIntegrationArn(), Map.of(), REGION).get(0); + } + + private static String loadId(Integration integration, String sourceDatabase) { + return integration.destinationFor(sourceDatabase).orElseThrow().getLoadId(); + } } diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/ExternalStatementParserTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/ExternalStatementParserTest.java index ca7358b2e2..2fbe58b24d 100644 --- a/src/test/java/io/floci/aws/services/redshift/spectrum/ExternalStatementParserTest.java +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/ExternalStatementParserTest.java @@ -367,4 +367,43 @@ class ExternalStatementParserTest { + "TABLE PROPERTIES ('z'='1', 'a'='2', 'm'='3')").orElseThrow(); assertThat(List.copyOf(table.properties().keySet()), equalTo(List.of("z", "a", "m"))); } + + @Test + void parsesCreateDatabaseFromIntegration() { + ExternalStatement.CreateIntegrationDatabase database = (ExternalStatement.CreateIntegrationDatabase) parser.parse( + "CREATE DATABASE Orders_DW FROM INTEGRATION 'a1b2c3d4-5678-90ab-cdef-EXAMPLE11111' DATABASE 'Orders';") + .orElseThrow(); + assertThat(database.databaseName(), equalTo("orders_dw")); + assertThat(database.integrationId(), equalTo("a1b2c3d4-5678-90ab-cdef-EXAMPLE11111")); + assertThat(database.sourceDatabase(), equalTo("Orders")); + } + + @Test + void parsesCreateDatabaseFromIntegrationWithBareSourceDatabaseAndOptions() { + ExternalStatement.CreateIntegrationDatabase database = (ExternalStatement.CreateIntegrationDatabase) parser.parse( + "create database \"Sales\" from integration 'abc' database SourceDb SET HISTORY_MODE = true") + .orElseThrow(); + assertThat(database.databaseName(), equalTo("Sales")); + assertThat(database.sourceDatabase(), equalTo("sourcedb")); + } + + @Test + void parsesCreateDatabaseFromIntegrationWithoutSourceDatabase() { + ExternalStatement.CreateIntegrationDatabase database = (ExternalStatement.CreateIntegrationDatabase) parser.parse( + "CREATE DATABASE dw FROM INTEGRATION 'abc' SET REFRESH_INTERVAL 7200").orElseThrow(); + assertThat(database.sourceDatabase(), nullValue()); + } + + @Test + void rejectsTrailingStatementsAfterIntegrationDatabaseOptions() { + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () -> parser.parse( + "CREATE DATABASE dw FROM INTEGRATION 'abc' DATABASE 'orders' SET x = 1; SELECT 1")); + assertThat(error.sqlState(), equalTo("42601")); + } + + @Test + void leavesPlainCreateDatabaseToTheBackend() { + assertThat(parser.parse("CREATE DATABASE dw").isPresent(), equalTo(false)); + assertThat(parser.parse("CREATE DATABASE dw WITH OWNER admin").isPresent(), equalTo(false)); + } }