feat(redshift): emulate Redshift UNLOAD TO s3 over Simple Query protocol (#3129)

* feat(redshift): parse UNLOAD TO s3 statements

* feat(redshift): add S3Service.authorizeAnonymousPutObject for the UNLOAD writer

* feat(redshift): simulate Redshift UNLOAD TO s3 via CopyOut

* feat(redshift): dispatch UNLOAD via the intercepting bridge

* test(redshift): cover UNLOAD to S3 end to end

* docs(redshift): document UNLOAD to S3 support

* fix(redshift): drain backend on UNLOAD streaming failure and handle final slice error

* refactor(redshift): clean up inline FQCN imports across main and test sources

* fix(redshift): address review feedback on UNLOAD to S3 simulator

* fix(redshift): authorize ListBucket on UNLOAD prefix probe and clean up manifest on backend EOF

* fix(redshift): authorize UNLOAD cleanup deletes and skip them under ALLOWOVERWRITE

* fix(redshift): fail open on UNLOAD MAXFILESIZE above the buffering ceiling

* feat(redshift): repeat the UNLOAD header row at the start of every slice

* test(redshift): cover UNLOAD to S3 over JDBC in the SDK compatibility suite

* docs(redshift): document UNLOAD per-file header, MAXFILESIZE bytes, and over-cap fail-open

* fix(redshift): clean up new UNLOAD slice objects even under ALLOWOVERWRITE

deleteWritten previously bailed entirely when ALLOWOVERWRITE was set, to avoid
destroying a pre-existing object a slice key had overwritten. That also left
genuinely new slice keys behind on a MANIFEST failure, exposing a partial result
with no manifest. Track which slice keys existed before the write and skip only
those on cleanup.

* fix(redshift): never delete UNLOAD output under ALLOWOVERWRITE

The preExistingKeys heuristic could not distinguish an overwrite from a fresh
write atomically: two concurrent UNLOADs to the same prefix could both classify a
key as new, and one operation's cleanup could then delete the other's output.
Drop the heuristic and simply never delete under ALLOWOVERWRITE. Non-overwrite
runs verified the prefix was empty, so their cleanup is still safe. A failed
MANIFEST + ALLOWOVERWRITE UNLOAD may leave data objects without a manifest, which
is now documented.

* fix(redshift): read UNLOAD objects via getObject in the integration test

listObjects returns metadata-only S3Object entries whose getData() is null, so
unloadToS3PrefixWritesRowsAsObjects and unloadGzipWritesCompressedObject threw
NullPointerException in CI. Fetch each body with getObject, as the MANIFEST test
already does.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-06 15:58:37 -05:00
1 parent ee2f55b784
commit 4570bf62c5
17 files changed
+1853 -69

No files matched your search

@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.services.redshift;
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.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.awaitility.Awaitility;
@@ -10,15 +12,25 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@@ -28,7 +40,7 @@ class RedshiftInterceptorIntegrationTest {
RedshiftService service;
@Inject
io.github.hectorvent.floci.services.s3.S3Service s3;
S3Service s3;
private String clusterId;
@@ -118,7 +130,7 @@ class RedshiftInterceptorIntegrationTest {
String bucket = "redshift-copy-it";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "people/p1.txt",
"1|alice\n2|bob\n".getBytes(java.nio.charset.StandardCharsets.UTF_8), "text/plain", java.util.Map.of());
"1|alice\n2|bob\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE people (id int, name text)");
@@ -137,8 +149,8 @@ class RedshiftInterceptorIntegrationTest {
String bucket = "redshift-copy-it-prefix";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "d/a", "1|a\n".getBytes(java.nio.charset.StandardCharsets.UTF_8), "text/plain", java.util.Map.of());
s3.putObject(bucket, "d/b", "2|b\n".getBytes(java.nio.charset.StandardCharsets.UTF_8), "text/plain", java.util.Map.of());
s3.putObject(bucket, "d/a", "1|a\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
s3.putObject(bucket, "d/b", "2|b\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE t (id int, v text)");
@@ -157,11 +169,11 @@ class RedshiftInterceptorIntegrationTest {
String bucket = "redshift-copy-it-gzip";
s3.createBucket(bucket, "us-east-1");
java.io.ByteArrayOutputStream raw = new java.io.ByteArrayOutputStream();
try (java.util.zip.GZIPOutputStream gz = new java.util.zip.GZIPOutputStream(raw)) {
gz.write("10|x\n11|y\n".getBytes(java.nio.charset.StandardCharsets.UTF_8));
ByteArrayOutputStream raw = new ByteArrayOutputStream();
try (GZIPOutputStream gz = new GZIPOutputStream(raw)) {
gz.write("10|x\n11|y\n".getBytes(StandardCharsets.UTF_8));
}
s3.putObject(bucket, "g/data.gz", raw.toByteArray(), "application/gzip", java.util.Map.of());
s3.putObject(bucket, "g/data.gz", raw.toByteArray(), "application/gzip", Map.of());
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE g (id int, v text)");
@@ -183,7 +195,7 @@ class RedshiftInterceptorIntegrationTest {
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE t2 (id int)");
SQLException ex = org.junit.jupiter.api.Assertions.assertThrows(
SQLException ex = assertThrows(
SQLException.class,
() -> c.createStatement().execute("COPY t2 FROM 's3://redshift-copy-it-missing/does/not/exist'"));
assertTrue(
@@ -204,12 +216,12 @@ class RedshiftInterceptorIntegrationTest {
c.setAutoCommit(false);
Statement st = c.createStatement();
st.execute("INSERT INTO tx_test VALUES (1)");
org.junit.jupiter.api.Assertions.assertThrows(
assertThrows(
SQLException.class,
() -> st.execute("COPY tx_test FROM 's3://redshift-copy-it-tx/does/not/exist'"));
// The backend must now be in the aborted transaction state ('E').
// Subsequent statements in this transaction block must fail.
org.junit.jupiter.api.Assertions.assertThrows(
assertThrows(
SQLException.class,
() -> st.execute("INSERT INTO tx_test VALUES (2)"));
c.rollback();
@@ -220,4 +232,99 @@ class RedshiftInterceptorIntegrationTest {
}
}
}
@Test
void unloadToS3PrefixWritesRowsAsObjects() throws Exception {
clusterId = "it-unload-basic";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String bucket = "redshift-unload-it";
s3.createBucket(bucket, "us-east-1");
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE u_src (id int, name text)");
c.createStatement().execute("INSERT INTO u_src VALUES (1, 'alice'), (2, 'bob')");
c.createStatement().execute(
"UNLOAD ('select id, name from u_src order by id') TO 's3://redshift-unload-it/out/'");
}
List<S3Object> objs =
s3.listObjects(bucket, "out/", null, 100);
assertTrue(objs.size() >= 1, "UNLOAD must write at least one object");
StringBuilder all = new StringBuilder();
objs.stream()
.sorted(Comparator.comparing(S3Object::getKey))
// listObjects returns metadata-only entries; fetch each body with getObject.
.forEach(o -> all.append(new String(
s3.getObject(bucket, o.getKey()).getData(), StandardCharsets.UTF_8)));
assertEquals("1|alice\n2|bob\n", all.toString());
}
@Test
void unloadGzipWritesCompressedObject() throws Exception {
clusterId = "it-unload-gzip";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String bucket = "redshift-unload-it-gzip";
s3.createBucket(bucket, "us-east-1");
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE g_src (id int)");
c.createStatement().execute("INSERT INTO g_src VALUES (7), (8)");
c.createStatement().execute("UNLOAD ('select id from g_src order by id') TO 's3://redshift-unload-it-gzip/g/' GZIP");
}
var objs = s3.listObjects(bucket, "g/", null, 100);
assertEquals(1, objs.size());
assertTrue(objs.get(0).getKey().endsWith(".gz"), objs.get(0).getKey());
byte[] data = s3.getObject(bucket, objs.get(0).getKey()).getData();
ByteArrayOutputStream raw = new ByteArrayOutputStream();
try (var in = new GZIPInputStream(new ByteArrayInputStream(data))) {
in.transferTo(raw);
}
assertEquals("7\n8\n", raw.toString(StandardCharsets.UTF_8));
}
@Test
void unloadWithManifestWritesAManifestObject() throws Exception {
clusterId = "it-unload-manifest";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String bucket = "redshift-unload-it-manifest";
s3.createBucket(bucket, "us-east-1");
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE m_src (id int)");
c.createStatement().execute("INSERT INTO m_src VALUES (1)");
c.createStatement().execute("UNLOAD ('select id from m_src') TO 's3://redshift-unload-it-manifest/m/' MANIFEST");
}
var manifest = s3.getObject(bucket, "m/manifest");
assertNotNull(manifest);
String json = new String(manifest.getData(), StandardCharsets.UTF_8);
assertTrue(json.contains("\"entries\""), json);
assertTrue(json.contains("s3://redshift-unload-it-manifest/m/"), json);
}
@Test
void unloadIntoNonEmptyPrefixWithoutAllowOverwriteRaisesSqlError() throws Exception {
clusterId = "it-unload-overwrite";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String bucket = "redshift-unload-it-ow";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "o/existing", "x".getBytes(StandardCharsets.UTF_8),
"text/plain", Map.of());
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE o_src (id int)");
c.createStatement().execute("INSERT INTO o_src VALUES (1)");
SQLException ex = assertThrows(SQLException.class,
() -> c.createStatement().execute("UNLOAD ('select id from o_src') TO 's3://redshift-unload-it-ow/o/'"));
assertTrue(ex.getMessage().toLowerCase().contains("allowoverwrite"), ex.getMessage());
}
// With ALLOWOVERWRITE the same statement succeeds.
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute(
"UNLOAD ('select id from o_src') TO 's3://redshift-unload-it-ow/o/' ALLOWOVERWRITE");
}
}
}
@@ -17,6 +17,7 @@ import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.when;
@QuarkusTest
@@ -110,7 +111,7 @@ public class RedshiftOperationsTest {
void testClusterAndSnapshotLifecycle() {
when(containerManager.start(any(), eq("cluster-src"), any(), any()))
.thenReturn(new RedshiftContainerHandle("c1", "cluster-src", "localhost", 5439));
org.mockito.Mockito.doAnswer(invocation -> {
doAnswer(invocation -> {
Path p = invocation.getArgument(3);
Files.writeString(p, "-- dump sql table test_data;");
return null;
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup;
@@ -17,6 +18,7 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;
@@ -334,8 +336,8 @@ class RedshiftQueryHandlerTest {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("Description", "desc");
io.github.hectorvent.floci.core.common.AwsException ex = org.junit.jupiter.api.Assertions.assertThrows(
io.github.hectorvent.floci.core.common.AwsException.class,
AwsException ex = assertThrows(
AwsException.class,
() -> handler.handle("CreateClusterSubnetGroup", params));
assertEquals("InvalidParameterValue", ex.getErrorCode());
}
@@ -345,8 +347,8 @@ class RedshiftQueryHandlerTest {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("NodeType", "dc2.large");
io.github.hectorvent.floci.core.common.AwsException ex = org.junit.jupiter.api.Assertions.assertThrows(
io.github.hectorvent.floci.core.common.AwsException.class,
AwsException ex = assertThrows(
AwsException.class,
() -> handler.handle("ModifyCluster", params));
assertEquals("InvalidParameterValue", ex.getErrorCode());
}
@@ -1,6 +1,9 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
@@ -11,6 +14,7 @@ import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup;
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
import io.github.hectorvent.floci.services.redshift.model.Parameter;
import io.github.hectorvent.floci.services.redshift.model.Snapshot;
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -39,9 +43,9 @@ class RedshiftServiceTest {
private AccountAwareStorageBackend<ClusterParameterGroup> parameterGroupBackend;
private AccountAwareStorageBackend<ClusterSubnetGroup> subnetGroupBackend;
private RedshiftContainerManager cm;
private io.github.hectorvent.floci.core.common.RegionResolver regionResolver;
private io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager proxyManager;
private io.github.hectorvent.floci.core.common.docker.DockerHostResolver dockerHostResolver;
private RegionResolver regionResolver;
private RedshiftProxyManager proxyManager;
private DockerHostResolver dockerHostResolver;
private RedshiftService service;
@BeforeEach
@@ -54,19 +58,19 @@ class RedshiftServiceTest {
parameterGroupBackend = mock(AccountAwareStorageBackend.class);
subnetGroupBackend = mock(AccountAwareStorageBackend.class);
cm = mock(RedshiftContainerManager.class);
proxyManager = mock(io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager.class);
dockerHostResolver = mock(io.github.hectorvent.floci.core.common.docker.DockerHostResolver.class);
proxyManager = mock(RedshiftProxyManager.class);
dockerHostResolver = mock(DockerHostResolver.class);
when(dockerHostResolver.resolve()).thenReturn("localhost");
io.github.hectorvent.floci.config.EmulatorConfig config = mock(io.github.hectorvent.floci.config.EmulatorConfig.class);
io.github.hectorvent.floci.config.EmulatorConfig.StorageConfig storageConfig = mock(io.github.hectorvent.floci.config.EmulatorConfig.StorageConfig.class);
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.StorageConfig storageConfig = mock(EmulatorConfig.StorageConfig.class);
when(config.storage()).thenReturn(storageConfig);
when(storageConfig.persistentPath()).thenReturn("target/test-data");
io.github.hectorvent.floci.config.EmulatorConfig.ServicesConfig servicesConfig =
mock(io.github.hectorvent.floci.config.EmulatorConfig.ServicesConfig.class);
io.github.hectorvent.floci.config.EmulatorConfig.RedshiftServiceConfig redshiftConfig =
mock(io.github.hectorvent.floci.config.EmulatorConfig.RedshiftServiceConfig.class);
EmulatorConfig.ServicesConfig servicesConfig =
mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.RedshiftServiceConfig redshiftConfig =
mock(EmulatorConfig.RedshiftServiceConfig.class);
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.redshift()).thenReturn(redshiftConfig);
when(redshiftConfig.proxyBasePort()).thenReturn(7100);
@@ -79,7 +83,7 @@ class RedshiftServiceTest {
when(sf.<ClusterSubnetGroup>create(eq("redshift"), eq("redshift-subnet-groups.json"), any())).thenReturn(subnetGroupBackend);
when(clusterBackend.accountId()).thenReturn("111111111111");
regionResolver = new io.github.hectorvent.floci.core.common.RegionResolver("us-east-1", "111111111111");
regionResolver = new RegionResolver("us-east-1", "111111111111");
service = new RedshiftService(sf, cm, config, regionResolver, proxyManager, dockerHostResolver);
}
@@ -6,14 +6,21 @@ import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CopyStatementParserTest {
/** parse() returns S3Statement now; every COPY test wants the S3CopyFrom view. */
private static CopyStatementParser.S3CopyFrom copyFrom(String sql) {
CopyStatementParser.S3Statement s = CopyStatementParser.parse(sql);
return (CopyStatementParser.S3CopyFrom) s;
}
@Test
void parsesMinimalCopyFromKey() {
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY sales FROM 's3://warehouse/data/sales.txt'");
assertEquals("sales", c.targetTable());
assertEquals(List.of(), c.columns());
@@ -28,7 +35,7 @@ class CopyStatementParserTest {
@Test
void parsesColumnsOptionsAndPrefix() {
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY public.events (id, ts, note) FROM 's3://bkt/evt/' "
+ "GZIP DELIMITER ',' IGNOREHEADER 2 NULL AS '\\\\N' FORMAT AS CSV");
assertEquals("public.events", c.targetTable());
@@ -44,7 +51,7 @@ class CopyStatementParserTest {
@Test
void defaultsDelimiterToCommaForCsvAndTreatsHeaderKeywordAsOneLine() {
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY t FROM 's3://b/k' CSV HEADER");
assertEquals(",", c.delimiter());
assertEquals(1, c.headerLines());
@@ -52,21 +59,21 @@ class CopyStatementParserTest {
@Test
void decodesTabDelimiterToken() {
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY t FROM 's3://b/k' DELIMITER '\\\\t'");
assertEquals("\t", c.delimiter());
}
@Test
void bucketOnlyPathGivesEmptyPrefix() {
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse("COPY t FROM 's3://only-bucket'");
CopyStatementParser.S3CopyFrom c = copyFrom("COPY t FROM 's3://only-bucket'");
assertEquals("only-bucket", c.bucket());
assertEquals("", c.keyOrPrefix());
}
@Test
void stripsLeadingComments() {
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
CopyStatementParser.S3CopyFrom c = copyFrom(
"-- load nightly\n/* batch */ COPY t FROM 's3://b/k'");
assertEquals("t", c.targetTable());
}
@@ -95,7 +102,7 @@ class CopyStatementParserTest {
@Test
void quotedIdentifiersSurvive() {
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY \"My Schema\".\"Tab\" (\"col one\") FROM 's3://b/k'");
assertEquals("\"My Schema\".\"Tab\"", c.targetTable());
assertEquals(List.of("\"col one\""), c.columns());
@@ -103,7 +110,7 @@ class CopyStatementParserTest {
@Test
void explicitDelimiterOverridesCsvDefault() {
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY t FROM 's3://b/k' CSV DELIMITER '\t'");
assertEquals("\t", c.delimiter());
assertTrue(c.csv());
@@ -127,13 +134,13 @@ class CopyStatementParserTest {
@Test
void toleratesALoneTrailingSemicolon() {
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse("COPY t FROM 's3://b/k' GZIP;");
CopyStatementParser.S3CopyFrom c = copyFrom("COPY t FROM 's3://b/k' GZIP;");
assertTrue(c.gzip());
}
@Test
void aQuotedKeywordInAnOptionValueDoesNotChangeParsing() {
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY t FROM 's3://b/k' NULL AS 'csv' DELIMITER ';'");
assertFalse(c.csv());
assertEquals(";", c.delimiter());
@@ -164,8 +171,116 @@ class CopyStatementParserTest {
@Test
void parsesEscapedSingleQuoteInDelimiter() {
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
CopyStatementParser.S3CopyFrom c = copyFrom(
"COPY t FROM 's3://b/k' DELIMITER ''''");
assertEquals("'", c.delimiter());
}
private static CopyStatementParser.S3Unload unload(String sql) {
return (CopyStatementParser.S3Unload) CopyStatementParser.parse(sql);
}
@Test
void parsesMinimalUnload() {
CopyStatementParser.S3Unload u = unload(
"UNLOAD ('select id, name from sales') TO 's3://warehouse/out/'");
assertEquals("select id, name from sales", u.selectQuery());
assertEquals("warehouse", u.bucket());
assertEquals("out/", u.prefix());
assertEquals("|", u.delimiter());
assertFalse(u.csv());
assertFalse(u.gzip());
assertFalse(u.header());
assertFalse(u.manifest());
assertFalse(u.allowOverwrite());
assertTrue(u.parallel());
assertEquals(0L, u.maxFileSizeBytes());
assertNull(u.nullAs());
}
@Test
void parsesUnloadOptions() {
CopyStatementParser.S3Unload u = unload(
"UNLOAD ('select * from t') TO 's3://b/p/' "
+ "FORMAT AS CSV DELIMITER ',' HEADER GZIP ADDQUOTES MANIFEST "
+ "ALLOWOVERWRITE PARALLEL OFF NULL AS 'nil' MAXFILESIZE 5 MB");
assertTrue(u.csv());
assertEquals(",", u.delimiter());
assertTrue(u.header());
assertTrue(u.gzip());
assertTrue(u.addQuotes());
assertTrue(u.manifest());
assertTrue(u.allowOverwrite());
assertFalse(u.parallel());
assertEquals("nil", u.nullAs());
assertEquals(5L * 1024 * 1024, u.maxFileSizeBytes());
}
@Test
void unloadDefaultsCsvDelimiterToComma() {
assertEquals(",", unload("UNLOAD ('select 1') TO 's3://b/p/' CSV").delimiter());
}
@Test
void unloadParsesMaxFileSizeUnits() {
assertEquals(10L * 1024 * 1024, unload("UNLOAD ('select 1') TO 's3://b/p/' MAXFILESIZE 10 MB").maxFileSizeBytes());
assertEquals(1024L * 1024 * 1024 / 8, unload("UNLOAD ('select 1') TO 's3://b/p/' MAXFILESIZE 0.125 GB").maxFileSizeBytes());
assertEquals(4096L, unload("UNLOAD ('select 1') TO 's3://b/p/' MAXFILESIZE 4096").maxFileSizeBytes());
}
@Test
void unloadRejectsMaxFileSizeAboveTheBufferingCeiling() {
// The simulator buffers a file at a time, so a per-file size it cannot hold fails open.
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' MAXFILESIZE 2 GB"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' MAXFILESIZE 500 MB"));
}
@Test
void unloadUnescapesDoubledSingleQuotesInSelect() {
assertEquals("select 'x' from t",
unload("UNLOAD ('select ''x'' from t') TO 's3://b/p/'").selectQuery());
}
@Test
void unloadAcceptsWithCteSelect() {
assertNotNull(unload("UNLOAD ('with c as (select 1) select * from c') TO 's3://b/p/'"));
}
@Test
void unloadRejectsSubqueryBreakoutAttempts() {
assertNull(CopyStatementParser.parse("UNLOAD ('select 1) TO PROGRAM ''id'' --') TO 's3://b/p/'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1; drop table t') TO 's3://b/p/'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select $$x$$') TO 's3://b/p/'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1)') TO 's3://b/p/'"));
assertNull(CopyStatementParser.parse("UNLOAD ('delete from t') TO 's3://b/p/'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1 /* c */') TO 's3://b/p/'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select E''breakout''') TO 's3://b/p/'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select U&''breakout''') TO 's3://b/p/'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select \\1') TO 's3://b/p/'"));
}
@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/' IAM_ROLE 'arn:aws:iam::0:role/r'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' REGION 'us-west-2'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' EXTENSION 'csv'"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' ZSTD"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' PARTITION BY (dt)"));
}
@Test
void unloadRejectsDuplicateOptionsAndUnknownTokens() {
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' GZIP GZIP"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/' FOO"));
assertNull(CopyStatementParser.parse("UNLOAD ('select 1') TO 's3://b/p/'; SELECT 1"));
}
@Test
void unloadQuotedKeywordInValueDoesNotFlipParsing() {
CopyStatementParser.S3Unload u = unload("UNLOAD ('select 1') TO 's3://b/p/' NULL AS 'csv'");
assertFalse(u.csv());
assertEquals("csv", u.nullAs());
}
}
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -12,6 +13,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
@@ -68,7 +70,7 @@ class RedshiftAuthProxyTest {
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
mock(io.github.hectorvent.floci.services.s3.S3Service.class));
mock(S3Service.class));
proxy.start(proxyPort);
try (Socket client = new Socket("localhost", proxyPort)) {
@@ -122,7 +124,7 @@ class RedshiftAuthProxyTest {
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
mock(io.github.hectorvent.floci.services.s3.S3Service.class));
mock(S3Service.class));
proxy.start(proxyPort);
// Connect, then drop without ever sending a startup packet.
@@ -141,7 +143,7 @@ class RedshiftAuthProxyTest {
// yet; free it shortly after so the retrying bind can finally take it.
ServerSocket squatter = new ServerSocket();
squatter.setReuseAddress(true);
squatter.bind(new java.net.InetSocketAddress(proxyPort));
squatter.bind(new InetSocketAddress(proxyPort));
Thread.ofVirtual().start(() -> {
try {
Thread.sleep(200);
@@ -153,7 +155,7 @@ class RedshiftAuthProxyTest {
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
mock(io.github.hectorvent.floci.services.s3.S3Service.class));
mock(S3Service.class));
proxy.start(proxyPort); // must not throw despite the port being busy at first
assertTrue(portAccepts(proxyPort), "proxy never bound the port after the squatter released it");
@@ -166,7 +168,7 @@ class RedshiftAuthProxyTest {
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "old", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
mock(io.github.hectorvent.floci.services.s3.S3Service.class));
mock(S3Service.class));
proxy.start(proxyPort);
proxy.updateMasterPassword("rotated");
@@ -12,6 +12,7 @@ import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
@@ -212,4 +213,52 @@ class RedshiftInterceptingBridgeTest {
assertEquals('Q', forwarded.type());
assertTrue(forwarded.getSql().contains("s3://wh/k"), forwarded.getSql());
}
@Test
void unloadQueryIsDispatchedToTheSimulator() throws Exception {
startBridge();
Mockito.when(s3Stub.listObjectsWithPrefixes(Mockito.eq("b"), Mockito.eq("out/"),
Mockito.isNull(), Mockito.anyInt(), Mockito.any(), Mockito.any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
AtomicReference<byte[]> put = new AtomicReference<>();
Mockito.when(s3Stub.putObject(Mockito.eq("b"), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
.thenAnswer(inv -> {
put.compareAndSet(null, inv.getArgument(2));
return null;
});
// Fake backend: expect the fabricated COPY (...) TO STDOUT and play one row.
Thread be = Thread.ofVirtual().start(() -> {
try {
PostgresWireDecoder in = new PostgresWireDecoder(testBackendEnd.getInputStream());
PostgresWireDecoder.FrontendMessage q = in.nextMessage();
assertTrue(q.getSql().contains("TO STDOUT"), q.getSql());
OutputStream out = testBackendEnd.getOutputStream();
out.write(new byte[]{'H', 0, 0, 0, 7, 0, 0, 0});
byte[] row = "1|a\n".getBytes(StandardCharsets.US_ASCII);
out.write('d');
out.write(new byte[]{(byte) (0), 0, 0, (byte) (4 + row.length)});
out.write(row);
out.write(new byte[]{'c', 0, 0, 0, 4});
byte[] tag = "COPY 1\0".getBytes(StandardCharsets.US_ASCII);
out.write('C');
out.write(new byte[]{0, 0, 0, (byte) (4 + tag.length)});
out.write(tag);
out.write(new byte[]{'Z', 0, 0, 0, 5, 'I'});
out.flush();
} catch (IOException e) {
LOG.debugv(e, "fake backend ended");
}
});
OutputStream clientOut = testClientEnd.getOutputStream();
clientOut.write(PostgresWireDecoder.encodeQuery("UNLOAD ('select a,b from t') TO 's3://b/out/'"));
clientOut.flush();
PostgresWireDecoder fromPump = new PostgresWireDecoder(testClientEnd.getInputStream());
assertEquals('C', fromPump.nextMessage().type());
assertEquals('Z', fromPump.nextMessage().type());
be.join();
assertNotNull(put.get(), "the simulator should have written one S3 object");
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -28,7 +29,7 @@ class RedshiftProxyManagerTest {
private RedshiftProxyManager newManager() {
return new RedshiftProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class),
mock(io.github.hectorvent.floci.services.s3.S3Service.class));
mock(S3Service.class));
}
private static void start(RedshiftProxyManager manager, String key, int proxyPort) {
@@ -7,6 +7,7 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
@@ -14,12 +15,17 @@ import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -108,6 +114,598 @@ class S3CopySimulatorTest {
return new PostgresWireDecoder(testBackend.getInputStream()).nextMessage();
}
/** Play a PostgreSQL backend for a fabricated COPY (...) TO STDOUT: 'H', N 'd' rows, 'c', 'C', 'Z'. */
private void playUnloadBackend(String... rows) throws IOException {
OutputStream out = testBackend.getOutputStream();
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
PostgresWireDecoder.FrontendMessage q = in.nextMessage();
assertEquals('Q', q.type());
assertTrue(q.getSql().contains("TO STDOUT"), q.getSql());
out.write(new byte[]{'H', 0, 0, 0, 7, 0, 0, 0}); // CopyOutResponse
for (String row : rows) {
byte[] b = row.getBytes(StandardCharsets.US_ASCII);
out.write('d');
out.write(intBytes(4 + b.length));
out.write(b);
}
out.write(new byte[]{'c', 0, 0, 0, 4}); // CopyDone
byte[] tag = "COPY 2\0".getBytes(StandardCharsets.US_ASCII);
out.write('C');
out.write(intBytes(4 + tag.length));
out.write(tag);
out.write(new byte[]{'Z', 0, 0, 0, 5, 'I'});
out.flush();
}
private CopyStatementParser.S3Unload unloadSpec(String bucket, String prefix,
boolean gzip, boolean manifest, boolean allowOverwrite, boolean parallel, long maxFileSize) {
return new CopyStatementParser.S3Unload("select a,b from t", bucket, prefix,
"|", false, gzip, false, false, null, manifest, allowOverwrite, parallel, maxFileSize);
}
@Test
void unloadWritesSingleObjectAndForwardsCommandComplete() throws Exception {
Map<String, byte[]> written = new ConcurrentHashMap<>();
when(s3.putObject(eq("wh"), any(), any(), any(), any())).thenAnswer(inv -> {
written.put(inv.getArgument(1), inv.getArgument(2));
return null;
});
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
Thread backend = backendThread(() -> playUnloadBackend("1|alice\n", "2|bob\n"));
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
joinBackend(backend);
assertTrue(handled);
assertEquals(1, written.size());
assertTrue(written.containsKey("out/0000_part_00"), written.keySet().toString());
assertEquals("1|alice\n2|bob\n", new String(written.get("out/0000_part_00"), StandardCharsets.US_ASCII));
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
assertEquals('C', in.nextMessage().type());
assertEquals('Z', in.nextMessage().type());
}
@Test
void unloadRepeatsTheHeaderRowInEverySlice() throws Exception {
long saved = S3CopySimulator.UNLOAD_TARGET_FILE_BYTES;
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = 4; // one data row per slice
try {
Map<String, byte[]> written = new ConcurrentHashMap<>();
when(s3.putObject(eq("wh"), any(), any(), any(), any())).thenAnswer(inv -> {
written.put(inv.getArgument(1), inv.getArgument(2));
return null;
});
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3Unload spec = new CopyStatementParser.S3Unload(
"select a,b from t", "wh", "out/", "|", true, false, true, false, null,
false, false, true, 0);
// The fake backend stands in for PostgreSQL: the first CopyData frame is the header row.
Thread backend = backendThread(() -> playUnloadBackend("h1|h2\n", "1|a\n", "2|b\n", "3|c\n"));
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
joinBackend(backend);
assertEquals(3, written.size(), written.keySet().toString());
for (Map.Entry<String, byte[]> e : written.entrySet()) {
String body = new String(e.getValue(), StandardCharsets.US_ASCII);
assertTrue(body.startsWith("h1|h2\n"), e.getKey() + " -> " + body);
}
} finally {
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = saved;
}
}
@Test
void unloadSplitsIntoMultipleObjectsOnNewlineBoundaries() throws Exception {
long saved = S3CopySimulator.UNLOAD_TARGET_FILE_BYTES;
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = 6; // force a split after each row
try {
Map<String, byte[]> written = new ConcurrentHashMap<>();
when(s3.putObject(eq("wh"), any(), any(), any(), any())).thenAnswer(inv -> {
written.put(inv.getArgument(1), inv.getArgument(2));
return null;
});
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
Thread backend = backendThread(() -> playUnloadBackend("1|alice\n", "2|bob\n", "3|carol\n"));
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
joinBackend(backend);
assertTrue(written.containsKey("out/0000_part_00"));
assertTrue(written.containsKey("out/0001_part_00"));
assertTrue(written.containsKey("out/0002_part_00"));
assertEquals(3, written.size(), written.keySet().toString());
StringBuilder all = new StringBuilder();
written.entrySet().stream().sorted(Map.Entry.comparingByKey())
.forEach(e -> all.append(new String(e.getValue(), StandardCharsets.US_ASCII)));
assertEquals("1|alice\n2|bob\n3|carol\n", all.toString());
} finally {
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = saved;
}
}
@Test
void unloadParallelOffUsesThreeDigitKeyNames() throws Exception {
Map<String, byte[]> written = new ConcurrentHashMap<>();
when(s3.putObject(eq("wh"), any(), any(), any(), any())).thenAnswer(inv -> {
written.put(inv.getArgument(1), inv.getArgument(2));
return null;
});
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, false, 0);
Thread backend = backendThread(() -> playUnloadBackend("1|a\n"));
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
joinBackend(backend);
assertTrue(written.containsKey("out/000"), written.keySet().toString());
}
@Test
void unloadGzipAppendsGzSuffixAndWritesDecompressibleBytes() throws Exception {
Map<String, byte[]> written = new ConcurrentHashMap<>();
when(s3.putObject(eq("wh"), any(), any(), any(), any())).thenAnswer(inv -> {
written.put(inv.getArgument(1), inv.getArgument(2));
return null;
});
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", true, false, false, true, 0);
Thread backend = backendThread(() -> playUnloadBackend("1|a\n", "2|b\n"));
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
joinBackend(backend);
assertTrue(written.containsKey("out/0000_part_00.gz"), written.keySet().toString());
byte[] gz = written.get("out/0000_part_00.gz");
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(gz))) {
in.transferTo(out);
}
assertEquals("1|a\n2|b\n", out.toString(StandardCharsets.US_ASCII));
}
@Test
void unloadManifestListsEveryDataObject() throws Exception {
long saved = S3CopySimulator.UNLOAD_TARGET_FILE_BYTES;
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = 8;
try {
Map<String, byte[]> written = new ConcurrentHashMap<>();
when(s3.putObject(eq("wh"), any(), any(), any(), any())).thenAnswer(inv -> {
written.put(inv.getArgument(1), inv.getArgument(2));
return null;
});
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, true, false, true, 0);
Thread backend = backendThread(() -> playUnloadBackend("1|alice\n", "2|bob\n", "3|carol\n"));
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
joinBackend(backend);
String manifest = new String(written.get("out/manifest"), StandardCharsets.UTF_8);
assertTrue(manifest.contains("s3://wh/out/0000_part_00"), manifest);
assertTrue(manifest.contains("s3://wh/out/0001_part_00"), manifest);
assertTrue(manifest.contains("\"content_length\":"), manifest);
} finally {
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = saved;
}
}
@Test
void unloadIntoNonEmptyPrefixWithoutAllowOverwriteErrorsAndSkipsSelect() throws Exception {
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(
List.of(new S3Object("wh", "out/old", new byte[]{1}, "text/plain")), List.of(), false, null));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
// No backend thread: the select must never run.
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
assertTrue(handled);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
assertEquals('E', in.nextMessage().type());
assertEquals('Z', in.nextMessage().type());
}
@Test
void unloadForwardsBackendErrorWhenSelectIsInvalid() throws Exception {
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
Thread backend = backendThread(() -> {
OutputStream out = testBackend.getOutputStream();
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
assertEquals('Q', in.nextMessage().type());
byte[] err = "SERROR\0C42703\0Mcolumn \"nope\" does not exist\0\0".getBytes(StandardCharsets.US_ASCII);
out.write('E');
out.write(intBytes(4 + err.length));
out.write(err);
out.write(new byte[]{'Z', 0, 0, 0, 5, 'I'});
out.flush();
});
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
joinBackend(backend);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
assertEquals('E', in.nextMessage().type());
assertEquals('Z', in.nextMessage().type());
testClient.setSoTimeout(400);
assertThrows(SocketTimeoutException.class, () -> testClient.getInputStream().read());
}
@Test
void unloadAbortsWhenResultExceedsTotalCeiling() throws Exception {
long saved = S3CopySimulator.UNLOAD_MAX_TOTAL_BYTES;
S3CopySimulator.UNLOAD_MAX_TOTAL_BYTES = 16;
try {
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 1_000_000);
Thread backend = backendThread(() -> {
OutputStream out = testBackend.getOutputStream();
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
assertEquals('Q', in.nextMessage().type());
out.write(new byte[]{'H', 0, 0, 0, 7, 0, 0, 0});
byte[] big = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n".getBytes(StandardCharsets.US_ASCII);
out.write('d');
out.write(intBytes(4 + big.length));
out.write(big);
out.flush();
try {
out.write(new byte[]{'c', 0, 0, 0, 4});
out.flush();
} catch (IOException ignored) {
// Backend socket is closed immediately by simulator on ceiling exceed
}
});
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
joinBackend(backend);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
PostgresWireDecoder.FrontendMessage err = in.nextMessage();
assertEquals('E', err.type());
assertTrue(new String(err.body(), StandardCharsets.US_ASCII).contains("54000"));
assertEquals('Z', in.nextMessage().type());
assertNull(in.nextMessage(), "Client must receive EOF after ReadyForQuery on connection close");
} finally {
S3CopySimulator.UNLOAD_MAX_TOTAL_BYTES = saved;
}
}
@Test
void unloadInTransactionBlockReportsFailedTransactionStatusOnError() throws Exception {
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(
List.of(new S3Object("wh", "out/old", new byte[]{1}, "text/plain")), List.of(), false, null));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
Thread backend = backendThread(() -> {
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
PostgresWireDecoder.FrontendMessage q = in.nextMessage();
assertEquals('Q', q.type());
assertTrue(q.getSql().contains("FLOCI_ABORT_TX"));
OutputStream out = testBackend.getOutputStream();
byte[] err = "SERROR\0C42601\0Msyntax error\0\0".getBytes(StandardCharsets.US_ASCII);
out.write('E');
out.write(intBytes(4 + err.length));
out.write(err);
out.write(new byte[]{'Z', 0, 0, 0, 5, 'E'});
out.flush();
});
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'T');
joinBackend(backend);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
assertEquals('E', in.nextMessage().type());
PostgresWireDecoder.FrontendMessage z = in.nextMessage();
assertEquals('Z', z.type());
assertEquals('E', (char) z.body()[0]);
}
@Test
void unloadStreamingFailureDrainsBackendAndSendsSingleError() throws Exception {
long saved = S3CopySimulator.UNLOAD_TARGET_FILE_BYTES;
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = 8; // Force flush on first row
try {
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
when(s3.putObject(eq("wh"), any(), any(), any(), any()))
.thenThrow(new RuntimeException("simulated S3 storage failure"));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
Thread backend = backendThread(() -> {
OutputStream out = testBackend.getOutputStream();
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
assertEquals('Q', in.nextMessage().type());
out.write(new byte[]{'H', 0, 0, 0, 7, 0, 0, 0});
// Send multiple rows so the backend has pending messages when putObject throws mid-stream on the first slice
byte[] row1 = "1|alice\n".getBytes(StandardCharsets.US_ASCII);
out.write('d');
out.write(intBytes(4 + row1.length));
out.write(row1);
byte[] row2 = "2|bob\n".getBytes(StandardCharsets.US_ASCII);
out.write('d');
out.write(intBytes(4 + row2.length));
out.write(row2);
out.write(new byte[]{'c', 0, 0, 0, 4});
byte[] tag = "COPY 2\0".getBytes(StandardCharsets.US_ASCII);
out.write('C');
out.write(intBytes(4 + tag.length));
out.write(tag);
out.write(new byte[]{'Z', 0, 0, 0, 5, 'I'});
out.flush();
});
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
joinBackend(backend);
assertTrue(handled);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
assertEquals('E', in.nextMessage().type());
assertEquals('Z', in.nextMessage().type());
testClient.setSoTimeout(400);
assertThrows(SocketTimeoutException.class, () -> testClient.getInputStream().read(),
"no leftover or duplicate messages should reach client");
} finally {
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = saved;
}
}
@Test
void unloadAbortsWhenMemoryBudgetExhaustedReports53400() throws Exception {
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
S3CopySimulator.UNLOAD_HEAP_MIB.acquire(192);
try {
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
assertTrue(handled);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
PostgresWireDecoder.FrontendMessage err = in.nextMessage();
assertEquals('E', err.type());
String errBody = new String(err.body(), StandardCharsets.UTF_8);
assertTrue(errBody.contains("53400"), errBody);
assertTrue(errBody.contains("memory budget exhausted"), errBody);
assertEquals('Z', in.nextMessage().type());
} finally {
S3CopySimulator.UNLOAD_HEAP_MIB.release(192);
}
}
@Test
void unloadFabricatedCopySqlMatchesFormattingOptions() throws Exception {
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3Unload spec = new CopyStatementParser.S3Unload(
"select a from t", "wh", "out/", "\t", true, false, false, true, "\\N", false, true, true, 0);
AtomicReference<String> seenSql = new AtomicReference<>();
Thread backend = backendThread(() -> {
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
PostgresWireDecoder.FrontendMessage q = in.nextMessage();
seenSql.set(q.getSql());
OutputStream out = testBackend.getOutputStream();
out.write(new byte[]{'H', 0, 0, 0, 7, 0, 0, 0});
out.write(new byte[]{'c', 0, 0, 0, 4});
byte[] tag = "COPY 0\0".getBytes(StandardCharsets.US_ASCII);
out.write('C');
out.write(intBytes(4 + tag.length));
out.write(tag);
out.write(new byte[]{'Z', 0, 0, 0, 5, 'I'});
out.flush();
});
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
joinBackend(backend);
String sql = seenSql.get();
assertNotNull(sql);
assertTrue(sql.contains("FORMAT csv"), sql);
assertTrue(sql.contains("DELIMITER '\t'"), sql);
assertTrue(sql.contains("HEADER true"), sql);
assertTrue(sql.contains("FORCE_QUOTE *"), sql);
assertTrue(sql.contains("NULL '\\N'"), sql);
}
@Test
void unloadZeroRowsEmitsSingleEmptyObject() throws Exception {
Map<String, byte[]> written = new ConcurrentHashMap<>();
when(s3.putObject(eq("wh"), any(), any(), any(), any())).thenAnswer(inv -> {
written.put(inv.getArgument(1), inv.getArgument(2));
return null;
});
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
Thread backend = backendThread(() -> {
OutputStream out = testBackend.getOutputStream();
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
assertEquals('Q', in.nextMessage().type());
out.write(new byte[]{'H', 0, 0, 0, 7, 0, 0, 0});
out.write(new byte[]{'c', 0, 0, 0, 4});
byte[] tag = "COPY 0\0".getBytes(StandardCharsets.US_ASCII);
out.write('C');
out.write(intBytes(4 + tag.length));
out.write(tag);
out.write(new byte[]{'Z', 0, 0, 0, 5, 'I'});
out.flush();
});
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
joinBackend(backend);
assertTrue(handled);
assertEquals(1, written.size());
assertTrue(written.containsKey("out/0000_part_00"));
assertEquals(0, written.get("out/0000_part_00").length);
}
@Test
void unloadBucketNotFoundSurfacesNotFoundMessageInsteadOfAccessDenied() throws Exception {
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
assertTrue(handled);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
PostgresWireDecoder.FrontendMessage err = in.nextMessage();
assertEquals('E', err.type());
String body = new String(err.body(), StandardCharsets.UTF_8);
assertTrue(body.contains("not found"), body);
assertFalse(body.contains("access denied"), body);
assertEquals('Z', in.nextMessage().type());
}
@Test
void unloadManifestFailureCleansUpWrittenDataObjects() throws Exception {
List<String> deleted = new ArrayList<>();
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
when(s3.putObject(eq("wh"), any(), any(), any(), any())).thenAnswer(inv -> {
String key = inv.getArgument(1);
if (key.endsWith("manifest")) {
throw new RuntimeException("disk full writing manifest");
}
return null;
});
when(s3.deleteObject(eq("wh"), any())).thenAnswer(inv -> {
deleted.add(inv.getArgument(1));
return null;
});
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, true, false, true, 0);
Thread backend = backendThread(() -> playUnloadBackend("1|a\n"));
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
joinBackend(backend);
assertEquals(1, deleted.size());
assertEquals("out/0000_part_00", deleted.get(0));
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
assertEquals('E', in.nextMessage().type());
assertEquals('Z', in.nextMessage().type());
}
@Test
void unloadManifestFailureUnderAllowOverwriteLeavesEveryDataObjectInPlace() throws Exception {
long saved = S3CopySimulator.UNLOAD_TARGET_FILE_BYTES;
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = 4; // one data row per slice
try {
List<String> deleted = new ArrayList<>();
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
when(s3.putObject(eq("wh"), any(), any(), any(), any())).thenAnswer(inv -> {
if (((String) inv.getArgument(1)).endsWith("manifest")) {
throw new RuntimeException("disk full writing manifest");
}
return null;
});
when(s3.deleteObject(eq("wh"), any())).thenAnswer(inv -> {
deleted.add(inv.getArgument(1));
return null;
});
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, true, true, true, 0);
Thread backend = backendThread(() -> playUnloadBackend("1|a\n", "2|b\n"));
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
joinBackend(backend);
// Under ALLOWOVERWRITE a written key may have replaced pre-existing (or another
// operation's) data, so cleanup deletes nothing and the partial result is left behind.
assertTrue(deleted.isEmpty(), "ALLOWOVERWRITE cleanup must not delete any object, got " + deleted);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
assertEquals('E', in.nextMessage().type());
assertEquals('Z', in.nextMessage().type());
} finally {
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = saved;
}
}
@Test
void unloadWithoutAllowOverwriteFailsIfListBucketDenied() throws Exception {
doThrow(new AwsException("AccessDenied", "Access Denied", 403))
.when(s3).authorizeAnonymousListBucket(eq("wh"));
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, false, false, true, 0);
boolean handled = S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
assertTrue(handled);
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
PostgresWireDecoder.FrontendMessage err = in.nextMessage();
assertEquals('E', err.type());
String body = new String(err.body(), StandardCharsets.UTF_8);
assertTrue(body.contains("42501"), body);
assertTrue(body.contains("access denied"), body);
assertEquals('Z', in.nextMessage().type());
}
@Test
void unloadBackendEofMidStreamWithManifestCleansUpWrittenDataObjects() throws Exception {
long saved = S3CopySimulator.UNLOAD_TARGET_FILE_BYTES;
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = 6;
try {
List<String> deleted = new ArrayList<>();
when(s3.listObjectsWithPrefixes(eq("wh"), eq("out/"), isNull(), anyInt(), any(), any()))
.thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
when(s3.deleteObject(eq("wh"), any())).thenAnswer(inv -> {
deleted.add(inv.getArgument(1));
return null;
});
CopyStatementParser.S3Unload spec = unloadSpec("wh", "out/", false, true, false, true, 0);
Thread backend = backendThread(() -> {
OutputStream out = testBackend.getOutputStream();
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
assertEquals('Q', in.nextMessage().type());
out.write(new byte[]{'H', 0, 0, 0, 7, 0, 0, 0});
byte[] row = "1|alice\n".getBytes(StandardCharsets.US_ASCII);
out.write('d');
out.write(intBytes(4 + row.length));
out.write(row);
out.flush();
testBackend.close();
});
S3CopySimulator.runUnload(simClient, simBackend, spec, s3, 'I');
joinBackend(backend);
assertEquals(1, deleted.size());
assertEquals("out/0000_part_00", deleted.get(0));
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
PostgresWireDecoder.FrontendMessage err = in.nextMessage();
assertEquals('E', err.type());
String body = new String(err.body(), StandardCharsets.UTF_8);
assertTrue(body.contains("backend closed mid-stream"), body);
assertEquals('Z', in.nextMessage().type());
} finally {
S3CopySimulator.UNLOAD_TARGET_FILE_BYTES = saved;
}
}
/** Play a minimal happy-path PostgreSQL backend: 'G' then, after CopyDone, 'C' and 'Z'. */
private void playHappyBackend(ByteArrayOutputStream capturedCopyData) throws IOException {
OutputStream out = testBackend.getOutputStream();
@@ -1149,4 +1149,18 @@ class S3ServiceTest {
"configuration config-" + i + " was lost by a concurrent put");
}
}
@Test
void authorizeAnonymousPutObjectIsANoOpWhenEnforceAuthIsOff() {
// Default test config has FLOCI_SERVICES_S3_ENFORCE_AUTH unset/false.
s3Service.createBucket("anon-put-bucket", "us-east-1");
assertDoesNotThrow(() -> s3Service.authorizeAnonymousPutObject("anon-put-bucket", "some/key"));
}
@Test
void authorizeAnonymousDeleteObjectIsANoOpWhenEnforceAuthIsOff() {
s3Service.createBucket("anon-del-bucket", "us-east-1");
assertDoesNotThrow(() -> s3Service.authorizeAnonymousDeleteObject("anon-del-bucket", "some/key"));
}
}