mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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
This commit is contained in:
1 parent
f72a1e535e
commit
5807e901a4
17 files changed
+2189
-119
No files matched your search
@@ -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) {
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String> 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<String, Object> streamLocks = new ConcurrentHashMap<>();
|
||||
private final StreamingViewSupport<KinesisViewBinding> 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<KinesisViewBinding> 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<KinesisViewBinding> 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<KinesisRecord> batch : batches(records)) {
|
||||
for (List<KinesisRecord> 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<List<KinesisRecord>> batches(List<KinesisRecord> records) {
|
||||
List<List<KinesisRecord>> batches = new ArrayList<>();
|
||||
List<KinesisRecord> 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<KinesisRecord> 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);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<MskViewBinding> support;
|
||||
private final Map<String, Object> 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<MskViewBinding> 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<MskViewBinding> 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<Integer, Long> ends = new TreeMap<>();
|
||||
Map<Integer, Long> checkpoints = new TreeMap<>();
|
||||
List<KafkaTopicPartition> fromBeginning = new ArrayList<>();
|
||||
List<KafkaOffsetDto> 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<KafkaTopicPartition> 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<Integer, Long> ends,
|
||||
Map<Integer, Long> checkpoints, Instant refreshTime) {
|
||||
Map<Integer, Long> pending = new TreeMap<>(ends);
|
||||
MskViewBinding current = view;
|
||||
long loaded = 0;
|
||||
int idlePolls = 0;
|
||||
while (!pending.isEmpty() && idlePolls < MAX_IDLE_POLLS) {
|
||||
List<KafkaRecordDto> records = unseen(restClient.poll(consumer, POLL_TIMEOUT), ends, checkpoints);
|
||||
if (records.isEmpty()) {
|
||||
idlePolls++;
|
||||
continue;
|
||||
}
|
||||
idlePolls = 0;
|
||||
for (List<KafkaRecordDto> batch : StreamingViewSupport.batches(records,
|
||||
record -> length(record.key()) + length(record.value()))) {
|
||||
backend.execute(loadSql(view, batch, refreshTime));
|
||||
Map<Integer, Long> 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<KafkaRecordDto> unseen(List<KafkaRecordDto> polled, Map<Integer, Long> ends,
|
||||
Map<Integer, Long> checkpoints) {
|
||||
List<KafkaRecordDto> 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<Permission> permissions = new ArrayList<>();
|
||||
permissions.add(new Permission("kafka:GetBootstrapBrokers", schema.clusterArn()));
|
||||
if ("IAM".equals(schema.authentication())) {
|
||||
AwsArnUtils.Arn cluster = clusterArn(schema);
|
||||
// cluster/<name>/<uuid>, whose topics and groups are topic/<name>/<uuid>/<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<String> 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<KafkaRecordDto> 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<KafkaHeaderDto> headers) {
|
||||
ObjectNode object = JSON.createObjectNode();
|
||||
Map<String, String> 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)) + "'";
|
||||
}
|
||||
}
|
||||
@@ -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<String, Long> 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<Integer, Long> lastLoaded) {
|
||||
Map<String, Long> 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);
|
||||
}
|
||||
}
|
||||
@@ -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<MskViewBinding> {
|
||||
|
||||
@Inject
|
||||
public MskViewRegistry(StorageFactory storageFactory) {
|
||||
super(storageFactory.<MskViewBinding>create("redshift", "redshift-msk-views.json",
|
||||
new TypeReference<>() { }));
|
||||
}
|
||||
|
||||
MskViewRegistry(AccountAwareStorageBackend<MskViewBinding> bindings) {
|
||||
super(bindings);
|
||||
}
|
||||
}
|
||||
+98
-20
@@ -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<RedshiftService> redshift) {
|
||||
MskStreamingViews mskViews, Instance<RedshiftService> 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<String, String, String> clusterRegion) {
|
||||
this(registry, kinesisSchemas, mskSchemas, functions, materializer, parser, glue, metadata, catalogLocks,
|
||||
views, inMemoryMskViews(), clusterRegion);
|
||||
}
|
||||
|
||||
private static MskStreamingViews inMemoryMskViews() {
|
||||
return new MskStreamingViews(new MskViewRegistry(
|
||||
AccountAwareStorageBackend.<MskViewBinding>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<String, String, String> 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<KinesisViewBinding> 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<MskViewBinding> 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<KinesisViewBinding> view = views.find(session, refresh.viewSchema(), refresh.viewName());
|
||||
@@ -277,6 +312,11 @@ public class SpectrumQueryPreparation {
|
||||
refreshStreamingView(view.get(), kinesis, session, backend);
|
||||
return true;
|
||||
}
|
||||
Optional<MskViewBinding> 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<KinesisViewBinding> 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<MskViewBinding> 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<String, ExternalSchemaBinding> bindings = bindingsOf(registry, session);
|
||||
if (statement.orElse(null) instanceof ExternalStatement.CreateTable && session.inTransaction()) {
|
||||
@@ -723,14 +769,15 @@ public class SpectrumQueryPreparation {
|
||||
|
||||
private <B extends SchemaBinding> void dropStreamingSchema(ExternalStatement.DropSchema statement, B binding,
|
||||
SchemaBindingRegistry<B> schemaRegistry,
|
||||
List<KinesisViewBinding> dependents,
|
||||
List<String> 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<String, KinesisSchemaBinding> kinesis,
|
||||
SpectrumSession session, BackendSql backend) {
|
||||
requireStreamingViewShape(view, session);
|
||||
Set<ExternalReferenceScanner.Reference> 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<String, MskSchemaBinding> msk,
|
||||
SpectrumSession session, BackendSql backend) {
|
||||
requireStreamingViewShape(view, session);
|
||||
Set<ExternalReferenceScanner.Reference> 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<ExternalReferenceScanner.Reference> 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<String, KinesisSchemaBinding> kinesis,
|
||||
@@ -793,6 +857,19 @@ public class SpectrumQueryPreparation {
|
||||
views.refresh(view, schema, catalogRegion(session), backend);
|
||||
}
|
||||
|
||||
private void refreshMskStreamingView(MskViewBinding view, Map<String, MskSchemaBinding> 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 <B extends SchemaBinding> Map<String, B> bindingsOf(SchemaBindingRegistry<B> schemaRegistry,
|
||||
SpectrumSession session) {
|
||||
Map<String, B> 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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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<B extends SchemaBinding> {
|
||||
|
||||
/** 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<B> registry;
|
||||
private final Function<B, String> viewSchema;
|
||||
private final Function<B, String> viewName;
|
||||
private final Function<B, String> sourceSchema;
|
||||
private final Function<B, String> sourceName;
|
||||
private final Map<String, Object> sourceLocks = new ConcurrentHashMap<>();
|
||||
|
||||
StreamingViewSupport(SchemaBindingRegistry<B> registry, Function<B, String> viewSchema,
|
||||
Function<B, String> viewName, Function<B, String> sourceSchema,
|
||||
Function<B, String> 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<B> 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 <R> List<List<R>> batches(List<R> records, ToLongFunction<R> size) {
|
||||
List<List<R>> batches = new ArrayList<>();
|
||||
List<R> 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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user