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:
Vũ Thế Huy authored and GitHub committed 2026-11-23 13:35:08 -04:00
1 parent f72a1e535e
commit 5807e901a4
17 files changed
+2189 -119

No files matched your search

@@ -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,
@@ -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<KafkaRecordDto> 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<KafkaOffsetDto> 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<KafkaRecordDto> 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<KafkaHeaderDto> 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<String> rows(Statement statement) throws SQLException {
List<String> 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());
}
}
}
@@ -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"));
}
}
@@ -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.<MskViewBinding>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<Integer> 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<String> 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<String> 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<KafkaRecordDto> 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<List<Permission>> 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<List<Permission>> 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));
}
}
@@ -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);
}
}
@@ -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<MskViewBinding>(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));
}
}
@@ -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);
}
@@ -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.<MskSchemaBinding>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.<MskViewBinding>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.<KinesisViewBinding>inMemory(ACCOUNT)),
null, null, null, Clock.systemUTC());
preparation = new SpectrumQueryPreparation(mock(ExternalCatalogRegistry.class),
new KinesisSchemaRegistry(AccountAwareStorageBackend.<KinesisSchemaBinding>inMemory(ACCOUNT)),
mskSchemas, new ExternalFunctionRegistry(AccountAwareStorageBackend.<ExternalFunctionBinding>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));
}
}