mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift): support Redshift UNLOAD to Parquet (#7548)
* feat(redshift): support UNLOAD to Parquet * refactor(redshift): share internal S3 scratch plumbing * fix(redshift): warn when UNLOAD staging cleanup fails
This commit is contained in:
1 parent
189521e5cc
commit
f7cf6fef6e
27 files changed
+1252
-167
No files matched your search
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
|
||||
import io.github.hectorvent.floci.services.iam.ScpProvider;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.s3.S3Controller;
|
||||
import io.github.hectorvent.floci.services.s3.S3ScratchSpace;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.scheduler.SchedulerController;
|
||||
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
|
||||
@@ -1623,7 +1624,7 @@ class IamEnforcementFilterTest {
|
||||
when(iamService.resolveCallerContext(eq("ASIASESSION"), any()))
|
||||
.thenReturn(CallerContext.of(List.of(identityPolicy)));
|
||||
when(iamService.resolveCallerArns("ASIASESSION")).thenReturn(Optional.of(callerArns));
|
||||
when(iamService.spectrumScratchResourceArn("ASIASESSION")).thenReturn(Optional.of(SCRATCH_OBJECT));
|
||||
when(iamService.scratchResourceArn("ASIASESSION")).thenReturn(Optional.of(SCRATCH_OBJECT));
|
||||
when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), anyString(), anyString(), anyString()))
|
||||
.thenReturn(List.of(resource));
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
@@ -1645,7 +1646,7 @@ class IamEnforcementFilterTest {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, assumedRoleArns(), NO_STATEMENTS);
|
||||
|
||||
newFilterWithRealEvaluator().filter(containerRequest);
|
||||
scratchFilter(S3ScratchSpace.SPECTRUM, true).filter(containerRequest);
|
||||
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
@@ -1657,7 +1658,7 @@ class IamEnforcementFilterTest {
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"s3:*\","
|
||||
+ "\"Resource\":\"*\"}]}");
|
||||
|
||||
newFilterWithRealEvaluator().filter(containerRequest);
|
||||
scratchFilter(S3ScratchSpace.SPECTRUM, true).filter(containerRequest);
|
||||
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
@@ -1669,7 +1670,7 @@ class IamEnforcementFilterTest {
|
||||
S3Service s3Service = mock(S3Service.class);
|
||||
when(s3ServiceProvider.isResolvable()).thenReturn(true);
|
||||
when(s3ServiceProvider.get()).thenReturn(s3Service);
|
||||
when(s3Service.isSpectrumScratchBucket(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET)).thenReturn(false);
|
||||
when(s3Service.isScratchBucket(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET)).thenReturn(false);
|
||||
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, assumedRoleArns(), NO_STATEMENTS);
|
||||
@@ -1689,7 +1690,7 @@ class IamEnforcementFilterTest {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
stubSignedS3Request(containerRequest, attempt[0], attempt[1], assumedRoleArns(), NO_STATEMENTS);
|
||||
|
||||
newFilterWithRealEvaluator().filter(containerRequest);
|
||||
scratchFilter(S3ScratchSpace.SPECTRUM, true).filter(containerRequest);
|
||||
|
||||
verify(containerRequest).abortWith(any(Response.class));
|
||||
}
|
||||
@@ -1703,7 +1704,7 @@ class IamEnforcementFilterTest {
|
||||
"arn:aws:iam::222233334444:user/alice", IamService.CallerArns.TYPE_USER, null, "alice",
|
||||
false), NO_STATEMENTS);
|
||||
|
||||
newFilterWithRealEvaluator().filter(containerRequest);
|
||||
scratchFilter(S3ScratchSpace.SPECTRUM, true).filter(containerRequest);
|
||||
|
||||
verify(containerRequest).abortWith(any(Response.class));
|
||||
}
|
||||
@@ -1712,13 +1713,72 @@ class IamEnforcementFilterTest {
|
||||
void anUnrelatedRoleSessionCannotWriteTheSpectrumScratchBucket() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, assumedRoleArns(), NO_STATEMENTS);
|
||||
when(iamService.spectrumScratchResourceArn("ASIASESSION")).thenReturn(Optional.empty());
|
||||
when(iamService.scratchResourceArn("ASIASESSION")).thenReturn(Optional.empty());
|
||||
|
||||
newFilterWithRealEvaluator().filter(containerRequest);
|
||||
scratchFilter(S3ScratchSpace.SPECTRUM, true).filter(containerRequest);
|
||||
|
||||
verify(containerRequest).abortWith(any(Response.class));
|
||||
}
|
||||
|
||||
private static final String UNLOAD_PREFIX = "arn:aws:s3:::floci-internal-redshift-unload-staging/"
|
||||
+ "unload/123e4567-e89b-12d3-a456-426614174000/";
|
||||
|
||||
private IamEnforcementFilter scratchFilter(S3ScratchSpace space, boolean internalBucket) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<S3Service> provider = mock(Instance.class);
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
when(provider.isResolvable()).thenReturn(true);
|
||||
when(provider.get()).thenReturn(s3);
|
||||
when(s3.isScratchBucket(space.bucketName())).thenReturn(internalBucket);
|
||||
return newFilterWithRealEvaluator(provider);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unloadScratchAccessIsScopedAheadOfRoleDenies() {
|
||||
for (String action : List.of("s3:GetObject", "s3:PutObject", "s3:AbortMultipartUpload", "s3:DeleteObject")) {
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
stubSignedS3Request(ctx, action, UNLOAD_PREFIX + "output.parquet/data_0.parquet", assumedRoleArns(),
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"s3:*\",\"Resource\":\"*\"}]}");
|
||||
when(iamService.scratchResourceArn("ASIASESSION")).thenReturn(Optional.of(UNLOAD_PREFIX));
|
||||
scratchFilter(S3ScratchSpace.UNLOAD, true).filter(ctx);
|
||||
verify(ctx, never()).abortWith(any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unloadScratchListingsCannotEscapeTheTransferPrefix() {
|
||||
for (String prefix : List.of("unload/123e4567-e89b-12d3-a456-426614174000/output.parquet/", "", "unload/", "other/")) {
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
stubSignedS3Request(ctx, "s3:ListBucket", "arn:aws:s3:::floci-internal-redshift-unload-staging", assumedRoleArns(), NO_STATEMENTS);
|
||||
when(iamService.scratchResourceArn("ASIASESSION")).thenReturn(Optional.of(UNLOAD_PREFIX));
|
||||
ctx.getUriInfo().getQueryParameters().putSingle("prefix", prefix);
|
||||
scratchFilter(S3ScratchSpace.UNLOAD, true).filter(ctx);
|
||||
if (prefix.startsWith("unload/123e4567-e89b-12d3-a456-426614174000/")) {
|
||||
verify(ctx, never()).abortWith(any());
|
||||
} else {
|
||||
verify(ctx).abortWith(any(Response.class));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unloadScratchAllowanceRejectsOtherKeysSessionsAndBuckets() {
|
||||
for (String resource : List.of("arn:aws:s3:::user-destination/file.parquet",
|
||||
"arn:aws:s3:::floci-internal-redshift-unload-staging/unload/other/input.csv", UNLOAD_PREFIX + "input.csv")) {
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
stubSignedS3Request(ctx, "s3:GetObject", resource, assumedRoleArns(), NO_STATEMENTS);
|
||||
when(iamService.scratchResourceArn("ASIASESSION"))
|
||||
.thenReturn(resource.equals(UNLOAD_PREFIX + "input.csv") ? Optional.empty() : Optional.of(UNLOAD_PREFIX));
|
||||
scratchFilter(S3ScratchSpace.UNLOAD, true).filter(ctx);
|
||||
verify(ctx).abortWith(any(Response.class));
|
||||
}
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
stubSignedS3Request(ctx, "s3:PutObject", UNLOAD_PREFIX + "input.csv", assumedRoleArns(), NO_STATEMENTS);
|
||||
when(iamService.scratchResourceArn("ASIASESSION")).thenReturn(Optional.of(UNLOAD_PREFIX));
|
||||
scratchFilter(S3ScratchSpace.UNLOAD, false).filter(ctx);
|
||||
verify(ctx).abortWith(any(Response.class));
|
||||
}
|
||||
|
||||
// FullAWSAccess baseline auto-attached to every OU/account when SCP enforcement is on.
|
||||
private static final String FULL_AWS_ACCESS =
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}";
|
||||
|
||||
@@ -2615,16 +2615,40 @@ class IamServiceTest {
|
||||
accountId, accessKeyId, "secret", "token",
|
||||
"arn:aws:iam::222233334444:role/R", Instant.now().plusSeconds(900), null);
|
||||
|
||||
assertTrue(service.spectrumScratchResourceArn(accessKeyId).isEmpty());
|
||||
assertTrue(service.scratchResourceArn(accessKeyId).isEmpty());
|
||||
|
||||
String scratchArn = "arn:aws:s3:::floci-internal-redshift-spectrum-scratch/spectrum-1234.csv";
|
||||
service.registerSpectrumScratchResource(accessKeyId, scratchArn);
|
||||
service.registerScratchResource(accessKeyId, scratchArn);
|
||||
|
||||
assertEquals(Optional.of(scratchArn), service.spectrumScratchResourceArn(accessKeyId));
|
||||
assertEquals(Optional.of(scratchArn), service.scratchResourceArn(accessKeyId));
|
||||
|
||||
service.clearSpectrumScratchResource(accessKeyId);
|
||||
service.clearScratchResource(accessKeyId);
|
||||
|
||||
assertTrue(service.spectrumScratchResourceArn(accessKeyId).isEmpty());
|
||||
assertTrue(service.scratchResourceArn(accessKeyId).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unloadScratchPrefixRegistrationAndClear() {
|
||||
String accountId = "222233334444";
|
||||
String accessKeyId = "ASIAUNLOAD";
|
||||
AccountAwareStorageBackend<SessionCredential> sessions = new AccountAwareStorageBackend<>(
|
||||
new InMemoryStorage<>(), null, "000000000000");
|
||||
IamService service = iamService(false, new InMemoryStorage<>(), sessions);
|
||||
|
||||
service.registerSessionForAccount(
|
||||
accountId, accessKeyId, "secret", "token",
|
||||
"arn:aws:iam::222233334444:role/R", Instant.now().plusSeconds(900), null);
|
||||
|
||||
assertTrue(service.scratchResourceArn(accessKeyId).isEmpty());
|
||||
|
||||
String scratchArn = "arn:aws:s3:::floci-internal-redshift-unload-staging/unload/123e4567-e89b-12d3-a456-426614174000/";
|
||||
service.registerScratchResource(accessKeyId, scratchArn);
|
||||
|
||||
assertEquals(Optional.of(scratchArn), service.scratchResourceArn(accessKeyId));
|
||||
|
||||
service.registerScratchResource(accessKeyId, null);
|
||||
|
||||
assertTrue(service.scratchResourceArn(accessKeyId).isEmpty());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
package io.github.hectorvent.floci.services.redshift;
|
||||
|
||||
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import io.github.hectorvent.floci.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
class RedshiftUnloadParquetIntegrationTest {
|
||||
@Inject
|
||||
RedshiftService redshift;
|
||||
@Inject
|
||||
S3Service s3;
|
||||
@Inject
|
||||
FlociDuckClient duck;
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() {
|
||||
SidecarContainersProfile.requireDocker();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@Timeout(180)
|
||||
@ValueSource(booleans = {false, true})
|
||||
void typedParquetRoundTripsOverSimpleAndNamedExtendedQueries(boolean extended) throws Exception {
|
||||
String id = "unload-pq-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String bucket = id;
|
||||
s3.createBucket(bucket, "us-east-1");
|
||||
Cluster cluster = redshift.createCluster(id, "dc2.large", "admin", "Secret123");
|
||||
try {
|
||||
await().atMost(Duration.ofSeconds(120)).pollInterval(Duration.ofSeconds(1))
|
||||
.until(() -> "available".equals(redshift.describeClusters(id).getFirst().getClusterStatus()));
|
||||
String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort()
|
||||
+ "/dev?socketTimeout=90&" + (extended ? "prepareThreshold=1" : "preferQueryMode=simple");
|
||||
try (Connection connection = DriverManager.getConnection(url, "admin", "Secret123");
|
||||
Statement statement = connection.createStatement()) {
|
||||
statement.execute("CREATE TEMP TABLE pq_src (id bigint, amount decimal(18,4), label text, "
|
||||
+ "optional text, day date, happened timestamp, active boolean)");
|
||||
statement.execute("INSERT INTO pq_src VALUES (9007199254740993, 12345678901234.5678, "
|
||||
+ "'comma,quote\"line\nnext', NULL, '2026-11-04', '2026-11-04 12:34:56.123456', true), "
|
||||
+ "(2, NULL, '', '', NULL, NULL, false)");
|
||||
String unload = "UNLOAD ('SELECT * FROM pq_src ORDER BY id') TO 's3://" + bucket
|
||||
+ "/data/' FORMAT AS PARQUET MANIFEST ALLOWOVERWRITE";
|
||||
try (PreparedStatement prepared = connection.prepareStatement(unload)) {
|
||||
if (extended) {
|
||||
assertNull(prepared.getMetaData());
|
||||
}
|
||||
prepared.execute();
|
||||
prepared.execute();
|
||||
}
|
||||
List<Map<String, Object>> rows = duck.query("SELECT id::VARCHAR AS id, amount::VARCHAR AS amount, "
|
||||
+ "label, optional, day::VARCHAR AS day, happened::VARCHAR AS happened, active "
|
||||
+ "FROM read_parquet('s3://" + bucket + "/data/*.parquet') ORDER BY id::BIGINT", null);
|
||||
assertEquals(2, rows.size());
|
||||
assertEquals("", rows.get(0).get("label"));
|
||||
assertEquals("", rows.get(0).get("optional"));
|
||||
assertNull(rows.get(0).get("amount"));
|
||||
assertEquals("9007199254740993", rows.get(1).get("id"));
|
||||
assertEquals("12345678901234.5678", rows.get(1).get("amount"));
|
||||
assertEquals("comma,quote\"line\nnext", rows.get(1).get("label"));
|
||||
assertNull(rows.get(1).get("optional"));
|
||||
assertEquals("2026-11-04", rows.get(1).get("day"));
|
||||
assertEquals("2026-11-04 12:34:56.123456", rows.get(1).get("happened"));
|
||||
assertEquals(true, rows.get(1).get("active"));
|
||||
S3Object data = s3.listObjects(bucket, "data/", null, 100).stream()
|
||||
.filter(object -> object.getKey().endsWith(".parquet")).findFirst().orElseThrow();
|
||||
byte[] bytes = s3.getObject(bucket, data.getKey()).getData();
|
||||
assertEquals("PAR1", new String(bytes, 0, 4, StandardCharsets.US_ASCII));
|
||||
assertEquals("PAR1", new String(bytes, bytes.length - 4, 4, StandardCharsets.US_ASCII));
|
||||
String manifest = new String(s3.getObject(bucket, "data/manifest").getData(), StandardCharsets.UTF_8);
|
||||
assertTrue(manifest.contains(data.getKey()));
|
||||
assertTrue(manifest.contains(String.valueOf(bytes.length)));
|
||||
try (PreparedStatement empty = connection.prepareStatement("UNLOAD ('SELECT * FROM pq_src WHERE false') "
|
||||
+ "TO 's3://" + bucket + "/empty/' PARQUET PARALLEL OFF")) {
|
||||
empty.execute();
|
||||
}
|
||||
List<Map<String, Object>> emptyCount = duck.query("SELECT count(*) AS n FROM read_parquet('s3://"
|
||||
+ bucket + "/empty/000.parquet')", null);
|
||||
assertEquals(0, ((Number) emptyCount.getFirst().get("n")).intValue());
|
||||
assertEquals(7, duck.query("DESCRIBE SELECT * FROM read_parquet('s3://" + bucket
|
||||
+ "/empty/000.parquet')", null).size());
|
||||
statement.execute("UNLOAD ('SELECT optional FROM pq_src ORDER BY id') TO 's3://"
|
||||
+ bucket + "/single-column/' PARQUET");
|
||||
List<Map<String, Object>> singleColumn = duck.query("SELECT optional FROM read_parquet('s3://"
|
||||
+ bucket + "/single-column/*.parquet')", null);
|
||||
assertEquals(2, singleColumn.size());
|
||||
assertEquals("", singleColumn.get(0).get("optional"));
|
||||
assertNull(singleColumn.get(1).get("optional"));
|
||||
statement.execute("UNLOAD ('SELECT id FROM generate_series(1, 250000) AS g(id) ORDER BY id') "
|
||||
+ "TO 's3://" + bucket + "/split/' PARQUET PARALLEL OFF MAXFILESIZE 65536 MANIFEST");
|
||||
List<S3Object> parts = s3.listObjects(bucket, "split/", null, 100).stream()
|
||||
.filter(object -> object.getKey().endsWith(".parquet")).toList();
|
||||
assertTrue(parts.size() > 1, "DuckDB should split at row-group boundaries");
|
||||
String splitManifest = new String(s3.getObject(bucket, "split/manifest").getData(), StandardCharsets.UTF_8);
|
||||
for (int i = 0; i < parts.size(); i++) {
|
||||
S3Object part = parts.get(i);
|
||||
assertEquals(String.format("split/%03d.parquet", i), part.getKey());
|
||||
assertTrue(splitManifest.contains(part.getKey()));
|
||||
assertTrue(splitManifest.contains(String.valueOf(part.getSize())));
|
||||
}
|
||||
List<Map<String, Object>> splitRows = duck.query("SELECT count(*) AS n, count(DISTINCT id) AS unique_ids "
|
||||
+ "FROM read_parquet('s3://" + bucket + "/split/*.parquet')", null);
|
||||
assertEquals(250000, ((Number) splitRows.getFirst().get("n")).intValue());
|
||||
assertEquals(250000, ((Number) splitRows.getFirst().get("unique_ids")).intValue());
|
||||
assertUnsupportedTypes(connection, statement, url, bucket);
|
||||
SQLException rejected = assertThrows(SQLException.class, () -> statement.execute(
|
||||
"UNLOAD ('SELECT missing FROM pq_src') TO 's3://" + bucket + "/bad/' PARQUET"));
|
||||
assertEquals("42703", rejected.getSQLState());
|
||||
try (ResultSet result = statement.executeQuery("SELECT 1")) {
|
||||
assertTrue(result.next());
|
||||
assertEquals(1, result.getInt(1));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
redshift.deleteCluster(id);
|
||||
for (S3Object object : s3.listObjects(bucket, null, null, 1000)) {
|
||||
s3.deleteObject(bucket, object.getKey());
|
||||
}
|
||||
s3.deleteBucket(bucket);
|
||||
}
|
||||
}
|
||||
private void assertUnsupportedTypes(Connection connection, Statement statement, String url, String bucket) throws Exception {
|
||||
int backendPid;
|
||||
try (ResultSet pid = statement.executeQuery("SELECT pg_backend_pid()")) {
|
||||
assertTrue(pid.next());
|
||||
backendPid = pid.getInt(1);
|
||||
}
|
||||
String numericUnload = "UNLOAD ('SELECT amount::numeric AS total FROM pq_src') TO 's3://"
|
||||
+ bucket + "/unsupported/' PARQUET";
|
||||
SQLException numeric = assertThrows(SQLException.class, () -> statement.execute(numericUnload));
|
||||
assertEquals("0A000", numeric.getSQLState());
|
||||
assertTrue(numeric.getMessage().contains("column \"total\""));
|
||||
assertTrue(numeric.getMessage().contains("NUMERIC without declared precision and scale"));
|
||||
assertTrue(numeric.getMessage().contains("DECIMAL(p,s)"));
|
||||
// Observe the rejected connection before sending it another command that could finish its transaction.
|
||||
try (Connection observer = DriverManager.getConnection(url, "admin", "Secret123");
|
||||
Statement inspection = observer.createStatement();
|
||||
ResultSet state = inspection.executeQuery("SELECT xact_start IS NULL FROM pg_stat_activity WHERE pid = " + backendPid)) {
|
||||
assertTrue(state.next());
|
||||
assertTrue(state.getBoolean(1), "Type rejection must not leave an implicit transaction open");
|
||||
}
|
||||
String uuidUnload = "UNLOAD ('SELECT NULL::uuid AS payload') TO 's3://" + bucket + "/unsupported/' PARQUET";
|
||||
SQLException uuid = assertThrows(SQLException.class, () -> statement.execute(uuidUnload));
|
||||
assertEquals("0A000", uuid.getSQLState());
|
||||
assertTrue(uuid.getMessage().contains("column \"payload\""));
|
||||
assertTrue(uuid.getMessage().contains("UUID (OID 2950)"));
|
||||
assertTrue(uuid.getMessage().contains("VARCHAR"));
|
||||
assertTrue(s3.listObjects(bucket, "unsupported/", null, 100).isEmpty());
|
||||
connection.setAutoCommit(false);
|
||||
try {
|
||||
statement.execute("SELECT 1");
|
||||
SQLException rejected = assertThrows(SQLException.class, () -> statement.execute(numericUnload));
|
||||
assertEquals("0A000", rejected.getSQLState());
|
||||
SQLException failedTransaction = assertThrows(SQLException.class, () -> statement.execute("SELECT 1"));
|
||||
assertEquals("25P02", failedTransaction.getSQLState());
|
||||
} finally {
|
||||
connection.rollback();
|
||||
connection.setAutoCommit(true);
|
||||
}
|
||||
statement.execute("SELECT 1");
|
||||
}
|
||||
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
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.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import io.github.hectorvent.floci.testing.SidecarContainersProfile;
|
||||
import io.github.hectorvent.floci.testing.SidecarS3AuthEnforcedProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarS3AuthEnforcedProfile.class)
|
||||
class RedshiftUnloadParquetS3AuthIntegrationTest {
|
||||
@Inject
|
||||
RedshiftService redshift;
|
||||
@Inject
|
||||
S3Service s3;
|
||||
@Inject
|
||||
IamService iam;
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() {
|
||||
SidecarContainersProfile.requireDocker();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(180)
|
||||
void destinationOnlyRoleCanConvertButDestinationDeniesStillApply() throws Exception {
|
||||
String name = "unload-auth-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String role = iam.createRole(name, "/", """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}
|
||||
""", null, 0, null).getArn();
|
||||
s3.createBucket(name, "us-east-1");
|
||||
iam.putRolePolicy(name, "destination-only", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"arn:aws:s3:::%s"},
|
||||
{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/*"},
|
||||
{"Effect":"Deny","Action":"s3:*","Resource":["arn:aws:s3:::floci-internal-redshift-unload-staging",
|
||||
"arn:aws:s3:::floci-internal-redshift-unload-staging/*"]}]}
|
||||
""".formatted(name, name));
|
||||
try {
|
||||
Cluster cluster = redshift.createCluster(name, "dc2.large", "admin", "Secret123", null, List.of(), List.of(role));
|
||||
await().atMost(Duration.ofSeconds(120)).until(() ->
|
||||
"available".equals(redshift.describeClusters(name).getFirst().getClusterStatus()));
|
||||
String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort() + "/dev?socketTimeout=60";
|
||||
try (Connection connection = DriverManager.getConnection(url, "admin", "Secret123");
|
||||
Statement statement = connection.createStatement()) {
|
||||
statement.execute("UNLOAD ('SELECT 1 AS id') TO 's3://" + name + "/out/' IAM_ROLE '" + role
|
||||
+ "' PARQUET MANIFEST PARALLEL OFF");
|
||||
assertTrue(s3.getObject(name, "out/000.parquet").getSize() > 0);
|
||||
assertTrue(s3.getObject(name, "out/manifest").getSize() > 0);
|
||||
assertTrue(s3.listObjects(S3Service.REDSHIFT_UNLOAD_STAGING_BUCKET, null, null, 100).isEmpty());
|
||||
assertTrue(s3.listBuckets().stream().noneMatch(bucket ->
|
||||
bucket.getName().equals(S3Service.REDSHIFT_UNLOAD_STAGING_BUCKET)));
|
||||
s3.putBucketPolicy(name, """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Principal":{"AWS":"%s"},
|
||||
"Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/denied/*"}]}
|
||||
""".formatted(role, name));
|
||||
SQLException denied = assertThrows(SQLException.class, () -> statement.execute(
|
||||
"UNLOAD ('SELECT 2 AS id') TO 's3://" + name + "/denied/' IAM_ROLE '" + role + "' PARQUET"));
|
||||
assertEquals("42501", denied.getSQLState());
|
||||
assertTrue(s3.listObjects(name, "denied/", null, 100).isEmpty());
|
||||
}
|
||||
} finally {
|
||||
redshift.deleteCluster(name);
|
||||
s3.deleteBucketPolicy(name);
|
||||
for (S3Object object : s3.listObjects(name, null, null, 100)) {
|
||||
s3.deleteObject(name, object.getKey());
|
||||
}
|
||||
s3.deleteBucket(name);
|
||||
iam.deleteRolePolicy(name, "destination-only");
|
||||
iam.deleteRole(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
-1
@@ -364,9 +364,26 @@ class CopyStatementParserTest {
|
||||
assertNull(CopyStatementParser.parse("UNLOAD ('select \\1') TO 's3://b/p/'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unloadAcceptsParquetFormatsAndRejectsTextOptions() {
|
||||
for (String format : List.of("PARQUET", "FORMAT PARQUET", "FORMAT AS PARQUET", "format as parquet")) {
|
||||
CopyStatementParser.S3Unload spec = unload("UNLOAD ('select 1') TO 's3://b/p/' "
|
||||
+ format + " MANIFEST ALLOWOVERWRITE PARALLEL OFF EXTENSION 'pq'");
|
||||
assertNotNull(spec);
|
||||
assertTrue(spec.parquet());
|
||||
assertTrue(spec.manifest());
|
||||
assertFalse(spec.parallel());
|
||||
assertEquals("pq", spec.extension());
|
||||
}
|
||||
for (String option : List.of("CSV", "FORMAT CSV", "GZIP", "HEADER", "ADDQUOTES", "ESCAPE",
|
||||
"DELIMITER ','", "NULL AS 'nil'", "PARQUET")) {
|
||||
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' PARQUET " + option), option);
|
||||
}
|
||||
assertFalse(unload("UNLOAD ('select 1') TO 's3://b/p/' EXTENSION 'parquet'").parquet());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unloadRejectsUnsupportedOptions() {
|
||||
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' PARQUET"));
|
||||
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' ENCRYPTED"));
|
||||
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' MASTER_SYMMETRIC_KEY 'k'"));
|
||||
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' KMS_KEY_ID 'k'"));
|
||||
|
||||
+2
-2
@@ -46,7 +46,7 @@ class RedshiftAuthProxyTest {
|
||||
int port = FreePorts.anyInterfacePort();
|
||||
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", 1, "admin", "password", "dev",
|
||||
mock(RdsSigV4Validator.class), realTls(), (user, password) -> PasswordValidator.AuthResult.REJECT,
|
||||
mock(S3Service.class), mock(IamService.class), "111111111111", List.of(), 5000, 5000, 10, null, audit);
|
||||
mock(S3Service.class), mock(IamService.class), "111111111111", List.of(), 5000, 5000, 10, null, audit, null);
|
||||
proxy.start(port);
|
||||
try (Socket client = new Socket("localhost", port)) {
|
||||
client.setSoTimeout(5000);
|
||||
@@ -79,7 +79,7 @@ class RedshiftAuthProxyTest {
|
||||
int port = FreePorts.anyInterfacePort();
|
||||
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(), "admin", "password", "dev",
|
||||
mock(RdsSigV4Validator.class), realTls(), (user, password) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
|
||||
mock(S3Service.class), mock(IamService.class), "111111111111", List.of(), 5000, 5000, 10, null, audit);
|
||||
mock(S3Service.class), mock(IamService.class), "111111111111", List.of(), 5000, 5000, 10, null, audit, null);
|
||||
proxy.start(port);
|
||||
try (Socket client = new Socket("localhost", port)) {
|
||||
client.setSoTimeout(5000);
|
||||
|
||||
+1
-1
@@ -78,7 +78,7 @@ class RedshiftInterceptingBridgeTest {
|
||||
s3Stub = Mockito.mock(S3Service.class);
|
||||
RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(
|
||||
bridgeClientEnd, bridgeBackendEnd, s3Stub, Mockito.mock(IamService.class), "000000000000", List.of(),
|
||||
spectrumInterceptor, "000000000000:c", "dev", null, audit, "analyst");
|
||||
spectrumInterceptor, "000000000000:c", "dev", null, audit, "analyst", null);
|
||||
bridgeThread = Thread.ofVirtual().name("bridge-under-test").start(bridge::run);
|
||||
}
|
||||
|
||||
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
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.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class RedshiftParquetWriterTest {
|
||||
@Test
|
||||
void mapsDeclaredNumericTypesAndRejectsLossyConversions() {
|
||||
assertEquals("DECIMAL(18,4)", RedshiftParquetWriter.type("amount", 1700, (18 << 16) + 4 + 4));
|
||||
assertEquals("BIGINT", RedshiftParquetWriter.type("amount", 20, -1));
|
||||
assertEquals("DATE", RedshiftParquetWriter.type("amount", 1082, -1));
|
||||
assertEquals("TIMESTAMP", RedshiftParquetWriter.type("amount", 1114, -1));
|
||||
assertThrows(S3CopySimulator.S3TransferException.class, () -> RedshiftParquetWriter.type("amount", 1700, -1));
|
||||
assertThrows(S3CopySimulator.S3TransferException.class, () -> RedshiftParquetWriter.type("amount", 17, -1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedErrorsIdentifyTheColumnTypeAndSuggestedCast() {
|
||||
for (int oid : List.of(17, 114, 2950, 3802, 1007, 99999)) {
|
||||
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
|
||||
() -> RedshiftParquetWriter.type("payload", oid, -1));
|
||||
assertEquals("0A000", error.sqlState());
|
||||
assertTrue(error.getMessage().contains("column \"payload\""));
|
||||
assertTrue(error.getMessage().contains("OID " + oid));
|
||||
assertTrue(error.getMessage().contains("Cast it explicitly"));
|
||||
}
|
||||
for (int modifier : List.of(-1, (40 << 16) + 2 + 4, (18 << 16) + 20 + 4,
|
||||
(18 << 16) + 0x7ff + 4)) {
|
||||
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
|
||||
() -> RedshiftParquetWriter.type("total", 1700, modifier));
|
||||
assertEquals("0A000", error.sqlState());
|
||||
assertTrue(error.getMessage().contains("column \"total\""));
|
||||
assertTrue(error.getMessage().contains("NUMERIC"));
|
||||
assertTrue(error.getMessage().contains("DECIMAL(p,s)"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void delegatesSizingToDuckDbAndCleansStagingOnSuccessAndFailure() throws Exception {
|
||||
for (boolean failure : List.of(false, true)) {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
FlociDuckClient duck = mock(FlociDuckClient.class);
|
||||
byte[] parquet = "PAR1payloadPAR1".getBytes(StandardCharsets.UTF_8);
|
||||
when(s3.openObjectStream(eq(RedshiftParquetWriter.STAGING_BUCKET), anyString(), isNull()))
|
||||
.thenReturn(new ByteArrayInputStream(parquet), new ByteArrayInputStream(parquet));
|
||||
when(duck.query(anyString(), anyString(), eq("123456789012")))
|
||||
.thenReturn(List.of(Map.of("filename", "s3://floci-internal-redshift-unload-staging/output/data_0.parquet"),
|
||||
Map.of("filename", "s3://floci-internal-redshift-unload-staging/output/data_1.parquet")));
|
||||
if (failure) {
|
||||
when(duck.query(anyString(), anyString(), eq("123456789012")))
|
||||
.thenThrow(new IllegalStateException("sidecar unavailable"));
|
||||
}
|
||||
List<RedshiftParquetWriter.Column> columns = List.of(
|
||||
new RedshiftParquetWriter.Column("a\"b", "BIGINT"),
|
||||
new RedshiftParquetWriter.Column("amount", "DECIMAL(18,4)"));
|
||||
byte[] csv = "1,123.4500\n".getBytes(StandardCharsets.UTF_8);
|
||||
RedshiftParquetWriter writer = writer(s3, duck);
|
||||
if (failure) {
|
||||
assertThrows(IllegalStateException.class, () -> writer.convert(csv, columns, "123456789012", null, 8192));
|
||||
} else {
|
||||
List<byte[]> files = writer.convert(csv, columns, "123456789012", null, 8192);
|
||||
assertEquals(2, files.size());
|
||||
assertArrayEquals(parquet, files.get(0));
|
||||
assertArrayEquals(parquet, files.get(1));
|
||||
}
|
||||
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
|
||||
verify(duck).query(sql.capture(), contains("SET threads = 1"), eq("123456789012"));
|
||||
assertTrue(sql.getValue().contains("columns = {'c0': 'BIGINT', 'c1': 'DECIMAL(18,4)'}"));
|
||||
assertTrue(sql.getValue().contains("c0 AS \"a\"\"b\""));
|
||||
assertTrue(sql.getValue().contains("COMPRESSION SNAPPY"));
|
||||
assertTrue(sql.getValue().contains("FILE_SIZE_BYTES 8192, RETURN_STATS true"));
|
||||
verify(s3).deleteObjectsWithPrefix(eq(RedshiftParquetWriter.STAGING_BUCKET), startsWith("unload/"), any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyResultRetainsSchemaWithoutInferringFromCsv() throws Exception {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
FlociDuckClient duck = mock(FlociDuckClient.class);
|
||||
when(duck.query(anyString(), anyString(), anyString()))
|
||||
.thenReturn(List.of(Map.of("filename", "s3://floci-internal-redshift-unload-staging/output/data_0.parquet")));
|
||||
when(s3.openObjectStream(anyString(), anyString(), isNull()))
|
||||
.thenReturn(new ByteArrayInputStream(new byte[0]));
|
||||
writer(s3, duck).convert(new byte[0], List.of(new RedshiftParquetWriter.Column("id", "INTEGER")),
|
||||
"123456789012", null, 8192);
|
||||
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
|
||||
verify(duck).query(sql.capture(), anyString(), eq("123456789012"));
|
||||
assertTrue(sql.getValue().contains("SELECT CAST(NULL AS INTEGER) AS \"id\" WHERE false"));
|
||||
assertFalse(sql.getValue().contains("read_csv"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void forwardsRoleSessionCredentialsToTheSidecar() throws Exception {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
FlociDuckClient duck = mock(FlociDuckClient.class);
|
||||
when(duck.query(anyString(), anyString(), eq("access"), eq("secret"), eq("token")))
|
||||
.thenReturn(List.of(Map.of("filename", "s3://floci-internal-redshift-unload-staging/output/data_0.parquet")));
|
||||
when(s3.openObjectStream(anyString(), anyString(), isNull()))
|
||||
.thenReturn(new ByteArrayInputStream(new byte[0]));
|
||||
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("access", "secret", "token");
|
||||
writer(s3, duck).convert(new byte[0], List.of(new RedshiftParquetWriter.Column("id", "INTEGER")),
|
||||
"123456789012", session, 8192);
|
||||
verify(duck).query(anyString(), anyString(), eq("access"), eq("secret"), eq("token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void registersAndRevokesStagingScopeEvenWhenConversionFails() throws Exception {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
IamService iam = mock(IamService.class);
|
||||
FlociDuckClient duck = mock(FlociDuckClient.class);
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
when(duck.query(anyString(), anyString(), eq("access"), eq("secret"), eq("token")))
|
||||
.thenThrow(new IllegalStateException("sidecar failed"));
|
||||
RedshiftParquetWriter writer = new RedshiftParquetWriter(duck, s3, iam, config);
|
||||
assertThrows(IllegalStateException.class, () -> writer.convert(new byte[0],
|
||||
List.of(new RedshiftParquetWriter.Column("id", "INTEGER")), "123456789012",
|
||||
new RedshiftRoleAccess.RoleSession("access", "secret", "token"), 8192));
|
||||
ArgumentCaptor<String> scopes = ArgumentCaptor.forClass(String.class);
|
||||
verify(iam).registerScratchResource(eq("access"), scopes.capture());
|
||||
verify(iam).clearScratchResource("access");
|
||||
assertTrue(scopes.getAllValues().get(0).matches(
|
||||
"arn:aws:s3:::floci-internal-redshift-unload-staging/unload/[0-9a-f-]{36}/"));
|
||||
verify(s3).deleteObjectsWithPrefix(eq(RedshiftParquetWriter.STAGING_BUCKET), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesToUseAnExistingUntaggedStagingBucket() {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
FlociDuckClient duck = mock(FlociDuckClient.class);
|
||||
when(s3.createInternalBucket(anyString(), anyString())).thenThrow(
|
||||
new AwsException("BucketAlreadyOwnedByYou", "exists", 409));
|
||||
assertThrows(IOException.class, () -> writer(s3, duck).convert(new byte[0],
|
||||
List.of(new RedshiftParquetWriter.Column("id", "INTEGER")), "123456789012", null, 8192));
|
||||
verifyNoInteractions(duck);
|
||||
verify(s3, never()).putBucketTagging(anyString(), any());
|
||||
verify(s3, never()).putObject(anyString(), anyString(), any(byte[].class), anyString(), any());
|
||||
}
|
||||
|
||||
private RedshiftParquetWriter writer(S3Service s3, FlociDuckClient duck) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.defaultRegion()).thenReturn("us-east-1");
|
||||
return new RedshiftParquetWriter(duck, s3, mock(IamService.class), config);
|
||||
}
|
||||
}
|
||||
+61
-2
@@ -56,6 +56,65 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
class S3CopySimulatorTest {
|
||||
|
||||
@Test
|
||||
void parquetSlicesWaitForCompleteCsvRecordsAndManifestUsesConvertedLengths() throws Exception {
|
||||
long previous = S3CopySimulator.UNLOAD_TARGET_FILE_BYTES;
|
||||
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = 3;
|
||||
try {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
RedshiftParquetWriter writer = mock(RedshiftParquetWriter.class);
|
||||
List<RedshiftParquetWriter.Column> columns = List.of(new RedshiftParquetWriter.Column("v", "VARCHAR"));
|
||||
byte[] parquet = "PAR1testPAR1".getBytes(StandardCharsets.UTF_8);
|
||||
when(writer.convert(any(), eq(columns), eq("000000000000"), isNull(), eq(3L))).thenReturn(List.of(parquet));
|
||||
CopyStatementParser.S3Unload spec = (CopyStatementParser.S3Unload) CopyStatementParser.parse(
|
||||
"UNLOAD ('select v from t') TO 's3://b/p/' PARQUET MANIFEST");
|
||||
try (S3CopySimulator.UnloadCollector collector = S3CopySimulator.prepareUnload(
|
||||
spec, s3, null, "000000000000", null, writer)) {
|
||||
collector.columns(columns);
|
||||
collector.accept("\"first\n".getBytes(StandardCharsets.UTF_8));
|
||||
verifyNoInteractions(writer);
|
||||
collector.accept("second\"\n".getBytes(StandardCharsets.UTF_8));
|
||||
collector.accept("last\n".getBytes(StandardCharsets.UTF_8));
|
||||
collector.complete();
|
||||
}
|
||||
ArgumentCaptor<byte[]> slices = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(writer, times(2)).convert(slices.capture(), eq(columns), eq("000000000000"), isNull(), eq(3L));
|
||||
assertEquals("\"first\nsecond\"\n", new String(slices.getAllValues().get(0), StandardCharsets.UTF_8));
|
||||
verify(s3).putObject(eq("b"), eq("p/0000_part_00.parquet"), eq(parquet), eq("application/octet-stream"), any());
|
||||
verify(s3).putObject(eq("b"), eq("p/0001_part_00.parquet"), eq(parquet), eq("application/octet-stream"), any());
|
||||
} finally {
|
||||
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = previous;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void duckDbPartsUseExistingFlociNamesAndManifestLengths() throws Exception {
|
||||
S3Service target = mock(S3Service.class);
|
||||
RedshiftParquetWriter writer = mock(RedshiftParquetWriter.class);
|
||||
List<RedshiftParquetWriter.Column> columns = List.of(new RedshiftParquetWriter.Column("v", "VARCHAR"));
|
||||
byte[] first = new byte[30];
|
||||
byte[] second = new byte[20];
|
||||
when(writer.convert(any(), eq(columns), eq("000000000000"), isNull(), eq(1024L)))
|
||||
.thenReturn(List.of(first, second));
|
||||
CopyStatementParser.S3Unload spec = (CopyStatementParser.S3Unload) CopyStatementParser.parse(
|
||||
"UNLOAD ('select v from t') TO 's3://b/p/' PARQUET MANIFEST MAXFILESIZE 1024");
|
||||
try (S3CopySimulator.UnloadCollector collector = S3CopySimulator.prepareUnload(
|
||||
spec, target, null, "000000000000", null, writer)) {
|
||||
collector.columns(columns);
|
||||
collector.accept("value\n".getBytes(StandardCharsets.UTF_8));
|
||||
collector.complete();
|
||||
}
|
||||
verify(target).putObject(eq("b"), eq("p/0000_part_00.parquet"), eq(first), anyString(), any());
|
||||
verify(target).putObject(eq("b"), eq("p/0001_part_00.parquet"), eq(second), anyString(), any());
|
||||
ArgumentCaptor<byte[]> manifest = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(target).putObject(eq("b"), eq("p/manifest"), manifest.capture(), eq("application/json"), any());
|
||||
String json = new String(manifest.getValue(), StandardCharsets.UTF_8);
|
||||
assertTrue(json.contains("p/0000_part_00.parquet"));
|
||||
assertTrue(json.contains("p/0001_part_00.parquet"));
|
||||
assertTrue(json.contains("30"));
|
||||
assertTrue(json.contains("20"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void quotedDefaultIsValidatedAsAnArnForCopyAndUnload() {
|
||||
IamService iamService = mock(IamService.class);
|
||||
@@ -69,7 +128,7 @@ class S3CopySimulatorTest {
|
||||
S3CopySimulator.S3TransferException copyError = assertThrows(S3CopySimulator.S3TransferException.class,
|
||||
() -> S3CopySimulator.prepareCopy(copy, s3, iamService, "000000000000", List.of(ROLE_ARN)));
|
||||
S3CopySimulator.S3TransferException unloadError = assertThrows(S3CopySimulator.S3TransferException.class,
|
||||
() -> S3CopySimulator.prepareUnload(unload, s3, iamService, "000000000000", List.of(ROLE_ARN)));
|
||||
() -> S3CopySimulator.prepareUnload(unload, s3, iamService, "000000000000", List.of(ROLE_ARN), null));
|
||||
assertEquals("42501", copyError.sqlState());
|
||||
assertEquals("42501", unloadError.sqlState());
|
||||
assertTrue(copyError.getMessage().contains("malformed ARN"), copyError.getMessage());
|
||||
@@ -88,7 +147,7 @@ class S3CopySimulatorTest {
|
||||
S3CopySimulator.S3TransferException copyError = assertThrows(S3CopySimulator.S3TransferException.class,
|
||||
() -> S3CopySimulator.prepareCopy(copy, s3, null, "000000000000", List.of()));
|
||||
S3CopySimulator.S3TransferException unloadError = assertThrows(S3CopySimulator.S3TransferException.class,
|
||||
() -> S3CopySimulator.prepareUnload(unload, s3, null, "000000000000", List.of()));
|
||||
() -> S3CopySimulator.prepareUnload(unload, s3, null, "000000000000", List.of(), null));
|
||||
assertEquals("42501", copyError.sqlState());
|
||||
assertEquals("42501", unloadError.sqlState());
|
||||
assertTrue(copyError.getMessage().contains("No default IAM role"));
|
||||
|
||||
+7
-7
@@ -245,9 +245,9 @@ class ExternalTableMaterializerTest {
|
||||
verify(duck).execute(argThat(sql -> sql.contains("LIMIT 1001")), isNull(), anyString(),
|
||||
startsWith("ASIA"), anyString(), notNull());
|
||||
verify(duck, never()).execute(anyString(), any(), anyString(), eq(ACCOUNT));
|
||||
verify(iam).registerSpectrumScratchResource(startsWith("ASIA"),
|
||||
verify(iam).registerScratchResource(startsWith("ASIA"),
|
||||
startsWith("arn:aws:s3:::floci-internal-redshift-spectrum-scratch/spectrum-"));
|
||||
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
|
||||
verify(iam).clearScratchResource(startsWith("ASIA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -265,7 +265,7 @@ class ExternalTableMaterializerTest {
|
||||
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
|
||||
|
||||
assertThat(exception.sqlState(), equalTo("42501"));
|
||||
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
|
||||
verify(iam).clearScratchResource(startsWith("ASIA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -301,7 +301,7 @@ class ExternalTableMaterializerTest {
|
||||
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
|
||||
|
||||
assertThat(exception.sqlState(), equalTo("58030"));
|
||||
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
|
||||
verify(iam).clearScratchResource(startsWith("ASIA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -321,7 +321,7 @@ class ExternalTableMaterializerTest {
|
||||
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
|
||||
|
||||
assertThat(exception.sqlState(), equalTo("58030"));
|
||||
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
|
||||
verify(iam).clearScratchResource(startsWith("ASIA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -340,7 +340,7 @@ class ExternalTableMaterializerTest {
|
||||
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
|
||||
|
||||
assertThat(exception.sqlState(), equalTo("58030"));
|
||||
verify(iam).clearSpectrumScratchResource(startsWith("ASIA"));
|
||||
verify(iam).clearScratchResource(startsWith("ASIA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -742,7 +742,7 @@ class ExternalTableMaterializerTest {
|
||||
SpectrumReadException exception = assertThrows(SpectrumReadException.class,
|
||||
() -> materializer.ensureCurrent(backend, session(false), BINDING, "events"));
|
||||
|
||||
assertThat(exception.getMessage(), containsString("not the Spectrum scratch bucket"));
|
||||
assertThat(exception.getMessage(), containsString("not Floci scratch space"));
|
||||
verify(duck, never()).execute(anyString(), any(), anyString(), anyString());
|
||||
verify(s3, never()).putBucketTagging(eq(ExternalTableMaterializer.SCRATCH_BUCKET), any());
|
||||
verify(s3, never()).deleteObject(eq(ExternalTableMaterializer.SCRATCH_BUCKET), anyString());
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
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.atomic.AtomicReference;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class S3ScratchSpaceTest {
|
||||
@ParameterizedTest
|
||||
@EnumSource(S3ScratchSpace.class)
|
||||
void createsTagsReusesAndRejectsUntaggedBuckets(S3ScratchSpace space) throws Exception {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
space.ensureBucket(s3, "us-east-1");
|
||||
AtomicReference<Map<String, String>> tags = new AtomicReference<>();
|
||||
verify(s3).putBucketTagging(eq(space.bucketName()), argThat(value -> {
|
||||
tags.set(value);
|
||||
return true;
|
||||
}));
|
||||
when(s3.createInternalBucket(anyString(), anyString())).thenThrow(
|
||||
new AwsException("BucketAlreadyOwnedByYou", "exists", 409));
|
||||
when(s3.getBucketTagging(space.bucketName())).thenReturn(tags.get());
|
||||
space.ensureBucket(s3, "us-east-1");
|
||||
verify(s3, times(1)).putBucketTagging(anyString(), any());
|
||||
when(s3.getBucketTagging(space.bucketName())).thenReturn(Map.of());
|
||||
assertThrows(IOException.class, () -> space.ensureBucket(s3, "us-east-1"));
|
||||
verify(s3, times(1)).putBucketTagging(anyString(), any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(S3ScratchSpace.class)
|
||||
void concurrentInitializationWaitsForTheInternalTag(S3ScratchSpace space) throws Exception {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
CountDownLatch tagging = new CountDownLatch(1);
|
||||
CountDownLatch releaseTag = new CountDownLatch(1);
|
||||
AtomicReference<Map<String, String>> tags = new AtomicReference<>(Map.of());
|
||||
when(s3.createInternalBucket(anyString(), anyString())).thenReturn(null).thenThrow(
|
||||
new AwsException("BucketAlreadyOwnedByYou", "exists", 409));
|
||||
doAnswer(invocation -> {
|
||||
tagging.countDown();
|
||||
assertTrue(releaseTag.await(10, TimeUnit.SECONDS));
|
||||
tags.set(invocation.getArgument(1));
|
||||
return null;
|
||||
}).when(s3).putBucketTagging(anyString(), any());
|
||||
when(s3.getBucketTagging(anyString())).thenAnswer(invocation -> tags.get());
|
||||
try (ExecutorService executor = Executors.newFixedThreadPool(2)) {
|
||||
Future<?> first = executor.submit(() -> { space.ensureBucket(s3, "us-east-1"); return null; });
|
||||
assertTrue(tagging.await(10, TimeUnit.SECONDS));
|
||||
AtomicReference<Thread> secondThread = new AtomicReference<>();
|
||||
Future<?> second = executor.submit(() -> {
|
||||
secondThread.set(Thread.currentThread());
|
||||
space.ensureBucket(s3, "us-east-1");
|
||||
return null;
|
||||
});
|
||||
try {
|
||||
await().atMost(Duration.ofSeconds(5)).until(() -> secondThread.get() != null
|
||||
&& secondThread.get().getState() == Thread.State.BLOCKED);
|
||||
verify(s3, times(1)).createInternalBucket(anyString(), anyString());
|
||||
} finally {
|
||||
releaseTag.countDown();
|
||||
}
|
||||
first.get(10, TimeUnit.SECONDS);
|
||||
second.get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -206,11 +206,14 @@ class S3ServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void listBucketsHidesSpectrumScratchBucketButKeepsOtherInternalPrefixBuckets() {
|
||||
void listBucketsHidesScratchBucketsButKeepsOtherInternalPrefixBuckets() {
|
||||
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));
|
||||
s3Service.createBucket(S3Service.REDSHIFT_UNLOAD_STAGING_BUCKET, "us-east-1");
|
||||
s3Service.putBucketTagging(S3Service.REDSHIFT_UNLOAD_STAGING_BUCKET, Map.of(
|
||||
S3Service.INTERNAL_BUCKET_TAG_KEY, S3Service.REDSHIFT_UNLOAD_STAGING_TAG_VALUE));
|
||||
String userBucket = S3Service.INTERNAL_BUCKET_PREFIX + "customer-data";
|
||||
s3Service.createBucket(userBucket, "us-east-1");
|
||||
|
||||
@@ -224,13 +227,19 @@ class S3ServiceTest {
|
||||
}
|
||||
|
||||
@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());
|
||||
void scratchSetupRejectsUserBucketsAndReusesInternalBuckets() throws Exception {
|
||||
for (S3ScratchSpace space : S3ScratchSpace.values()) {
|
||||
s3Service.createBucket(space.bucketName(), "us-east-1");
|
||||
assertThrows(IOException.class, () -> space.ensureBucket(s3Service, "us-east-1"));
|
||||
assertFalse(s3Service.isScratchBucket(space.bucketName()));
|
||||
assertTrue(s3Service.getBucketTagging(space.bucketName()).isEmpty());
|
||||
assertTrue(s3Service.listBuckets().stream().anyMatch(bucket -> space.bucketName().equals(bucket.getName())));
|
||||
s3Service.deleteBucket(space.bucketName());
|
||||
space.ensureBucket(s3Service, "us-east-1");
|
||||
space.ensureBucket(s3Service, "us-east-1");
|
||||
assertTrue(s3Service.isScratchBucket(space.bucketName()));
|
||||
assertTrue(s3Service.listBuckets().stream().noneMatch(bucket -> space.bucketName().equals(bucket.getName())));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user