feat(redshift): materialize Glue external tables into PostgreSQL (#4996)

* feat(redshift): materialize Glue external tables into PostgreSQL

Add ExternalTableMaterializer, which loads a Glue-backed external table
into the cluster's PostgreSQL through a staging table, plus
SpectrumCatalogResolver (Glue binding first, phase-one catalog as a
fallback) and SpectrumGlueCsvAdapter (simple CSV tables keep the
streaming path and need no floci-duck sidecar).

The bound IAM role is enforced for every S3 object read, including
Iceberg metadata, manifests and data files, before DuckDB sees them.
SpectrumS3Reader now reads through the role as well, so a phase-one
external schema needs a real role associated with the cluster.

Spectrum semantics: hidden files and folder markers are ignored, a
partitioned table without registered partitions returns no rows, and a
sized string value wider than its column in bytes becomes NULL.

Also: PartitionProjection accepts IN lists for injected columns and
checks each table alias, S3Service hides the Spectrum scratch bucket from
ListBuckets, S3TransferException becomes public, and
FLOCI_SERVICES_REDSHIFT_SPECTRUM_MAX_ROWS is added.

* fix(redshift): harden external table loads against review findings

- A session outside a transaction waits for a slow load instead of
  failing after 30 seconds; only a session in a transaction keeps the
  timeout, since it can hold a PostgreSQL lock the Java lock cannot see.
- A missing S3 bucket is reported as XX000, not as access denied.
- A load failure goes to the log with its cause and returns a generic
  message, because the cause can carry DuckDB request text.
- The partition fingerprint includes input format and SerDe, so a format
  change at the same location reloads the table.
- A partition value wider than its sized string key becomes NULL, as a
  data column does, instead of failing the whole load.
- The first load of an account removes scratch objects left by a JVM
  that died mid-load, keeping those younger than an hour.
- Document why the phase-one reader enforces the role without the
  cluster association check.

* fix(redshift): use a real IAM role in the Spectrum compat test

The external schema now enforces its IAM role, so the compat test needs a
role that exists, trusts redshift.amazonaws.com and is associated with the
cluster. Create it through the IAM SDK client, pass it to CreateCluster and
delete it in the cleanup.

* fix(redshift): address review findings on the external table materializer

- PartitionProjection: a table name must end at an identifier boundary, comma
  separated sources are checked like FROM and JOIN sources, an unqualified
  injected column is accepted when exactly one source declares it, and a
  constant may be wrapped in parentheses.
- The partition fingerprint covers the whole descriptor (columns, formats,
  SerDe and parameters), and an Iceberg table is read on every query because
  its snapshot can change without any visible change to the Glue table.
- A transactional load that keeps the committed columns keeps the schema
  signature, so a view that depends on the table can still be refilled.
- Files under a hidden folder such as _temporary are ignored, not only
  hidden file names.
- The scratch bucket is told apart from a user bucket of the same name by a
  tag: a user bucket is listed, never written to, and never swept.
- Drop the SPECTRUM_MAX_ROWS row from the docs until routing makes the cap
  reachable.

* fix(redshift): verify slow-load wait with timeout
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-04 09:20:44 -04:00
1 parent 2c544fdb9f
commit 06ceec2aee
25 files changed
+3178 -82

No files matched your search

@@ -6,13 +6,64 @@ import io.github.hectorvent.floci.services.glue.model.Table;
import org.junit.jupiter.api.Test;
import java.util.List;
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.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertThrows;
class GlueTableResolverTest {
private static Column column(String name, String type) {
Column column = new Column();
column.setName(name);
column.setType(type);
return column;
}
private static Table table(String format, String location, List<Column> columns) {
StorageDescriptor descriptor = new StorageDescriptor();
descriptor.setInputFormat(format);
descriptor.setLocation(location);
descriptor.setColumns(columns);
Table table = new Table();
table.setName("events");
table.setStorageDescriptor(descriptor);
return table;
}
@Test
void readPlanForParquetUsesLocationGlob() {
GlueTableResolver.ReadPlan plan = GlueTableResolver.readPlan(table(
"org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat", "s3://bucket/events/",
List.of(column("id", "int"))));
assertThat(plan.fromClause(), equalTo("read_parquet('s3://bucket/events/**', union_by_name = true)"));
assertThat(plan.iceberg(), is(false));
}
@Test
void readPlanForIcebergUsesMetadataLocation() {
Table table = table(null, "s3://bucket/iceberg/", List.of(column("id", "int")));
table.setParameters(Map.of("table_type", "ICEBERG", "metadata_location", "s3://bucket/iceberg/metadata/v1.json"));
assertThat(GlueTableResolver.readPlan(table).fromClause(), equalTo("iceberg_scan('s3://bucket/iceberg/metadata/v1.json')"));
}
@Test
void readPlanAppendsPartitionKeysWithoutDuplicates() {
Table table = table("org.apache.hadoop.mapred.TextInputFormat", "s3://bucket/events",
List.of(column("id", "int"), column("dt", "string")));
table.setPartitionKeys(List.of(column("DT", "string"), column("region", "string")));
assertThat(GlueTableResolver.readPlan(table).columns().stream().map(Column::getName).toList(), contains("id", "dt", "region"));
}
@Test
void readPlanRejectsMissingLocation() {
assertThrows(IllegalArgumentException.class, () -> GlueTableResolver.readPlan(table("input", " ", List.of())));
}
@Test
void inferReadFunctionDetectsParquetFromInputFormat() {
StorageDescriptor sd = new StorageDescriptor();
@@ -64,4 +115,52 @@ class GlueTableResolverTest {
void isIcebergTableFalseWhenParametersMissing() {
assertThat(GlueTableResolver.isIcebergTable(new Table()), is(false));
}
@Test
void readPlanUsesExplicitCsvOptionsInsteadOfSniffingWhenTheTableDeclaresThem() {
Table table = table("org.apache.hadoop.mapred.TextInputFormat", "s3://bucket/events/",
List.of(column("id", "int"), column("name", "string")));
table.setParameters(Map.of("skip.header.line.count", "0", "serialization.null.format", "NA"));
StorageDescriptor.SerDeInfo serde = new StorageDescriptor.SerDeInfo();
serde.setParameters(Map.of("field.delim", "|", "quoteChar", "'", "escapeChar", "\\"));
table.getStorageDescriptor().setSerdeInfo(serde);
String from = GlueTableResolver.readPlan(table).fromClause();
assertThat(from, equalTo("read_csv('s3://bucket/events/**', header = false, delim = '|', quote = '''', "
+ "escape = '\\', nullstr = 'NA', columns = {'id': 'VARCHAR', 'name': 'VARCHAR'})"));
}
@Test
void readPlanDefaultsTheDelimiterToACommaWhenOnlyTheHeaderCountIsDeclared() {
Table table = table("org.apache.hadoop.mapred.TextInputFormat", "s3://bucket/events/",
List.of(column("id", "int")));
table.setParameters(Map.of("skip.header.line.count", "0"));
String from = GlueTableResolver.readPlan(table).fromClause();
assertThat(from, equalTo("read_csv('s3://bucket/events/**', header = false, delim = ',', "
+ "columns = {'id': 'VARCHAR'})"));
}
@Test
void readPlanTreatsOneSkippedLineAsAHeaderAndMoreAsSkippedRows() {
Table oneLine = table("org.apache.hadoop.mapred.TextInputFormat", "s3://bucket/events/",
List.of(column("id", "int")));
oneLine.setParameters(Map.of("skip.header.line.count", "1"));
Table twoLines = table("org.apache.hadoop.mapred.TextInputFormat", "s3://bucket/events/",
List.of(column("id", "int")));
twoLines.setParameters(Map.of("skip.header.line.count", "2"));
assertThat(GlueTableResolver.readPlan(oneLine).fromClause(), containsString("header = true"));
assertThat(GlueTableResolver.readPlan(twoLines).fromClause(), containsString("header = false, skip = 2"));
}
@Test
void readPlanKeepsSniffingWhenTheTableDeclaresNoCsvOptions() {
Table table = table("org.apache.hadoop.mapred.TextInputFormat", "s3://bucket/events/",
List.of(column("id", "int")));
assertThat(GlueTableResolver.readPlan(table).fromClause(), equalTo("read_csv_auto('s3://bucket/events/**')"));
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.quarkus.test.junit.QuarkusTest;
@@ -35,6 +36,15 @@ class RedshiftSpectrumIntegrationTest {
@Inject
S3Service s3Service;
@Inject
IamService iamService;
private static final String ROLE_NAME = "SpectrumItRole";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/" + ROLE_NAME;
private static final String TRUST_POLICY = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
private String clusterId;
private String bucket;
@@ -55,6 +65,17 @@ class RedshiftSpectrumIntegrationTest {
}
}
private Cluster createClusterWithRole(String identifier) {
if (iamService.findRole("000000000000", ROLE_NAME).isEmpty()) {
iamService.createRole(ROLE_NAME, "/", TRUST_POLICY, null, 0, null);
iamService.putRolePolicy(ROLE_NAME, "AllowS3", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":["s3:GetObject","s3:ListBucket"],"Resource":"*"}]}""");
}
return redshiftService.createCluster(identifier, "dc2.large", "admin", "Secret123",
null, List.of(), List.of(ROLE_ARN));
}
@AfterEach
void cleanUp() {
if (clusterId != null) {
@@ -75,13 +96,13 @@ class RedshiftSpectrumIntegrationTest {
s3Service.putObject(bucket, "events/part-1.csv",
"id,name\n1,Alice\n2,Bob\n".getBytes(StandardCharsets.UTF_8), "text/csv", null);
clusterId = "it-spectrum-" + System.nanoTime();
Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123");
Cluster cluster = createClusterWithRole(clusterId);
try (Connection connection = waitForConnection(cluster, "admin", "Secret123");
Statement statement = connection.createStatement()) {
statement.execute("CREATE EXTERNAL SCHEMA analytics FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'");
statement.execute("CREATE EXTERNAL SCHEMA analytics FROM DATA CATALOG DATABASE 'dev' IAM_ROLE '" + ROLE_ARN + "'");
SQLException duplicateSchema = assertThrows(SQLException.class, () -> statement.execute(
"CREATE EXTERNAL SCHEMA analytics FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'"));
"CREATE EXTERNAL SCHEMA analytics FROM DATA CATALOG DATABASE 'dev' IAM_ROLE '" + ROLE_ARN + "'"));
assertEquals("42P06", duplicateSchema.getSQLState());
statement.execute("CREATE EXTERNAL TABLE analytics.events (id INTEGER, name VARCHAR) "
+ "STORED AS TEXTFILE LOCATION 's3://" + bucket + "/events/' "
@@ -117,7 +138,7 @@ class RedshiftSpectrumIntegrationTest {
s3Service.putObject(bucket, "events/part-1.csv",
"id,name\n1,Alice\n2,Bob\n".getBytes(StandardCharsets.UTF_8), "text/csv", null);
clusterId = "it-spectrum-ext-" + System.nanoTime();
Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123");
Cluster cluster = createClusterWithRole(clusterId);
String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort()
+ "/dev?socketTimeout=20&loginTimeout=20";
@@ -125,7 +146,7 @@ class RedshiftSpectrumIntegrationTest {
.pollInterval(Duration.ofMillis(500)).ignoreExceptions()
.until(() -> DriverManager.getConnection(url, "admin", "Secret123"), Objects::nonNull);
Statement setup = connection.createStatement()) {
setup.execute("CREATE EXTERNAL SCHEMA analytics_ext FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'");
setup.execute("CREATE EXTERNAL SCHEMA analytics_ext FROM DATA CATALOG DATABASE 'dev' IAM_ROLE '" + ROLE_ARN + "'");
setup.execute("CREATE EXTERNAL TABLE analytics_ext.events (id INTEGER, name VARCHAR) "
+ "STORED AS TEXTFILE LOCATION 's3://" + bucket + "/events/' "
+ "TBLPROPERTIES ('skip.header.line.count'='1')");
@@ -156,7 +177,7 @@ class RedshiftSpectrumIntegrationTest {
"id,name\n1,Alice\n2,Bob\n3,Carol\n4,Dave\n5,Eve\n".getBytes(StandardCharsets.UTF_8),
"text/csv", null);
clusterId = "it-spectrum-fetch-" + System.nanoTime();
Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123");
Cluster cluster = createClusterWithRole(clusterId);
String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort()
+ "/dev?socketTimeout=20&loginTimeout=20";
@@ -164,7 +185,7 @@ class RedshiftSpectrumIntegrationTest {
.pollInterval(Duration.ofMillis(500)).ignoreExceptions()
.until(() -> DriverManager.getConnection(url, "admin", "Secret123"), Objects::nonNull);
Statement setup = connection.createStatement()) {
setup.execute("CREATE EXTERNAL SCHEMA analytics_fetch FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'");
setup.execute("CREATE EXTERNAL SCHEMA analytics_fetch FROM DATA CATALOG DATABASE 'dev' IAM_ROLE '" + ROLE_ARN + "'");
setup.execute("CREATE EXTERNAL TABLE analytics_fetch.events (id INTEGER, name VARCHAR) "
+ "STORED AS TEXTFILE LOCATION 's3://" + bucket + "/events/' "
+ "TBLPROPERTIES ('skip.header.line.count'='1')");
@@ -1,22 +1,42 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.Duration;
import java.time.Instant;
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.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class RedshiftRoleAccessTest {
@Test
void s3ResourcesInheritTheRoleArnPartition() {
String roleArn = "arn:aws-cn:iam::111111111111:role/spectrum-role";
assertEquals("arn:aws-cn:s3:::bucket", RedshiftRoleAccess.bucketArn(roleArn, "bucket"));
assertEquals("arn:aws-cn:s3:::bucket/key", RedshiftRoleAccess.objectArn(roleArn, "bucket", "key"));
}
@Test
void authorizeRoleActionThrowsWhenEnforcedPolicyDeniesTheAction() {
S3Service s3 = mock(S3Service.class);
@@ -35,6 +55,134 @@ class RedshiftRoleAccessTest {
assertThat(exception.getMessage(), containsString("S3 access denied"));
}
private static final String ACCOUNT = "111111111111";
private static final String ROLE_ARN = "arn:aws:iam::111111111111:role/spectrum-role";
private static final String TRUST_POLICY = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
private static final String EC2_TRUST_POLICY = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
private static IamService iamServiceWithRole(String trustPolicy) {
IamService iamService = mock(IamService.class);
IamRole role = mock(IamRole.class);
when(role.getAssumeRolePolicyDocument()).thenReturn(trustPolicy);
when(iamService.findRole(ACCOUNT, "spectrum-role")).thenReturn(Optional.of(role));
return iamService;
}
private static void assertRefused(String message, String iamRoleArn, IamService iamService,
String clusterAccount, List<String> associated) {
S3CopySimulator.S3TransferException exception = assertThrows(S3CopySimulator.S3TransferException.class,
() -> RedshiftRoleAccess.resolveRoleSession(iamRoleArn, iamService, clusterAccount, associated));
assertThat(exception.sqlState(), equalTo("42501"));
assertThat(exception.getMessage(), containsString(message));
}
@Test
void resolveRoleSessionRefusesMalformedNonRoleAndCrossAccountArns() {
IamService iamService = iamServiceWithRole(TRUST_POLICY);
assertRefused("malformed ARN", "not-an-arn", iamService, ACCOUNT, List.of());
assertRefused("not an IAM role ARN", "arn:aws:iam::111111111111:user/someone", iamService, ACCOUNT, List.of());
assertRefused("cross-account", ROLE_ARN, iamService, "222222222222", List.of(ROLE_ARN));
}
@Test
void resolveRoleSessionRefusesARoleTheClusterDoesNotHaveOrThatDoesNotExist() {
assertRefused("not associated", ROLE_ARN, iamServiceWithRole(TRUST_POLICY), ACCOUNT, List.of());
IamService missing = mock(IamService.class);
when(missing.findRole(ACCOUNT, "spectrum-role")).thenReturn(Optional.empty());
assertRefused("does not exist", ROLE_ARN, missing, ACCOUNT, List.of(ROLE_ARN));
}
@Test
void resolveRoleSessionRefusesARoleWhoseTrustPolicyExcludesRedshift() {
assertRefused("trust policy", ROLE_ARN, iamServiceWithRole(EC2_TRUST_POLICY), ACCOUNT, List.of(ROLE_ARN));
}
@Test
void resolveRoleSessionMintsASessionThatExpiresAfterTheRequestedTtl() {
IamService iamService = iamServiceWithRole(TRUST_POLICY);
Instant before = Instant.now();
RedshiftRoleAccess.RoleSession session = RedshiftRoleAccess.resolveRoleSession(
ROLE_ARN, iamService, ACCOUNT, List.of(ROLE_ARN), RedshiftRoleAccess.STREAMING_ROLE_SESSION_TTL);
ArgumentCaptor<Instant> expiry = ArgumentCaptor.forClass(Instant.class);
verify(iamService).registerSessionForAccount(eq(ACCOUNT), eq(session.accessKeyId()), anyString(),
eq(session.sessionToken()), eq(ROLE_ARN), expiry.capture(), isNull());
assertThat(expiry.getValue().isAfter(before.plus(Duration.ofMinutes(29))), equalTo(true));
assertThat(expiry.getValue().isBefore(before.plus(Duration.ofMinutes(31))), equalTo(true));
}
@Test
void authorizeRoleActionAllowsWhatTheIdentityPolicyGrants() {
S3Service s3 = mock(S3Service.class);
when(s3.isAuthEnforced()).thenReturn(true);
IamService iamService = mock(IamService.class);
when(iamService.resolvePrincipalContext(ROLE_ARN)).thenReturn(CallerContext.of(List.of("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}""")));
RedshiftRoleAccess.authorizeRoleAction(s3, iamService, ROLE_ARN, "s3:GetObject", "arn:aws:s3:::bucket/key");
}
@Test
void authorizeRoleListHonoursAnS3PrefixCondition() {
S3Service s3 = mock(S3Service.class);
when(s3.isAuthEnforced()).thenReturn(true);
IamService iamService = mock(IamService.class);
when(iamService.resolvePrincipalContext(ROLE_ARN)).thenReturn(CallerContext.of(List.of("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:ListBucket",
"Resource":"arn:aws:s3:::bucket","Condition":{"StringLike":{"s3:prefix":["events/*"]}}}]}""")));
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "token");
RedshiftRoleAccess.authorizeRoleList(s3, iamService, session, ROLE_ARN, "bucket", "events/");
S3CopySimulator.S3TransferException denied = assertThrows(S3CopySimulator.S3TransferException.class,
() -> RedshiftRoleAccess.authorizeRoleList(s3, iamService, session, ROLE_ARN, "bucket", "other/"));
assertThat(denied.sqlState(), equalTo("42501"));
}
@Test
void aMissingBucketIsNotReportedAsAccessDenied() {
S3Service s3 = mock(S3Service.class);
when(s3.isAuthEnforced()).thenReturn(false);
IamService iamService = mock(IamService.class);
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "token");
doThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist", 404)).when(s3)
.authorizeSignedListBucket("ASIAX", "token", "bucket");
S3CopySimulator.S3TransferException missing = assertThrows(S3CopySimulator.S3TransferException.class,
() -> RedshiftRoleAccess.authorizeRoleList(s3, iamService, session, ROLE_ARN, "bucket", ""));
assertThat(missing.sqlState(), equalTo("XX000"));
assertThat(missing.getMessage(), containsString("does not exist"));
}
@Test
void aBucketPolicyDenyIsReportedAsAccessDeniedForListAndRead() {
S3Service s3 = mock(S3Service.class);
when(s3.isAuthEnforced()).thenReturn(false);
IamService iamService = mock(IamService.class);
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "token");
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedListBucket("ASIAX", "token", "bucket");
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedGetObject("ASIAX", "token", "bucket", "key");
S3CopySimulator.S3TransferException list = assertThrows(S3CopySimulator.S3TransferException.class,
() -> RedshiftRoleAccess.authorizeRoleList(s3, iamService, session, ROLE_ARN, "bucket", ""));
S3CopySimulator.S3TransferException read = assertThrows(S3CopySimulator.S3TransferException.class,
() -> RedshiftRoleAccess.authorizeRoleRead(s3, iamService, session, ROLE_ARN, "bucket", "key"));
assertThat(list.sqlState(), equalTo("42501"));
assertThat(read.sqlState(), equalTo("42501"));
assertThat(read.getMessage(), containsString("s3://bucket/key"));
}
@Test
void authorizeRoleActionSkipsCheckWhenEnforcementDisabled() {
S3Service s3 = mock(S3Service.class);
@@ -0,0 +1,896 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
import io.github.hectorvent.floci.services.glue.GlueService;
import io.github.hectorvent.floci.services.glue.model.Column;
import io.github.hectorvent.floci.services.glue.model.Partition;
import io.github.hectorvent.floci.services.glue.model.StorageDescriptor;
import io.github.hectorvent.floci.services.glue.model.Table;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
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.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ExternalTableMaterializerTest {
private static final String ACCOUNT = "000000000000";
private static final ExternalSchemaBinding BINDING = new ExternalSchemaBinding(ACCOUNT, ACCOUNT + ":c",
"dev", "analytics", "lake", "arn:aws:iam::000000000000:role/R");
private static final String TRUST_POLICY = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
private FlociDuckClient duck;
private GlueService glue;
private S3Service s3;
private IamService iam;
private RecordingBackend backend;
private ExternalTableMaterializer materializer;
private static final class RecordingBackend implements BackendSql {
private final List<String> statements = new ArrayList<>();
@Override
public void execute(String sql) {
statements.add(sql);
}
@Override
public long copyIn(String copySql, InputStream data) {
statements.add(copySql);
return 2;
}
}
@BeforeEach
void setUp() {
duck = mock(FlociDuckClient.class);
glue = mock(GlueService.class);
s3 = mock(S3Service.class);
iam = mock(IamService.class);
IamRole role = mock(IamRole.class);
when(role.getAssumeRolePolicyDocument()).thenReturn(TRUST_POLICY);
when(iam.findRole(ACCOUNT, "R")).thenReturn(Optional.of(role));
EmulatorConfig config = mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS);
when(config.services().redshift().spectrumMaxRows()).thenReturn(1000L);
when(config.defaultRegion()).thenReturn("us-east-1");
when(duck.query(anyString(), any(), anyString())).thenReturn(List.of());
backend = new RecordingBackend();
materializer = new ExternalTableMaterializer(duck, glue, s3, iam, config);
when(s3.openObjectStream(eq(ExternalTableMaterializer.SCRATCH_BUCKET), anyString(), isNull()))
.thenReturn(new ByteArrayInputStream("id,name\n1,Alice\n2,Bob\n".getBytes(StandardCharsets.UTF_8)));
S3Object icebergMetadata = new S3Object("bucket", "events/metadata/v1.json",
"{\"current-snapshot-id\":\"1\",\"snapshots\":[{\"snapshot-id\":\"1\","
.concat("\"manifest-list\":\"s3://bucket/events/metadata/snap*.avro\"}]}")
.getBytes(StandardCharsets.UTF_8), "application/json");
when(s3.getObject(eq("bucket"), argThat(key -> key.startsWith("events/metadata/"))))
.thenReturn(icebergMetadata);
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("events/"), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(
List.of(new S3Object("bucket", "events/p1.csv", new byte[]{1}, "text/csv", "etag1")),
List.of(), false, null));
when(s3.isAuthEnforced()).thenReturn(false);
when(s3.listObjectsWithPrefixes(eq(ExternalTableMaterializer.SCRATCH_BUCKET), eq("spectrum-"), eq(""),
eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
}
@Test
void loadsThroughAStagingTableAndCachesUnchangedData() {
Table table = csvTable();
when(glue.getTable("lake", "events")).thenReturn(table);
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
assertThat(backend.statements.get(0), containsString("CREATE TEMP TABLE \"floci_spectrum_stg_"));
assertThat(backend.statements.get(0), containsString("\"id\" integer, \"name\" text"));
assertThat(backend.statements.get(1), containsString("COPY pg_temp.\"floci_spectrum_stg_"));
assertThat(backend.statements.get(2), containsString("CREATE TABLE \"analytics\".\"events\""));
assertThat(backend.statements.get(2), containsString("FROM pg_temp.\"floci_spectrum_stg_"));
assertThat(backend.statements.stream().noneMatch(sql -> sql.contains("events__stg")), equalTo(true));
verify(s3).openObjectStream(eq(ExternalTableMaterializer.SCRATCH_BUCKET), anyString(), isNull());
verify(s3, never()).getObject(eq(ExternalTableMaterializer.SCRATCH_BUCKET), anyString());
verify(duck).execute(argThat(sql -> sql.contains("LIMIT 1001")), isNull(), anyString(), eq(ACCOUNT));
int size = backend.statements.size();
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.CURRENT));
assertThat(backend.statements.size(), equalTo(size));
}
@Test
void readsOnlyTheExactS3ObjectsThatWereListedAndAuthorized() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("events/"), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(
new S3Object("bucket", "events/part*'one'.csv", new byte[]{1}, "text/csv", "etag1")),
List.of(), false, null));
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).execute(argThat(sql -> sql.contains("read_csv_auto(['s3://bucket/events/part[*]''one''.csv'])")
&& !sql.contains("/**")), isNull(), anyString(), eq(ACCOUNT));
}
@Test
void deniesIcebergDataFilesReferencedByManifestBeforeScanningThem() {
Table table = icebergTable("s3://bucket/events/metadata/v[1].json");
when(glue.getTable("lake", "events")).thenReturn(table);
when(s3.isAuthEnforced()).thenReturn(true);
when(duck.query(anyString(), any(), eq(ACCOUNT))).thenAnswer(invocation -> {
String sql = invocation.getArgument(0);
if (!sql.contains("status IN ('ADDED', 'EXISTING')") || sql.contains("content = 'DATA'")) {
return List.of();
}
return List.of(
Map.of("file_path", "s3://bucket/events/data.parquet", "manifest_content", "DATA",
"content", "EXISTING", "status", "ADDED"),
Map.of("file_path", "s3://bucket/private/deletes.parquet", "manifest_content", "DELETES",
"content", "POSITION_DELETES", "status", "ADDED"));
});
when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"},
{"Effect":"Deny","Action":"s3:GetObject","Resource":"arn:aws:s3:::bucket/private/deletes.parquet"}
]}""")));
SpectrumSqlException exception = assertThrows(SpectrumSqlException.class,
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(exception.sqlState(), equalTo("42501"));
verify(duck).query(argThat(sql -> sql.contains("iceberg_metadata('s3://bucket/events/metadata/v[[]1].json')")),
any(), eq(ACCOUNT));
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
}
@Test
void deniesIcebergManifestBeforeTheMetadataScanReadsIt() {
Table table = icebergTable("s3://bucket/events/metadata/v1.json");
when(glue.getTable("lake", "events")).thenReturn(table);
when(s3.isAuthEnforced()).thenReturn(true);
when(duck.query(anyString(), any(), eq(ACCOUNT))).thenAnswer(invocation -> {
String sql = invocation.getArgument(0);
if (sql.contains("read_avro")) {
return List.of(Map.of("manifest_path", "s3://bucket/private/manifest.avro"));
}
return List.of();
});
when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"},
{"Effect":"Deny","Action":"s3:GetObject","Resource":"arn:aws:s3:::bucket/private/manifest.avro"}
]}""")));
SpectrumSqlException exception = assertThrows(SpectrumSqlException.class,
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(exception.sqlState(), equalTo("42501"));
verify(duck).query(argThat(sql -> sql.contains("read_avro('s3://bucket/events/metadata/snap[*].avro')")),
any(), eq(ACCOUNT));
verify(duck, never()).query(argThat(sql -> sql.contains("iceberg_metadata")), any(), eq(ACCOUNT));
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
}
@Test
void emptyS3LocationCreatesAnEmptyTableWithoutCallingDuckDb() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("events/"), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
assertThat(backend.statements.size(), equalTo(2));
}
@Test
void doesNotCacheLoadsThatMayBeRolledBack() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(true), BINDING, "events");
assertThat(materializer.ensureCurrent(backend, session(true), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
}
@Test
void forgettingOneClusterInvalidatesOnlyItsFingerprints() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
SpectrumSession first = session(ACCOUNT + ":first", false);
SpectrumSession second = session(ACCOUNT + ":second", false);
ExternalSchemaBinding firstBinding = new ExternalSchemaBinding(ACCOUNT, first.clusterKey(), "dev",
"analytics", "lake", BINDING.iamRoleArn());
ExternalSchemaBinding secondBinding = new ExternalSchemaBinding(ACCOUNT, second.clusterKey(), "dev",
"analytics", "lake", BINDING.iamRoleArn());
materializer.ensureCurrent(backend, first, firstBinding, "events");
materializer.ensureCurrent(backend, second, secondBinding, "events");
int sizeBeforeForget = backend.statements.size();
materializer.forgetCluster(first.clusterKey());
assertThat(materializer.ensureCurrent(backend, first, firstBinding, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
assertThat(materializer.ensureCurrent(backend, second, secondBinding, "events"),
equalTo(ExternalTableMaterializer.Outcome.CURRENT));
assertThat(backend.statements.size(), equalTo(sizeBeforeForget + 3));
}
@Test
void missingGlueTableIsNotTreatedAsAnExternalTable() {
when(glue.getTable("lake", "native")).thenThrow(new AwsException("EntityNotFoundException", "missing", 400));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "native"),
equalTo(ExternalTableMaterializer.Outcome.NOT_EXTERNAL));
assertThat(backend.statements.size(), equalTo(0));
}
@Test
void deniesAListedObjectUsingItsExactKeyBeforeDuckDbReadsIt() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
when(s3.isAuthEnforced()).thenReturn(true);
S3Object publicObject = new S3Object("bucket", "events/public.csv", new byte[]{1}, "text/csv", "etag1");
S3Object privateObject = new S3Object("bucket", "events/private.csv", new byte[]{2}, "text/csv", "etag2");
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("events/"), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(publicObject, privateObject), List.of(), false, null));
when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"},
{"Effect":"Deny","Action":"s3:GetObject","Resource":"arn:aws:s3:::bucket/events/private.csv"}
]}""")));
SpectrumSqlException exception = assertThrows(SpectrumSqlException.class,
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(exception.sqlState(), equalTo("42501"));
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
}
@Test
void doesNotReuseAStagingTableCacheEntryAcrossRedshiftDatabases() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
SpectrumSession otherDatabase = new SpectrumSession(ACCOUNT, BINDING.clusterKey(), "reporting",
List.of(BINDING.iamRoleArn()), false);
ExternalSchemaBinding otherBinding = new ExternalSchemaBinding(ACCOUNT, BINDING.clusterKey(),
"reporting", "analytics", "lake", BINDING.iamRoleArn());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
int statementCount = backend.statements.size();
assertThat(materializer.ensureCurrent(backend, otherDatabase, otherBinding, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
assertThat(backend.statements.size(), equalTo(statementCount + 3));
}
@Test
void partitionedTableWithoutRegisteredPartitionsLoadsNoRows() {
Table table = csvTable();
table.setPartitionKeys(List.of(new Column("day", "string")));
when(glue.getTable("lake", "events")).thenReturn(table);
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
}
@Test
void readsObjectsFromRegisteredPartitionLocationsOutsideTheTableRoot() {
Table table = csvTable();
table.setPartitionKeys(List.of(new Column("day", "string")));
when(glue.getTable("lake", "events")).thenReturn(table);
StorageDescriptor partitionDescriptor = new StorageDescriptor();
partitionDescriptor.setLocation("s3://bucket/archived/day=2026-09-25/");
partitionDescriptor.setInputFormat("org.apache.hadoop.mapred.TextInputFormat");
partitionDescriptor.setColumns(table.getStorageDescriptor().getColumns());
Partition partition = new Partition();
partition.setValues(List.of("2026-09-25"));
partition.setStorageDescriptor(partitionDescriptor);
when(glue.getPartitions("lake", "events")).thenReturn(List.of(partition));
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("archived/day=2026-09-25/"), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(
new S3Object("bucket", "archived/day=2026-09-25/part.csv", new byte[]{1}, "text/csv", "partition-etag")),
List.of(), false, null));
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).execute(argThat(sql -> sql.contains("s3://bucket/archived/day=2026-09-25/part.csv")
&& sql.contains("CAST('2026-09-25' AS VARCHAR)") && sql.contains("AS \"day\"")),
any(), anyString(), eq(ACCOUNT));
}
@Test
void reloadRefillsTheExistingTableInPlaceSoDependentViewsSurvive() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("events/"), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(
List.of(new S3Object("bucket", "events/p1.csv", new byte[]{1, 2}, "text/csv", "etag2")),
List.of(), false, null));
backend.statements.clear();
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
String swap = backend.statements.getLast();
assertThat(swap, containsString("TRUNCATE \"analytics\".\"events\""));
assertThat(swap, containsString("INSERT INTO \"analytics\".\"events\" SELECT * FROM pg_temp.\"floci_spectrum_stg_"));
assertThat(swap.contains("RENAME TO"), equalTo(false));
assertThat(swap.contains("DROP TABLE IF EXISTS \"analytics\".\"events\";"), equalTo(false));
}
@Test
void reloadRunsTheInPlaceStepsInOrderAndDropsTheStagingTable() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
forceReload();
backend.statements.clear();
materializer.ensureCurrent(backend, session(false), BINDING, "events");
String swap = backend.statements.getLast();
int create = swap.indexOf("CREATE TABLE IF NOT EXISTS \"analytics\".\"events\"");
int truncate = swap.indexOf("TRUNCATE");
int insert = swap.indexOf("INSERT INTO");
int dropStaging = swap.indexOf("DROP TABLE pg_temp.\"floci_spectrum_stg_");
assertThat(create >= 0 && create < truncate && truncate < insert && insert < dropStaging, equalTo(true));
}
@Test
void aLoadInsideATransactionThatKeepsTheColumnsStillRefillsInPlaceAfterwards() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
materializer.ensureCurrent(backend, session(true), BINDING, "events");
backend.statements.clear();
materializer.ensureCurrent(backend, session(false), BINDING, "events");
assertThat(backend.statements.getLast(), containsString("CREATE TABLE IF NOT EXISTS \"analytics\".\"events\""));
assertThat(backend.statements.getLast(), not(containsString("DROP TABLE IF EXISTS \"analytics\"")));
}
@Test
void aTransactionalLoadThatReplacesTheTableIsNotTrustedAsItsCommittedColumns() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
Table changed = csvTable();
changed.setVersionId("2");
changed.getStorageDescriptor().setColumns(List.of(new Column("id", "bigint")));
when(glue.getTable("lake", "events")).thenReturn(changed);
materializer.ensureCurrent(backend, session(true), BINDING, "events");
backend.statements.clear();
materializer.ensureCurrent(backend, session(false), BINDING, "events");
assertThat(backend.statements.getLast(), containsString("CREATE TABLE \"analytics\".\"events\""));
}
@Test
void forgettingATableDropsItsSchemaSignatureSoItIsRecreated() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
materializer.forget(BINDING.clusterKey(), "dev", "analytics", "events");
backend.statements.clear();
materializer.ensureCurrent(backend, session(false), BINDING, "events");
assertThat(backend.statements.getLast(), containsString("CREATE TABLE \"analytics\".\"events\""));
}
private void forceReload() {
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("events/"), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(
List.of(new S3Object("bucket", "events/p1.csv", new byte[]{9}, "text/csv", "etag-changed")),
List.of(), false, null));
}
@Test
void schemaChangeReplacesTheTableInsteadOfRefillingIt() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
Table changed = csvTable();
changed.setVersionId("2");
changed.getStorageDescriptor().setColumns(List.of(new Column("id", "bigint")));
when(glue.getTable("lake", "events")).thenReturn(changed);
backend.statements.clear();
materializer.ensureCurrent(backend, session(false), BINDING, "events");
assertThat(backend.statements.getLast(), containsString("CREATE TABLE \"analytics\".\"events\""));
}
@Test
void deniesAnIcebergMetadataLocationOutsideTheTableLocation() {
Table table = icebergTable("s3://other-bucket/events/metadata/v1.metadata.json");
when(glue.getTable("lake", "events")).thenReturn(table);
SpectrumSqlException exception = assertThrows(SpectrumSqlException.class,
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(exception.sqlState(), equalTo("42501"));
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
}
@Test
void scansIcebergThroughTheSameGlobEscapedMetadataLiteralThatWasAuthorized() {
when(glue.getTable("lake", "events")).thenReturn(icebergTable("s3://bucket/events/metadata/v[1].json"));
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).execute(argThat(sql -> sql.contains("iceberg_scan('s3://bucket/events/metadata/v[[]1].json')")),
any(), anyString(), eq(ACCOUNT));
}
@Test
void deniesAnIcebergTableWhoseSnapshotsHaveNoCurrentSnapshot() {
when(s3.getObject(eq("bucket"), eq("events/metadata/v2.json"))).thenReturn(new S3Object("bucket",
"events/metadata/v2.json",
"{\"current-snapshot-id\":-1,\"snapshots\":[{\"snapshot-id\":\"1\",\"manifest-list\":\"s3://bucket/events/metadata/snap.avro\"}]}"
.getBytes(StandardCharsets.UTF_8), "application/json"));
when(glue.getTable("lake", "events")).thenReturn(icebergTable("s3://bucket/events/metadata/v2.json"));
SpectrumSqlException exception = assertThrows(SpectrumSqlException.class,
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(exception.sqlState(), equalTo("XX000"));
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
}
@Test
void ignoresHiddenFilesAndFolderMarkersLikeSpectrum() {
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("events/"), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(
new S3Object("bucket", "events/p1.csv", new byte[]{1}, "text/csv", "etag1"),
new S3Object("bucket", "events/_SUCCESS", new byte[0], "text/plain", "etag2"),
new S3Object("bucket", "events/.hidden.csv", new byte[]{1}, "text/csv", "etag3"),
new S3Object("bucket", "events/#draft.csv", new byte[]{1}, "text/csv", "etag4"),
new S3Object("bucket", "events/old.csv~", new byte[]{1}, "text/csv", "etag5"),
new S3Object("bucket", "events/nested/", new byte[0], "binary/octet-stream", "etag6")),
List.of(), false, null));
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).execute(argThat(sql -> sql.contains("s3://bucket/events/p1.csv")
&& !sql.contains("_SUCCESS") && !sql.contains(".hidden") && !sql.contains("#draft")
&& !sql.contains("old.csv~") && !sql.contains("nested/")), any(), anyString(), eq(ACCOUNT));
}
@Test
void ignoresFilesUnderAHiddenFolderBelowThePrefix() {
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("events/"), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(
new S3Object("bucket", "events/p1.csv", new byte[]{1}, "text/csv", "etag1"),
new S3Object("bucket", "events/_temporary/0/part.csv", new byte[]{1}, "text/csv", "etag2"),
new S3Object("bucket", "events/.staging/part.csv", new byte[]{1}, "text/csv", "etag3"),
new S3Object("bucket", "events/day=1/part.csv", new byte[]{1}, "text/csv", "etag4")),
List.of(), false, null));
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).execute(argThat(sql -> sql.contains("s3://bucket/events/p1.csv")
&& sql.contains("s3://bucket/events/day=1/part.csv")
&& !sql.contains("_temporary") && !sql.contains(".staging")), any(), anyString(), eq(ACCOUNT));
}
@Test
void reloadsWhenAPartitionChangesItsDelimiterOrColumnsAtTheSameLocationAndFormat() {
Table table = csvTable();
table.setPartitionKeys(List.of(new Column("day", "string")));
when(glue.getTable("lake", "events")).thenReturn(table);
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("events/"), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(
List.of(new S3Object("bucket", "events/p1.csv", new byte[]{1}, "text/csv", "etag1")),
List.of(), false, null));
Partition partition = partitionAt("org.apache.hadoop.mapred.TextInputFormat", table);
partition.getStorageDescriptor().setSerdeInfo(serdeWith(Map.of("field.delim", ",")));
when(glue.getPartitions("lake", "events")).thenReturn(List.of(partition));
materializer.ensureCurrent(backend, session(false), BINDING, "events");
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.CURRENT));
Partition delimiterChanged = partitionAt("org.apache.hadoop.mapred.TextInputFormat", table);
delimiterChanged.getStorageDescriptor().setSerdeInfo(serdeWith(Map.of("field.delim", "|")));
when(glue.getPartitions("lake", "events")).thenReturn(List.of(delimiterChanged));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
Partition columnsChanged = partitionAt("org.apache.hadoop.mapred.TextInputFormat", table);
columnsChanged.getStorageDescriptor().setSerdeInfo(serdeWith(Map.of("field.delim", "|")));
columnsChanged.getStorageDescriptor().setColumns(List.of(new Column("id", "bigint")));
when(glue.getPartitions("lake", "events")).thenReturn(List.of(columnsChanged));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
}
private static StorageDescriptor.SerDeInfo serdeWith(Map<String, String> parameters) {
StorageDescriptor.SerDeInfo serde = new StorageDescriptor.SerDeInfo();
serde.setSerializationLibrary("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe");
serde.setParameters(parameters);
return serde;
}
@Test
void readsAnIcebergTableOnEveryQueryBecauseItsSnapshotCanChangeUnseen() {
when(glue.getTable("lake", "events")).thenReturn(icebergTable("s3://bucket/events/metadata/v1.metadata.json"));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
}
@Test
void refusesToUseAScratchBucketNameThatBelongsToAUserBucket() {
when(s3.createBucket(eq(ExternalTableMaterializer.SCRATCH_BUCKET), anyString()))
.thenThrow(new AwsException("BucketAlreadyOwnedByYou", "owned", 409));
when(s3.getBucketTagging(ExternalTableMaterializer.SCRATCH_BUCKET)).thenReturn(Map.of());
when(glue.getTable("lake", "events")).thenReturn(csvTable());
SpectrumReadException exception = assertThrows(SpectrumReadException.class,
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(exception.getMessage(), containsString("not the Spectrum scratch bucket"));
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
verify(s3, never()).deleteObject(eq(ExternalTableMaterializer.SCRATCH_BUCKET), anyString());
}
@Test
void tagsTheScratchBucketItCreatesAndReusesATaggedOne() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(s3).putBucketTagging(ExternalTableMaterializer.SCRATCH_BUCKET, Map.of(
S3Service.INTERNAL_BUCKET_TAG_KEY, S3Service.REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE));
when(s3.createBucket(eq(ExternalTableMaterializer.SCRATCH_BUCKET), anyString()))
.thenThrow(new AwsException("BucketAlreadyOwnedByYou", "owned", 409));
when(s3.getBucketTagging(ExternalTableMaterializer.SCRATCH_BUCKET)).thenReturn(Map.of(
S3Service.INTERNAL_BUCKET_TAG_KEY, S3Service.REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE));
forceReload();
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
}
@Test
void authorizesTheIcebergMetadataObjectAsTheRole() {
when(glue.getTable("lake", "events")).thenReturn(icebergTable("s3://bucket/events/metadata/v1.metadata.json"));
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(s3).authorizeSignedGetObject(anyString(), anyString(), eq("bucket"), eq("events/metadata/v1.metadata.json"));
}
@Test
void listsWithTheTableLocationPrefixSoPrefixConditionsApply() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
when(s3.isAuthEnforced()).thenReturn(true);
when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"arn:aws:s3:::bucket",
"Condition":{"StringLike":{"s3:prefix":["events/*"]}}},
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}
]}""")));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
}
@Test
void deniesListingWhenThePrefixConditionDoesNotMatchTheTableLocation() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
when(s3.isAuthEnforced()).thenReturn(true);
when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"arn:aws:s3:::bucket",
"Condition":{"StringLike":{"s3:prefix":["other/*"]}}},
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}
]}""")));
SpectrumSqlException exception = assertThrows(SpectrumSqlException.class,
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(exception.sqlState(), equalTo("42501"));
}
@Test
void projectingTableWithoutRegisteredPartitionsIgnoresItsLocationTemplate() {
Table table = csvTable();
table.setPartitionKeys(List.of(new Column("dt", "string")));
table.setParameters(Map.of("projection.enabled", "true",
"storage.location.template", "s3://other-bucket/events/${dt}/"));
when(glue.getTable("lake", "events")).thenReturn(table);
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
verify(s3, never()).listObjectsWithPrefixes(eq("other-bucket"), anyString(), anyString(), anyInt(), any(), any());
}
@Test
void sweepsStaleScratchObjectsOnceAndKeepsRecentOnes() {
S3Object stale = new S3Object(ExternalTableMaterializer.SCRATCH_BUCKET, "spectrum-old.csv",
new byte[]{1}, "text/csv", "e1");
stale.setLastModified(Instant.now().minus(Duration.ofHours(3)));
S3Object recent = new S3Object(ExternalTableMaterializer.SCRATCH_BUCKET, "spectrum-new.csv",
new byte[]{1}, "text/csv", "e2");
when(s3.listObjectsWithPrefixes(eq(ExternalTableMaterializer.SCRATCH_BUCKET), eq("spectrum-"), eq(""),
eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(stale, recent), List.of(), false, null));
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
forceReload();
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(s3).deleteObject(ExternalTableMaterializer.SCRATCH_BUCKET, "spectrum-old.csv");
verify(s3, never()).deleteObject(ExternalTableMaterializer.SCRATCH_BUCKET, "spectrum-new.csv");
verify(s3, times(1)).listObjectsWithPrefixes(eq(ExternalTableMaterializer.SCRATCH_BUCKET),
eq("spectrum-"), eq(""), eq(1000), any(), any());
}
@Test
void nullsAPartitionValueWiderThanItsVarcharKey() {
Table table = csvTable();
table.setPartitionKeys(List.of(new Column("day", "varchar(3)")));
when(glue.getTable("lake", "events")).thenReturn(table);
StorageDescriptor descriptor = new StorageDescriptor();
descriptor.setLocation("s3://bucket/events/");
descriptor.setInputFormat("org.apache.hadoop.mapred.TextInputFormat");
descriptor.setColumns(table.getStorageDescriptor().getColumns());
Partition partition = new Partition();
partition.setValues(List.of("2026-09-25"));
partition.setStorageDescriptor(descriptor);
when(glue.getPartitions("lake", "events")).thenReturn(List.of(partition));
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).execute(argThat(sql -> sql.contains("CAST(NULL AS VARCHAR)")
&& !sql.contains("2026-09-25") && sql.contains("AS \"day\"")), any(), anyString(), eq(ACCOUNT));
}
@Test
void reloadsWhenAPartitionChangesFormatAtTheSameLocation() {
Table table = csvTable();
table.setPartitionKeys(List.of(new Column("day", "string")));
when(glue.getTable("lake", "events")).thenReturn(table);
Partition partition = partitionAt("org.apache.hadoop.mapred.TextInputFormat", table);
when(glue.getPartitions("lake", "events")).thenReturn(List.of(partition));
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("events/"), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(
List.of(new S3Object("bucket", "events/p1.csv", new byte[]{1}, "text/csv", "etag1")),
List.of(), false, null));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.CURRENT));
when(glue.getPartitions("lake", "events")).thenReturn(List.of(
partitionAt("org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat", table)));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
}
@Test
void aSessionOutsideATransactionWaitsOutASlowLoadInsteadOfTimingOut() throws Exception {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
CountDownLatch loading = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(invocation -> {
loading.countDown();
release.await(10, TimeUnit.SECONDS);
return null;
}).when(duck).execute(anyString(), any(), anyString(), anyString());
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Future<ExternalTableMaterializer.Outcome> first = executor.submit(
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(loading.await(10, TimeUnit.SECONDS), equalTo(true));
Future<ExternalTableMaterializer.Outcome> second = executor.submit(
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThrows(TimeoutException.class, () -> second.get(300, TimeUnit.MILLISECONDS));
release.countDown();
assertThat(first.get(10, TimeUnit.SECONDS), equalTo(ExternalTableMaterializer.Outcome.LOADED));
assertThat(second.get(10, TimeUnit.SECONDS), equalTo(ExternalTableMaterializer.Outcome.CURRENT));
} finally {
release.countDown();
executor.shutdownNow();
}
}
private Partition partitionAt(String inputFormat, Table table) {
StorageDescriptor descriptor = new StorageDescriptor();
descriptor.setLocation("s3://bucket/events/");
descriptor.setInputFormat(inputFormat);
descriptor.setColumns(table.getStorageDescriptor().getColumns());
Partition partition = new Partition();
partition.setValues(List.of("2026-09-25"));
partition.setStorageDescriptor(descriptor);
return partition;
}
@Test
void listsEveryPageOfTheTableLocation() {
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("events/"), eq(""), eq(1000), isNull(), any()))
.thenReturn(new S3Service.ListObjectsResult(
List.of(new S3Object("bucket", "events/p1.csv", new byte[]{1}, "text/csv", "etag1")),
List.of(), true, "page-2"));
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("events/"), eq(""), eq(1000), eq("page-2"), any()))
.thenReturn(new S3Service.ListObjectsResult(
List.of(new S3Object("bucket", "events/p2.csv", new byte[]{1}, "text/csv", "etag2")),
List.of(), false, null));
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).execute(argThat(sql -> sql.contains("s3://bucket/events/p1.csv")
&& sql.contains("s3://bucket/events/p2.csv")), any(), anyString(), eq(ACCOUNT));
}
private Table icebergTable(String metadataLocation) {
Table table = csvTable();
table.setParameters(Map.of("table_type", "ICEBERG", "metadata_location", metadataLocation));
return table;
}
private static SpectrumSession session(boolean inTransaction) {
return session(BINDING.clusterKey(), inTransaction);
}
private static SpectrumSession session(String clusterKey, boolean inTransaction) {
return new SpectrumSession(ACCOUNT, clusterKey, "dev", List.of(BINDING.iamRoleArn()), inTransaction);
}
private Table csvTable() {
Column id = new Column();
id.setName("id");
id.setType("int");
Column name = new Column();
name.setName("name");
name.setType("string");
StorageDescriptor descriptor = new StorageDescriptor();
descriptor.setInputFormat("org.apache.hadoop.mapred.TextInputFormat");
descriptor.setLocation("s3://bucket/events/");
descriptor.setColumns(List.of(id, name));
Table table = new Table();
table.setName("events");
table.setVersionId("1");
table.setStorageDescriptor(descriptor);
return table;
}
@Test
void deniesReadsThatOnlyTheBucketPolicyForbids() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedGetObject(anyString(), anyString(), eq("bucket"), eq("events/p1.csv"));
SpectrumSqlException exception = assertThrows(SpectrumSqlException.class,
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
assertThat(exception.sqlState(), equalTo("42501"));
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
}
@Test
void authorizesListingAndEveryObjectAsTheRoleSessionAndReleasesIt() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(s3).authorizeSignedListBucket(anyString(), anyString(), eq("bucket"));
verify(s3).authorizeSignedGetObject(anyString(), anyString(), eq("bucket"), eq("events/p1.csv"));
verify(iam).unregisterSession(eq(ACCOUNT), anyString());
}
@Test
void releasesTheRoleSessionWhenAuthorizationFails() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedListBucket(anyString(), anyString(), eq("bucket"));
assertThrows(SpectrumSqlException.class,
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
verify(iam).unregisterSession(eq(ACCOUNT), anyString());
}
@Test
void reloadsAfterTheSchemaWasForgottenEvenWhenNothingChanged() {
when(glue.getTable("lake", "events")).thenReturn(csvTable());
materializer.ensureCurrent(backend, session(false), BINDING, "events");
assertThat(materializer.loadedTables(BINDING.clusterKey(), "dev", "analytics"),
equalTo(Set.of("events")));
materializer.forgetSchema(BINDING.clusterKey(), "dev", "analytics");
assertThat(materializer.loadedTables(BINDING.clusterKey(), "dev", "analytics"), equalTo(Set.of()));
assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"),
equalTo(ExternalTableMaterializer.Outcome.LOADED));
}
@Test
void readsHeaderlessDelimitedCsvWithTheTablesDeclaredOptions() {
Table table = csvTable();
table.setParameters(Map.of("skip.header.line.count", "0"));
StorageDescriptor.SerDeInfo serde = new StorageDescriptor.SerDeInfo();
serde.setParameters(Map.of("field.delim", "|"));
table.getStorageDescriptor().setSerdeInfo(serde);
when(glue.getTable("lake", "events")).thenReturn(table);
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).execute(argThat(sql -> sql.contains("read_csv(['s3://bucket/events/p1.csv']")
&& sql.contains("header = false") && sql.contains("delim = '|'")
&& sql.contains("columns = {'id': 'VARCHAR', 'name': 'VARCHAR'}")),
isNull(), anyString(), eq(ACCOUNT));
}
@Test
void sparsePartitionKeepsTheTablesColumnsAndCsvOptions() {
Table table = csvTable();
table.setPartitionKeys(List.of(new Column("day", "string")));
table.setParameters(Map.of("skip.header.line.count", "0"));
when(glue.getTable("lake", "events")).thenReturn(table);
StorageDescriptor sparse = new StorageDescriptor();
sparse.setLocation("s3://bucket/archived/day=2026-09-25/");
Partition partition = new Partition();
partition.setValues(List.of("2026-09-25"));
partition.setStorageDescriptor(sparse);
when(glue.getPartitions("lake", "events")).thenReturn(List.of(partition));
when(s3.listObjectsWithPrefixes(eq("bucket"), eq("archived/day=2026-09-25/"), eq(""), eq(1000), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(
new S3Object("bucket", "archived/day=2026-09-25/part.csv", new byte[]{1}, "text/csv", "e")),
List.of(), false, null));
materializer.ensureCurrent(backend, session(false), BINDING, "events");
verify(duck).execute(argThat(sql -> sql.contains("header = false")
&& sql.contains("columns = {'id': 'VARCHAR', 'name': 'VARCHAR'}")
&& sql.contains("CAST('2026-09-25' AS VARCHAR)")), any(), anyString(), eq(ACCOUNT));
}
}
@@ -38,6 +38,16 @@ class GlueTypeMapperTest {
equalTo("COALESCE(CAST('\\x' || hex(\"payload\") AS VARCHAR), '\\N') AS \"payload\""));
}
@Test
void nullsSizedStringValuesWiderThanTheColumnInBytes() {
String expected = "COALESCE(CAST(CASE WHEN strlen(CAST(\"name\" AS VARCHAR)) > %d THEN NULL ELSE \"name\" END"
+ " AS VARCHAR), '\\N') AS \"name\"";
assertThat(GlueTypeMapper.duckProjection("name", "varchar(10)"), equalTo(expected.formatted(10)));
assertThat(GlueTypeMapper.duckProjection("name", "varchar"), equalTo(expected.formatted(256)));
assertThat(GlueTypeMapper.duckProjection("name", "char"), equalTo(expected.formatted(1)));
}
@Test
void canonicalisesRedshiftAliases() {
assertThat(GlueTypeMapper.canonicalGlueType("DOUBLE PRECISION"), equalTo("double"));
@@ -41,6 +41,19 @@ class SpectrumCatalogTest {
assertEquals(java.util.Optional.of(schema), catalog.schema(ACCOUNT, "dev", "analytics"));
}
@Test
void legacySchemaLookupKeepsTheSchemaWhoseLocationCoversTheTablesOfThisDatabase() {
String roleA = "arn:aws:iam::000000000000:role/A";
String roleB = "arn:aws:iam::000000000000:role/B";
catalog.createSchema(new SpectrumExternalSchema(ACCOUNT, "glue_a", "analytics", "s3://other/root/", roleA));
SpectrumExternalSchema owning = new SpectrumExternalSchema(
ACCOUNT, "glue_b", "analytics", "s3://warehouse/events/", roleB);
catalog.createSchema(owning);
catalog.createTable(table("events"));
assertEquals(java.util.Optional.of(owning), catalog.findLegacySchema(ACCOUNT, "dev", "analytics"));
}
@Test
void createsAndListsExternalTablesInStableNameOrder() {
SpectrumExternalTable second = table("zebra");
@@ -0,0 +1,101 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import io.github.hectorvent.floci.services.glue.model.Column;
import io.github.hectorvent.floci.services.glue.model.StorageDescriptor;
import io.github.hectorvent.floci.services.glue.model.Table;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SpectrumGlueCsvAdapterTest {
private static final String ACCOUNT = "000000000000";
private static final String ROLE = "arn:aws:iam::000000000000:role/Reader";
private static final ExternalSchemaBinding BINDING = new ExternalSchemaBinding(
ACCOUNT, "cluster-1", "dev", "analytics", "warehouse", ROLE);
private final SpectrumGlueCsvAdapter adapter = new SpectrumGlueCsvAdapter();
@Test
void adaptsDeclaredTextfileColumnsAndHeaderCount() {
Table table = csvTable("s3://events-bucket/events/");
table.getStorageDescriptor().setColumns(List.of(
new Column("id", "int"), new Column("name", "string"), new Column("code", "char")));
table.setParameters(Map.of("EXTERNAL", "TRUE", "skip.header.line.count", "1"));
SpectrumGlueCsvAdapter.CsvTable adapted = adapter.adapt(BINDING, table, ACCOUNT, "dev").orElseThrow();
assertEquals("s3://events-bucket/events/", adapted.table().location());
assertEquals(List.of(
new SpectrumColumn("id", SpectrumColumn.Type.INTEGER),
new SpectrumColumn("name", SpectrumColumn.Type.VARCHAR),
new SpectrumColumn("code", SpectrumColumn.Type.CHAR)), adapted.table().columns());
assertEquals(',', adapted.table().delimiter());
assertEquals(1, adapted.table().headerLines());
assertEquals(ACCOUNT, adapted.schema().accountId());
assertEquals("dev", adapted.schema().databaseName());
assertEquals("analytics", adapted.schema().schemaName());
assertEquals(ROLE, adapted.schema().iamRoleArn());
}
@Test
void adaptsUnsizedVarcharButLeavesOtherWidthsToTheDuckDbPath() {
Table unsized = csvTable("s3://events-bucket/events/");
unsized.getStorageDescriptor().setColumns(List.of(new Column("name", "varchar")));
assertEquals(List.of(new SpectrumColumn("name", SpectrumColumn.Type.VARCHAR)),
adapter.adapt(BINDING, unsized, ACCOUNT, "dev").orElseThrow().table().columns());
Table sized = csvTable("s3://events-bucket/events/");
sized.getStorageDescriptor().setColumns(List.of(new Column("name", "varchar(10)")));
assertTrue(adapter.adapt(BINDING, sized, ACCOUNT, "dev").isEmpty());
}
@Test
void adaptsExplicitQuoteAndEscapeProperties() {
Table table = csvTable("s3://events-bucket/events/");
StorageDescriptor.SerDeInfo serde = table.getStorageDescriptor().getSerdeInfo();
serde.setSerializationLibrary("org.apache.hadoop.hive.serde2.OpenCSVSerde");
serde.setParameters(Map.of("separatorChar", "|", "quoteChar", "~", "escapeChar", "!"));
SpectrumExternalTable adapted = adapter.adapt(BINDING, table, ACCOUNT, "dev").orElseThrow().table();
assertEquals('|', adapted.delimiter());
assertEquals('~', adapted.quote());
assertEquals('!', adapted.escape());
}
@Test
void refusesMissingLocationUnsupportedSerdeAndPartitionedTables() {
assertTrue(adapter.adapt(BINDING, csvTable(null), ACCOUNT, "dev").isEmpty());
Table unsupportedSerde = csvTable("s3://events-bucket/events/");
unsupportedSerde.getStorageDescriptor().getSerdeInfo()
.setSerializationLibrary("org.openx.data.jsonserde.JsonSerDe");
assertTrue(adapter.adapt(BINDING, unsupportedSerde, ACCOUNT, "dev").isEmpty());
Table partitioned = csvTable("s3://events-bucket/events/");
partitioned.setPartitionKeys(List.of(new Column("day", "date")));
assertTrue(adapter.adapt(BINDING, partitioned, ACCOUNT, "dev").isEmpty());
}
private static Table csvTable(String location) {
StorageDescriptor descriptor = new StorageDescriptor();
descriptor.setLocation(location);
descriptor.setInputFormat("org.apache.hadoop.mapred.TextInputFormat");
descriptor.setOutputFormat("org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat");
descriptor.setColumns(List.of(new Column("id", "int"), new Column("name", "string")));
StorageDescriptor.SerDeInfo serde = new StorageDescriptor.SerDeInfo();
serde.setSerializationLibrary("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe");
serde.setParameters(Map.of("field.delim", ",", "serialization.format", ","));
descriptor.setSerdeInfo(serde);
Table table = new Table();
table.setName("events");
table.setTableType("EXTERNAL_TABLE");
table.setStorageDescriptor(descriptor);
return table;
}
}
@@ -9,6 +9,7 @@ import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
@@ -16,20 +17,94 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class SpectrumMaterializerTest {
@Test
void materializesRowsAndSetsSurplusVarcharValuesToNull() throws Exception {
void materializesThroughBackendSqlWithoutBufferingRowsInTheCaller() throws Exception {
SpectrumS3Reader reader = mock(SpectrumS3Reader.class);
when(reader.read(any(SpectrumSession.class),
any(SpectrumExternalSchema.class),
any(SpectrumExternalTable.class)))
.thenReturn(Stream.of(new SpectrumRow(List.of("1", "Alice\nSmith")),
new SpectrumRow(Arrays.asList("2", null))));
SpectrumExternalTable table = new SpectrumExternalTable("000000000000", "dev", "analytics", "events",
List.of(new SpectrumColumn("id", SpectrumColumn.Type.INTEGER),
new SpectrumColumn("name", SpectrumColumn.Type.VARCHAR)),
"s3://warehouse/events/", ',', '"', '\\', "\\N", 0);
CapturingBackendSql backend = new CapturingBackendSql();
SpectrumMaterializer.Materialization materialized = new SpectrumMaterializer().materialize(
backend, new SpectrumSession("000000000000", "cluster-1", "dev", List.of(), false),
schema(), table, reader, "spectrum_tmp_test");
assertEquals("spectrum_tmp_test", materialized.identifier());
assertEquals(List.of(
"CREATE TEMP TABLE \"spectrum_tmp_test\" (\"id\" INTEGER, \"name\" VARCHAR(256))",
"COPY \"spectrum_tmp_test\" (\"id\", \"name\") FROM STDIN"), backend.commands);
assertEquals("1\tAlice\\nSmith\n2\t\\N\n",
new String(backend.copiedInput, StandardCharsets.UTF_8));
}
@Test
void copyFailureDropsTemporaryTableAndPreservesBackendSqlState() {
SpectrumS3Reader reader = mock(SpectrumS3Reader.class);
when(reader.read(any(SpectrumSession.class),
any(SpectrumExternalSchema.class),
any(SpectrumExternalTable.class)))
.thenReturn(Stream.of(new SpectrumRow(List.of("1"))));
SpectrumReadException backendFailure = new SpectrumReadException("42501", "COPY denied");
CapturingBackendSql backend = new CapturingBackendSql(backendFailure);
SpectrumReadException thrown = assertThrows(SpectrumReadException.class,
() -> new SpectrumMaterializer().materialize(backend, session(), schema(), oneColumnTable(), reader,
"spectrum_tmp_test"));
assertSame(backendFailure, thrown);
assertEquals(List.of(
"CREATE TEMP TABLE \"spectrum_tmp_test\" (\"id\" INTEGER)",
"COPY \"spectrum_tmp_test\" (\"id\") FROM STDIN",
"DROP TABLE IF EXISTS \"spectrum_tmp_test\""), backend.commands);
}
@Test
void rowReadFailurePreservesSqlStateAndDropsTemporaryTable() {
SpectrumS3Reader reader = mock(SpectrumS3Reader.class);
SpectrumReadException rowFailure = new SpectrumReadException("22000", "bad CSV row");
when(reader.read(any(SpectrumSession.class),
any(SpectrumExternalSchema.class),
any(SpectrumExternalTable.class)))
.thenReturn(Stream.generate(() -> {
throw rowFailure;
}));
CapturingBackendSql backend = new CapturingBackendSql();
SpectrumReadException thrown = assertThrows(SpectrumReadException.class,
() -> new SpectrumMaterializer().materialize(backend, session(), schema(), oneColumnTable(), reader,
"spectrum_tmp_test"));
assertSame(rowFailure, thrown);
assertEquals(List.of(
"CREATE TEMP TABLE \"spectrum_tmp_test\" (\"id\" INTEGER)",
"COPY \"spectrum_tmp_test\" (\"id\") FROM STDIN",
"DROP TABLE IF EXISTS \"spectrum_tmp_test\""), backend.commands);
}
@Test
void materializesRowsWithGeneratedIdentifierAndCopyFramingAndNullsSurplusVarcharValues() throws Exception {
try (ServerSocket listener = new ServerSocket(0); Socket backend = new Socket("localhost", listener.getLocalPort())) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<BackendCapture> captured = executor.submit(() -> serve(listener));
Future<byte[]> captured = executor.submit(() -> serve(listener));
SpectrumS3Reader reader = mock(SpectrumS3Reader.class);
when(reader.read(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()))
when(reader.read(any(), any()))
.thenReturn(Stream.of(new SpectrumRow(Arrays.asList("1", null)),
new SpectrumRow(List.of("two", "x")),
new SpectrumRow(List.of("3", "v".repeat(256))),
@@ -44,23 +119,22 @@ class SpectrumMaterializerTest {
.materialize(backend, table, null, reader);
new SpectrumMaterializer().cleanup(backend, materialization);
BackendCapture capture = captured.get();
byte[] copy = captured.get();
assertTrue(materialization.identifier().startsWith("spectrum_tmp_"));
assertFalse(materialization.identifier().contains("events"));
assertTrue(capture.createSql().contains("\"value\" VARCHAR(256)"));
String copyRows = new String(capture.copyRows(), StandardCharsets.UTF_8);
String copyRows = new String(copy, StandardCharsets.UTF_8);
assertTrue(copyRows.contains("1\t\\N\ntwo\tx\n"));
assertTrue(copyRows.contains("3\t" + "v".repeat(256) + "\n4\t\\N\n5\t\\N\n"));
executor.shutdownNow();
}
}
private static BackendCapture serve(ServerSocket listener) throws IOException {
private static byte[] serve(ServerSocket listener) throws IOException {
try (Socket socket = listener.accept()) {
InputStream input = socket.getInputStream();
OutputStream output = socket.getOutputStream();
ByteArrayOutputStream copyRows = new ByteArrayOutputStream();
String createSql = readQuery(input);
readQuery(input);
send(output, 'C', "CREATE 0\0".getBytes(StandardCharsets.UTF_8));
send(output, 'Z', new byte[]{'I'});
readQuery(input);
@@ -79,16 +153,15 @@ class SpectrumMaterializerTest {
readQuery(input);
send(output, 'C', "DROP TABLE\0".getBytes(StandardCharsets.UTF_8));
send(output, 'Z', new byte[]{'I'});
return new BackendCapture(createSql, copyRows.toByteArray());
return copyRows.toByteArray();
}
}
private static String readQuery(InputStream input) throws IOException {
private static void readQuery(InputStream input) throws IOException {
Frame frame = readFrame(input);
if (frame.type() != 'Q') {
throw new IOException("expected query");
}
return new String(frame.body(), 0, frame.body().length - 1, StandardCharsets.UTF_8);
}
private static Frame readFrame(InputStream input) throws IOException {
@@ -116,6 +189,50 @@ class SpectrumMaterializerTest {
private record Frame(char type, byte[] body) {
}
private record BackendCapture(String createSql, byte[] copyRows) {
private static SpectrumExternalSchema schema() {
return new SpectrumExternalSchema("000000000000", "dev", "analytics", "s3://warehouse/root/", null);
}
private static SpectrumSession session() {
return new SpectrumSession("000000000000", "cluster-1", "dev", List.of(), false);
}
private static SpectrumExternalTable oneColumnTable() {
return new SpectrumExternalTable("000000000000", "dev", "analytics", "events",
List.of(new SpectrumColumn("id", SpectrumColumn.Type.INTEGER)),
"s3://warehouse/events/", ',', '"', '\\', "\\N", 0);
}
private static final class CapturingBackendSql implements BackendSql {
private final ArrayList<String> commands = new ArrayList<>();
private final SpectrumReadException copyFailure;
private byte[] copiedInput;
private CapturingBackendSql() {
this(null);
}
private CapturingBackendSql(SpectrumReadException copyFailure) {
this.copyFailure = copyFailure;
}
@Override
public void execute(String sql) {
commands.add(sql);
}
@Override
public long copyIn(String copySql, InputStream data) {
commands.add(copySql);
if (copyFailure != null) {
throw copyFailure;
}
try {
copiedInput = data.readAllBytes();
} catch (IOException exception) {
throw new SpectrumReadException("22000", "Unable to capture Spectrum rows", exception);
}
return 2;
}
}
}
@@ -1,6 +1,10 @@
package io.github.hectorvent.floci.services.redshift.spectrum;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftRoleAccess;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.Test;
@@ -8,11 +12,17 @@ import org.junit.jupiter.api.Test;
import java.util.List;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class SpectrumS3ReaderTest {
@@ -43,6 +53,24 @@ class SpectrumS3ReaderTest {
new SpectrumRow(Arrays.asList("2", null, "false", "3.00", "2026-01-03"))), rows);
}
@Test
void keepsEscapedQuotesInsideQuotedFieldsWithoutJoiningTheNextRecord() {
S3Service s3 = mock(S3Service.class);
S3Object data = object("events/data.csv", "\"a\\\"b\",c\nnext,row\n");
when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null))
.thenReturn(new S3Service.ListObjectsResult(List.of(data), List.of(), false, null));
when(s3.getObject("warehouse", "events/data.csv")).thenReturn(data);
SpectrumExternalTable table = new SpectrumExternalTable("000000000000", "dev", "analytics", "events",
List.of(new SpectrumColumn("first", SpectrumColumn.Type.VARCHAR),
new SpectrumColumn("second", SpectrumColumn.Type.VARCHAR)),
"s3://warehouse/events/", ',', '"', '\\', "\\N", 0);
List<SpectrumRow> rows = new SpectrumS3Reader(s3, null).read(schema(), table).toList();
assertEquals(List.of(new SpectrumRow(List.of("a\"b", "c")),
new SpectrumRow(List.of("next", "row"))), rows);
}
@Test
void readsPrefixObjectsInSortedKeyOrder() {
S3Service s3 = mock(S3Service.class);
@@ -107,10 +135,83 @@ class SpectrumS3ReaderTest {
assertEquals("42501", exception.sqlState());
}
@Test
void deniesRoleGetObjectBeforeFetchingTheObject() {
S3Service s3 = mock(S3Service.class);
when(s3.isAuthEnforced()).thenReturn(true);
S3Object data = object("events/data.csv", "value\n");
when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null))
.thenReturn(new S3Service.ListObjectsResult(List.of(data), List.of(), false, null));
IamService iam = iamWithRole();
String role = "arn:aws:iam::000000000000:role/Reader";
when(iam.resolvePrincipalContext(role)).thenReturn(CallerContext.of(List.of(policy(
"s3:ListBucket", RedshiftRoleAccess.bucketArn(role, "warehouse")))));
SpectrumReadException exception = assertThrows(SpectrumReadException.class,
() -> new SpectrumS3Reader(s3, iam).read(session(role), schema(role), table(
SpectrumColumn.Type.VARCHAR)).toList());
assertEquals("42501", exception.sqlState());
verify(s3, never()).getObject("warehouse", "events/data.csv");
verify(s3, never()).authorizeAnonymousGetObject("warehouse", "events/data.csv");
}
@Test
void readsRowsWhenTheBoundRoleAllowsListingAndObjectReads() {
S3Service s3 = mock(S3Service.class);
when(s3.isAuthEnforced()).thenReturn(true);
S3Object data = object("events/data.csv", "hello\n");
when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null))
.thenReturn(new S3Service.ListObjectsResult(List.of(data), List.of(), false, null));
when(s3.getObject("warehouse", "events/data.csv")).thenReturn(data);
IamService iam = iamWithRole();
String role = "arn:aws:iam::000000000000:role/Reader";
when(iam.resolvePrincipalContext(role)).thenReturn(CallerContext.of(List.of(
policy("s3:ListBucket", RedshiftRoleAccess.bucketArn(role, "warehouse")),
policy("s3:GetObject", RedshiftRoleAccess.objectArn(role, "warehouse", "events/data.csv")))));
List<SpectrumRow> rows = new SpectrumS3Reader(s3, iam)
.read(session(role), schema(role), table(SpectrumColumn.Type.VARCHAR)).toList();
assertEquals(List.of(new SpectrumRow(List.of("hello"))), rows);
verify(s3, never()).authorizeAnonymousListBucket("warehouse");
verify(s3, never()).authorizeAnonymousGetObject("warehouse", "events/data.csv");
}
@Test
void deniesRoleListBucketBeforeListingObjects() {
S3Service s3 = mock(S3Service.class);
when(s3.isAuthEnforced()).thenReturn(true);
IamService iam = iamWithRole();
String role = "arn:aws:iam::000000000000:role/Reader";
when(iam.resolvePrincipalContext(role)).thenReturn(CallerContext.of(List.of(policy(
"s3:GetObject", RedshiftRoleAccess.objectArn(role, "warehouse", "events/data.csv")))));
SpectrumReadException exception = assertThrows(SpectrumReadException.class,
() -> new SpectrumS3Reader(s3, iam).read(session(role), schema(role), table(
SpectrumColumn.Type.VARCHAR)).toList());
assertEquals("42501", exception.sqlState());
verify(s3, never()).listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null);
}
private static SpectrumExternalSchema schema() {
return new SpectrumExternalSchema("000000000000", "dev", "analytics", "s3://warehouse/root/", null);
}
private static SpectrumExternalSchema schema(String role) {
return new SpectrumExternalSchema("000000000000", "dev", "analytics", "s3://warehouse/root/", role);
}
private static SpectrumSession session(String role) {
return new SpectrumSession("000000000000", "cluster-1", "dev", List.of(role), false);
}
private static String policy(String action, String resource) {
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\""
+ action + "\",\"Resource\":\"" + resource + "\"}]}";
}
private static SpectrumExternalTable table(SpectrumColumn.Type type) {
return new SpectrumExternalTable("000000000000", "dev", "analytics", "events",
List.of(new SpectrumColumn("value", type)), "s3://warehouse/events/", ',', '"', '\\', "\\N", 0);
@@ -119,4 +220,71 @@ class SpectrumS3ReaderTest {
private static S3Object object(String key, String content) {
return new S3Object("warehouse", key, content.getBytes(StandardCharsets.UTF_8), "text/csv");
}
@Test
void deniesReadsThatOnlyTheBucketPolicyForbids() {
S3Service s3 = mock(S3Service.class);
when(s3.isAuthEnforced()).thenReturn(true);
S3Object data = object("events/data.csv", "value\n");
when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null))
.thenReturn(new S3Service.ListObjectsResult(List.of(data), List.of(), false, null));
IamService iam = iamWithRole();
String role = "arn:aws:iam::000000000000:role/Reader";
when(iam.resolvePrincipalContext(role)).thenReturn(CallerContext.of(List.of(
policy("s3:ListBucket", RedshiftRoleAccess.bucketArn(role, "warehouse")),
policy("s3:GetObject", RedshiftRoleAccess.objectArn(role, "warehouse", "events/data.csv")))));
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedGetObject(anyString(), anyString(), eq("warehouse"), eq("events/data.csv"));
SpectrumReadException exception = assertThrows(SpectrumReadException.class,
() -> new SpectrumS3Reader(s3, iam).read(session(role), schema(role), table(
SpectrumColumn.Type.VARCHAR)).toList());
assertEquals("42501", exception.sqlState());
verify(s3, never()).getObject("warehouse", "events/data.csv");
}
@Test
void closingTheStreamReleasesTheRoleSession() {
S3Service s3 = mock(S3Service.class);
S3Object data = object("events/data.csv", "hello\n");
when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null))
.thenReturn(new S3Service.ListObjectsResult(List.of(data), List.of(), false, null));
when(s3.getObject("warehouse", "events/data.csv")).thenReturn(data);
IamService iam = iamWithRole();
String role = "arn:aws:iam::000000000000:role/Reader";
try (Stream<SpectrumRow> rows = new SpectrumS3Reader(s3, iam)
.read(session(role), schema(role), table(SpectrumColumn.Type.VARCHAR))) {
assertEquals(1, rows.count());
}
verify(s3).authorizeSignedListBucket(anyString(), anyString(), eq("warehouse"));
verify(s3).authorizeSignedGetObject(anyString(), anyString(), eq("warehouse"), eq("events/data.csv"));
verify(iam).unregisterSession(eq("000000000000"), anyString());
}
@Test
void releasesTheRoleSessionWhenListingIsDenied() {
S3Service s3 = mock(S3Service.class);
IamService iam = iamWithRole();
String role = "arn:aws:iam::000000000000:role/Reader";
doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3)
.authorizeSignedListBucket(anyString(), anyString(), eq("warehouse"));
assertThrows(SpectrumReadException.class, () -> new SpectrumS3Reader(s3, iam)
.read(session(role), schema(role), table(SpectrumColumn.Type.VARCHAR)).toList());
verify(iam).unregisterSession(eq("000000000000"), anyString());
}
private static IamService iamWithRole() {
IamService iam = mock(IamService.class);
IamRole role = mock(IamRole.class);
when(role.getAssumeRolePolicyDocument()).thenReturn("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}""");
when(iam.findRole("000000000000", "Reader")).thenReturn(Optional.of(role));
return iam;
}
}
@@ -144,6 +144,34 @@ class S3ServiceTest {
assertEquals(2, buckets.size());
}
@Test
void listBucketsHidesSpectrumScratchBucketButKeepsOtherInternalPrefixBuckets() {
s3Service.createBucket("bucket-a", "us-east-1");
s3Service.createBucket(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET, "us-east-1");
s3Service.putBucketTagging(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET, Map.of(
S3Service.INTERNAL_BUCKET_TAG_KEY, S3Service.REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE));
String userBucket = S3Service.INTERNAL_BUCKET_PREFIX + "customer-data";
s3Service.createBucket(userBucket, "us-east-1");
List<Bucket> buckets = s3Service.listBuckets();
assertEquals(2, buckets.size());
assertTrue(buckets.stream().anyMatch(bucket -> "bucket-a".equals(bucket.getName())));
assertTrue(buckets.stream().anyMatch(bucket -> userBucket.equals(bucket.getName())));
assertFalse(buckets.stream().anyMatch(bucket ->
S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET.equals(bucket.getName())));
}
@Test
void listBucketsKeepsAUserBucketThatOnlySharesTheScratchBucketName() {
s3Service.createBucket(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET, "us-east-1");
List<Bucket> buckets = s3Service.listBuckets();
assertEquals(1, buckets.size());
assertEquals(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET, buckets.get(0).getName());
}
@Test
void putObjectLastModifiedHasMillisecondPrecision() {
s3Service.createBucket("test-bucket", null);