From 5807e901a47494cc97eed1d95eb08e77341c6a3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20Th=E1=BA=BF=20Huy?= <31652864+vuthehuyht@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:35:08 +0700 Subject: [PATCH] feat(redshift): add streaming materialized views over Amazon MSK (#9206) CREATE MATERIALIZED VIEW over a topic of an MSK external schema, REFRESH MATERIALIZED VIEW, DROP MATERIALIZED VIEW and DROP SCHEMA ... CASCADE now work, with the transaction, AUTO REFRESH YES, JOIN and aggregate guards of the Kinesis views. The topic's staging table has Redshift's eight Kafka columns. A refresh positions each partition itself by manual assignment and a seek, reads up to the end offset the partition has when the refresh starts, and saves per-partition checkpoints only after the batch statement commits. Each view reads through its own consumer group. The first refresh starts at the earliest offset, and a partition that ends before its checkpoint is read again from its beginning. With IAM enforcement on, CREATE and REFRESH check kafka:GetBootstrapBrokers on the cluster and, with AUTHENTICATION iam, kafka-cluster:Connect, DescribeTopic, ReadData, AlterGroup and DescribeGroup on the cluster, topic and group ARNs. A missing cluster fails with 42704, a cluster without a running broker or an unreachable broker with 58030, and a missing topic with 42P01. KafkaRestClient.partitionOffsets reads a partition's beginning and end offsets. StreamingViewSupport holds the source lock, drop, unbind and batching shared by the Kinesis and MSK views, and DROP SCHEMA of an MSK schema holds a schema lock so no view is created while it runs. Closes #7814 --- docs/services/redshift.md | 64 +- .../common/kafka/KafkaPartitionOffsets.java | 8 + .../core/common/kafka/KafkaRestClient.java | 25 + .../spectrum/KinesisStreamingViews.java | 102 +-- .../redshift/spectrum/MskStreamingViews.java | 475 ++++++++++++ .../redshift/spectrum/MskViewBinding.java | 54 ++ .../redshift/spectrum/MskViewRegistry.java | 22 + .../spectrum/SpectrumQueryPreparation.java | 118 ++- .../spectrum/StreamingViewSupport.java | 130 ++++ .../kafka/KafkaRestClientAssignmentTest.java | 46 ++ ...dshiftMskStreamingViewIntegrationTest.java | 229 ++++++ .../spectrum/KinesisStreamingViewsTest.java | 2 +- .../spectrum/MskStreamingViewsTest.java | 692 ++++++++++++++++++ .../redshift/spectrum/MskTestFixtures.java | 29 + .../spectrum/MskViewRegistryTest.java | 92 +++ .../SpectrumMskSchemaPreparationTest.java | 11 +- .../SpectrumMskViewPreparationTest.java | 209 ++++++ 17 files changed, 2189 insertions(+), 119 deletions(-) create mode 100644 src/main/java/io/floci/aws/core/common/kafka/KafkaPartitionOffsets.java create mode 100644 src/main/java/io/floci/aws/services/redshift/spectrum/MskStreamingViews.java create mode 100644 src/main/java/io/floci/aws/services/redshift/spectrum/MskViewBinding.java create mode 100644 src/main/java/io/floci/aws/services/redshift/spectrum/MskViewRegistry.java create mode 100644 src/main/java/io/floci/aws/services/redshift/spectrum/StreamingViewSupport.java create mode 100644 src/test/java/io/floci/aws/services/redshift/RedshiftMskStreamingViewIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/redshift/spectrum/MskStreamingViewsTest.java create mode 100644 src/test/java/io/floci/aws/services/redshift/spectrum/MskTestFixtures.java create mode 100644 src/test/java/io/floci/aws/services/redshift/spectrum/MskViewRegistryTest.java create mode 100644 src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumMskViewPreparationTest.java diff --git a/docs/services/redshift.md b/docs/services/redshift.md index ee137442a8..f206451aa3 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -1085,7 +1085,8 @@ CLUSTER_ARN 'arn:aws:kafka:us-east-1:123456789012:cluster/my-cluster/00000000-00 - `AUTHENTICATION` accepts `iam` or `none`. `AUTHENTICATION mtls`, `AUTHENTICATION_ARN`, `SECRET_ARN`, `URI`, `IAM_ROLE DEFAULT` and `FROM KAFKA` schemas are refused with SQLSTATE `0A000`. - The role and cluster ARN are not checked when the schema is created. -- A statement that names a relation of the schema (`SELECT * FROM msk.my_topic`, `INSERT INTO msk.t`, `UPDATE msk.t`, `CREATE TABLE msk.t (...)`) is refused with SQLSTATE `0A000`. Streaming materialized views over MSK topics are not yet wired. +- A statement that names a relation of the schema (`SELECT * FROM msk.my_topic`, `INSERT INTO msk.t`, `UPDATE msk.t`, `CREATE TABLE msk.t (...)`) is refused with SQLSTATE `0A000`. A topic is read through a streaming materialized view; see + [Streaming materialized views over Amazon MSK](#streaming-materialized-views-over-amazon-msk). - `CREATE EXTERNAL SCHEMA` inside an explicit transaction fails with SQLSTATE `0A000`, and `DROP SCHEMA` with `25001`, because the schema registration is not part of the PostgreSQL transaction. - `DROP EXTERNAL DATABASE` and dropping several schemas in one statement are outside this implementation. @@ -1132,6 +1133,67 @@ service, never through Firehose or S3. the last view that reads the stream, so `DROP SCHEMA` without `CASCADE` works once every view is dropped. - Refreshes of the views over one stream run one at a time. +### Streaming materialized views over Amazon MSK + +A streaming materialized view reads one topic of an MSK external schema, and `REFRESH` loads what the topic +holds since the last refresh. + +```sql +CREATE MATERIALIZED VIEW my_view [AUTO REFRESH NO] AS +SELECT kafka_partition, kafka_offset, kafka_timestamp, refresh_time, + JSON_PARSE(FROM_VARBYTE(kafka_value, 'utf-8')) AS doc +FROM msk."my_topic"; + +REFRESH MATERIALIZED VIEW my_view; +DROP MATERIALIZED VIEW [IF EXISTS] my_view [CASCADE | RESTRICT]; +``` + +The topic's relation has the eight columns Redshift documents: `kafka_partition` (`bigint`), `kafka_offset` +(`bigint`), `kafka_timestamp_type` (`char(1)`), `kafka_timestamp` (`timestamp`), `kafka_key` (`varbyte`), +`kafka_value` (`varbyte`), `kafka_headers` (`super`) and `refresh_time` (`timestamp`). The view is a PostgreSQL +table that `SELECT` fills; an unqualified name is created in `public`. Records are read from the cluster's +Redpanda container through the Kafka REST Proxy sidecar that EventBridge Pipes uses, so Docker is needed. + +- **Refresh:** every partition is assigned and positioned by Floci itself, never by a group rebalance. The first + refresh reads each partition from its earliest offset. Every later one starts at the offset after the last + record that a refresh loaded, kept per partition. A refresh reads each partition up to the offset it ends at + when the refresh starts; a record at or past that offset waits for the next refresh. A batch is loaded, run through the view's `SELECT` and committed as one statement, + and the partition's offset is saved only after that commit, so it never runs ahead of the data. A crash between + the commit and the save re-reads that last batch. `TRUNCATE` or `DELETE` on the view does not move the offsets. + A partition that ends before its saved offset means the topic was deleted and created again, so that partition is + read from its beginning. A recreated topic that has already grown past the old offset cannot be told apart from + the old one, and its earlier records are skipped. +- **Stopping early:** a refresh also stops after three polls of one second that return no records, because the offsets + left may hold none (transaction markers, compaction). It logs a warning naming the partitions that fell short, and + the next refresh continues from the saved offsets. +- **Consumer groups:** each view reads through its own group, named `floci-redshift-msk-` and a hash of the view, + so it never shares a group with EventBridge Pipes or Lambda. The consumer instance is closed when the refresh + ends, and refreshes of the views over one topic run one at a time. +- **Broker failures:** `CREATE MATERIALIZED VIEW` and `REFRESH` fail with SQLSTATE `58030` when the cluster has + no running broker, the Kafka REST bridge cannot start, or the broker cannot be reached, so an unavailable + broker never looks like an empty topic. A refresh that fails leaves the offsets where they were. + A cluster that does not exist, or a `CLUSTER_ARN` that is not a cluster ARN, fails with `42704`, and a topic that does + not exist with `42P01`. +- **Columns:** `kafka_timestamp_type` is `C` when the record has a timestamp and `U` otherwise. Floci cannot tell + `LogAppendTime` from `CreateTime`, because the Kafka REST Proxy does not report it. `kafka_headers` is a JSON + object of header name to value as UTF-8 text, or null for a header without a value; a name that repeats keeps + its last value. Bytes that are not UTF-8 text, and a NUL, which `jsonb` refuses, become U+FFFD, so one binary + header cannot fail every refresh. `kafka_key` and `kafka_headers` values of a record that has none are null and `{}`. +- **IAM:** `CREATE MATERIALIZED VIEW`, before it looks at the broker, and each refresh check the schema's role + against `kafka:GetBootstrapBrokers` on the cluster, with trust + for `redshift.amazonaws.com`, when IAM enforcement is on. With `AUTHENTICATION iam` it also checks + `kafka-cluster:Connect` on the cluster, `kafka-cluster:DescribeTopic` and `kafka-cluster:ReadData` on the topic, + and `kafka-cluster:AlterGroup` and `kafka-cluster:DescribeGroup` on the view's consumer group. +- **Not supported:** `AUTO REFRESH YES` is refused with `0A000`; refresh the view yourself. `JOIN`, grouping and + aggregation in the view are refused with `0A000` as for Kinesis, as is a view that reads more than one topic. + `ALTER MATERIALIZED VIEW`, a view that reads both Kinesis and MSK, and PartiQL navigation into `SUPER` values are + not implemented. +- `CREATE MATERIALIZED VIEW` over a topic fails with `0A000` inside a transaction block, and `DROP MATERIALIZED VIEW` + and `REFRESH MATERIALIZED VIEW` of a streaming view with `25001`. +- Floci keeps a staging table named after the topic in the external schema. Do not query it. It is dropped with + the last view that reads the topic, so `DROP SCHEMA` without `CASCADE` works once every view is dropped, and + `DROP SCHEMA ... CASCADE` also drops the views that read the schema. + ### Scalar Lambda UDFs `CREATE EXTERNAL FUNCTION` registers a scalar Lambda UDF, and `DROP FUNCTION` removes it. diff --git a/src/main/java/io/floci/aws/core/common/kafka/KafkaPartitionOffsets.java b/src/main/java/io/floci/aws/core/common/kafka/KafkaPartitionOffsets.java new file mode 100644 index 0000000000..db354c0110 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/kafka/KafkaPartitionOffsets.java @@ -0,0 +1,8 @@ +package io.floci.aws.core.common.kafka; + +/** + * The offsets a partition holds right now: {@code beginningOffset} is the first offset still on the broker + * and {@code endOffset} the offset the next record will get, so the partition is empty when they are equal. + */ +public record KafkaPartitionOffsets(long beginningOffset, long endOffset) { +} diff --git a/src/main/java/io/floci/aws/core/common/kafka/KafkaRestClient.java b/src/main/java/io/floci/aws/core/common/kafka/KafkaRestClient.java index 99ca0eae69..d28944c355 100644 --- a/src/main/java/io/floci/aws/core/common/kafka/KafkaRestClient.java +++ b/src/main/java/io/floci/aws/core/common/kafka/KafkaRestClient.java @@ -109,6 +109,31 @@ public class KafkaRestClient { return partitions; } + /** + * The first and next offset of one partition ({@code GET /topics/{topic}/partitions/{id}/offsets}), so a + * caller can read exactly up to where the partition ends now. A missing topic raises + * {@link KafkaTopicNotFoundException}; Karapace answers a missing partition with 40402, which stays a + * {@link KafkaRestClientException}. + */ + public KafkaPartitionOffsets partitionOffsets(URI restBaseUri, String topic, int partition) { + JsonNode response; + try { + response = send("GET", restBaseUri.resolve("topics/" + urlEncode(topic) + "/partitions/" + partition + + "/offsets"), null); + } catch (KafkaRestClientException e) { + if (e.getStatusCode() == 404 && isTopicNotFoundError(e.getResponseBody())) { + throw new KafkaTopicNotFoundException(topic, e); + } + throw e; + } + if (!response.path("beginning_offset").isIntegralNumber() || !response.path("end_offset").isIntegralNumber()) { + throw new KafkaRestClientException("GET", "topics/" + topic + "/partitions/" + partition + "/offsets", + 200, "no beginning_offset and end_offset in " + response); + } + return new KafkaPartitionOffsets(response.path("beginning_offset").asLong(), + response.path("end_offset").asLong()); + } + private boolean isTopicNotFoundError(String responseBody) { if (responseBody == null || responseBody.isBlank()) { return false; diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViews.java b/src/main/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViews.java index fe1a49d7b6..80f712f0a4 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViews.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViews.java @@ -22,7 +22,9 @@ import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; + +import static io.floci.aws.services.redshift.spectrum.StreamingViewSupport.schemaOrDefault; +import static io.floci.aws.services.redshift.spectrum.StreamingViewSupport.table; /** * Streaming materialized views over Kinesis Data Streams. A view is a PostgreSQL table, and the stream's relation @@ -35,14 +37,10 @@ import java.util.concurrent.ConcurrentHashMap; @ApplicationScoped public class KinesisStreamingViews { - /** The schema an unqualified view name is created in. */ - static final String DEFAULT_VIEW_SCHEMA = "public"; - private static final String REDSHIFT_PRINCIPAL = ServicePrincipals.of("redshift"); private static final List READ_ACTIONS = List.of("kinesis:DescribeStreamSummary", "kinesis:GetShardIterator", "kinesis:GetRecords", "kinesis:ListShards", "kinesis:DescribeStream"); private static final int PAGE_LIMIT = 1000; - private static final int BATCH_BYTES = 4 * 1024 * 1024; private static final DateTimeFormatter TIMESTAMP = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"); private final KinesisViewRegistry registry; @@ -50,7 +48,7 @@ public class KinesisStreamingViews { private final ServiceRoleAuthorizer authorizer; private final RegionResolver regionResolver; private final Clock clock; - private final Map streamLocks = new ConcurrentHashMap<>(); + private final StreamingViewSupport support; @Inject public KinesisStreamingViews(KinesisViewRegistry registry, KinesisService kinesis, @@ -60,6 +58,8 @@ public class KinesisStreamingViews { this.authorizer = authorizer; this.regionResolver = regionResolver; this.clock = clock; + this.support = new StreamingViewSupport<>(registry, KinesisViewBinding::viewSchema, + KinesisViewBinding::viewName, KinesisViewBinding::streamSchema, KinesisViewBinding::streamName); } public Optional find(SpectrumSession session, String viewSchema, String viewName) { @@ -78,65 +78,24 @@ public class KinesisStreamingViews { } public void unbind(KinesisViewBinding view) { - registry.unbind(view.accountId(), view.clusterKey(), view.databaseName(), view.bindingName()); + support.unbind(view); } /** Unbinds a view captured earlier, unless a view of the same name over another stream has replaced it. */ public void unbindIfCurrent(KinesisViewBinding captured) { - synchronized (streamLock(captured.accountId(), captured.clusterKey(), captured.databaseName(), - captured.streamSchema(), captured.streamName())) { - registry.find(captured.accountId(), captured.clusterKey(), captured.databaseName(), - captured.bindingName()).filter(current -> readsSameStream(current, captured)) - .ifPresent(this::unbind); - } + support.unbindIfCurrent(captured); } - private static boolean readsSameStream(KinesisViewBinding first, KinesisViewBinding second) { - return first.streamSchema().equals(second.streamSchema()) && first.streamName().equals(second.streamName()); - } - - /** The SQL that drops a view's table, for the statement that drops a schema it reads from. */ - static String dropSql(KinesisViewBinding view, boolean ifExists, boolean cascade) { - return "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + table(view.viewSchema(), view.viewName()) - + (cascade ? " CASCADE" : " RESTRICT"); - } - - /** - * Drops a view's table and its binding, and the stream's staging table once no other view reads the stream. - * Without that, a plain DROP SCHEMA of the stream's schema would keep failing on the leftover table. - */ + /** Drops a view's table and its binding, and the stream's staging table once no other view reads the stream. */ public void drop(KinesisViewBinding named, boolean ifExists, boolean cascade, BackendSql backend) { - synchronized (streamLock(named.accountId(), named.clusterKey(), named.databaseName(), named.streamSchema(), - named.streamName())) { - // the binding read before the lock may be gone or replaced by a view of the same name since - Optional registered = registry.find(named.accountId(), named.clusterKey(), - named.databaseName(), named.bindingName()); - if (registered.isEmpty() || !readsSameStream(registered.get(), named)) { - if (ifExists) { - return; - } - throw new SpectrumSqlException("42P01", "materialized view \"" + named.viewSchema() + "." - + named.viewName() + "\" does not exist"); - } - KinesisViewBinding view = registered.get(); - boolean lastReader = registry.list(view.accountId(), view.clusterKey(), view.databaseName()).stream() - .noneMatch(other -> !other.bindingName().equals(view.bindingName()) - && other.streamSchema().equals(view.streamSchema()) - && other.streamName().equals(view.streamName())); - String sql = dropSql(view, ifExists, cascade); - if (lastReader) { - sql += "; DROP TABLE IF EXISTS " + table(view.streamSchema(), view.streamName()); - } - backend.execute(sql); - unbind(view); - } + support.drop(named, ifExists, cascade, backend); } public void create(ExternalStatement.CreateStreamingView statement, String streamName, KinesisSchemaBinding schema, SpectrumSession session, String clusterRegion, BackendSql backend) { String viewSchema = schemaOrDefault(statement.viewSchema()); - synchronized (streamLock(session.accountId(), session.clusterKey(), session.databaseName(), + synchronized (support.lock(session.accountId(), session.clusterKey(), session.databaseName(), schema.schemaName(), streamName)) { if (find(session, viewSchema, statement.viewName()).isPresent()) { throw new SpectrumSqlException("42P07", "relation \"" + viewSchema + "." + statement.viewName() @@ -158,8 +117,7 @@ public class KinesisStreamingViews { public long refresh(KinesisViewBinding view, KinesisSchemaBinding schema, String clusterRegion, BackendSql backend) { // refreshes of the views over one stream share its staging table, so they run one at a time - synchronized (streamLock(view.accountId(), view.clusterKey(), view.databaseName(), view.streamSchema(), - view.streamName())) { + synchronized (support.lock(view)) { // the binding read before the lock may be stale: a refresh ahead of this one moved the checkpoints KinesisViewBinding latest = registry.find(view.accountId(), view.clusterKey(), view.databaseName(), view.bindingName()).orElseThrow(() -> new SpectrumSqlException("42P01", @@ -168,12 +126,6 @@ public class KinesisStreamingViews { } } - private Object streamLock(String accountId, String clusterKey, String database, String streamSchema, - String streamName) { - return streamLocks.computeIfAbsent(String.join("\u001f", accountId, clusterKey, database, streamSchema, - streamName), key -> new Object()); - } - private long refreshLocked(KinesisViewBinding view, KinesisSchemaBinding schema, String clusterRegion, BackendSql backend) { String region = region(schema, clusterRegion); @@ -198,7 +150,8 @@ public class KinesisStreamingViews { if (records == null || records.isEmpty()) { break; } - for (List batch : batches(records)) { + for (List batch : StreamingViewSupport.batches(records, + record -> record.getData() == null ? 0 : record.getData().length)) { backend.execute(loadSql(view, shardId, batch, refreshTime)); current = current.withCheckpoint(shardId, batch.getLast().getSequenceNumber()); registry.replace(current); @@ -231,25 +184,6 @@ public class KinesisStreamingViews { return clusterRegion != null ? clusterRegion : regionResolver.getDefaultRegion(); } - /** Splits a page so no statement carries more than about {@value #BATCH_BYTES} bytes of record data. */ - private static List> batches(List records) { - List> batches = new ArrayList<>(); - List batch = new ArrayList<>(); - long bytes = 0; - for (KinesisRecord record : records) { - long size = record.getData() == null ? 0 : record.getData().length; - if (!batch.isEmpty() && bytes + size > BATCH_BYTES) { - batches.add(batch); - batch = new ArrayList<>(); - bytes = 0; - } - batch.add(record); - bytes += size; - } - batches.add(batch); - return batches; - } - private static String loadSql(KinesisViewBinding view, String shardId, List batch, Instant refreshTime) { String staging = table(view.streamSchema(), view.streamName()); @@ -274,12 +208,4 @@ public class KinesisStreamingViews { return instant == null ? "NULL::timestamp" : "TIMESTAMP '" + TIMESTAMP.format(instant.atOffset(ZoneOffset.UTC)) + "'"; } - - private static String schemaOrDefault(String schema) { - return schema == null ? DEFAULT_VIEW_SCHEMA : schema; - } - - private static String table(String schema, String name) { - return ExternalTableMaterializer.quote(schema) + "." + ExternalTableMaterializer.quote(name); - } } diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/MskStreamingViews.java b/src/main/java/io/floci/aws/services/redshift/spectrum/MskStreamingViews.java new file mode 100644 index 0000000000..1a820d38a4 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/MskStreamingViews.java @@ -0,0 +1,475 @@ +package io.floci.aws.services.redshift.spectrum; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.Digests; +import io.floci.aws.core.common.PostgresWire; +import io.floci.aws.core.common.ServicePrincipals; +import io.floci.aws.core.common.kafka.KafkaConsumerHandle; +import io.floci.aws.core.common.kafka.KafkaHeaderDto; +import io.floci.aws.core.common.kafka.KafkaOffsetDto; +import io.floci.aws.core.common.kafka.KafkaPartitionOffsets; +import io.floci.aws.core.common.kafka.KafkaRecordDto; +import io.floci.aws.core.common.kafka.KafkaRestClient; +import io.floci.aws.core.common.kafka.KafkaRestClientException; +import io.floci.aws.core.common.kafka.KafkaTopicNotFoundException; +import io.floci.aws.core.common.kafka.KafkaTopicPartition; +import io.floci.aws.core.common.kafka.KarapaceManager; +import io.floci.aws.services.iam.ServiceRoleAuthorizer; +import io.floci.aws.services.iam.ServiceRoleAuthorizer.Permission; +import io.floci.aws.services.msk.MskService; +import io.floci.aws.services.msk.model.ClusterState; +import io.floci.aws.services.msk.model.MskCluster; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.UncheckedIOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; + +import static io.floci.aws.services.redshift.spectrum.StreamingViewSupport.schemaOrDefault; +import static io.floci.aws.services.redshift.spectrum.StreamingViewSupport.table; + +/** + * Streaming materialized views over Amazon MSK topics. A view is a PostgreSQL table, and the topic's relation of + * its external schema is a staging table of Redshift's eight Kafka metadata columns. A refresh reads each + * partition from its checkpoint up to the offset the partition ends at when the refresh starts, loads a batch of + * records into the staging table, runs the view's query over it into the view and empties the staging table again, + * as one statement string, which PostgreSQL runs as a single implicit transaction. A checkpoint is saved only once + * that statement has committed, so it never runs ahead of the data; a crash between the commit and the save + * re-reads the last batch. + * + *

Floci positions every partition itself, by manual assignment and an explicit seek, so no group rebalance and + * no offset the broker keeps for a group decides what is read. Each view reads through its own consumer group, + * apart from those of Pipes and Lambda, and the consumer instance is closed when the refresh ends. + */ +@ApplicationScoped +public class MskStreamingViews { + + private static final Logger LOG = Logger.getLogger(MskStreamingViews.class); + + static final String GROUP_PREFIX = "floci-redshift-msk-"; + static final Duration POLL_TIMEOUT = Duration.ofSeconds(1); + /** + * A partition's last offsets may hold no record (transaction markers, compaction), so a poll that keeps + * returning nothing ends the refresh even when a partition has not reached the offset it ended at. + */ + static final int MAX_IDLE_POLLS = 3; + + private static final String REDSHIFT_PRINCIPAL = ServicePrincipals.of("redshift"); + private static final String BROKER_UNAVAILABLE = "58030"; + private static final String EARLIEST = "earliest"; + private static final String TIMESTAMP_CREATE_TIME = "C"; + private static final String TIMESTAMP_UNKNOWN = "U"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final DateTimeFormatter TIMESTAMP = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"); + + private final MskViewRegistry registry; + private final MskService msk; + private final KarapaceManager karapace; + private final KafkaRestClient restClient; + private final ServiceRoleAuthorizer authorizer; + private final Clock clock; + private final StreamingViewSupport support; + private final Map schemaLocks = new ConcurrentHashMap<>(); + + @Inject + public MskStreamingViews(MskViewRegistry registry, MskService msk, KarapaceManager karapace, + KafkaRestClient restClient, ServiceRoleAuthorizer authorizer, Clock clock) { + this.registry = registry; + this.msk = msk; + this.karapace = karapace; + this.restClient = restClient; + this.authorizer = authorizer; + this.clock = clock; + this.support = new StreamingViewSupport<>(registry, MskViewBinding::viewSchema, MskViewBinding::viewName, + MskViewBinding::topicSchema, MskViewBinding::topicName); + } + + public Optional find(SpectrumSession session, String viewSchema, String viewName) { + return registry.find(session.accountId(), session.clusterKey(), session.databaseName(), + MskViewBinding.nameOf(schemaOrDefault(viewSchema), viewName)); + } + + /** The views that read a topic of {@code topicSchema}. */ + public List overSchema(SpectrumSession session, String topicSchema) { + return registry.list(session.accountId(), session.clusterKey(), session.databaseName()).stream() + .filter(view -> view.topicSchema().equals(topicSchema)).toList(); + } + + public void forgetCluster(String accountId, String clusterKey) { + registry.removeCluster(accountId, clusterKey); + } + + public void unbind(MskViewBinding view) { + support.unbind(view); + } + + /** Unbinds a view captured earlier, unless a view of the same name over another topic has replaced it. */ + public void unbindIfCurrent(MskViewBinding captured) { + support.unbindIfCurrent(captured); + } + + /** Drops a view's table and its binding, and the topic's staging table once no other view reads the topic. */ + public void drop(MskViewBinding named, boolean ifExists, boolean cascade, BackendSql backend) { + support.drop(named, ifExists, cascade, backend); + } + + /** + * Creates the view's table and the topic's staging table. Redshift reads the topic's partitions when the + * view is created, so a cluster without a running broker, an unreachable broker and a missing topic fail here. + */ + public void create(ExternalStatement.CreateStreamingView statement, String topicName, MskSchemaBinding schema, + SpectrumSession session, BackendSql backend) { + // the schema lock keeps a DROP SCHEMA of the topic's schema from running between the view's creation and its + // binding, which would leave a binding over a staging table that is gone + synchronized (schemaLock(session.accountId(), session.clusterKey(), session.databaseName(), + schema.schemaName())) { + createLocked(statement, topicName, schema, session, backend); + } + } + + /** + * Runs {@code action} while no view is created in the schema: a DROP SCHEMA reads the schema's views, drops + * them and unbinds them as one step. + */ + public void exclusivelyOnSchema(SpectrumSession session, String schemaName, Runnable action) { + synchronized (schemaLock(session.accountId(), session.clusterKey(), session.databaseName(), schemaName)) { + action.run(); + } + } + + private void createLocked(ExternalStatement.CreateStreamingView statement, String topicName, + MskSchemaBinding schema, SpectrumSession session, BackendSql backend) { + String viewSchema = schemaOrDefault(statement.viewSchema()); + synchronized (support.lock(session.accountId(), session.clusterKey(), session.databaseName(), + schema.schemaName(), topicName)) { + if (find(session, viewSchema, statement.viewName()).isPresent()) { + throw new SpectrumSqlException("42P07", "relation \"" + viewSchema + "." + statement.viewName() + + "\" already exists"); + } + MskViewBinding candidate = new MskViewBinding(session.accountId(), session.clusterKey(), + session.databaseName(), viewSchema, statement.viewName(), schema.schemaName(), topicName, + statement.select(), Map.of()); + // before any broker lookup, so a role that may not read the topic cannot tell whether it exists + requireAuthorized(candidate, schema, groupOf(candidate)); + URI restBaseUri = restBaseUri(session.accountId(), schema); + try { + restClient.listPartitions(restBaseUri, topicName); + } catch (KafkaTopicNotFoundException | KafkaRestClientException | UncheckedIOException e) { + throw readFailure(topicName, schema, e); + } + backend.execute("CREATE TABLE IF NOT EXISTS " + table(schema.schemaName(), topicName) + + " (kafka_partition bigint, kafka_offset bigint, kafka_timestamp_type char(1), " + + "kafka_timestamp timestamp, kafka_key pg_catalog.varbyte, kafka_value pg_catalog.varbyte, " + + "kafka_headers pg_catalog.super, refresh_time timestamp); " + + "CREATE TABLE " + table(viewSchema, statement.viewName()) + " AS " + statement.select() + + " WITH NO DATA"); + registry.bind(new MskViewBinding(session.accountId(), session.clusterKey(), session.databaseName(), + viewSchema, statement.viewName(), schema.schemaName(), topicName, statement.select(), Map.of())); + } + } + + /** Loads what the topic holds past each partition's checkpoint into the view; returns the records loaded. */ + public long refresh(MskViewBinding view, MskSchemaBinding schema, BackendSql backend) { + // refreshes of the views over one topic share its staging table, so they run one at a time + synchronized (support.lock(view)) { + // the binding read before the lock may be stale: a refresh ahead of this one moved the checkpoints + MskViewBinding latest = registry.find(view.accountId(), view.clusterKey(), view.databaseName(), + view.bindingName()).orElseThrow(() -> new SpectrumSqlException("42P01", + "relation \"" + view.viewSchema() + "." + view.viewName() + "\" does not exist")); + if (!support.readsSameSource(latest, view)) { + // dropped and created again over another topic while this refresh waited: that view has its own + // topic's lock, and this call holds another one + throw new SpectrumSqlException("42P01", "materialized view \"" + view.viewSchema() + "." + + view.viewName() + "\" was replaced by a view over another topic; retry the statement"); + } + return refreshLocked(latest, schema, backend); + } + } + + /** The consumer group a view reads through: its own, and never one of Pipes or Lambda. */ + static String groupOf(MskViewBinding view) { + return GROUP_PREFIX + Digests.sha256Hex(String.join("\u001f", view.accountId(), view.clusterKey(), + view.databaseName(), view.viewSchema(), view.viewName())).substring(0, 16); + } + + private Object schemaLock(String accountId, String clusterKey, String database, String schemaName) { + return schemaLocks.computeIfAbsent(String.join("\u001f", accountId, clusterKey, database, schemaName), + key -> new Object()); + } + + private long refreshLocked(MskViewBinding view, MskSchemaBinding schema, BackendSql backend) { + String group = groupOf(view); + requireAuthorized(view, schema, group); + URI restBaseUri = restBaseUri(view.accountId(), schema); + String topic = view.topicName(); + Instant refreshTime = clock.instant(); + try { + Map ends = new TreeMap<>(); + Map checkpoints = new TreeMap<>(); + List fromBeginning = new ArrayList<>(); + List resumeAt = new ArrayList<>(); + for (int partition : restClient.listPartitions(restBaseUri, topic)) { + KafkaPartitionOffsets offsets = restClient.partitionOffsets(restBaseUri, topic, partition); + Long lastLoaded = view.checkpoints().get(Integer.toString(partition)); + if (lastLoaded != null && lastLoaded + 1 > offsets.endOffset()) { + // the partition ends before its checkpoint, so the topic was deleted and created again: its + // offsets started over, and waiting for them to pass the old checkpoint would skip its records + LOG.warnv("Partition {0} of topic {1} ends at offset {2}, before the checkpoint {3} of view {4}.{5}; " + + "reading it from the beginning", partition, topic, offsets.endOffset(), lastLoaded, + view.viewSchema(), view.viewName()); + lastLoaded = null; + } + long next = lastLoaded == null ? offsets.beginningOffset() + : Math.max(lastLoaded + 1, offsets.beginningOffset()); + if (next >= offsets.endOffset()) { + continue; + } + ends.put(partition, offsets.endOffset()); + if (lastLoaded == null) { + fromBeginning.add(new KafkaTopicPartition(topic, partition)); + } else { + resumeAt.add(new KafkaOffsetDto(topic, partition, lastLoaded + 1)); + checkpoints.put(partition, lastLoaded); + } + } + if (ends.isEmpty()) { + return 0; + } + KafkaConsumerHandle consumer = restClient.createConsumer(restBaseUri, group, EARLIEST); + try { + List assigned = new ArrayList<>(); + ends.keySet().forEach(partition -> assigned.add(new KafkaTopicPartition(topic, partition))); + restClient.assign(consumer, assigned); + restClient.seekToBeginning(consumer, fromBeginning); + restClient.seek(consumer, resumeAt); + return load(view, backend, consumer, ends, checkpoints, refreshTime); + } finally { + closeQuietly(consumer); + } + } catch (KafkaTopicNotFoundException | KafkaRestClientException | UncheckedIOException e) { + throw readFailure(topic, schema, e); + } + } + + /** Polls until every partition has reached the offset it ended at, or the topic stops returning records. */ + private long load(MskViewBinding view, BackendSql backend, KafkaConsumerHandle consumer, Map ends, + Map checkpoints, Instant refreshTime) { + Map pending = new TreeMap<>(ends); + MskViewBinding current = view; + long loaded = 0; + int idlePolls = 0; + while (!pending.isEmpty() && idlePolls < MAX_IDLE_POLLS) { + List records = unseen(restClient.poll(consumer, POLL_TIMEOUT), ends, checkpoints); + if (records.isEmpty()) { + idlePolls++; + continue; + } + idlePolls = 0; + for (List batch : StreamingViewSupport.batches(records, + record -> length(record.key()) + length(record.value()))) { + backend.execute(loadSql(view, batch, refreshTime)); + Map lastLoaded = new TreeMap<>(); + for (KafkaRecordDto record : batch) { + lastLoaded.merge(record.partition(), record.offset(), Math::max); + } + checkpoints.putAll(lastLoaded); + current = current.withCheckpoints(lastLoaded); + registry.replace(current); + loaded += batch.size(); + } + for (KafkaRecordDto record : records) { + Long end = pending.get(record.partition()); + if (end != null && record.offset() >= end - 1) { + pending.remove(record.partition()); + } + } + } + if (!pending.isEmpty()) { + // the offsets left may hold no record (transaction markers, compaction), or the proxy may be slow; either + // way the next refresh continues from the checkpoints + LOG.warnv("Refresh of {0}.{1} stopped after {2} polls with no records, before partitions {3} reached the " + + "offsets they ended at ({4}); the next refresh continues from the checkpoints", + view.viewSchema(), view.viewName(), MAX_IDLE_POLLS, pending.keySet(), pending); + } + return loaded; + } + + /** Drops what a poll returns for a partition the refresh did not assign, or at an offset already loaded. */ + private static List unseen(List polled, Map ends, + Map checkpoints) { + List records = new ArrayList<>(); + for (KafkaRecordDto record : polled) { + Long loaded = checkpoints.get(record.partition()); + Long end = ends.get(record.partition()); + // a record at or past the end the refresh started with belongs to the next one + if (end != null && record.offset() < end && (loaded == null || record.offset() > loaded)) { + records.add(record); + } + } + return records; + } + + private URI restBaseUri(String accountId, MskSchemaBinding schema) { + MskCluster cluster = msk.getClusterForAccount(accountId, schema.clusterArn()) + .orElseThrow(() -> clusterNotFound(schema, null)); + String bootstrapBrokers = cluster.getBootstrapBrokers(); + if (cluster.getState() != ClusterState.ACTIVE || bootstrapBrokers == null || bootstrapBrokers.isBlank()) { + throw new SpectrumSqlException(BROKER_UNAVAILABLE, "MSK cluster " + schema.clusterArn() + + " has no running broker (state " + cluster.getState() + ")"); + } + try { + return karapace.ensureStarted(bootstrapBrokers); + } catch (RuntimeException e) { + throw new SpectrumSqlException(BROKER_UNAVAILABLE, "The Kafka REST bridge for MSK cluster " + + schema.clusterArn() + " is unavailable: " + e.getMessage()); + } + } + + /** What a failed read of the topic is reported as, by CREATE and REFRESH alike. */ + private static SpectrumSqlException readFailure(String topic, MskSchemaBinding schema, RuntimeException cause) { + if (cause instanceof KafkaTopicNotFoundException) { + return new SpectrumSqlException("42P01", "topic \"" + topic + "\" does not exist in MSK cluster " + + schema.clusterArn()); + } + return new SpectrumSqlException(BROKER_UNAVAILABLE, "Cannot read topic \"" + topic + "\" from MSK cluster " + + schema.clusterArn() + ": " + cause.getMessage()); + } + + private void closeQuietly(KafkaConsumerHandle consumer) { + try { + restClient.close(consumer); + } catch (RuntimeException e) { + // the refresh outcome is already decided, so this must not replace it; the instance stays on the proxy + // until its idle timeout, which is worth a trace + LOG.warnv(e, "Could not close the Kafka REST consumer {0}: {1}", consumer.baseUri(), e.getMessage()); + } + } + + /** + * Refreshing reads the cluster's bootstrap brokers and, with IAM authentication, connects and reads the topic + * as a member of the view's group, as the role Redshift assumes. + */ + private void requireAuthorized(MskViewBinding view, MskSchemaBinding schema, String group) { + List permissions = new ArrayList<>(); + permissions.add(new Permission("kafka:GetBootstrapBrokers", schema.clusterArn())); + if ("IAM".equals(schema.authentication())) { + AwsArnUtils.Arn cluster = clusterArn(schema); + // cluster//, whose topics and groups are topic/// and group/... + String clusterPath = cluster.resource().substring(cluster.resource().indexOf('/') + 1); + String topicArn = AwsArnUtils.Arn.of("kafka", cluster.region(), cluster.accountId(), + "topic/" + clusterPath + "/" + view.topicName()).toString(); + String groupArn = AwsArnUtils.Arn.of("kafka", cluster.region(), cluster.accountId(), + "group/" + clusterPath + "/" + group).toString(); + permissions.add(new Permission("kafka-cluster:Connect", schema.clusterArn())); + permissions.add(new Permission("kafka-cluster:DescribeTopic", topicArn)); + permissions.add(new Permission("kafka-cluster:ReadData", topicArn)); + permissions.add(new Permission("kafka-cluster:AlterGroup", groupArn)); + permissions.add(new Permission("kafka-cluster:DescribeGroup", groupArn)); + } + Optional refusal = authorizer.refusal(schema.iamRoleArn(), view.accountId(), REDSHIFT_PRINCIPAL, + null, permissions); + if (refusal.isPresent()) { + throw new SpectrumSqlException("42501", refusal.get()); + } + } + + /** + * The schema's cluster ARN, which CREATE EXTERNAL SCHEMA keeps as written. One that is not the ARN of a + * cluster names no cluster, so it is the same error as a cluster that is gone. + */ + private static AwsArnUtils.Arn clusterArn(MskSchemaBinding schema) { + AwsArnUtils.Arn arn; + try { + arn = AwsArnUtils.parse(schema.clusterArn()); + } catch (IllegalArgumentException e) { + throw clusterNotFound(schema, e); + } + String resource = arn.resource(); + boolean namedCluster = resource.startsWith("cluster/") && resource.indexOf('/') != resource.lastIndexOf('/'); + if (!"kafka".equals(arn.service()) || arn.region().isBlank() || !namedCluster) { + throw clusterNotFound(schema, null); + } + return arn; + } + + private static SpectrumSqlException clusterNotFound(MskSchemaBinding schema, RuntimeException cause) { + SpectrumSqlException error = new SpectrumSqlException("42704", + "MSK cluster " + schema.clusterArn() + " does not exist"); + if (cause != null) { + error.addSuppressed(cause); + } + return error; + } + + private static long length(byte[] bytes) { + return bytes == null ? 0 : bytes.length; + } + + private static String loadSql(MskViewBinding view, List batch, Instant refreshTime) { + String staging = table(view.topicSchema(), view.topicName()); + StringBuilder rows = new StringBuilder(); + for (KafkaRecordDto record : batch) { + if (!rows.isEmpty()) { + rows.append(", "); + } + boolean timestamped = record.timestamp() >= 0; + rows.append('(').append(record.partition()).append(", ").append(record.offset()).append(", ") + .append(PostgresWire.quoteLiteral(timestamped ? TIMESTAMP_CREATE_TIME : TIMESTAMP_UNKNOWN)) + .append(", ").append(timestamped ? timestamp(Instant.ofEpochMilli(record.timestamp())) + : "NULL::timestamp") + .append(", ").append(varbyte(record.key())).append(", ").append(varbyte(record.value())) + .append(", ").append(PostgresWire.quoteLiteral(headersJson(record.headers()))) + .append("::jsonb::pg_catalog.super, ").append(timestamp(refreshTime)).append(')'); + } + return "INSERT INTO " + staging + " VALUES " + rows + "; INSERT INTO " + + table(view.viewSchema(), view.viewName()) + " " + view.select() + "; TRUNCATE " + staging; + } + + /** + * The headers as a JSON object of header name to value, the value as UTF-8 text or null for a header without + * one. A name that repeats keeps its last value: a JSON object holds a name once. Bytes that are not UTF-8 text, + * and a NUL, which jsonb refuses, become U+FFFD, so one binary header cannot fail every refresh of the view. + */ + static String headersJson(List headers) { + ObjectNode object = JSON.createObjectNode(); + Map values = new LinkedHashMap<>(); + if (headers != null) { + for (KafkaHeaderDto header : headers) { + values.put(jsonbText(header.key()), header.value() == null ? null + : jsonbText(new String(header.value(), StandardCharsets.UTF_8))); + } + } + values.forEach(object::put); + return object.toString(); + } + + private static String jsonbText(String text) { + return text == null ? null : text.replace('\u0000', '�'); + } + + private static String varbyte(byte[] bytes) { + return bytes == null ? "NULL::pg_catalog.varbyte" + : "decode('" + HexFormat.of().formatHex(bytes) + "', 'hex')::pg_catalog.varbyte"; + } + + private static String timestamp(Instant instant) { + return "TIMESTAMP '" + TIMESTAMP.format(instant.atOffset(ZoneOffset.UTC)) + "'"; + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/MskViewBinding.java b/src/main/java/io/floci/aws/services/redshift/spectrum/MskViewBinding.java new file mode 100644 index 0000000000..33d7fa8655 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/MskViewBinding.java @@ -0,0 +1,54 @@ +package io.floci.aws.services.redshift.spectrum; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * A streaming materialized view over a topic of an MSK external schema. {@code select} is the view's query as + * written, which reads the topic's relation of the external schema; {@code checkpoints} holds, per partition, + * the offset of the last record a committed refresh loaded, so the next refresh starts at the offset after it. + */ +@RegisterForReflection +public record MskViewBinding(String accountId, String clusterKey, String databaseName, String viewSchema, + String viewName, String topicSchema, String topicName, String select, + Map checkpoints) implements SchemaBinding { + /** Separates the schema from the view in the registry key; a quoted identifier cannot be told apart otherwise. */ + private static final char KEY_SEPARATOR = '\u001f'; + + public MskViewBinding { + SchemaBinding.require(accountId, "accountId"); + SchemaBinding.require(clusterKey, "clusterKey"); + SchemaBinding.require(databaseName, "databaseName"); + SchemaBinding.require(viewSchema, "viewSchema"); + SchemaBinding.require(viewName, "viewName"); + SchemaBinding.require(topicSchema, "topicSchema"); + SchemaBinding.require(topicName, "topicName"); + SchemaBinding.require(select, "select"); + checkpoints = checkpoints == null ? Map.of() : Map.copyOf(checkpoints); + } + + @Override + public String schemaName() { + return viewSchema; + } + + @Override + public String bindingName() { + return nameOf(viewSchema, viewName); + } + + /** The registry name of the view {@code viewName} of {@code viewSchema}. */ + static String nameOf(String viewSchema, String viewName) { + return viewSchema + KEY_SEPARATOR + viewName; + } + + /** This view with each partition moved to the given last loaded offset. */ + public MskViewBinding withCheckpoints(Map lastLoaded) { + Map updated = new LinkedHashMap<>(checkpoints); + lastLoaded.forEach((partition, offset) -> updated.put(Integer.toString(partition), offset)); + return new MskViewBinding(accountId, clusterKey, databaseName, viewSchema, viewName, topicSchema, + topicName, select, updated); + } +} diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/MskViewRegistry.java b/src/main/java/io/floci/aws/services/redshift/spectrum/MskViewRegistry.java new file mode 100644 index 0000000000..04d23452e5 --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/MskViewRegistry.java @@ -0,0 +1,22 @@ +package io.floci.aws.services.redshift.spectrum; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +/** The streaming materialized views over MSK topics, keyed by cluster, database, schema and view name. */ +@ApplicationScoped +public class MskViewRegistry extends SchemaBindingRegistry { + + @Inject + public MskViewRegistry(StorageFactory storageFactory) { + super(storageFactory.create("redshift", "redshift-msk-views.json", + new TypeReference<>() { })); + } + + MskViewRegistry(AccountAwareStorageBackend bindings) { + super(bindings); + } +} 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 b6b82cbda9..ce75be610f 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 @@ -48,6 +48,7 @@ public class SpectrumQueryPreparation { private final MskSchemaRegistry mskSchemas; private final ExternalFunctionRegistry functions; private final KinesisStreamingViews views; + private final MskStreamingViews mskViews; private final ExternalTableMaterializer materializer; private final ExternalStatementParser parser; private final GlueService glue; @@ -76,9 +77,10 @@ public class SpectrumQueryPreparation { ExternalTableMaterializer materializer, ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks, KinesisStreamingViews views, - Instance redshift) { + MskStreamingViews mskViews, Instance redshift) { this(registry, kinesisSchemas, mskSchemas, functions, materializer, parser, glue, metadata, catalogLocks, - views, (accountId, clusterIdentifier) -> redshift.get().clusterRegion(accountId, clusterIdentifier).orElse(null)); + views, mskViews, + (accountId, clusterIdentifier) -> redshift.get().clusterRegion(accountId, clusterIdentifier).orElse(null)); } SpectrumQueryPreparation(ExternalCatalogRegistry registry, ExternalTableMaterializer materializer, @@ -118,8 +120,25 @@ public class SpectrumQueryPreparation { ExternalTableMaterializer materializer, ExternalStatementParser parser, GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks, KinesisStreamingViews views, BiFunction clusterRegion) { + this(registry, kinesisSchemas, mskSchemas, functions, materializer, parser, glue, metadata, catalogLocks, + views, inMemoryMskViews(), clusterRegion); + } + + private static MskStreamingViews inMemoryMskViews() { + return new MskStreamingViews(new MskViewRegistry( + AccountAwareStorageBackend.inMemory("000000000000")), + null, null, null, null, Clock.systemUTC()); + } + + SpectrumQueryPreparation(ExternalCatalogRegistry registry, KinesisSchemaRegistry kinesisSchemas, + MskSchemaRegistry mskSchemas, ExternalFunctionRegistry functions, + ExternalTableMaterializer materializer, ExternalStatementParser parser, + GlueService glue, ExternalMetadataWriter metadata, ExternalCatalogLocks catalogLocks, + KinesisStreamingViews views, MskStreamingViews mskViews, + BiFunction clusterRegion) { this.functions = functions; this.views = views; + this.mskViews = mskViews; this.clusterRegion = clusterRegion; this.registry = registry; this.kinesisSchemas = kinesisSchemas; @@ -208,9 +227,11 @@ public class SpectrumQueryPreparation { case ExternalStatement.CreateStreamingView view -> streamSource(view.select(), session).isPresent() || !ExternalReferenceScanner.scan(view.select(), bindingsOf(mskSchemas, session).keySet()).isEmpty(); case ExternalStatement.RefreshView view -> - views.find(session, view.viewSchema(), view.viewName()).isPresent(); + views.find(session, view.viewSchema(), view.viewName()).isPresent() + || mskViews.find(session, view.viewSchema(), view.viewName()).isPresent(); case ExternalStatement.DropView view -> - views.find(session, view.viewSchema(), view.viewName()).isPresent(); + views.find(session, view.viewSchema(), view.viewName()).isPresent() + || mskViews.find(session, view.viewSchema(), view.viewName()).isPresent(); case null -> false; }; } @@ -251,25 +272,39 @@ public class SpectrumQueryPreparation { if (statement.orElse(null) instanceof ExternalStatement.DropSchema schema && kinesis.containsKey(schema.schemaName())) { rejectTransaction(session); + List dependents = views.overSchema(session, schema.schemaName()); dropStreamingSchema(schema, kinesis.get(schema.schemaName()), kinesisSchemas, - views.overSchema(session, schema.schemaName()), session, backend); + dependents.stream().map(dependent -> StreamingViewSupport.dropSql(dependent.viewSchema(), dependent.viewName(), true, true)).toList(), + () -> dependents.forEach(views::unbindIfCurrent), session, backend); return true; } if (statement.orElse(null) instanceof ExternalStatement.DropSchema schema && msk.containsKey(schema.schemaName())) { rejectTransaction(session); - dropStreamingSchema(schema, msk.get(schema.schemaName()), mskSchemas, List.of(), session, backend); + // no view may be created between reading the schema's views and dropping it, or its binding would outlive it + mskViews.exclusivelyOnSchema(session, schema.schemaName(), () -> { + List dependents = mskViews.overSchema(session, schema.schemaName()); + dropStreamingSchema(schema, msk.get(schema.schemaName()), mskSchemas, + dependents.stream().map(dependent -> StreamingViewSupport.dropSql(dependent.viewSchema(), dependent.viewName(), true, true)).toList(), + () -> dependents.forEach(mskViews::unbindIfCurrent), session, backend); + }); return true; } if (statement.orElse(null) instanceof ExternalStatement.CreateStreamingView view) { - if (!ExternalReferenceScanner.scan(view.select(), msk.keySet()).isEmpty()) { + boolean overKinesis = !ExternalReferenceScanner.scan(view.select(), kinesis.keySet()).isEmpty(); + boolean overMsk = !ExternalReferenceScanner.scan(view.select(), msk.keySet()).isEmpty(); + if (overKinesis && overMsk) { throw new SpectrumSqlException("0A000", - "Streaming materialized views over MSK external schemas are not supported"); + "A streaming materialized view reads exactly one stream or topic"); } - if (!ExternalReferenceScanner.scan(view.select(), kinesis.keySet()).isEmpty()) { + if (overKinesis) { createStreamingView(view, kinesis, session, backend); return true; } + if (overMsk) { + createMskStreamingView(view, msk, session, backend); + return true; + } } if (statement.orElse(null) instanceof ExternalStatement.RefreshView refresh) { Optional view = views.find(session, refresh.viewSchema(), refresh.viewName()); @@ -277,6 +312,11 @@ public class SpectrumQueryPreparation { refreshStreamingView(view.get(), kinesis, session, backend); return true; } + Optional mskView = mskViews.find(session, refresh.viewSchema(), refresh.viewName()); + if (mskView.isPresent()) { + refreshMskStreamingView(mskView.get(), msk, session, backend); + return true; + } } if (statement.orElse(null) instanceof ExternalStatement.DropView drop) { Optional view = views.find(session, drop.viewSchema(), drop.viewName()); @@ -285,6 +325,12 @@ public class SpectrumQueryPreparation { views.drop(view.get(), drop.ifExists(), drop.cascade(), backend); return true; } + Optional mskView = mskViews.find(session, drop.viewSchema(), drop.viewName()); + if (mskView.isPresent()) { + rejectTransaction(session); + mskViews.drop(mskView.get(), drop.ifExists(), drop.cascade(), backend); + return true; + } } Map bindings = bindingsOf(registry, session); if (statement.orElse(null) instanceof ExternalStatement.CreateTable && session.inTransaction()) { @@ -723,14 +769,15 @@ public class SpectrumQueryPreparation { private void dropStreamingSchema(ExternalStatement.DropSchema statement, B binding, SchemaBindingRegistry schemaRegistry, - List dependents, + List dropDependentSql, + Runnable unbindDependents, SpectrumSession session, BackendSql backend) { requireSchemaOwner(backend, binding.schemaName()); // CASCADE takes the streaming views that read the schema with it; RESTRICT stops on their staging tables. StringBuilder dropViews = new StringBuilder(); if (statement.cascade()) { - for (KinesisViewBinding dependent : dependents) { - dropViews.append(KinesisStreamingViews.dropSql(dependent, true, true)).append("; "); + for (String dropDependent : dropDependentSql) { + dropViews.append(dropDependent).append("; "); } } // One implicit PostgreSQL transaction keeps the local schema and its SVV metadata in sync. @@ -738,7 +785,7 @@ public class SpectrumQueryPreparation { + ExternalTableMaterializer.quote(binding.schemaName()) + (statement.cascade() ? " CASCADE" : " RESTRICT") + "; " + metadata.purgeSql(binding.schemaName())); if (statement.cascade()) { - dependents.forEach(views::unbindIfCurrent); + unbindDependents.run(); } // a concurrent drop and re-create of the name may have bound a newer schema meanwhile if (binding.equals(schemaRegistry.find(session.accountId(), session.clusterKey(), session.databaseName(), @@ -755,6 +802,30 @@ public class SpectrumQueryPreparation { private void createStreamingView(ExternalStatement.CreateStreamingView view, Map kinesis, SpectrumSession session, BackendSql backend) { + requireStreamingViewShape(view, session); + Set streams = + ExternalReferenceScanner.scan(view.select(), kinesis.keySet()); + if (streams.size() != 1) { + throw new SpectrumSqlException("0A000", "A streaming materialized view reads exactly one stream"); + } + ExternalReferenceScanner.Reference stream = streams.iterator().next(); + views.create(view, stream.table(), kinesis.get(stream.schema()), session, catalogRegion(session), backend); + } + + private void createMskStreamingView(ExternalStatement.CreateStreamingView view, + Map msk, + SpectrumSession session, BackendSql backend) { + requireStreamingViewShape(view, session); + Set topics = ExternalReferenceScanner.scan(view.select(), msk.keySet()); + if (topics.size() != 1) { + throw new SpectrumSqlException("0A000", "A streaming materialized view reads exactly one topic"); + } + ExternalReferenceScanner.Reference topic = topics.iterator().next(); + mskViews.create(view, topic.table(), msk.get(topic.schema()), session, backend); + } + + /** What a streaming view over any source must satisfy, before the source is looked at. */ + private static void requireStreamingViewShape(ExternalStatement.CreateStreamingView view, SpectrumSession session) { if (session.inTransaction()) { throw new SpectrumSqlException("0A000", "CREATE MATERIALIZED VIEW over a stream inside a transaction is not supported"); @@ -771,13 +842,6 @@ public class SpectrumQueryPreparation { throw new SpectrumSqlException("0A000", "A streaming materialized view cannot group or aggregate: each refresh batch is inserted on its own"); } - Set streams = - ExternalReferenceScanner.scan(view.select(), kinesis.keySet()); - if (streams.size() != 1) { - throw new SpectrumSqlException("0A000", "A streaming materialized view reads exactly one stream"); - } - ExternalReferenceScanner.Reference stream = streams.iterator().next(); - views.create(view, stream.table(), kinesis.get(stream.schema()), session, catalogRegion(session), backend); } private void refreshStreamingView(KinesisViewBinding view, Map kinesis, @@ -793,6 +857,19 @@ public class SpectrumQueryPreparation { views.refresh(view, schema, catalogRegion(session), backend); } + private void refreshMskStreamingView(MskViewBinding view, Map msk, + SpectrumSession session, BackendSql backend) { + if (session.inTransaction()) { + throw new SpectrumSqlException("25001", + "REFRESH MATERIALIZED VIEW of a streaming view cannot run inside a transaction block"); + } + MskSchemaBinding schema = msk.get(view.topicSchema()); + if (schema == null) { + throw new SpectrumSqlException("42P01", "external schema \"" + view.topicSchema() + "\" does not exist"); + } + mskViews.refresh(view, schema, backend); + } + private Map bindingsOf(SchemaBindingRegistry schemaRegistry, SpectrumSession session) { Map bindings = new LinkedHashMap<>(); @@ -808,6 +885,7 @@ public class SpectrumQueryPreparation { mskSchemas.removeCluster(accountId, clusterKey); functions.removeCluster(accountId, clusterKey); views.forgetCluster(accountId, clusterKey); + mskViews.forgetCluster(accountId, clusterKey); materializer.forgetCluster(clusterKey); } diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/StreamingViewSupport.java b/src/main/java/io/floci/aws/services/redshift/spectrum/StreamingViewSupport.java new file mode 100644 index 0000000000..c772128f0b --- /dev/null +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/StreamingViewSupport.java @@ -0,0 +1,130 @@ +package io.floci.aws.services.redshift.spectrum; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.ToLongFunction; + +/** + * What the streaming materialized views over Kinesis streams and over MSK topics share: the locks that serialize + * the work on one source (a stream or a topic), the drop of a view and its staging table, and the SQL helpers. + * A source is named by its external schema and its name, which the two kinds of binding spell differently. + */ +final class StreamingViewSupport { + + /** The schema an unqualified view name is created in. */ + static final String DEFAULT_VIEW_SCHEMA = "public"; + + private static final int BATCH_BYTES = 4 * 1024 * 1024; + + private final SchemaBindingRegistry registry; + private final Function viewSchema; + private final Function viewName; + private final Function sourceSchema; + private final Function sourceName; + private final Map sourceLocks = new ConcurrentHashMap<>(); + + StreamingViewSupport(SchemaBindingRegistry registry, Function viewSchema, + Function viewName, Function sourceSchema, + Function sourceName) { + this.registry = registry; + this.viewSchema = viewSchema; + this.viewName = viewName; + this.sourceSchema = sourceSchema; + this.sourceName = sourceName; + } + + /** The lock of one source: its refreshes share a staging table, so they and its creates and drops take turns. */ + Object lock(String accountId, String clusterKey, String database, String schema, String name) { + return sourceLocks.computeIfAbsent(String.join("\u001f", accountId, clusterKey, database, schema, name), + key -> new Object()); + } + + Object lock(B binding) { + return lock(binding.accountId(), binding.clusterKey(), binding.databaseName(), sourceSchema.apply(binding), + sourceName.apply(binding)); + } + + boolean readsSameSource(B first, B second) { + return sourceSchema.apply(first).equals(sourceSchema.apply(second)) + && sourceName.apply(first).equals(sourceName.apply(second)); + } + + void unbind(B view) { + registry.unbind(view.accountId(), view.clusterKey(), view.databaseName(), view.bindingName()); + } + + /** Unbinds a view captured earlier, unless a view of the same name over another source has replaced it. */ + void unbindIfCurrent(B captured) { + synchronized (lock(captured)) { + registry.find(captured.accountId(), captured.clusterKey(), captured.databaseName(), + captured.bindingName()).filter(current -> readsSameSource(current, captured)) + .ifPresent(this::unbind); + } + } + + /** The SQL that drops a view's table, for the statement that drops a schema it reads from. */ + static String dropSql(String viewSchema, String viewName, boolean ifExists, boolean cascade) { + return "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + table(viewSchema, viewName) + + (cascade ? " CASCADE" : " RESTRICT"); + } + + /** + * Drops a view's table and its binding, and the source's staging table once no other view reads the source. + * Without that, a plain DROP SCHEMA of the source's schema would keep failing on the leftover table. + */ + void drop(B named, boolean ifExists, boolean cascade, BackendSql backend) { + synchronized (lock(named)) { + // the binding read before the lock may be gone or replaced by a view of the same name since + Optional registered = registry.find(named.accountId(), named.clusterKey(), named.databaseName(), + named.bindingName()); + if (registered.isEmpty() || !readsSameSource(registered.get(), named)) { + if (ifExists) { + return; + } + throw new SpectrumSqlException("42P01", "materialized view \"" + viewSchema.apply(named) + "." + + viewName.apply(named) + "\" does not exist"); + } + B view = registered.get(); + boolean lastReader = registry.list(view.accountId(), view.clusterKey(), view.databaseName()).stream() + .noneMatch(other -> !other.bindingName().equals(view.bindingName()) + && readsSameSource(other, view)); + String sql = dropSql(viewSchema.apply(view), viewName.apply(view), ifExists, cascade); + if (lastReader) { + sql += "; DROP TABLE IF EXISTS " + table(sourceSchema.apply(view), sourceName.apply(view)); + } + backend.execute(sql); + unbind(view); + } + } + + /** Splits records so no statement carries more than about {@value #BATCH_BYTES} bytes of record data. */ + static List> batches(List records, ToLongFunction size) { + List> batches = new ArrayList<>(); + List batch = new ArrayList<>(); + long bytes = 0; + for (R record : records) { + long recordBytes = size.applyAsLong(record); + if (!batch.isEmpty() && bytes + recordBytes > BATCH_BYTES) { + batches.add(batch); + batch = new ArrayList<>(); + bytes = 0; + } + batch.add(record); + bytes += recordBytes; + } + batches.add(batch); + return batches; + } + + static String schemaOrDefault(String schema) { + return schema == null ? DEFAULT_VIEW_SCHEMA : schema; + } + + static String table(String schema, String name) { + return ExternalTableMaterializer.quote(schema) + "." + ExternalTableMaterializer.quote(name); + } +} diff --git a/src/test/java/io/floci/aws/core/common/kafka/KafkaRestClientAssignmentTest.java b/src/test/java/io/floci/aws/core/common/kafka/KafkaRestClientAssignmentTest.java index 303eef73a2..61500f19b5 100644 --- a/src/test/java/io/floci/aws/core/common/kafka/KafkaRestClientAssignmentTest.java +++ b/src/test/java/io/floci/aws/core/common/kafka/KafkaRestClientAssignmentTest.java @@ -69,6 +69,22 @@ class KafkaRestClientAssignmentTest { record(exchange); respond(exchange, 503, "{\"error_code\":50301,\"message\":\"broker unavailable\"}"); }); + fakeServer.createContext("/topics/orders/partitions/0/offsets", exchange -> { + record(exchange); + respond(exchange, 200, "{\"beginning_offset\":2,\"end_offset\":7}"); + }); + fakeServer.createContext("/topics/orders/partitions/9/offsets", exchange -> { + record(exchange); + respond(exchange, 404, "{\"error_code\":40402,\"message\":\"Partition 9 not found\"}"); + }); + fakeServer.createContext("/topics/missing/partitions/0/offsets", exchange -> { + record(exchange); + respond(exchange, 404, "{\"error_code\":40401,\"message\":\"Topic missing not found\"}"); + }); + fakeServer.createContext("/topics/malformed/partitions/0/offsets", exchange -> { + record(exchange); + respond(exchange, 200, "{}"); + }); fakeServer.createContext("/consumers/refresh-group", exchange -> { record(exchange); respond(exchange, 200, "{\"instance_id\":\"rest-consumer-1\"," @@ -124,6 +140,36 @@ class KafkaRestClientAssignmentTest { assertEquals("/topics/orders/partitions", lastRequestPath.get()); } + @Test + void partitionOffsetsReturnsTheBeginningAndEndOffset() { + KafkaPartitionOffsets offsets = client.partitionOffsets(restBaseUri(), "orders", 0); + + assertEquals(new KafkaPartitionOffsets(2, 7), offsets); + assertEquals("GET", lastRequestMethod.get()); + assertEquals("/topics/orders/partitions/0/offsets", lastRequestPath.get()); + } + + @Test + void partitionOffsetsOfMissingTopicRaisesTopicNotFound() { + KafkaTopicNotFoundException thrown = assertThrows(KafkaTopicNotFoundException.class, + () -> client.partitionOffsets(restBaseUri(), "missing", 0)); + + assertEquals("missing", thrown.getTopic()); + } + + @Test + void partitionOffsetsOfMissingPartitionIsARestClientFailureNotAMissingTopic() { + KafkaRestClientException thrown = assertThrows(KafkaRestClientException.class, + () -> client.partitionOffsets(restBaseUri(), "orders", 9)); + + assertEquals(404, thrown.getStatusCode()); + } + + @Test + void partitionOffsetsWithoutOffsetsInTheResponseIsARestClientFailure() { + assertThrows(KafkaRestClientException.class, () -> client.partitionOffsets(restBaseUri(), "malformed", 0)); + } + @Test void listPartitionsOfMissingTopicRaisesTopicNotFound() { KafkaTopicNotFoundException thrown = assertThrows(KafkaTopicNotFoundException.class, diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftMskStreamingViewIntegrationTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftMskStreamingViewIntegrationTest.java new file mode 100644 index 0000000000..1507db5876 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftMskStreamingViewIntegrationTest.java @@ -0,0 +1,229 @@ +package io.floci.aws.services.redshift; + +import io.floci.aws.core.common.kafka.KafkaConsumerHandle; +import io.floci.aws.core.common.kafka.KafkaHeaderDto; +import io.floci.aws.core.common.kafka.KafkaOffsetDto; +import io.floci.aws.core.common.kafka.KafkaPartitionOffsets; +import io.floci.aws.core.common.kafka.KafkaRecordDto; +import io.floci.aws.core.common.kafka.KafkaRestClient; +import io.floci.aws.core.common.kafka.KafkaTopicNotFoundException; +import io.floci.aws.core.common.kafka.KarapaceManager; +import io.floci.aws.services.msk.MskService; +import io.floci.aws.services.msk.model.MskCluster; +import io.floci.aws.services.redshift.model.Cluster; +import io.floci.aws.testing.DockerAvailability; +import io.quarkus.test.InjectMock; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicLong; + +import static io.floci.aws.services.redshift.RedshiftConnections.waitForConnection; +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.anyInt; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.when; + +/** + * Streams an MSK topic into a materialized view through a real cluster connection. The MSK cluster is the mock + * one and the Kafka REST Proxy is scripted, so this covers the SQL side of a refresh (staging table, view, + * checkpoints, error states); a refresh against a real Redpanda broker is not covered here. + */ +@QuarkusTest +class RedshiftMskStreamingViewIntegrationTest { + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/MskViewItRole"; + private static final URI REST = URI.create("http://localhost:18082/"); + private static final KafkaConsumerHandle CONSUMER = + new KafkaConsumerHandle("it-consumer", URI.create("http://localhost:18082/consumers/g/instances/it-consumer")); + + @Inject + RedshiftService redshiftService; + + @Inject + MskService mskService; + + @InjectMock + KarapaceManager karapace; + + @InjectMock + KafkaRestClient restClient; + + private final List topic = new CopyOnWriteArrayList<>(); + private final AtomicLong position = new AtomicLong(); + private String clusterId; + private MskCluster mskCluster; + + @BeforeAll + static void requireDocker() throws InterruptedException { + Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker daemon must be available for Redshift integration tests"); + } + + @BeforeEach + void scriptTheKafkaRestProxy() { + mskCluster = mskService.createCluster("it-msk-" + UUID.randomUUID().toString().substring(0, 8)); + when(karapace.ensureStarted(anyString())).thenReturn(REST); + when(restClient.listPartitions(eq(REST), anyString())).thenReturn(List.of(0)); + when(restClient.partitionOffsets(eq(REST), anyString(), anyInt())) + .thenAnswer(invocation -> new KafkaPartitionOffsets(0, topic.size())); + when(restClient.createConsumer(eq(REST), anyString(), anyString())).thenReturn(CONSUMER); + doAnswer(invocation -> { + position.set(0); + return null; + }).when(restClient).seekToBeginning(any(), anyList()); + doAnswer(invocation -> { + List offsets = invocation.getArgument(1); + if (!offsets.isEmpty()) { + position.set(offsets.get(0).offset()); + } + return null; + }).when(restClient).seek(any(), anyList()); + when(restClient.poll(eq(CONSUMER), any())).thenAnswer(invocation -> { + List unread = new ArrayList<>(); + for (long offset = position.get(); offset < topic.size(); offset++) { + unread.add(topic.get((int) offset)); + } + position.set(topic.size()); + return unread; + }); + } + + @AfterEach + void cleanUp() { + if (clusterId != null) { + redshiftService.deleteCluster(clusterId); + } + mskService.deleteCluster(mskCluster.getClusterArn()); + } + + private void produce(String value, String... headers) { + List kafkaHeaders = new ArrayList<>(); + for (int i = 0; i < headers.length; i += 2) { + kafkaHeaders.add(new KafkaHeaderDto(headers[i], headers[i + 1].getBytes(StandardCharsets.UTF_8))); + } + long offset = topic.size(); + topic.add(new KafkaRecordDto("orders", 0, offset, 1_700_000_000_000L + offset, "CreateTime", + ("k" + offset).getBytes(StandardCharsets.UTF_8), value.getBytes(StandardCharsets.UTF_8), kafkaHeaders)); + } + + private static List rows(Statement statement) throws SQLException { + List rows = new ArrayList<>(); + try (ResultSet result = statement.executeQuery("SELECT kafka_partition, kafka_offset, kafka_timestamp_type, " + + "k, body, trace FROM orders_mv ORDER BY kafka_offset")) { + while (result.next()) { + rows.add(result.getLong(1) + ":" + result.getLong(2) + ":" + result.getString(3) + ":" + + result.getString(4) + ":" + result.getString(5) + ":" + result.getString(6)); + } + } + return rows; + } + + private void createSchemaAndView(Statement statement) throws SQLException { + statement.execute("CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE '" + ROLE_ARN + + "' AUTHENTICATION iam CLUSTER_ARN '" + mskCluster.getClusterArn() + "'"); + statement.execute("CREATE MATERIALIZED VIEW orders_mv AUTO REFRESH NO AS " + + "SELECT kafka_partition, kafka_offset, kafka_timestamp_type, FROM_VARBYTE(kafka_key, 'utf-8') AS k, " + + "FROM_VARBYTE(kafka_value, 'utf-8') AS body, kafka_headers->>'trace' AS trace FROM msk.orders"); + } + + @Test + @Timeout(180) + void refreshLoadsOnlyWhatTheTopicGainedAndKeepsItsPositionAcrossATruncate() throws Exception { + produce("one", "trace", "t1"); + produce("two"); + clusterId = "it-mv-" + UUID.randomUUID().toString().substring(0, 8); + Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123"); + try (Connection connection = waitForConnection(cluster, "admin", "Secret123"); + Statement statement = connection.createStatement()) { + createSchemaAndView(statement); + assertEquals(List.of(), rows(statement)); + + statement.execute("REFRESH MATERIALIZED VIEW orders_mv"); + assertEquals(List.of("0:0:C:k0:one:t1", "0:1:C:k1:two:null"), rows(statement)); + + produce("three"); + statement.execute("REFRESH MATERIALIZED VIEW orders_mv"); + statement.execute("REFRESH MATERIALIZED VIEW orders_mv"); + assertEquals(List.of("0:0:C:k0:one:t1", "0:1:C:k1:two:null", "0:2:C:k2:three:null"), rows(statement)); + + statement.execute("TRUNCATE orders_mv"); + statement.execute("REFRESH MATERIALIZED VIEW orders_mv"); + assertEquals(List.of(), rows(statement)); + produce("four"); + statement.execute("REFRESH MATERIALIZED VIEW orders_mv"); + assertEquals(List.of("0:3:C:k3:four:null"), rows(statement)); + + statement.execute("DROP MATERIALIZED VIEW orders_mv"); + SQLException gone = assertThrows(SQLException.class, () -> statement.executeQuery("SELECT 1 FROM orders_mv")); + assertEquals("42P01", gone.getSQLState()); + statement.execute("DROP SCHEMA msk"); + } + } + + @Test + @Timeout(180) + void aBrokerThatIsDownFailsTheRefreshAndTheViewKeepsItsRows() throws Exception { + produce("one"); + clusterId = "it-mv-" + UUID.randomUUID().toString().substring(0, 8); + Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123"); + try (Connection connection = waitForConnection(cluster, "admin", "Secret123"); + Statement statement = connection.createStatement()) { + createSchemaAndView(statement); + statement.execute("REFRESH MATERIALIZED VIEW orders_mv"); + produce("two"); + when(restClient.listPartitions(eq(REST), anyString())).thenThrow(new UncheckedIOException(new IOException("refused"))); + + SQLException down = assertThrows(SQLException.class, () -> statement.execute("REFRESH MATERIALIZED VIEW orders_mv")); + + assertEquals("58030", down.getSQLState()); + assertEquals(List.of("0:0:C:k0:one:null"), rows(statement)); + when(restClient.listPartitions(eq(REST), anyString())).thenReturn(List.of(0)); + statement.execute("REFRESH MATERIALIZED VIEW orders_mv"); + assertEquals(List.of("0:0:C:k0:one:null", "0:1:C:k1:two:null"), rows(statement)); + } + } + + @Test + @Timeout(180) + void refusesAutoRefreshYesAndAViewOverAMissingTopic() throws Exception { + clusterId = "it-mv-" + UUID.randomUUID().toString().substring(0, 8); + Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123"); + try (Connection connection = waitForConnection(cluster, "admin", "Secret123"); + Statement statement = connection.createStatement()) { + statement.execute("CREATE EXTERNAL SCHEMA msk FROM MSK IAM_ROLE '" + ROLE_ARN + + "' AUTHENTICATION iam CLUSTER_ARN '" + mskCluster.getClusterArn() + "'"); + + SQLException auto = assertThrows(SQLException.class, () -> statement.execute( + "CREATE MATERIALIZED VIEW v AUTO REFRESH YES AS SELECT * FROM msk.orders")); + assertEquals("0A000", auto.getSQLState()); + + when(restClient.listPartitions(eq(REST), anyString())).thenThrow(new KafkaTopicNotFoundException( + "no_such_topic", new RuntimeException("404"))); + SQLException missing = assertThrows(SQLException.class, () -> statement.execute( + "CREATE MATERIALIZED VIEW v AS SELECT * FROM msk.no_such_topic")); + assertEquals("42P01", missing.getSQLState()); + } + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViewsTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViewsTest.java index a36d37681b..472fd426ae 100644 --- a/src/test/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViewsTest.java +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/KinesisStreamingViewsTest.java @@ -290,7 +290,7 @@ class KinesisStreamingViewsTest { assertThat(views.overSchema(SESSION, "kds"), equalTo(List.of(view))); assertThat(views.overSchema(SESSION, "other"), equalTo(List.of())); - assertThat(KinesisStreamingViews.dropSql(view, true, false), + assertThat(StreamingViewSupport.dropSql(view.viewSchema(), view.viewName(), true, false), equalTo("DROP TABLE IF EXISTS \"public\".\"events_mv\" RESTRICT")); } } diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/MskStreamingViewsTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/MskStreamingViewsTest.java new file mode 100644 index 0000000000..fd03eba33c --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/MskStreamingViewsTest.java @@ -0,0 +1,692 @@ +package io.floci.aws.services.redshift.spectrum; + +import io.floci.aws.core.common.kafka.KafkaConsumerHandle; +import io.floci.aws.core.common.kafka.KafkaHeaderDto; +import io.floci.aws.core.common.kafka.KafkaOffsetDto; +import io.floci.aws.core.common.kafka.KafkaPartitionOffsets; +import io.floci.aws.core.common.kafka.KafkaRecordDto; +import io.floci.aws.core.common.kafka.KafkaRestClient; +import io.floci.aws.core.common.kafka.KafkaRestClientException; +import io.floci.aws.core.common.kafka.KafkaTopicNotFoundException; +import io.floci.aws.core.common.kafka.KafkaTopicPartition; +import io.floci.aws.core.common.kafka.KarapaceManager; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.iam.ServiceRoleAuthorizer; +import io.floci.aws.services.iam.ServiceRoleAuthorizer.Permission; +import io.floci.aws.services.msk.MskService; +import io.floci.aws.services.msk.model.ClusterState; +import io.floci.aws.services.msk.model.MskCluster; +import io.floci.aws.testing.ThreadStates; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CountDownLatch; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.clearInvocations; +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; + +class MskStreamingViewsTest { + private static final String ACCOUNT = "000000000000"; + private static final String ROLE = "arn:aws:iam::000000000000:role/R"; + private static final String CLUSTER_ARN = "arn:aws:kafka:us-east-1:000000000000:cluster/orders/abc-123"; + private static final String BOOTSTRAP = "localhost:19092"; + private static final URI REST = URI.create("http://localhost:18082/"); + private static final KafkaConsumerHandle CONSUMER = + new KafkaConsumerHandle("rest-consumer-1", URI.create("http://localhost:18082/consumers/g/instances/rest-consumer-1")); + private static final SpectrumSession SESSION = new SpectrumSession(ACCOUNT, ACCOUNT + ":c", "dev", List.of(), false); + private static final String SELECT = "SELECT kafka_partition, kafka_offset, from_varbyte(kafka_value, 'utf-8') AS v " + + "FROM msk.\"orders\""; + private static final MskSchemaBinding SCHEMA = new MskSchemaBinding(ACCOUNT, SESSION.clusterKey(), "dev", "msk", ROLE, + "IAM", CLUSTER_ARN); + private static final Instant NOW = Instant.parse("2026-01-02T03:04:05Z"); + + private MskViewRegistry registry; + private MskService msk; + private KarapaceManager karapace; + private KafkaRestClient restClient; + private ServiceRoleAuthorizer authorizer; + private BackendSql backend; + private MskStreamingViews views; + private MskCluster cluster; + + @BeforeEach + void setUp() { + registry = new MskViewRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)); + msk = mock(MskService.class); + cluster = MskTestFixtures.activeCluster(CLUSTER_ARN, BOOTSTRAP); + when(msk.getClusterForAccount(ACCOUNT, CLUSTER_ARN)).thenReturn(Optional.of(cluster)); + karapace = mock(KarapaceManager.class); + MskTestFixtures.bridgeAt(karapace, BOOTSTRAP, REST); + restClient = mock(KafkaRestClient.class); + when(restClient.createConsumer(eq(REST), anyString(), anyString())).thenReturn(CONSUMER); + authorizer = mock(ServiceRoleAuthorizer.class); + when(authorizer.refusal(anyString(), anyString(), anyString(), any(), anyList())).thenReturn(Optional.empty()); + backend = mock(BackendSql.class); + views = new MskStreamingViews(registry, msk, karapace, restClient, authorizer, + Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private static ExternalStatement.CreateStreamingView createStatement() { + return new ExternalStatement.CreateStreamingView(null, "orders_mv", false, SELECT); + } + + private MskViewBinding createView() { + when(restClient.listPartitions(REST, "orders")).thenReturn(List.of(0)); + views.create(createStatement(), "orders", SCHEMA, SESSION, backend); + return registry.find(ACCOUNT, SESSION.clusterKey(), "dev", MskViewBinding.nameOf("public", "orders_mv")) + .orElseThrow(); + } + + private MskViewBinding stored() { + return registry.find(ACCOUNT, SESSION.clusterKey(), "dev", MskViewBinding.nameOf("public", "orders_mv")) + .orElseThrow(); + } + + private void partitionEnds(long... ends) { + List partitions = new ArrayList<>(); + for (int partition = 0; partition < ends.length; partition++) { + partitions.add(partition); + when(restClient.partitionOffsets(REST, "orders", partition)) + .thenReturn(new KafkaPartitionOffsets(0, ends[partition])); + } + when(restClient.listPartitions(REST, "orders")).thenReturn(partitions); + } + + private static KafkaRecordDto record(int partition, long offset, String value) { + return new KafkaRecordDto("orders", partition, offset, 1_700_000_000_000L + offset, "CreateTime", + ("key-" + offset).getBytes(StandardCharsets.UTF_8), value.getBytes(StandardCharsets.UTF_8), List.of()); + } + + @Test + void createBuildsTheViewTableAndTheStagingTableWithTheEightKafkaColumnsAndBindsTheView() { + createView(); + + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(backend).execute(sql.capture()); + assertThat(sql.getValue(), startsWith("CREATE TABLE IF NOT EXISTS \"msk\".\"orders\" (kafka_partition bigint, " + + "kafka_offset bigint, kafka_timestamp_type char(1), kafka_timestamp timestamp, " + + "kafka_key pg_catalog.varbyte, kafka_value pg_catalog.varbyte, kafka_headers pg_catalog.super, " + + "refresh_time timestamp); ")); + assertThat(sql.getValue(), containsString("CREATE TABLE \"public\".\"orders_mv\" AS " + SELECT + " WITH NO DATA")); + MskViewBinding binding = stored(); + assertThat(binding.topicSchema(), equalTo("msk")); + assertThat(binding.topicName(), equalTo("orders")); + assertThat(binding.checkpoints().isEmpty(), is(true)); + } + + @Test + void createRefusesAViewNameThatIsTaken() { + createView(); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.create(createStatement(), "orders", SCHEMA, SESSION, backend)); + + assertThat(error.sqlState(), equalTo("42P07")); + } + + @Test + void createFailsForAClusterThatDoesNotExistWithoutTouchingTheBackend() { + when(msk.getClusterForAccount(ACCOUNT, CLUSTER_ARN)).thenReturn(Optional.empty()); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.create(createStatement(), "orders", SCHEMA, SESSION, backend)); + + assertThat(error.sqlState(), equalTo("42704")); + verifyNoInteractions(backend, restClient); + } + + @Test + void createFailsForAClusterWithoutARunningBroker() { + cluster.setState(ClusterState.CREATING); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.create(createStatement(), "orders", SCHEMA, SESSION, backend)); + + assertThat(error.sqlState(), equalTo("58030")); + assertThat(error.getMessage(), containsString("no running broker")); + verifyNoInteractions(backend, karapace); + } + + @Test + void createFailsForAClusterThatHasNoBootstrapBrokers() { + cluster.setBootstrapBrokers(null); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.create(createStatement(), "orders", SCHEMA, SESSION, backend)); + + assertThat(error.sqlState(), equalTo("58030")); + verifyNoInteractions(backend, karapace); + } + + @Test + void createFailsWhenTheKafkaRestBridgeCannotStart() { + when(karapace.ensureStarted(BOOTSTRAP)).thenThrow(new IllegalStateException("docker is not running")); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.create(createStatement(), "orders", SCHEMA, SESSION, backend)); + + assertThat(error.sqlState(), equalTo("58030")); + assertThat(error.getMessage(), containsString("docker is not running")); + verifyNoInteractions(backend); + } + + @Test + void createFailsForAMissingTopicAsAnUndefinedRelation() { + when(restClient.listPartitions(REST, "orders")).thenThrow(new KafkaTopicNotFoundException("orders", + new KafkaRestClientException("GET", "topics/orders/partitions", 404, "{\"error_code\":40401}"))); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.create(createStatement(), "orders", SCHEMA, SESSION, backend)); + + assertThat(error.sqlState(), equalTo("42P01")); + verifyNoInteractions(backend); + } + + @Test + void createFailsWhenTheBrokerCannotBeReachedAndLeavesNoBinding() { + when(restClient.listPartitions(REST, "orders")).thenThrow(new UncheckedIOException(new IOException("refused"))); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.create(createStatement(), "orders", SCHEMA, SESSION, backend)); + + assertThat(error.sqlState(), equalTo("58030")); + assertThat(registry.list(ACCOUNT, SESSION.clusterKey(), "dev"), hasSize(0)); + verifyNoInteractions(backend); + } + + @Test + void theFirstRefreshReadsEveryPartitionFromTheBeginningThroughManualAssignment() { + createView(); + partitionEnds(2, 1); + when(restClient.poll(eq(CONSUMER), any())).thenReturn( + List.of(record(0, 0, "a"), record(0, 1, "b"), record(1, 0, "c")), List.of()); + + long loaded = views.refresh(stored(), SCHEMA, backend); + + assertThat(loaded, equalTo(3L)); + verify(restClient).assign(CONSUMER, List.of(new KafkaTopicPartition("orders", 0), + new KafkaTopicPartition("orders", 1))); + verify(restClient).seekToBeginning(CONSUMER, List.of(new KafkaTopicPartition("orders", 0), + new KafkaTopicPartition("orders", 1))); + verify(restClient).seek(CONSUMER, List.of()); + verify(restClient, never()).subscribe(any(), anyList()); + verify(restClient).close(CONSUMER); + assertThat(stored().checkpoints(), equalTo(Map.of("0", 1L, "1", 0L))); + } + + @Test + void aRefreshLoadsTheBatchIntoTheStagingTableRunsTheViewQueryAndEmptiesTheStagingTable() { + createView(); + partitionEnds(1); + when(restClient.poll(eq(CONSUMER), any())).thenReturn(List.of(record(0, 0, "a")), List.of()); + + views.refresh(stored(), SCHEMA, backend); + + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(backend, times(2)).execute(sql.capture()); + String load = sql.getAllValues().get(1); + assertThat(load, startsWith("INSERT INTO \"msk\".\"orders\" VALUES (0, 0, E'C', " + + "TIMESTAMP '2023-11-14 22:13:20.000000', decode('6b65792d30', 'hex')::pg_catalog.varbyte, " + + "decode('61', 'hex')::pg_catalog.varbyte, E'{}'::jsonb::pg_catalog.super, " + + "TIMESTAMP '2026-01-02 03:04:05.000000'); ")); + assertThat(load, containsString("; INSERT INTO \"public\".\"orders_mv\" " + SELECT + "; TRUNCATE \"msk\".\"orders\"")); + } + + @Test + void aLaterRefreshResumesEachPartitionAfterItsCheckpointAndSeeksThere() { + createView(); + partitionEnds(2, 1); + when(restClient.poll(eq(CONSUMER), any())).thenReturn( + List.of(record(0, 0, "a"), record(0, 1, "b"), record(1, 0, "c")), List.of()); + views.refresh(stored(), SCHEMA, backend); + partitionEnds(4, 1); + when(restClient.poll(eq(CONSUMER), any())).thenReturn(List.of(record(0, 2, "d"), record(0, 3, "e")), List.of()); + + long loaded = views.refresh(stored(), SCHEMA, backend); + + assertThat(loaded, equalTo(2L)); + verify(restClient).seek(CONSUMER, List.of(new KafkaOffsetDto("orders", 0, 2))); + assertThat(stored().checkpoints(), equalTo(Map.of("0", 3L, "1", 0L))); + } + + @Test + void aRefreshOfATopicThatGainedNothingOpensNoConsumerAndLoadsNothing() { + createView(); + partitionEnds(1); + when(restClient.poll(eq(CONSUMER), any())).thenReturn(List.of(record(0, 0, "a")), List.of()); + views.refresh(stored(), SCHEMA, backend); + clearInvocations(restClient, backend); + + long loaded = views.refresh(stored(), SCHEMA, backend); + + assertThat(loaded, equalTo(0L)); + verify(restClient, never()).createConsumer(any(), anyString(), anyString()); + verify(backend, never()).execute(anyString()); + } + + @Test + void aTruncateOfTheViewDoesNotRewindTheCheckpoints() { + createView(); + partitionEnds(1); + when(restClient.poll(eq(CONSUMER), any())).thenReturn(List.of(record(0, 0, "a")), List.of()); + views.refresh(stored(), SCHEMA, backend); + + assertThat(views.refresh(stored(), SCHEMA, backend), equalTo(0L)); + assertThat(stored().checkpoints(), equalTo(Map.of("0", 0L))); + } + + @Test + void aBrokerThatIsDownFailsTheRefreshAndLeavesTheCheckpointsAndTheBackendAlone() { + createView(); + when(restClient.listPartitions(REST, "orders")).thenThrow(new UncheckedIOException(new IOException("refused"))); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.refresh(stored(), SCHEMA, backend)); + + assertThat(error.sqlState(), equalTo("58030")); + assertThat(error.getMessage(), containsString(CLUSTER_ARN)); + assertThat(stored().checkpoints().isEmpty(), is(true)); + verify(restClient, never()).createConsumer(any(), anyString(), anyString()); + } + + @Test + void aProxyErrorWhilePollingFailsTheRefreshAndClosesTheConsumer() { + createView(); + partitionEnds(1); + when(restClient.poll(eq(CONSUMER), any())).thenThrow( + new KafkaRestClientException("GET", "records", 500, "{\"error_code\":50002}")); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.refresh(stored(), SCHEMA, backend)); + + assertThat(error.sqlState(), equalTo("58030")); + assertThat(stored().checkpoints().isEmpty(), is(true)); + verify(restClient).close(CONSUMER); + } + + @Test + void aFailedBatchStatementKeepsTheCheckpointsBehindTheDataAndClosesTheConsumer() { + createView(); + partitionEnds(1); + when(restClient.poll(eq(CONSUMER), any())).thenReturn(List.of(record(0, 0, "a")), List.of()); + doThrow(new SpectrumReadException("42703", "column does not exist")).when(backend) + .execute(argThat(sql -> sql.startsWith("INSERT INTO"))); + + assertThrows(SpectrumReadException.class, () -> views.refresh(stored(), SCHEMA, backend)); + + assertThat(stored().checkpoints().isEmpty(), is(true)); + verify(restClient).close(CONSUMER); + } + + @Test + void aCloseFailureDoesNotHideTheRefreshOutcome() { + createView(); + partitionEnds(1); + when(restClient.poll(eq(CONSUMER), any())).thenReturn(List.of(record(0, 0, "a")), List.of()); + doThrow(new UncheckedIOException(new IOException("gone"))).when(restClient).close(CONSUMER); + + assertThat(views.refresh(stored(), SCHEMA, backend), equalTo(1L)); + } + + @Test + void aRefreshStopsAfterTheTopicStopsReturningRecordsEvenIfAnEndOffsetWasNotReached() { + createView(); + partitionEnds(5); + when(restClient.poll(eq(CONSUMER), any())).thenReturn(List.of(record(0, 0, "a")), List.of()); + + assertThat(views.refresh(stored(), SCHEMA, backend), equalTo(1L)); + + verify(restClient, times(1 + MskStreamingViews.MAX_IDLE_POLLS)).poll(eq(CONSUMER), any()); + assertThat(stored().checkpoints(), equalTo(Map.of("0", 0L))); + } + + @Test + void recordsOfAnUnassignedPartitionOrAtAnOffsetAlreadyLoadedAreIgnored() { + createView(); + partitionEnds(2); + when(restClient.poll(eq(CONSUMER), any())).thenReturn( + List.of(record(0, 0, "a"), record(7, 0, "stray"), record(0, 1, "b")), List.of()); + views.refresh(stored(), SCHEMA, backend); + partitionEnds(3); + when(restClient.poll(eq(CONSUMER), any())).thenReturn(List.of(record(0, 1, "again"), record(0, 2, "c")), List.of()); + + assertThat(views.refresh(stored(), SCHEMA, backend), equalTo(1L)); + assertThat(stored().checkpoints(), equalTo(Map.of("0", 2L))); + } + + @Test + void recordsAreSplitIntoStatementsOfBoundedSizeAndEachBatchMovesTheCheckpoint() { + createView(); + partitionEnds(3); + byte[] large = new byte[3 * 1024 * 1024]; + List polled = new ArrayList<>(); + for (int offset = 0; offset < 3; offset++) { + polled.add(new KafkaRecordDto("orders", 0, offset, 1L, "CreateTime", null, large, List.of())); + } + when(restClient.poll(eq(CONSUMER), any())).thenReturn(polled, List.of()); + + assertThat(views.refresh(stored(), SCHEMA, backend), equalTo(3L)); + + verify(backend, times(4)).execute(anyString()); + assertThat(stored().checkpoints(), equalTo(Map.of("0", 2L))); + } + + @Test + void aRecordWithoutATimestampOrKeyIsLoadedWithUnknownTypeAndNulls() { + createView(); + partitionEnds(1); + KafkaRecordDto record = new KafkaRecordDto("orders", 0, 0, -1, "CreateTime", null, + "v".getBytes(StandardCharsets.UTF_8), List.of(new KafkaHeaderDto("trace", null))); + when(restClient.poll(eq(CONSUMER), any())).thenReturn(List.of(record), List.of()); + + views.refresh(stored(), SCHEMA, backend); + + verify(backend).execute(argThat(sql -> sql.contains("VALUES (0, 0, E'U', NULL::timestamp, " + + "NULL::pg_catalog.varbyte, decode('76', 'hex')::pg_catalog.varbyte, " + + "E'{\"trace\":null}'::jsonb::pg_catalog.super, "))); + } + + @Test + void headersBecomeAJsonObjectOfNameToTextAndARepeatedNameKeepsItsLastValue() { + String json = MskStreamingViews.headersJson(List.of( + new KafkaHeaderDto("a", "1".getBytes(StandardCharsets.UTF_8)), + new KafkaHeaderDto("b", "café".getBytes(StandardCharsets.UTF_8)), + new KafkaHeaderDto("a", "2".getBytes(StandardCharsets.UTF_8)))); + + assertThat(json, equalTo("{\"a\":\"2\",\"b\":\"café\"}")); + assertThat(MskStreamingViews.headersJson(null), equalTo("{}")); + } + + @Test + void eachViewReadsThroughItsOwnConsumerGroupApartFromPipesAndLambda() { + MskViewBinding first = createView(); + MskViewBinding second = new MskViewBinding(ACCOUNT, SESSION.clusterKey(), "dev", "public", "other_mv", "msk", + "orders", SELECT, Map.of()); + + String group = MskStreamingViews.groupOf(first); + + assertThat(group, startsWith("floci-redshift-msk-")); + assertThat(group, not(startsWith("floci-pipes-"))); + assertThat(MskStreamingViews.groupOf(second), not(equalTo(group))); + assertThat(MskStreamingViews.groupOf(first), equalTo(group)); + partitionEnds(1); + when(restClient.poll(eq(CONSUMER), any())).thenReturn(List.of(record(0, 0, "a")), List.of()); + views.refresh(first, SCHEMA, backend); + verify(restClient).createConsumer(REST, group, "earliest"); + } + + @Test + void aRecordAtOrPastTheEndTheRefreshStartedWithBelongsToTheNextRefresh() { + createView(); + partitionEnds(2); + when(restClient.poll(eq(CONSUMER), any())).thenReturn( + List.of(record(0, 0, "a"), record(0, 1, "b"), record(0, 2, "late"), record(0, 3, "later")), List.of()); + + assertThat(views.refresh(stored(), SCHEMA, backend), equalTo(2L)); + + assertThat(stored().checkpoints(), equalTo(Map.of("0", 1L))); + verify(backend, never()).execute(argThat(sql -> sql.contains("decode('6c61746572'"))); + } + + @Test + void aRefreshQueuedBehindAReplacementOverAnotherTopicIsRefusedInsteadOfReadingTheNewTopic() { + MskViewBinding captured = createView(); + views.unbind(captured); + registry.bind(new MskViewBinding(ACCOUNT, SESSION.clusterKey(), "dev", "public", "orders_mv", "msk", + "payments", SELECT, Map.of())); + clearInvocations(restClient, karapace, backend); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.refresh(captured, SCHEMA, backend)); + + assertThat(error.sqlState(), equalTo("42P01")); + assertThat(error.getMessage(), containsString("replaced by a view over another topic")); + verifyNoInteractions(restClient, karapace, backend); + } + + @Test + void aTopicCreatedAgainWithLowerOffsetsIsReadFromItsBeginning() { + createView(); + partitionEnds(5); + when(restClient.poll(eq(CONSUMER), any())).thenReturn( + List.of(record(0, 0, "a"), record(0, 1, "b"), record(0, 2, "c"), record(0, 3, "d"), record(0, 4, "e")), + List.of()); + views.refresh(stored(), SCHEMA, backend); + clearInvocations(restClient); + partitionEnds(2); + when(restClient.createConsumer(eq(REST), anyString(), anyString())).thenReturn(CONSUMER); + when(restClient.poll(eq(CONSUMER), any())).thenReturn(List.of(record(0, 0, "x"), record(0, 1, "y")), List.of()); + + assertThat(views.refresh(stored(), SCHEMA, backend), equalTo(2L)); + + verify(restClient).seekToBeginning(CONSUMER, List.of(new KafkaTopicPartition("orders", 0))); + assertThat(stored().checkpoints(), equalTo(Map.of("0", 1L))); + } + + @Test + void aRefusedRoleCannotCreateAViewOrTellWhetherTheTopicExists() { + when(authorizer.refusal(anyString(), anyString(), anyString(), any(), anyList())) + .thenReturn(Optional.of("role is not authorized to kafka-cluster:DescribeTopic")); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.create(createStatement(), "orders", SCHEMA, SESSION, backend)); + + assertThat(error.sqlState(), equalTo("42501")); + assertThat(registry.list(ACCOUNT, SESSION.clusterKey(), "dev"), hasSize(0)); + verifyNoInteractions(backend, restClient, karapace); + } + + @Test + void aClusterArnThatIsNotAClusterArnIsAMissingClusterNotAnInternalError() { + for (String arn : new String[] {"not-an-arn", "arn:aws:kafka::000000000000:cluster/orders/abc-123", + "arn:aws:kafka:us-east-1:000000000000:topic/orders/abc-123/t", "arn:aws:kafka:us-east-1:000000000000:cluster/orders"}) { + MskSchemaBinding malformed = new MskSchemaBinding(ACCOUNT, SESSION.clusterKey(), "dev", "msk", ROLE, "IAM", arn); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.create(createStatement(), "orders", malformed, SESSION, backend)); + + assertThat(arn, error.sqlState(), equalTo("42704")); + assertThat(arn, error.getMessage(), containsString("does not exist")); + } + verifyNoInteractions(backend, restClient); + } + + @Test + void aBinaryHeaderValueCannotFailTheRefresh() { + String json = MskStreamingViews.headersJson(List.of( + new KafkaHeaderDto("trace", new byte[] {'a', 0, 'b'}), + new KafkaHeaderDto("bad\u0000name", new byte[] {(byte) 0xff}))); + + assertThat(json, equalTo("{\"trace\":\"a\uFFFDb\",\"bad\uFFFDname\":\"\uFFFD\"}")); + assertThat(json, not(containsString("\\u0000"))); + } + + @Test + void aViewIsNeverCreatedWhileTheSchemaIsBeingDropped() throws Exception { + when(restClient.listPartitions(REST, "orders")).thenReturn(List.of(0)); + CountDownLatch dropping = new CountDownLatch(1); + CountDownLatch finishDrop = new CountDownLatch(1); + Thread drop = Thread.ofVirtual().start(() -> views.exclusivelyOnSchema(SESSION, "msk", () -> { + dropping.countDown(); + try { + finishDrop.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + })); + dropping.await(); + Thread create = Thread.ofVirtual().start(() -> views.create(createStatement(), "orders", SCHEMA, SESSION, backend)); + + // the create is parked on the schema lock the drop holds, which is what keeps the view from existing yet + ThreadStates.awaitState(create, EnumSet.of(Thread.State.BLOCKED), Duration.ofSeconds(5), "the create"); + + assertThat(create.isAlive(), is(true)); + assertThat(registry.list(ACCOUNT, SESSION.clusterKey(), "dev"), hasSize(0)); + finishDrop.countDown(); + create.join(5_000); + drop.join(5_000); + assertThat(registry.list(ACCOUNT, SESSION.clusterKey(), "dev"), hasSize(1)); + } + + @Test + void iamAuthenticationChecksTheKafkaActionsOnTheClusterTopicAndConsumerGroup() { + MskViewBinding view = createView(); + partitionEnds(1); + when(restClient.poll(eq(CONSUMER), any())).thenReturn(List.of(record(0, 0, "a")), List.of()); + clearInvocations(authorizer); + + views.refresh(view, SCHEMA, backend); + + String group = MskStreamingViews.groupOf(view); + String topicArn = "arn:aws:kafka:us-east-1:000000000000:topic/orders/abc-123/orders"; + String groupArn = "arn:aws:kafka:us-east-1:000000000000:group/orders/abc-123/" + group; + @SuppressWarnings("unchecked") + ArgumentCaptor> permissions = ArgumentCaptor.forClass(List.class); + verify(authorizer).refusal(eq(ROLE), eq(ACCOUNT), eq("redshift.amazonaws.com"), isNull(), + permissions.capture()); + assertThat(permissions.getValue(), hasSize(6)); + assertThat(permissions.getValue(), hasItem(new Permission("kafka:GetBootstrapBrokers", CLUSTER_ARN))); + assertThat(permissions.getValue(), hasItem(new Permission("kafka-cluster:Connect", CLUSTER_ARN))); + assertThat(permissions.getValue(), hasItem(new Permission("kafka-cluster:DescribeTopic", topicArn))); + assertThat(permissions.getValue(), hasItem(new Permission("kafka-cluster:ReadData", topicArn))); + assertThat(permissions.getValue(), hasItem(new Permission("kafka-cluster:AlterGroup", groupArn))); + assertThat(permissions.getValue(), hasItem(new Permission("kafka-cluster:DescribeGroup", groupArn))); + } + + @Test + void unauthenticatedAccessChecksOnlyTheBootstrapBrokersAction() { + MskSchemaBinding open = new MskSchemaBinding(ACCOUNT, SESSION.clusterKey(), "dev", "msk", ROLE, "NONE", + CLUSTER_ARN); + MskViewBinding view = createView(); + partitionEnds(1); + when(restClient.poll(eq(CONSUMER), any())).thenReturn(List.of(record(0, 0, "a")), List.of()); + clearInvocations(authorizer); + + views.refresh(view, open, backend); + + @SuppressWarnings("unchecked") + ArgumentCaptor> permissions = ArgumentCaptor.forClass(List.class); + verify(authorizer).refusal(anyString(), anyString(), anyString(), any(), permissions.capture()); + assertThat(permissions.getValue(), equalTo(List.of(new Permission("kafka:GetBootstrapBrokers", CLUSTER_ARN)))); + } + + @Test + void aRefusedRoleFailsTheRefreshBeforeAnyBrokerOrBackendCall() { + MskViewBinding view = createView(); + clearInvocations(backend, restClient, karapace); + when(authorizer.refusal(anyString(), anyString(), anyString(), any(), anyList())) + .thenReturn(Optional.of("role is not authorized to kafka-cluster:ReadData")); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.refresh(view, SCHEMA, backend)); + + assertThat(error.sqlState(), equalTo("42501")); + verifyNoInteractions(backend, restClient, karapace); + } + + @Test + void refreshingAViewThatWasDroppedMeanwhileFailsAsAMissingRelation() { + MskViewBinding view = createView(); + views.unbind(view); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.refresh(view, SCHEMA, backend)); + + assertThat(error.sqlState(), equalTo("42P01")); + } + + @Test + void dropRemovesTheViewTableAndTheStagingTableOnceNoOtherViewReadsTheTopic() { + MskViewBinding view = createView(); + clearInvocations(backend); + + views.drop(view, false, false, backend); + + verify(backend).execute("DROP TABLE \"public\".\"orders_mv\" RESTRICT; DROP TABLE IF EXISTS \"msk\".\"orders\""); + assertThat(registry.list(ACCOUNT, SESSION.clusterKey(), "dev"), hasSize(0)); + } + + @Test + void dropKeepsTheStagingTableWhileAnotherViewStillReadsTheTopic() { + MskViewBinding view = createView(); + registry.bind(new MskViewBinding(ACCOUNT, SESSION.clusterKey(), "dev", "public", "other_mv", "msk", "orders", + SELECT, Map.of())); + clearInvocations(backend); + + views.drop(view, false, true, backend); + + verify(backend).execute("DROP TABLE \"public\".\"orders_mv\" CASCADE"); + assertThat(registry.list(ACCOUNT, SESSION.clusterKey(), "dev"), hasSize(1)); + } + + @Test + void dropOfAMissingViewIsAnErrorUnlessIfExistsIsGiven() { + MskViewBinding view = createView(); + views.unbind(view); + clearInvocations(backend); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> views.drop(view, false, false, backend)); + views.drop(view, true, false, backend); + + assertThat(error.sqlState(), equalTo("42P01")); + verify(backend, never()).execute(anyString()); + } + + @Test + void unbindIfCurrentLeavesAViewOfTheSameNameOverAnotherTopicAlone() { + MskViewBinding captured = createView(); + views.unbind(captured); + MskViewBinding replacement = new MskViewBinding(ACCOUNT, SESSION.clusterKey(), "dev", "public", "orders_mv", + "msk", "payments", SELECT, Map.of()); + registry.bind(replacement); + + views.unbindIfCurrent(captured); + + assertThat(registry.list(ACCOUNT, SESSION.clusterKey(), "dev"), equalTo(List.of(replacement))); + } + + @Test + void forgetClusterRemovesItsViews() { + createView(); + + views.forgetCluster(ACCOUNT, SESSION.clusterKey()); + + assertThat(registry.list(ACCOUNT, SESSION.clusterKey(), "dev"), hasSize(0)); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/MskTestFixtures.java b/src/test/java/io/floci/aws/services/redshift/spectrum/MskTestFixtures.java new file mode 100644 index 0000000000..f1b1ed62a6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/MskTestFixtures.java @@ -0,0 +1,29 @@ +package io.floci.aws.services.redshift.spectrum; + +import io.floci.aws.core.common.kafka.KarapaceManager; +import io.floci.aws.services.msk.model.ClusterState; +import io.floci.aws.services.msk.model.MskCluster; + +import java.net.URI; + +import static org.mockito.Mockito.when; + +/** The MSK cluster and Kafka REST bridge the streaming view tests read from. */ +final class MskTestFixtures { + + private MskTestFixtures() { + } + + /** A cluster that is ACTIVE and has a broker to bootstrap from. */ + static MskCluster activeCluster(String clusterArn, String bootstrapBrokers) { + MskCluster cluster = new MskCluster(clusterArn, "orders", "3.6.0"); + cluster.setState(ClusterState.ACTIVE); + cluster.setBootstrapBrokers(bootstrapBrokers); + return cluster; + } + + /** Makes the bridge for {@code bootstrapBrokers} answer at {@code restBaseUri}. */ + static void bridgeAt(KarapaceManager karapace, String bootstrapBrokers, URI restBaseUri) { + when(karapace.ensureStarted(bootstrapBrokers)).thenReturn(restBaseUri); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/MskViewRegistryTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/MskViewRegistryTest.java new file mode 100644 index 0000000000..cb084ff613 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/MskViewRegistryTest.java @@ -0,0 +1,92 @@ +package io.floci.aws.services.redshift.spectrum; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.core.storage.StorageFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class MskViewRegistryTest { + private static final String ACCOUNT = "000000000000"; + private MskViewRegistry registry; + + @BeforeEach + @SuppressWarnings("unchecked") + void setUp() { + StorageFactory factory = mock(StorageFactory.class); + when(factory.create(eq("redshift"), eq("redshift-msk-views.json"), any(TypeReference.class))) + .thenReturn(new AccountAwareStorageBackend(new InMemoryStorage<>(), null, ACCOUNT)); + registry = new MskViewRegistry(factory); + } + + private static MskViewBinding view(String schema, String name) { + return new MskViewBinding(ACCOUNT, "c1", "dev", schema, name, "msk", "orders", "SELECT 1", Map.of()); + } + + @Test + void aViewIsKeyedBySchemaAndNameSoTheSameNameInTwoSchemasIsTwoViews() { + registry.bind(view("public", "mv")); + registry.bind(view("analytics", "mv")); + + assertThat(registry.find(ACCOUNT, "c1", "dev", MskViewBinding.nameOf("public", "mv")).isPresent(), is(true)); + assertThat(registry.find(ACCOUNT, "c1", "dev", MskViewBinding.nameOf("analytics", "mv")).isPresent(), is(true)); + assertThat(registry.list(ACCOUNT, "c1", "dev").size(), equalTo(2)); + } + + @Test + void rejectsADuplicateView() { + registry.bind(view("public", "mv")); + + assertThrows(SpectrumSqlException.class, () -> registry.bind(view("public", "mv"))); + } + + @Test + void replacingAViewKeepsItsNewCheckpoints() { + MskViewBinding bound = view("public", "mv"); + registry.bind(bound); + + registry.replace(bound.withCheckpoints(Map.of(0, 41L, 1, 7L))); + + MskViewBinding found = registry.find(ACCOUNT, "c1", "dev", bound.bindingName()).orElseThrow(); + assertThat(found.checkpoints(), equalTo(Map.of("0", 41L, "1", 7L))); + } + + @Test + void withCheckpointsKeepsThePartitionsItDoesNotMention() { + MskViewBinding moved = view("public", "mv").withCheckpoints(Map.of(0, 1L, 1, 2L)).withCheckpoints(Map.of(1, 5L)); + + assertThat(moved.checkpoints(), equalTo(Map.of("0", 1L, "1", 5L))); + } + + @Test + void aBindingSurvivesAJsonRoundTripWithItsCheckpoints() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + MskViewBinding original = view("public", "mv").withCheckpoints(Map.of(0, 9_000_000_000L)); + + MskViewBinding restored = mapper.readValue(mapper.writeValueAsString(original), MskViewBinding.class); + + assertThat(restored, equalTo(original)); + } + + @Test + void clearRemovesEveryView() { + registry.bind(view("public", "mv")); + + registry.clear(); + + assertThat(registry.list(ACCOUNT, "c1", "dev").isEmpty(), is(true)); + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumMskSchemaPreparationTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumMskSchemaPreparationTest.java index c7ac872b36..bc8b5d1f05 100644 --- a/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumMskSchemaPreparationTest.java +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumMskSchemaPreparationTest.java @@ -240,7 +240,7 @@ class SpectrumMskSchemaPreparationTest { } @Test - void refusesCreateExternalTableAndStreamingMaterializedViewsOverAnMskSchema() { + void refusesCreateExternalTableOverAnMskSchema() { preparation.prepare(CREATE, SESSION, backend); String createTable = "CREATE EXTERNAL TABLE msk.orders (id INT) STORED AS TEXTFILE LOCATION 's3://bucket/orders/'"; assertThat(preparation.handlesDdl(createTable, SESSION), equalTo(true)); @@ -248,13 +248,6 @@ class SpectrumMskSchemaPreparationTest { () -> preparation.prepare(createTable, SESSION, backend)); assertThat(tableError.sqlState(), equalTo("0A000")); assertThat(tableError.getMessage(), containsString("CREATE EXTERNAL TABLE")); - - String createMv = "CREATE MATERIALIZED VIEW mv AS SELECT * FROM msk.orders"; - assertThat(preparation.handlesDdl(createMv, SESSION), equalTo(true)); - SpectrumSqlException mvError = assertThrows(SpectrumSqlException.class, - () -> preparation.prepare(createMv, SESSION, backend)); - assertThat(mvError.sqlState(), equalTo("0A000")); - assertThat(mvError.getMessage(), containsString("Streaming materialized views over MSK")); } @Test @@ -269,7 +262,7 @@ class SpectrumMskSchemaPreparationTest { () -> preparation.prepare(mixed, SESSION, backend)); assertThat(error.sqlState(), equalTo("0A000")); - assertThat(error.getMessage(), containsString("Streaming materialized views over MSK")); + assertThat(error.getMessage(), containsString("exactly one stream or topic")); verifyNoInteractions(kinesisService, backend); } diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumMskViewPreparationTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumMskViewPreparationTest.java new file mode 100644 index 0000000000..c75560c8d4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumMskViewPreparationTest.java @@ -0,0 +1,209 @@ +package io.floci.aws.services.redshift.spectrum; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.kafka.KafkaConsumerHandle; +import io.floci.aws.core.common.kafka.KafkaPartitionOffsets; +import io.floci.aws.core.common.kafka.KafkaRecordDto; +import io.floci.aws.core.common.kafka.KafkaRestClient; +import io.floci.aws.core.common.kafka.KarapaceManager; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.glue.GlueService; +import io.floci.aws.services.iam.ServiceRoleAuthorizer; +import io.floci.aws.services.msk.MskService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.util.List; +import java.util.Optional; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class SpectrumMskViewPreparationTest { + private static final String ACCOUNT = "000000000000"; + private static final String ROLE = "arn:aws:iam::000000000000:role/R"; + private static final String CLUSTER_ARN = "arn:aws:kafka:us-east-1:000000000000:cluster/orders/abc-123"; + private static final URI REST = URI.create("http://localhost:18082/"); + private static final KafkaConsumerHandle CONSUMER = + new KafkaConsumerHandle("c1", URI.create("http://localhost:18082/consumers/g/instances/c1")); + private static final SpectrumSession SESSION = new SpectrumSession(ACCOUNT, ACCOUNT + ":c", "dev", List.of(), false); + private static final SpectrumSession IN_TRANSACTION = + new SpectrumSession(ACCOUNT, ACCOUNT + ":c", "dev", List.of(), true); + private static final String CREATE_VIEW = "CREATE MATERIALIZED VIEW orders_mv AUTO REFRESH NO AS " + + "SELECT kafka_offset FROM msk.\"orders\""; + private static final String REFRESH = "REFRESH MATERIALIZED VIEW orders_mv"; + + private MskSchemaRegistry mskSchemas; + private KafkaRestClient restClient; + private BackendSql backend; + private SpectrumQueryPreparation preparation; + + @BeforeEach + void setUp() { + mskSchemas = new MskSchemaRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)); + mskSchemas.bind(new MskSchemaBinding(ACCOUNT, SESSION.clusterKey(), "dev", "msk", ROLE, "IAM", CLUSTER_ARN)); + MskService msk = mock(MskService.class); + when(msk.getClusterForAccount(ACCOUNT, CLUSTER_ARN)) + .thenReturn(Optional.of(MskTestFixtures.activeCluster(CLUSTER_ARN, "localhost:19092"))); + KarapaceManager karapace = mock(KarapaceManager.class); + MskTestFixtures.bridgeAt(karapace, "localhost:19092", REST); + restClient = mock(KafkaRestClient.class); + when(restClient.listPartitions(REST, "orders")).thenReturn(List.of(0)); + when(restClient.partitionOffsets(REST, "orders", 0)).thenReturn(new KafkaPartitionOffsets(0, 1)); + when(restClient.createConsumer(eq(REST), anyString(), anyString())).thenReturn(CONSUMER); + when(restClient.poll(eq(CONSUMER), any())).thenReturn(List.of(new KafkaRecordDto("orders", 0, 0, 1L, + "CreateTime", null, "v".getBytes(StandardCharsets.UTF_8), List.of())), List.of()); + ServiceRoleAuthorizer authorizer = mock(ServiceRoleAuthorizer.class); + when(authorizer.refusal(anyString(), anyString(), anyString(), any(), anyList())).thenReturn(Optional.empty()); + MskStreamingViews mskViews = new MskStreamingViews( + new MskViewRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)), msk, karapace, + restClient, authorizer, Clock.systemUTC()); + backend = mock(BackendSql.class); + when(backend.permitsCachePublication()).thenReturn(true); + ExternalMetadataWriter metadata = new ExternalMetadataWriter(mock(GlueService.class), new ObjectMapper()); + KinesisStreamingViews kinesisViews = new KinesisStreamingViews( + new KinesisViewRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)), + null, null, null, Clock.systemUTC()); + preparation = new SpectrumQueryPreparation(mock(ExternalCatalogRegistry.class), + new KinesisSchemaRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)), + mskSchemas, new ExternalFunctionRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)), + mock(ExternalTableMaterializer.class), new ExternalStatementParser(), mock(GlueService.class), metadata, + new ExternalCatalogLocks(), kinesisViews, mskViews, (accountId, clusterIdentifier) -> null); + } + + @Test + void aViewOverATopicIsHandledAndAViewOverAnythingElseIsLeftToPostgres() { + assertThat(preparation.handlesDdl(CREATE_VIEW, SESSION), is(true)); + assertThat(preparation.handlesDdl("CREATE MATERIALIZED VIEW v AS SELECT 1 FROM public.t", SESSION), is(false)); + assertThat(preparation.handlesDdl(REFRESH, SESSION), is(false)); + } + + @Test + void createRefreshAndDropRunAsTheirOwnCommands() { + assertThat(preparation.prepare(CREATE_VIEW, SESSION, backend), is(true)); + assertThat(preparation.handlesDdl(REFRESH, SESSION), is(true)); + assertThat(preparation.handlesDdl("DROP MATERIALIZED VIEW orders_mv", SESSION), is(true)); + + assertThat(preparation.prepare(REFRESH, SESSION, backend), is(true)); + verify(backend).execute(argThat(sql -> sql.startsWith("INSERT INTO \"msk\".\"orders\" VALUES (0, 0, "))); + assertThat(preparation.prepare("DROP MATERIALIZED VIEW orders_mv", SESSION, backend), is(true)); + + verify(backend).execute("DROP TABLE \"public\".\"orders_mv\" RESTRICT; DROP TABLE IF EXISTS \"msk\".\"orders\""); + assertThat(preparation.handlesDdl(REFRESH, SESSION), is(false)); + assertThat(preparation.commandTag(CREATE_VIEW), equalTo("CREATE MATERIALIZED VIEW")); + assertThat(preparation.commandTag(REFRESH), equalTo("REFRESH MATERIALIZED VIEW")); + assertThat(preparation.commandTag("DROP MATERIALIZED VIEW orders_mv"), equalTo("DROP MATERIALIZED VIEW")); + } + + @Test + void autoRefreshYesAndTransactionBlocksAreRefused() { + SpectrumSqlException auto = assertThrows(SpectrumSqlException.class, () -> preparation.prepare( + "CREATE MATERIALIZED VIEW v AUTO REFRESH YES AS SELECT * FROM msk.orders", SESSION, backend)); + SpectrumSqlException inTransaction = assertThrows(SpectrumSqlException.class, + () -> preparation.prepare(CREATE_VIEW, IN_TRANSACTION, backend)); + + assertThat(auto.sqlState(), equalTo("0A000")); + assertThat(auto.getMessage(), containsString("AUTO REFRESH YES")); + assertThat(inTransaction.sqlState(), equalTo("0A000")); + verify(backend, never()).execute(anyString()); + } + + @Test + void aJoinOrAnAggregateInTheViewIsRefused() { + SpectrumSqlException join = assertThrows(SpectrumSqlException.class, () -> preparation.prepare( + "CREATE MATERIALIZED VIEW v AS SELECT * FROM msk.orders o JOIN public.t ON o.kafka_offset = t.id", + SESSION, backend)); + SpectrumSqlException aggregate = assertThrows(SpectrumSqlException.class, () -> preparation.prepare( + "CREATE MATERIALIZED VIEW v AS SELECT kafka_partition, count(*) FROM msk.orders GROUP BY kafka_partition", + SESSION, backend)); + + assertThat(join.getMessage(), containsString("JOIN")); + assertThat(aggregate.getMessage(), containsString("aggregate")); + verify(backend, never()).execute(anyString()); + } + + @Test + void aViewReadsExactlyOneTopic() { + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, () -> preparation.prepare( + "CREATE MATERIALIZED VIEW v AS SELECT * FROM msk.orders WHERE kafka_offset IN (SELECT kafka_offset FROM msk.payments)", + SESSION, backend)); + + assertThat(error.sqlState(), equalTo("0A000")); + assertThat(error.getMessage(), containsString("exactly one topic")); + } + + @Test + void refreshInsideATransactionBlockIsRefused() { + preparation.prepare(CREATE_VIEW, SESSION, backend); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> preparation.prepare(REFRESH, IN_TRANSACTION, backend)); + + assertThat(error.sqlState(), equalTo("25001")); + } + + @Test + void dropInsideATransactionBlockIsRefused() { + preparation.prepare(CREATE_VIEW, SESSION, backend); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> preparation.prepare("DROP MATERIALIZED VIEW orders_mv", IN_TRANSACTION, backend)); + + assertThat(error.sqlState(), equalTo("25001")); + } + + @Test + void aPlainReadOfATopicRelationIsStillRefused() { + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> preparation.prepare("SELECT * FROM msk.orders", SESSION, backend)); + + assertThat(error.sqlState(), equalTo("0A000")); + assertThat(error.getMessage(), containsString("only read through a streaming materialized view")); + } + + @Test + void dropSchemaWithoutCascadeDoesNotDropTheViewsThatReadIt() { + preparation.prepare(CREATE_VIEW, SESSION, backend); + + preparation.prepare("DROP SCHEMA msk", SESSION, backend); + + verify(backend).execute(argThat(sql -> sql.startsWith("DROP SCHEMA \"msk\" RESTRICT"))); + verify(backend, never()).execute(argThat(sql -> sql.startsWith("DROP TABLE IF EXISTS \"public\".\"orders_mv\""))); + } + + @Test + void dropSchemaCascadeTakesTheViewsThatReadItWithIt() { + preparation.prepare(CREATE_VIEW, SESSION, backend); + + preparation.prepare("DROP SCHEMA msk CASCADE", SESSION, backend); + + verify(backend).execute(argThat(sql -> sql.startsWith( + "DROP TABLE IF EXISTS \"public\".\"orders_mv\" CASCADE; DROP SCHEMA \"msk\" CASCADE"))); + assertThat(preparation.handlesDdl(REFRESH, SESSION), is(false)); + assertThat(mskSchemas.find(ACCOUNT, SESSION.clusterKey(), "dev", "msk").isPresent(), is(false)); + } + + @Test + void forgettingTheRuntimeForgetsTheViews() { + preparation.prepare(CREATE_VIEW, SESSION, backend); + + preparation.forgetRuntime(ACCOUNT, SESSION.clusterKey()); + + assertThat(preparation.handlesDdl(REFRESH, SESSION), is(false)); + } +}