feat(redshift): intercept Extended Query protocol (#3474)

* feat(redshift): decode Extended Query wire messages

* feat(redshift): track Extended Query statements and portals

* feat(redshift): coordinate Extended Query backend responses

* refactor(redshift): share S3 COPY and UNLOAD transfers

* feat(redshift): execute S3 transfers through Extended Query

* fix(redshift): retain next-cycle pipelined portals

* feat(redshift): intercept Extended Query statements

* test(redshift): cover Extended Query JDBC compatibility

* test(redshift): cover Extended Query SDK compatibility

* docs(redshift): document Extended Query interception

* feat(redshift): implement extended query execution handling in BackendResponseCoordinator and update related classes

* feat(redshift): enhance ExtendedS3Exchange with client synchronization handling

* fix(redshift): synchronize extended COPY failures

* fix(redshift): tolerate backend ownership fragmentation

* fix(redshift): forward extended query flush frames

* fix(redshift): abort backend copy on unload failure

* fix(redshift): preserve later extended query mutations

* fix(redshift): return ready state after copy failure

* test(redshift): cover later sync cycle rollback

* fix(redshift): preserve independent mutations when rejecting a pipelined mutation

ExtendedQuerySession.rejectFrom() restored the whole statements/portals
map back to the rejected mutation's "before" snapshot and truncated the
journal to the end, discarding any later, independent mutation that
happened to run first. The coordinator already rejects one pipelined
mutation at a time in journal order, so this only ever needs to undo
that one mutation's own effect.

Each journal entry now also records its own "after" snapshot at
creation time, since reconstructing it later from the next entry's
"before" or from the live maps goes stale once an earlier reject's
cascading portal cleanup has already touched a key this mutation never
itself changed.

* fix(redshift): forward the real ReadyForQuery after a COPY/UNLOAD failure

readClientSync(client) called the two-argument overload without its
Flush-forwarding OutputStream, which did not compile.

Every error branch in the Extended Query COPY/UNLOAD path sent CopyFail
and Sync to the backend but never drained or forwarded the backend's
resulting ReadyForQuery: the client waited on a frame nobody ever read
off the wire. drainReadyForQuery already existed for exactly this but
was never called. Wire it into every COPY and UNLOAD error branch.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-13 08:54:52 -04:00
1 parent 04f0c3b7fd
commit e9454af855
15 files changed
+2717 -381

No files matched your search

@@ -14,9 +14,11 @@ import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
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;
@@ -31,6 +33,7 @@ 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.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@@ -68,26 +71,102 @@ class RedshiftInterceptorIntegrationTest {
}
}
private static String jdbcUrl(Cluster c) {
private static String jdbcUrl(Cluster cluster) {
// Use 127.0.0.1 explicitly instead of c.getEndpoint().getAddress() to avoid UnknownHostException
// in CI environments where floci.emulator.hostname is set to host.docker.internal.
// preferQueryMode=simple forces pgjdbc to use the simple query protocol ('Q' messages)
// rather than extended query protocol ('P'/'B'/'E'/'S' messages).
return "jdbc:postgresql://127.0.0.1:" + c.getEndpoint().getPort() + "/dev?preferQueryMode=simple";
return "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort() + "/dev";
}
private static String namedPreparedJdbcUrl(Cluster cluster) {
return jdbcUrl(cluster) + "?prepareThreshold=1";
}
private static Connection waitForConnection(Cluster cluster, String username, String password) throws SQLException {
return waitForConnection(jdbcUrl(cluster), username, password);
}
private static Connection waitForConnection(String jdbcUrl, String username, String password) throws SQLException {
try {
return Awaitility.await()
.atMost(Duration.ofSeconds(30))
.pollInterval(Duration.ofMillis(500))
.ignoreExceptions()
.until(() -> DriverManager.getConnection(jdbcUrl(cluster), username, password), Objects::nonNull);
.until(() -> DriverManager.getConnection(jdbcUrl, username, password), Objects::nonNull);
} catch (ConditionTimeoutException e) {
return DriverManager.getConnection(jdbcUrl(cluster), username, password); // throw original
return DriverManager.getConnection(jdbcUrl, username, password); // throw original
}
}
@Test
void preparedDdlCopyAndUnloadUseDefaultExtendedQuery() throws Exception {
clusterId = "it-extended-prepared";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String bucket = "redshift-extended";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "copy/data.txt",
"1|alice\n2|bob\n".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
try (Connection connection = waitForConnection(cluster, "admin", "Secret123");
PreparedStatement ddl = connection.prepareStatement(
"CREATE TABLE ext_sales (id int ENCODE az64, name text) "
+ "DISTSTYLE KEY DISTKEY (id)");
PreparedStatement copy = connection.prepareStatement(
"COPY ext_sales FROM 's3://redshift-extended/copy/data.txt'");
PreparedStatement unload = connection.prepareStatement(
"UNLOAD ('select id, name from ext_sales order by id') "
+ "TO 's3://redshift-extended/unload/' ALLOWOVERWRITE")) {
ddl.execute();
copy.execute();
unload.execute();
try (ResultSet rows = connection.createStatement().executeQuery(
"SELECT count(*) FROM ext_sales")) {
assertTrue(rows.next());
assertEquals(2, rows.getInt(1));
}
}
List<S3Object> objects = s3.listObjects(bucket, "unload/", null, 100);
assertEquals(1, objects.size());
assertEquals("1|alice\n2|bob\n", new String(
s3.getObject(bucket, objects.get(0).getKey()).getData(), StandardCharsets.UTF_8));
}
@Test
void namedPreparedCopyAndUnloadCanBeExecutedTwice() throws Exception {
clusterId = "it-extended-named";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
String bucket = "redshift-extended-named";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "copy/data.txt", "7|seven\n".getBytes(StandardCharsets.UTF_8),
"text/plain", Map.of());
try (Connection connection = waitForConnection(
namedPreparedJdbcUrl(cluster), "admin", "Secret123")) {
connection.createStatement().execute("CREATE TABLE named_sales (id int, name text)");
try (PreparedStatement copy = connection.prepareStatement(
"COPY named_sales FROM 's3://redshift-extended-named/copy/data.txt'")) {
copy.execute();
copy.execute();
}
try (PreparedStatement unload = connection.prepareStatement(
"UNLOAD ('select id, name from named_sales order by id') "
+ "TO 's3://redshift-extended-named/unload/' ALLOWOVERWRITE")) {
unload.execute();
unload.execute();
}
try (ResultSet rows = connection.createStatement().executeQuery(
"SELECT count(*) FROM named_sales")) {
assertTrue(rows.next());
assertEquals(2, rows.getInt(1));
}
}
List<S3Object> objects = s3.listObjects(bucket, "unload/", null, 100);
assertEquals(1, objects.size());
assertEquals("7|seven\n7|seven\n", new String(
s3.getObject(bucket, objects.get(0).getKey()).getData(), StandardCharsets.UTF_8));
}
@Test
void rewritesCreateTableDdlOverSimpleQueryProtocol() throws SQLException {
clusterId = "it-interceptor-create";
@@ -212,24 +291,26 @@ class RedshiftInterceptorIntegrationTest {
s3.createBucket(bucket, "us-east-1");
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE tx_test (id int)");
c.setAutoCommit(false);
Statement st = c.createStatement();
st.execute("INSERT INTO tx_test VALUES (1)");
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.
assertThrows(
SQLException.class,
() -> st.execute("INSERT INTO tx_test VALUES (2)"));
c.rollback();
c.setAutoCommit(true);
try (ResultSet rs = c.createStatement().executeQuery("SELECT count(*) FROM tx_test")) {
assertTrue(rs.next());
assertEquals(0, rs.getInt(1));
}
assertTimeoutPreemptively(Duration.ofSeconds(15), () -> {
c.createStatement().execute("CREATE TABLE tx_test (id int)");
c.setAutoCommit(false);
Statement st = c.createStatement();
st.execute("INSERT INTO tx_test VALUES (1)");
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.
assertThrows(
SQLException.class,
() -> st.execute("INSERT INTO tx_test VALUES (2)"));
c.rollback();
c.setAutoCommit(true);
try (ResultSet rs = c.createStatement().executeQuery("SELECT count(*) FROM tx_test")) {
assertTrue(rs.next());
assertEquals(0, rs.getInt(1));
}
});
}
}
@@ -273,12 +354,12 @@ class RedshiftInterceptorIntegrationTest {
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);
List<S3Object> 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))) {
try (InputStream in = new GZIPInputStream(new ByteArrayInputStream(data))) {
in.transferTo(raw);
}
assertEquals("7\n8\n", raw.toString(StandardCharsets.UTF_8));
@@ -297,7 +378,7 @@ class RedshiftInterceptorIntegrationTest {
c.createStatement().execute("UNLOAD ('select id from m_src') TO 's3://redshift-unload-it-manifest/m/' MANIFEST");
}
var manifest = s3.getObject(bucket, "m/manifest");
S3Object manifest = s3.getObject(bucket, "m/manifest");
assertNotNull(manifest);
String json = new String(manifest.getData(), StandardCharsets.UTF_8);
assertTrue(json.contains("\"entries\""), json);
@@ -0,0 +1,181 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class BackendResponseCoordinatorTest {
private static final byte[] EMPTY_BODY = new byte[0];
@Test
void parseBindAndDescribeCompleteBeforeExecuteBecomesReady() throws InterruptedException {
ExtendedQuerySession session = new ExtendedQuerySession();
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session);
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
coordinator.register(BackendResponseCoordinator.Operation.PARSE, session.stageParse("s", copy));
coordinator.register(BackendResponseCoordinator.Operation.BIND, session.stageBind("p", "s"));
coordinator.register(BackendResponseCoordinator.Operation.DESCRIBE_PORTAL, null);
BackendResponseCoordinator.Ticket execute = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null);
coordinator.onBackendFrame('1', EMPTY_BODY);
coordinator.onBackendFrame('2', EMPTY_BODY);
coordinator.onBackendFrame('n', EMPTY_BODY);
assertEquals(BackendResponseCoordinator.GateResult.READY, coordinator.awaitTurn(execute));
assertSame(copy, session.portal("p").orElseThrow());
}
@Test
void statementDescribeWaitsPastParameterDescription() throws InterruptedException {
ExtendedQuerySession session = new ExtendedQuerySession();
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session);
coordinator.register(BackendResponseCoordinator.Operation.DESCRIBE_STATEMENT, null);
coordinator.onBackendFrame('t', EMPTY_BODY);
assertFalse(coordinator.awaitIdle(1, TimeUnit.MILLISECONDS));
coordinator.onBackendFrame('T', EMPTY_BODY);
assertTrue(coordinator.awaitIdle(1, TimeUnit.SECONDS));
}
@Test
void asynchronousFramesDoNotCompleteTheHeadOperation() throws InterruptedException {
ExtendedQuerySession session = new ExtendedQuerySession();
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session);
coordinator.register(BackendResponseCoordinator.Operation.PARSE, null);
coordinator.onBackendFrame('N', EMPTY_BODY);
coordinator.onBackendFrame('A', EMPTY_BODY);
coordinator.onBackendFrame('S', EMPTY_BODY);
assertFalse(coordinator.awaitIdle(1, TimeUnit.MILLISECONDS));
coordinator.onBackendFrame('1', EMPTY_BODY);
assertTrue(coordinator.awaitIdle(1, TimeUnit.SECONDS));
}
@Test
void extendedErrorRejectsPipelinedMutationsAndSkipsUntilSync() throws InterruptedException {
ExtendedQuerySession session = new ExtendedQuerySession();
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session);
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
coordinator.register(BackendResponseCoordinator.Operation.PARSE, session.stageParse("s", copy));
coordinator.register(BackendResponseCoordinator.Operation.BIND, session.stageBind("p", "s"));
BackendResponseCoordinator.Ticket execute = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null);
coordinator.onBackendFrame('E', EMPTY_BODY);
assertEquals(BackendResponseCoordinator.GateResult.SKIPPED_AFTER_ERROR,
coordinator.awaitTurn(execute));
assertTrue(session.statement("s").isEmpty());
assertTrue(session.portal("p").isEmpty());
assertTrue(coordinator.isDiscardingUntilSync());
BackendResponseCoordinator.Ticket skipped = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null);
assertEquals(BackendResponseCoordinator.GateResult.SKIPPED_AFTER_ERROR,
coordinator.awaitTurn(skipped));
coordinator.register(BackendResponseCoordinator.Operation.SYNC, null);
coordinator.onBackendFrame('Z', new byte[]{'I'});
assertFalse(coordinator.isDiscardingUntilSync());
assertEquals('I', coordinator.lastReadyStatus());
}
@Test
void errorOnAnOperationWithoutAMutationRejectsLaterPipelinedMutations() {
ExtendedQuerySession session = new ExtendedQuerySession();
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session);
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
session.confirm(session.stageParse("s", copy));
coordinator.register(BackendResponseCoordinator.Operation.DESCRIBE_STATEMENT, null);
coordinator.register(BackendResponseCoordinator.Operation.BIND, session.stageBind("p", "s"));
coordinator.onBackendFrame('E', EMPTY_BODY);
assertTrue(session.portal("p").isEmpty());
}
@Test
void simpleQueryErrorCompletesOnlyWhenReadyForQueryArrives() throws InterruptedException {
ExtendedQuerySession session = new ExtendedQuerySession();
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session);
coordinator.register(BackendResponseCoordinator.Operation.SIMPLE_QUERY, null);
coordinator.onBackendFrame('E', EMPTY_BODY);
assertFalse(coordinator.isDiscardingUntilSync());
assertFalse(coordinator.awaitIdle(1, TimeUnit.MILLISECONDS));
coordinator.onBackendFrame('Z', new byte[]{'I'});
assertTrue(coordinator.awaitIdle(1, TimeUnit.SECONDS));
assertEquals('I', coordinator.lastReadyStatus());
}
@Test
void readyForQueryInsideATransactionRetainsPortals() {
ExtendedQuerySession session = new ExtendedQuerySession();
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session);
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
session.confirm(session.stageParse("s", copy));
session.confirm(session.stageBind("p", "s"));
coordinator.register(BackendResponseCoordinator.Operation.SYNC, null);
coordinator.onBackendFrame('Z', new byte[]{'T'});
assertSame(copy, session.portal("p").orElseThrow());
assertEquals('T', coordinator.lastReadyStatus());
}
@Test
void idleReadyForQueryKeepsPortalsStagedForTheNextPipelinedCycle() {
ExtendedQuerySession session = new ExtendedQuerySession();
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session);
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
session.confirm(session.stageParse("s", copy));
session.confirm(session.stageBind("old", "s"));
coordinator.register(BackendResponseCoordinator.Operation.SYNC, null);
coordinator.register(BackendResponseCoordinator.Operation.BIND, session.stageBind("next", "s"));
coordinator.onBackendFrame('Z', new byte[]{'I'});
assertTrue(session.portal("old").isEmpty());
assertSame(copy, session.portal("next").orElseThrow());
coordinator.onBackendFrame('E', EMPTY_BODY);
assertTrue(session.portal("old").isEmpty());
assertTrue(session.portal("next").isEmpty());
}
@Test
void closeWakesABlockedWaiter() throws Exception {
ExtendedQuerySession session = new ExtendedQuerySession();
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session);
coordinator.register(BackendResponseCoordinator.Operation.PARSE, null);
BackendResponseCoordinator.Ticket execute = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null);
CompletableFuture<BackendResponseCoordinator.GateResult> result = CompletableFuture.supplyAsync(() -> {
try {
return coordinator.awaitTurn(execute);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
});
coordinator.close();
assertEquals(BackendResponseCoordinator.GateResult.CLOSED, result.get(1, TimeUnit.SECONDS));
}
}
@@ -0,0 +1,228 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ExtendedQuerySessionTest {
@Test
void bindMakesAnInterceptedStatementVisibleThroughItsPortal() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
ExtendedQuerySession.Mutation parse = session.stageParse("copy-s", copy);
ExtendedQuerySession.Mutation bind = session.stageBind("copy-p", "copy-s");
assertSame(copy, session.statement("copy-s").orElseThrow());
assertSame(copy, session.portal("copy-p").orElseThrow());
session.confirm(parse);
session.confirm(bind);
}
@Test
void ordinaryUnnamedParseAndBindReplaceInterceptedUnnamedMappings() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
session.confirm(session.stageParse("", copy));
session.confirm(session.stageBind("", ""));
session.confirm(session.stageParse("", null));
session.confirm(session.stageBind("", ""));
assertTrue(session.statement("").isEmpty());
assertTrue(session.portal("").isEmpty());
}
@Test
void rejectingAParseRollsBackItAndEveryLaterPipelinedMutation() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
ExtendedQuerySession.Mutation parse = session.stageParse("s", copy);
session.stageBind("p", "s");
session.rejectFrom(parse);
assertTrue(session.statement("s").isEmpty());
assertTrue(session.portal("p").isEmpty());
}
@Test
void namedStatementsCoexist() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement first = CopyStatementParser.parse("COPY first FROM 's3://b/one'");
CopyStatementParser.S3Statement second = CopyStatementParser.parse("COPY second FROM 's3://b/two'");
session.confirm(session.stageParse("first", first));
session.confirm(session.stageParse("second", second));
assertSame(first, session.statement("first").orElseThrow());
assertSame(second, session.statement("second").orElseThrow());
}
@Test
void unnamedPortalRebindingReplacesItsStatement() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement first = CopyStatementParser.parse("COPY first FROM 's3://b/one'");
CopyStatementParser.S3Statement second = CopyStatementParser.parse("COPY second FROM 's3://b/two'");
session.confirm(session.stageParse("first", first));
session.confirm(session.stageParse("second", second));
session.confirm(session.stageBind("", "first"));
session.confirm(session.stageBind("", "second"));
assertSame(second, session.portal("").orElseThrow());
}
@Test
void twoPortalsCanReferenceOneStatement() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
session.confirm(session.stageParse("s", copy));
session.confirm(session.stageBind("first", "s"));
session.confirm(session.stageBind("second", "s"));
assertSame(copy, session.portal("first").orElseThrow());
assertSame(copy, session.portal("second").orElseThrow());
}
@Test
void closingAStatementAlsoClosesItsPortals() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
session.confirm(session.stageParse("s", copy));
session.confirm(session.stageBind("first", "s"));
session.confirm(session.stageBind("second", "s"));
session.confirm(session.stageClose('S', "s"));
assertTrue(session.statement("s").isEmpty());
assertTrue(session.portal("first").isEmpty());
assertTrue(session.portal("second").isEmpty());
}
@Test
void closingAPortalLeavesItsStatementAndOtherPortals() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
session.confirm(session.stageParse("s", copy));
session.confirm(session.stageBind("first", "s"));
session.confirm(session.stageBind("second", "s"));
session.confirm(session.stageClose('P', "first"));
assertSame(copy, session.statement("s").orElseThrow());
assertTrue(session.portal("first").isEmpty());
assertSame(copy, session.portal("second").orElseThrow());
}
@Test
void rejectingAStatementCloseRestoresTheStatementAndItsPortals() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
session.confirm(session.stageParse("s", copy));
session.confirm(session.stageBind("first", "s"));
session.confirm(session.stageBind("second", "s"));
ExtendedQuerySession.Mutation close = session.stageClose('S', "s");
assertTrue(session.statement("s").isEmpty());
assertTrue(session.portal("first").isEmpty());
assertTrue(session.portal("second").isEmpty());
session.rejectFrom(close);
assertSame(copy, session.statement("s").orElseThrow());
assertSame(copy, session.portal("first").orElseThrow());
assertSame(copy, session.portal("second").orElseThrow());
}
@Test
void rejectingAPortalCloseRestoresOnlyThatPortal() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
session.confirm(session.stageParse("s", copy));
session.confirm(session.stageBind("p", "s"));
ExtendedQuerySession.Mutation close = session.stageClose('P', "p");
session.rejectFrom(close);
assertSame(copy, session.statement("s").orElseThrow());
assertSame(copy, session.portal("p").orElseThrow());
}
@Test
void repeatedLookupDoesNotChangeRollbackState() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
ExtendedQuerySession.Mutation parse = session.stageParse("s", copy);
assertSame(copy, session.statement("s").orElseThrow());
assertSame(copy, session.statement("s").orElseThrow());
session.rejectFrom(parse);
assertTrue(session.statement("s").isEmpty());
}
@Test
void rejectingAnEarlierMutationRetainsLaterSyncCycleMutation() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
ExtendedQuerySession.Mutation rejected = session.stageParse("invalid", null);
ExtendedQuerySession.Mutation retained = session.stageParse("copy", copy);
session.rejectFrom(rejected);
assertSame(copy, session.statement("copy").orElseThrow());
session.confirm(retained);
}
@Test
void transactionEndClearsPortalsButRetainsStatements() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
session.confirm(session.stageParse("s", copy));
session.confirm(session.stageBind("p", "s"));
session.transactionEnded();
assertSame(copy, session.statement("s").orElseThrow());
assertTrue(session.portal("p").isEmpty());
}
@Test
void clearPortalsRetainsStatements() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
session.confirm(session.stageParse("s", copy));
session.confirm(session.stageBind("p", "s"));
session.clearPortals();
assertSame(copy, session.statement("s").orElseThrow());
assertTrue(session.portal("p").isEmpty());
}
@Test
void clearRemovesStatementsAndPortals() {
ExtendedQuerySession session = new ExtendedQuerySession();
CopyStatementParser.S3Statement copy = CopyStatementParser.parse("COPY t FROM 's3://b/k'");
session.confirm(session.stageParse("s", copy));
session.confirm(session.stageBind("p", "s"));
session.clear();
assertTrue(session.statement("s").isEmpty());
assertTrue(session.portal("p").isEmpty());
}
@Test
void closeRejectsAnInvalidTargetType() {
ExtendedQuerySession session = new ExtendedQuerySession();
assertThrows(IllegalArgumentException.class, () -> session.stageClose('X', "name"));
}
}
@@ -0,0 +1,222 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ExtendedS3ExchangeTest {
private Socket simClient;
private Socket simBackend;
private Socket testClient;
private Socket testBackend;
private S3Service s3;
private final AtomicReference<Throwable> backendFailure = new AtomicReference<>();
@BeforeEach
void setUp() throws IOException {
ServerSocket clientListener = new ServerSocket(0);
simClient = new Socket("localhost", clientListener.getLocalPort());
testClient = clientListener.accept();
clientListener.close();
ServerSocket backendListener = new ServerSocket(0);
simBackend = new Socket("localhost", backendListener.getLocalPort());
testBackend = backendListener.accept();
backendListener.close();
s3 = mock(S3Service.class);
}
@AfterEach
void tearDown() throws IOException {
for (Socket socket : new Socket[]{simClient, simBackend, testClient, testBackend}) {
if (socket != null && !socket.isClosed()) {
socket.close();
}
}
}
@Test
void copyInForwardsCommandCompleteWithoutReadyForQuery() throws Exception {
when(s3.objectExists("b", "in/data")).thenReturn(true);
when(s3.getObject("b", "in/data")).thenReturn(
new S3Object("b", "in/data", "1|a\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
CopyStatementParser.S3CopyFrom copy = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "in/data", "|", 0, false, false, null);
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(new ExtendedQuerySession());
BackendResponseCoordinator.Ticket ticket = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null);
ByteArrayOutputStream copied = new ByteArrayOutputStream();
writeSync();
Thread backend = backendThread(() -> playCopyIn(copied));
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), copy, s3, coordinator, ticket);
joinBackend(backend);
PostgresWireDecoder clientDecoder = new PostgresWireDecoder(testClient.getInputStream());
assertEquals('C', clientDecoder.nextMessage().type());
assertEquals("1|a\n", copied.toString(StandardCharsets.US_ASCII));
coordinator.onBackendFrame('Z', new byte[]{'I'});
assertTrue(coordinator.awaitIdle(1, TimeUnit.SECONDS));
testClient.setSoTimeout(200);
assertThrows(SocketTimeoutException.class, () -> testClient.getInputStream().read());
}
@Test
void copyOutWritesS3AndForwardsOnlyCommandComplete() throws Exception {
Map<String, byte[]> written = new ConcurrentHashMap<>();
when(s3.putObject(eq("b"), any(), any(), any(), any())).thenAnswer(invocation -> {
written.put(invocation.getArgument(1), invocation.getArgument(2));
return null;
});
CopyStatementParser.S3Unload unload = new CopyStatementParser.S3Unload(
"select a from t", "b", "out/", "|", false, false, false,
false, null, false, true, false, 0);
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(new ExtendedQuerySession());
BackendResponseCoordinator.Ticket ticket = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null);
writeSync();
Thread backend = backendThread(this::playCopyOut);
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), unload, s3, coordinator, ticket);
joinBackend(backend);
assertEquals("1\n2\n", new String(written.get("out/000"), StandardCharsets.US_ASCII));
PostgresWireDecoder clientDecoder = new PostgresWireDecoder(testClient.getInputStream());
assertEquals('C', clientDecoder.nextMessage().type());
coordinator.onBackendFrame('Z', new byte[]{'I'});
assertTrue(coordinator.awaitIdle(1, TimeUnit.SECONDS));
testClient.setSoTimeout(200);
assertThrows(SocketTimeoutException.class, () -> testClient.getInputStream().read());
}
@Test
void missingCopyInputSendsCopyFailAndWaitsForSyncRecovery() throws Exception {
CopyStatementParser.S3CopyFrom copy = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "missing", "|", 0, false, false, null);
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(new ExtendedQuerySession());
BackendResponseCoordinator.Ticket ticket = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null);
writeSync();
Thread backend = backendThread(() -> {
PostgresWireDecoder decoder = new PostgresWireDecoder(testBackend.getInputStream());
assertEquals('E', decoder.nextMessage().type());
testBackend.getOutputStream().write(new byte[]{'G', 0, 0, 0, 7, 0, 0, 0});
testBackend.getOutputStream().flush();
assertEquals('f', decoder.nextMessage().type());
assertEquals('S', decoder.nextMessage().type());
writeFrame(testBackend.getOutputStream(), 'E',
"SERROR\0C57014\0MCOPY aborted\0\0".getBytes(StandardCharsets.US_ASCII));
writeFrame(testBackend.getOutputStream(), 'Z', new byte[]{'E'});
testBackend.getOutputStream().flush();
});
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), copy, s3, coordinator, ticket);
joinBackend(backend);
testClient.setSoTimeout(1_000);
PostgresWireDecoder clientDecoder = new PostgresWireDecoder(testClient.getInputStream());
PostgresWireDecoder.FrontendMessage error = clientDecoder.nextMessage();
assertEquals('E', error.type());
assertTrue(new String(error.body(), StandardCharsets.US_ASCII).contains("XX000"));
assertTrue(new String(error.body(), StandardCharsets.US_ASCII).contains("s3://b/missing"));
assertEquals('Z', clientDecoder.nextMessage().type());
assertEquals('E', coordinator.lastReadyStatus());
assertTrue(coordinator.awaitIdle(1, TimeUnit.SECONDS));
}
private static PostgresWireDecoder.FrontendMessage executeFrame() {
return new PostgresWireDecoder.FrontendMessage('E', new byte[]{0, 0, 0, 0, 0});
}
private void playCopyIn(ByteArrayOutputStream copied) throws IOException {
PostgresWireDecoder decoder = new PostgresWireDecoder(testBackend.getInputStream());
assertEquals('E', decoder.nextMessage().type());
testBackend.getOutputStream().write(new byte[]{'G', 0, 0, 0, 7, 0, 0, 0});
testBackend.getOutputStream().flush();
while (true) {
PostgresWireDecoder.FrontendMessage message = decoder.nextMessage();
if (message.type() == 'd') {
copied.write(message.body());
} else if (message.type() == 'c') {
break;
}
}
assertEquals('S', decoder.nextMessage().type());
writeCommandComplete();
}
private void playCopyOut() throws IOException {
PostgresWireDecoder decoder = new PostgresWireDecoder(testBackend.getInputStream());
assertEquals('E', decoder.nextMessage().type());
OutputStream out = testBackend.getOutputStream();
out.write(new byte[]{'H', 0, 0, 0, 7, 0, 0, 0});
writeFrame(out, 'd', "1\n".getBytes(StandardCharsets.US_ASCII));
writeFrame(out, 'd', "2\n".getBytes(StandardCharsets.US_ASCII));
out.write(new byte[]{'c', 0, 0, 0, 4});
writeCommandComplete();
assertEquals('S', decoder.nextMessage().type());
}
private void writeCommandComplete() throws IOException {
writeFrame(testBackend.getOutputStream(), 'C', "COPY 2\0".getBytes(StandardCharsets.US_ASCII));
testBackend.getOutputStream().flush();
}
private void writeSync() throws IOException {
testClient.getOutputStream().write(new byte[]{'S', 0, 0, 0, 4});
testClient.getOutputStream().flush();
}
private static void writeFrame(OutputStream out, char type, byte[] body) throws IOException {
out.write(type);
out.write(new byte[]{0, 0, 0, (byte) (4 + body.length)});
out.write(body);
}
private Thread backendThread(BackendScript script) {
return Thread.ofVirtual().start(() -> {
try {
script.run();
} catch (Throwable failure) {
backendFailure.compareAndSet(null, failure);
}
});
}
private void joinBackend(Thread backend) throws InterruptedException {
backend.join();
Throwable failure = backendFailure.get();
if (failure != null) {
throw new AssertionError("fake backend failed", failure);
}
}
@FunctionalInterface
private interface BackendScript {
void run() throws IOException;
}
}
@@ -9,6 +9,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -20,6 +21,96 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class PostgresWireDecoderTest {
@Test
void decodesParseNameSqlAndParameterTypeOids() throws IOException {
byte[] packet = frame('P', concat(
cString("stmt-1"),
cString("select $1::int"),
int16(1),
int32(23)));
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(packet));
PostgresWireDecoder.ParseMessage parse = decoder.decodeParse(decoder.nextMessage());
assertEquals("stmt-1", parse.statementName());
assertEquals("select $1::int", parse.sql());
assertEquals(List.of(23), parse.parameterTypeOids());
}
@Test
void decodesBindNamesWithoutRetainingValueSemantics() throws IOException {
byte[] body = concat(cString("portal-1"), cString("stmt-1"), int16(0), int16(0), int16(0));
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(frame('B', body)));
PostgresWireDecoder.BindMessage bind = decoder.decodeBind(decoder.nextMessage());
assertEquals("portal-1", bind.portalName());
assertEquals("stmt-1", bind.statementName());
}
@Test
void decodesExecuteDescribeAndClose() throws IOException {
PostgresWireDecoder.ExecuteMessage execute = decodeExecute(frame('E', concat(cString("p"), int32(0))));
PostgresWireDecoder.TargetMessage describe = decodeDescribe(frame('D', concat(new byte[]{'S'}, cString("s"))));
PostgresWireDecoder.TargetMessage close = decodeClose(frame('C', concat(new byte[]{'P'}, cString("p"))));
assertEquals(new PostgresWireDecoder.ExecuteMessage("p", 0), execute);
assertEquals(new PostgresWireDecoder.TargetMessage('S', "s"), describe);
assertEquals(new PostgresWireDecoder.TargetMessage('P', "p"), close);
}
@Test
void rejectsParseWithMissingCStringTerminator() {
PostgresWireDecoder decoder = decoderFor('P', "stmt-1".getBytes(StandardCharsets.UTF_8));
assertThrows(IOException.class, () -> decoder.decodeParse(decoder.nextMessage()));
}
@Test
void rejectsParseWithTruncatedInt16() {
byte[] body = concat(cString("stmt-1"), cString("select 1"), new byte[]{0});
PostgresWireDecoder decoder = decoderFor('P', body);
assertThrows(IOException.class, () -> decoder.decodeParse(decoder.nextMessage()));
}
@Test
void rejectsParseWithTruncatedOidList() {
byte[] body = concat(cString("stmt-1"), cString("select $1"), int16(1), new byte[]{0, 0});
PostgresWireDecoder decoder = decoderFor('P', body);
assertThrows(IOException.class, () -> decoder.decodeParse(decoder.nextMessage()));
}
@Test
void rejectsDescribeWithInvalidTargetByte() {
PostgresWireDecoder decoder = decoderFor('D', concat(new byte[]{'X'}, cString("name")));
assertThrows(IOException.class, () -> decoder.decodeDescribe(decoder.nextMessage()));
}
@Test
void rejectsCloseWithInvalidTargetByte() {
PostgresWireDecoder decoder = decoderFor('C', concat(new byte[]{'X'}, cString("name")));
assertThrows(IOException.class, () -> decoder.decodeClose(decoder.nextMessage()));
}
@Test
void rejectsExecuteWithTrailingBytes() {
PostgresWireDecoder decoder = decoderFor('E', concat(cString("p"), int32(0), new byte[]{1}));
assertThrows(IOException.class, () -> decoder.decodeExecute(decoder.nextMessage()));
}
@Test
void encodeParsePreservesNameAndTypeOidsWhileReplacingSql() throws IOException {
PostgresWireDecoder.ParseMessage original = new PostgresWireDecoder.ParseMessage(
"ddl", "CREATE TABLE t (id int ENCODE az64)", List.of(23, 25));
byte[] encoded = PostgresWireDecoder.encodeParse(original, "CREATE TABLE t (id int)");
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(encoded));
PostgresWireDecoder.ParseMessage decoded = decoder.decodeParse(decoder.nextMessage());
assertEquals("ddl", decoded.statementName());
assertEquals("CREATE TABLE t (id int)", decoded.sql());
assertEquals(List.of(23, 25), decoded.parameterTypeOids());
}
@Test
void decodesASimpleQueryAndThenReportsEof() throws IOException {
byte[] packet = PostgresWireDecoder.encodeQuery("SELECT 1");
@@ -308,4 +399,69 @@ class PostgresWireDecoderTest {
assertNull(msg.body());
assertEquals(1 + (long) totalLength, bytesWritten[0]);
}
private static PostgresWireDecoder decoderFor(char type, byte[] body) {
return new PostgresWireDecoder(new ByteArrayInputStream(frame(type, body)));
}
private static PostgresWireDecoder.ExecuteMessage decodeExecute(byte[] packet) throws IOException {
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(packet));
return decoder.decodeExecute(decoder.nextMessage());
}
private static PostgresWireDecoder.TargetMessage decodeDescribe(byte[] packet) throws IOException {
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(packet));
return decoder.decodeDescribe(decoder.nextMessage());
}
private static PostgresWireDecoder.TargetMessage decodeClose(byte[] packet) throws IOException {
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(packet));
return decoder.decodeClose(decoder.nextMessage());
}
private static byte[] frame(char type, byte[] body) {
int length = body.length + 4;
byte[] packet = new byte[body.length + 5];
packet[0] = (byte) type;
packet[1] = (byte) ((length >> 24) & 0xFF);
packet[2] = (byte) ((length >> 16) & 0xFF);
packet[3] = (byte) ((length >> 8) & 0xFF);
packet[4] = (byte) (length & 0xFF);
System.arraycopy(body, 0, packet, 5, body.length);
return packet;
}
private static byte[] cString(String value) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
byte[] result = new byte[bytes.length + 1];
System.arraycopy(bytes, 0, result, 0, bytes.length);
return result;
}
private static byte[] int16(int value) {
return new byte[]{(byte) ((value >> 8) & 0xFF), (byte) (value & 0xFF)};
}
private static byte[] int32(int value) {
return new byte[]{
(byte) ((value >> 24) & 0xFF),
(byte) ((value >> 16) & 0xFF),
(byte) ((value >> 8) & 0xFF),
(byte) (value & 0xFF)
};
}
private static byte[] concat(byte[]... parts) {
int length = 0;
for (byte[] part : parts) {
length += part.length;
}
byte[] result = new byte[length];
int offset = 0;
for (byte[] part : parts) {
System.arraycopy(part, 0, result, offset, part.length);
offset += part.length;
}
return result;
}
}
@@ -5,8 +5,10 @@ import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.mockito.Mockito;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
@@ -123,6 +125,185 @@ class RedshiftInterceptingBridgeTest {
assertArrayEquals(parsePacket, nextForwarded().toPacketBytes());
}
@Test
void rewritesDdlParseWhilePreservingNameAndParameterOids() throws IOException {
startBridge();
PostgresWireDecoder.ParseMessage parse = new PostgresWireDecoder.ParseMessage(
"ddl", "CREATE TABLE sales (id int ENCODE az64, d date) "
+ "DISTSTYLE KEY DISTKEY (id) SORTKEY (d)", List.of(23, 25));
testClientEnd.getOutputStream().write(PostgresWireDecoder.encodeParse(parse, parse.sql()));
testClientEnd.getOutputStream().flush();
PostgresWireDecoder backendDecoder = new PostgresWireDecoder(testBackendEnd.getInputStream());
PostgresWireDecoder.ParseMessage forwarded = backendDecoder.decodeParse(backendDecoder.nextMessage());
assertEquals("ddl", forwarded.statementName());
assertEquals(List.of(23, 25), forwarded.parameterTypeOids());
String sql = forwarded.sql().toUpperCase();
assertFalse(sql.contains("DISTSTYLE"), sql);
assertFalse(sql.contains("DISTKEY"), sql);
assertFalse(sql.contains("SORTKEY"), sql);
assertFalse(sql.contains("ENCODE"), sql);
}
@Test
void parameterizedCopyParseFallsOpenByteForByte() throws IOException {
startBridge();
PostgresWireDecoder.ParseMessage parse = new PostgresWireDecoder.ParseMessage(
"copy", "COPY t FROM 's3://b/in/data'", List.of(25));
byte[] packet = PostgresWireDecoder.encodeParse(parse, parse.sql());
testClientEnd.getOutputStream().write(packet);
testClientEnd.getOutputStream().flush();
assertArrayEquals(packet, nextForwarded().toPacketBytes());
}
@Test
void pipelinedExtendedCopyPreservesResponseOrderAndSyncReadyForQuery() throws Exception {
startBridge();
Mockito.when(s3Stub.objectExists("b", "in/data")).thenReturn(true);
Mockito.when(s3Stub.getObject("b", "in/data")).thenReturn(
new S3Object("b", "in/data", "1|a\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
AtomicReference<Throwable> backendFailure = new AtomicReference<>();
Thread backend = Thread.ofVirtual().start(() -> {
try {
PostgresWireDecoder decoder = new PostgresWireDecoder(testBackendEnd.getInputStream());
PostgresWireDecoder.ParseMessage parse = decoder.decodeParse(decoder.nextMessage());
assertTrue(parse.sql().contains("FROM STDIN"), parse.sql());
writeBackendFrame('1', new byte[0]);
assertEquals('B', decoder.nextMessage().type());
writeBackendFrame('2', new byte[0]);
assertEquals('D', decoder.nextMessage().type());
writeBackendFrame('n', new byte[0]);
assertEquals('E', decoder.nextMessage().type());
writeBackendFrame('G', new byte[]{0, 0, 0});
while (decoder.nextMessage().type() != 'c') {
// Consume CopyData until the bridge completes CopyIn.
}
assertEquals('S', decoder.nextMessage().type());
writeBackendFrame('C', "COPY 1\0".getBytes(StandardCharsets.US_ASCII));
writeBackendFrame('Z', new byte[]{'I'});
} catch (Throwable failure) {
backendFailure.compareAndSet(null, failure);
}
});
PostgresWireDecoder.ParseMessage parse = new PostgresWireDecoder.ParseMessage(
"copy-s", "COPY t FROM 's3://b/in/data'", List.of());
ByteArrayOutputStream pipeline = new ByteArrayOutputStream();
pipeline.write(PostgresWireDecoder.encodeParse(parse, parse.sql()));
pipeline.write(frame('B', concat(cString("copy-p"), cString("copy-s"), new byte[6])));
pipeline.write(frame('D', concat(new byte[]{'P'}, cString("copy-p"))));
pipeline.write(frame('E', concat(cString("copy-p"), new byte[4])));
pipeline.write(frame('S', new byte[0]));
testClientEnd.getOutputStream().write(pipeline.toByteArray());
testClientEnd.getOutputStream().flush();
PostgresWireDecoder clientDecoder = new PostgresWireDecoder(testClientEnd.getInputStream());
assertEquals('1', clientDecoder.nextMessage().type());
assertEquals('2', clientDecoder.nextMessage().type());
assertEquals('n', clientDecoder.nextMessage().type());
assertEquals('C', clientDecoder.nextMessage().type());
assertEquals('Z', clientDecoder.nextMessage().type());
backend.join();
if (backendFailure.get() != null) {
throw new AssertionError("fake backend failed", backendFailure.get());
}
}
@Test
@Timeout(5)
void extendedUnloadWithManifestCompletesAfterCopyOutCommandComplete() throws Exception {
startBridge();
Mockito.when(s3Stub.putObject(
Mockito.eq("b"), Mockito.anyString(), Mockito.any(), Mockito.anyString(), Mockito.any()))
.thenReturn(null);
AtomicReference<Throwable> backendFailure = new AtomicReference<>();
Thread backend = Thread.ofVirtual().start(() -> {
try {
PostgresWireDecoder decoder = new PostgresWireDecoder(testBackendEnd.getInputStream());
PostgresWireDecoder.ParseMessage parse = decoder.decodeParse(decoder.nextMessage());
assertTrue(parse.sql().startsWith("COPY (select id from t) TO STDOUT"), parse.sql());
assertEquals('B', decoder.nextMessage().type());
assertEquals('D', decoder.nextMessage().type());
assertEquals('E', decoder.nextMessage().type());
assertEquals('S', decoder.nextMessage().type());
writeBackendFrame('1', new byte[0]);
writeBackendFrame('2', new byte[0]);
writeBackendFrame('n', new byte[0]);
writeBackendFrame('H', new byte[]{0, 0, 0});
writeBackendFrame('d', "1\n".getBytes(StandardCharsets.US_ASCII));
writeBackendFrame('c', new byte[0]);
writeBackendFrame('C', "COPY 1\0".getBytes(StandardCharsets.US_ASCII));
writeBackendFrame('Z', new byte[]{'I'});
} catch (Throwable failure) {
backendFailure.compareAndSet(null, failure);
}
});
PostgresWireDecoder.ParseMessage parse = new PostgresWireDecoder.ParseMessage(
"unload-s", "UNLOAD ('select id from t') TO 's3://b/out/' MANIFEST", List.of());
ByteArrayOutputStream pipeline = new ByteArrayOutputStream();
pipeline.write(PostgresWireDecoder.encodeParse(parse, parse.sql()));
pipeline.write(frame('B', concat(cString("unload-p"), cString("unload-s"), new byte[6])));
pipeline.write(frame('D', concat(new byte[]{'P'}, cString("unload-p"))));
pipeline.write(frame('E', concat(cString("unload-p"), new byte[4])));
pipeline.write(frame('S', new byte[0]));
testClientEnd.getOutputStream().write(pipeline.toByteArray());
testClientEnd.getOutputStream().flush();
testClientEnd.setSoTimeout(3000);
backend.join(1000);
if (backendFailure.get() != null) {
throw new AssertionError("fake backend failed", backendFailure.get());
}
PostgresWireDecoder clientDecoder = new PostgresWireDecoder(testClientEnd.getInputStream());
assertEquals('1', clientDecoder.nextMessage().type());
assertEquals('2', clientDecoder.nextMessage().type());
assertEquals('n', clientDecoder.nextMessage().type());
assertEquals('C', clientDecoder.nextMessage().type());
assertEquals('Z', clientDecoder.nextMessage().type());
backend.join();
if (backendFailure.get() != null) {
throw new AssertionError("fake backend failed", backendFailure.get());
}
}
private void writeBackendFrame(char type, byte[] body) throws IOException {
testBackendEnd.getOutputStream().write(frame(type, body));
testBackendEnd.getOutputStream().flush();
}
private static byte[] frame(char type, byte[] body) {
int length = 4 + body.length;
byte[] packet = new byte[5 + body.length];
packet[0] = (byte) type;
packet[1] = (byte) (length >>> 24);
packet[2] = (byte) (length >>> 16);
packet[3] = (byte) (length >>> 8);
packet[4] = (byte) length;
System.arraycopy(body, 0, packet, 5, body.length);
return packet;
}
private static byte[] cString(String value) {
return concat(value.getBytes(StandardCharsets.UTF_8), new byte[]{0});
}
private static byte[] concat(byte[]... values) {
int length = 0;
for (byte[] value : values) {
length += value.length;
}
byte[] result = new byte[length];
int offset = 0;
for (byte[] value : values) {
System.arraycopy(value, 0, result, offset, value.length);
offset += value.length;
}
return result;
}
@Test
void pumpsBackendBytesToTheClientUnchanged() throws IOException {
startBridge();
@@ -143,6 +143,58 @@ class S3CopySimulatorTest {
"|", false, gzip, false, false, null, manifest, allowOverwrite, parallel, maxFileSize);
}
@Test
void preparedCopyUsesSortedKeysAndBackendSql() {
when(s3.objectExists("b", "prefix/")).thenReturn(false);
when(s3.listObjectsWithPrefixes(
eq("b"), eq("prefix/"), isNull(), anyInt(), isNull(), isNull()))
.thenReturn(new S3Service.ListObjectsResult(
List.of(
new S3Object("b", "prefix/z", new byte[0], "text/plain"),
new S3Object("b", "prefix/a", new byte[0], "text/plain")),
List.of(), false, null));
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "prefix/", null, 0, false, true, null);
S3CopySimulator.CopyInput input = S3CopySimulator.prepareCopy(spec, s3);
assertEquals(List.of("prefix/a", "prefix/z"), input.keys());
assertEquals("COPY t FROM STDIN WITH (FORMAT csv, DELIMITER ',')",
S3CopySimulator.copyBackendSql(spec));
}
@Test
void preparedCopyReportsMissingObject() {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "missing", "|", 0, false, false, null);
S3CopySimulator.S3TransferException error = assertThrows(
S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.prepareCopy(spec, s3));
assertEquals("XX000", error.sqlState());
assertEquals("S3 object s3://b/missing not found", error.getMessage());
}
@Test
void unloadCollectorWritesOneEmptyObjectForZeroRows() throws Exception {
Map<String, byte[]> written = new ConcurrentHashMap<>();
when(s3.putObject(eq("b"), any(), any(), any(), any())).thenAnswer(invocation -> {
written.put(invocation.getArgument(1), invocation.getArgument(2));
return null;
});
CopyStatementParser.S3Unload spec = unloadSpec("b", "out/", false, false, true, false, 0);
try (S3CopySimulator.UnloadCollector collector = S3CopySimulator.prepareUnload(spec, s3)) {
collector.complete();
}
assertEquals(1, written.size());
assertEquals(0, written.get("out/000").length);
assertEquals("COPY (select a,b from t) TO STDOUT WITH (FORMAT text, DELIMITER '|')",
S3CopySimulator.unloadBackendSql(spec));
}
@Test
void unloadWritesSingleObjectAndForwardsCommandComplete() throws Exception {
Map<String, byte[]> written = new ConcurrentHashMap<>();