mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift): emulate Redshift COPY FROM s3 over Simple Query protocol (#3100)
* feat(redshift): parse COPY FROM s3 statements
* feat(redshift): simulate Redshift COPY FROM s3 via CopyIn
* feat(redshift): mediate the intercepting bridge pump with a backend lock
* feat(redshift): dispatch COPY FROM s3 via intercepting bridge
* test(redshift): cover COPY from S3 end to end
* docs(redshift): document COPY from S3 support
* fix(redshift): harden the S3 COPY simulator error and protocol handling
Address code review findings on the Part 4 COPY simulator:
- Guarantee exactly one client response on a mid-copy failure. The abort
path sent CopyFail, relayed the backend's ErrorResponse/ReadyForQuery,
then also synthesized its own, desynchronizing the client. It now emits
one response: the backend's, or a synthesized one only when the backend
is unreachable.
- Catch RuntimeException (AwsException) while streaming objects. A key that
vanished between listing and reading previously propagated out of the
bridge and closed the connection with the backend stuck in CopyIn.
- Reply to the client when the backend closes before CopyInResponse
instead of returning silently and leaving the client blocked.
- Stop doubling backslashes when quoting DELIMITER / NULL values. Under
standard_conforming_strings a backslash is literal, so NULL AS '\N' was
reaching the backend as '\N' and nulls loaded as text.
- Reject COPY statements carrying an option the simulator cannot honour
(PARQUET, JSON, MAXERROR, credentials, ...) or a trailing statement,
so they fail open to PostgreSQL rather than loading with wrong framing.
- Scan option keywords with string literals blanked, so NULL AS 'csv' no
longer flips the format and DELIMITER ';' no longer trips the trailing
check.
- Report the failed-transaction status ('E') in a synthesized error when
the client is in a transaction block; track it from the backend's
ReadyForQuery in the bridge.
- Bound the backend read timeout during an owned exchange (60s) instead of
blocking forever; back off between idle-wait retries.
- Relay asynchronous backend messages (NoticeResponse, ParameterStatus)
to the client instead of dropping them; log every tolerated AwsException.
- Honour the BackendExchange return value so a future interceptor can
decline before touching the backend.
Tests: cover the mid-copy abort (one E + one Z), backend EOF, literal
NULL AS '\N', the unsupported-clause and trailing-statement rejections,
failed-transaction status, plus a GZIP end-to-end case; the missing-object
integration test now seeds its own bucket.
* fix(redshift): address review feedback on COPY option parsing, prefix pagination, and tx state
* fix(redshift): handle backend tx abort sync failure and log socket close
* fix(redshift): verify backend transaction status 'E' after abort query
This commit is contained in:
1 parent
ee5c87d6d6
commit
85180a4d88
13 files changed
+1868
-64
No files matched your search
+114
@@ -27,6 +27,9 @@ class RedshiftInterceptorIntegrationTest {
|
||||
@Inject
|
||||
RedshiftService service;
|
||||
|
||||
@Inject
|
||||
io.github.hectorvent.floci.services.s3.S3Service s3;
|
||||
|
||||
private String clusterId;
|
||||
|
||||
@BeforeAll
|
||||
@@ -106,4 +109,115 @@ class RedshiftInterceptorIntegrationTest {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyFromS3SingleObjectLoadsRows() throws Exception {
|
||||
clusterId = "it-copy-single";
|
||||
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
|
||||
|
||||
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());
|
||||
|
||||
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
|
||||
c.createStatement().execute("CREATE TABLE people (id int, name text)");
|
||||
c.createStatement().execute("COPY people FROM 's3://redshift-copy-it/people/p1.txt'");
|
||||
try (ResultSet rs = c.createStatement().executeQuery("SELECT count(*) FROM people")) {
|
||||
assertTrue(rs.next());
|
||||
assertEquals(2, rs.getInt(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyFromS3PrefixConcatenatesObjects() throws Exception {
|
||||
clusterId = "it-copy-prefix";
|
||||
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
|
||||
|
||||
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());
|
||||
|
||||
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
|
||||
c.createStatement().execute("CREATE TABLE t (id int, v text)");
|
||||
c.createStatement().execute("COPY t FROM 's3://redshift-copy-it-prefix/d/'");
|
||||
try (ResultSet rs = c.createStatement().executeQuery("SELECT count(*) FROM t")) {
|
||||
assertTrue(rs.next());
|
||||
assertEquals(2, rs.getInt(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyFromS3GzipObjectLoadsRows() throws Exception {
|
||||
clusterId = "it-copy-gzip";
|
||||
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
|
||||
|
||||
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));
|
||||
}
|
||||
s3.putObject(bucket, "g/data.gz", raw.toByteArray(), "application/gzip", java.util.Map.of());
|
||||
|
||||
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
|
||||
c.createStatement().execute("CREATE TABLE g (id int, v text)");
|
||||
c.createStatement().execute("COPY g FROM 's3://redshift-copy-it-gzip/g/data.gz' GZIP");
|
||||
try (ResultSet rs = c.createStatement().executeQuery("SELECT count(*) FROM g")) {
|
||||
assertTrue(rs.next());
|
||||
assertEquals(2, rs.getInt(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyFromMissingObjectSurfacesASqlError() throws Exception {
|
||||
clusterId = "it-copy-missing";
|
||||
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
|
||||
|
||||
String bucket = "redshift-copy-it-missing";
|
||||
s3.createBucket(bucket, "us-east-1");
|
||||
|
||||
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
|
||||
c.createStatement().execute("CREATE TABLE t2 (id int)");
|
||||
SQLException ex = org.junit.jupiter.api.Assertions.assertThrows(
|
||||
SQLException.class,
|
||||
() -> c.createStatement().execute("COPY t2 FROM 's3://redshift-copy-it-missing/does/not/exist'"));
|
||||
assertTrue(
|
||||
ex.getMessage().toLowerCase().contains("not found"), ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyFromMissingObjectInTransactionAbortsTransaction() throws Exception {
|
||||
clusterId = "it-copy-tx-abort";
|
||||
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
|
||||
|
||||
String bucket = "redshift-copy-it-tx";
|
||||
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)");
|
||||
org.junit.jupiter.api.Assertions.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(
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
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.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class CopyStatementParserTest {
|
||||
|
||||
@Test
|
||||
void parsesMinimalCopyFromKey() {
|
||||
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
|
||||
"COPY sales FROM 's3://warehouse/data/sales.txt'");
|
||||
assertEquals("sales", c.targetTable());
|
||||
assertEquals(List.of(), c.columns());
|
||||
assertEquals("warehouse", c.bucket());
|
||||
assertEquals("data/sales.txt", c.keyOrPrefix());
|
||||
assertEquals("|", c.delimiter());
|
||||
assertEquals(0, c.headerLines());
|
||||
assertFalse(c.gzip());
|
||||
assertFalse(c.csv());
|
||||
assertNull(c.nullAs());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsesColumnsOptionsAndPrefix() {
|
||||
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
|
||||
"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());
|
||||
assertEquals(List.of("id", "ts", "note"), c.columns());
|
||||
assertEquals("bkt", c.bucket());
|
||||
assertEquals("evt/", c.keyOrPrefix());
|
||||
assertTrue(c.gzip());
|
||||
assertTrue(c.csv());
|
||||
assertEquals(",", c.delimiter());
|
||||
assertEquals(2, c.headerLines());
|
||||
assertEquals("\\N", c.nullAs());
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultsDelimiterToCommaForCsvAndTreatsHeaderKeywordAsOneLine() {
|
||||
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
|
||||
"COPY t FROM 's3://b/k' CSV HEADER");
|
||||
assertEquals(",", c.delimiter());
|
||||
assertEquals(1, c.headerLines());
|
||||
}
|
||||
|
||||
@Test
|
||||
void decodesTabDelimiterToken() {
|
||||
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
|
||||
"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'");
|
||||
assertEquals("only-bucket", c.bucket());
|
||||
assertEquals("", c.keyOrPrefix());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stripsLeadingComments() {
|
||||
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
|
||||
"-- load nightly\n/* batch */ COPY t FROM 's3://b/k'");
|
||||
assertEquals("t", c.targetTable());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInjectionInTableName() {
|
||||
assertNull(CopyStatementParser.parse("COPY t; DROP TABLE u; FROM 's3://b/k'"));
|
||||
assertNull(CopyStatementParser.parse("COPY (SELECT 1) FROM 's3://b/k'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInjectionInColumnList() {
|
||||
assertNull(CopyStatementParser.parse("COPY t (id, x) FROM STDIN) --) FROM 's3://b/k'"));
|
||||
assertNull(CopyStatementParser.parse("COPY t (id, ts::text) FROM 's3://b/k'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsNullForNonCopyAndForCopyWithoutS3() {
|
||||
assertNull(CopyStatementParser.parse("SELECT 1"));
|
||||
assertNull(CopyStatementParser.parse("CREATE TABLE t (id int) DISTKEY (id)"));
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM STDIN"));
|
||||
assertNull(CopyStatementParser.parse("COPY t TO 's3://b/k'"));
|
||||
assertNull(CopyStatementParser.parse(null));
|
||||
assertNull(CopyStatementParser.parse(" "));
|
||||
}
|
||||
|
||||
@Test
|
||||
void quotedIdentifiersSurvive() {
|
||||
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
|
||||
"COPY \"My Schema\".\"Tab\" (\"col one\") FROM 's3://b/k'");
|
||||
assertEquals("\"My Schema\".\"Tab\"", c.targetTable());
|
||||
assertEquals(List.of("\"col one\""), c.columns());
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitDelimiterOverridesCsvDefault() {
|
||||
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
|
||||
"COPY t FROM 's3://b/k' CSV DELIMITER '\t'");
|
||||
assertEquals("\t", c.delimiter());
|
||||
assertTrue(c.csv());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsNullForUnsupportedClauses() {
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' FORMAT AS PARQUET"));
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' JSON 'auto'"));
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' FIXEDWIDTH 'a:1,b:2'"));
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' GZIP MAXERROR 10"));
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' IAM_ROLE 'arn:aws:iam::0:role/r'"));
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' DATEFORMAT 'YYYY-MM-DD'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsNullWhenAStatementFollowsTheCopy() {
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k'; DROP TABLE staging"));
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' GZIP; SELECT 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void toleratesALoneTrailingSemicolon() {
|
||||
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse("COPY t FROM 's3://b/k' GZIP;");
|
||||
assertTrue(c.gzip());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aQuotedKeywordInAnOptionValueDoesNotChangeParsing() {
|
||||
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
|
||||
"COPY t FROM 's3://b/k' NULL AS 'csv' DELIMITER ';'");
|
||||
assertFalse(c.csv());
|
||||
assertEquals(";", c.delimiter());
|
||||
assertEquals("csv", c.nullAs());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsTyposInOptionKeywords() {
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' DELIMETER ','"));
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' GZIPP"));
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' HEADERR"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsLeftoverOrUnknownTokens() {
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' GZIP EXTRA_TOKEN"));
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' SOME_UNKNOWN_OPTION"));
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' CSV FOO"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsDuplicateOrConflictingOptions() {
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' GZIP GZIP"));
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' CSV FORMAT CSV"));
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' DELIMITER ',' DELIMITER '\t'"));
|
||||
assertNull(CopyStatementParser.parse("COPY t FROM 's3://b/k' HEADER IGNOREHEADER 2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsesEscapedSingleQuoteInDelimiter() {
|
||||
CopyStatementParser.S3CopyFrom c = CopyStatementParser.parse(
|
||||
"COPY t FROM 's3://b/k' DELIMITER ''''");
|
||||
assertEquals("'", c.delimiter());
|
||||
}
|
||||
}
|
||||
+8
-4
@@ -67,7 +67,8 @@ class RedshiftAuthProxyTest {
|
||||
int proxyPort = freePort();
|
||||
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
|
||||
"admin", "Secret123", "dev",
|
||||
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true);
|
||||
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
|
||||
mock(io.github.hectorvent.floci.services.s3.S3Service.class));
|
||||
proxy.start(proxyPort);
|
||||
|
||||
try (Socket client = new Socket("localhost", proxyPort)) {
|
||||
@@ -120,7 +121,8 @@ class RedshiftAuthProxyTest {
|
||||
int proxyPort = freePort();
|
||||
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
|
||||
"admin", "Secret123", "dev",
|
||||
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true);
|
||||
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
|
||||
mock(io.github.hectorvent.floci.services.s3.S3Service.class));
|
||||
proxy.start(proxyPort);
|
||||
|
||||
// Connect, then drop without ever sending a startup packet.
|
||||
@@ -150,7 +152,8 @@ class RedshiftAuthProxyTest {
|
||||
|
||||
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
|
||||
"admin", "Secret123", "dev",
|
||||
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true);
|
||||
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
|
||||
mock(io.github.hectorvent.floci.services.s3.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");
|
||||
@@ -162,7 +165,8 @@ class RedshiftAuthProxyTest {
|
||||
int proxyPort = freePort();
|
||||
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
|
||||
"admin", "old", "dev",
|
||||
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true);
|
||||
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
|
||||
mock(io.github.hectorvent.floci.services.s3.S3Service.class));
|
||||
proxy.start(proxyPort);
|
||||
|
||||
proxy.updateMasterPassword("rotated");
|
||||
|
||||
+75
-1
@@ -1,13 +1,18 @@
|
||||
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.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -27,6 +32,8 @@ class RedshiftInterceptingBridgeTest {
|
||||
private Socket testBackendEnd; // test reads what the bridge forwarded, writes backend replies
|
||||
private Thread bridgeThread;
|
||||
|
||||
private S3Service s3Stub;
|
||||
|
||||
private void startBridge() throws IOException {
|
||||
clientListener = new ServerSocket(0);
|
||||
testClientEnd = new Socket("localhost", clientListener.getLocalPort());
|
||||
@@ -36,7 +43,8 @@ class RedshiftInterceptingBridgeTest {
|
||||
bridgeBackendEnd = new Socket("localhost", backendListener.getLocalPort());
|
||||
testBackendEnd = backendListener.accept();
|
||||
|
||||
RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(bridgeClientEnd, bridgeBackendEnd);
|
||||
s3Stub = Mockito.mock(S3Service.class);
|
||||
RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(bridgeClientEnd, bridgeBackendEnd, s3Stub);
|
||||
bridgeThread = Thread.ofVirtual().name("bridge-under-test").start(bridge::run);
|
||||
}
|
||||
|
||||
@@ -138,4 +146,70 @@ class RedshiftInterceptingBridgeTest {
|
||||
assertFalse(bridgeThread.isAlive(), "bridge did not stop after Terminate");
|
||||
assertEquals(-1, testClientEnd.getInputStream().read(), "bridge left the client socket open");
|
||||
}
|
||||
|
||||
@Test
|
||||
void interceptsCopyFromS3AndDoesNotForwardTheOriginalQuery() throws Exception {
|
||||
startBridge();
|
||||
Mockito.when(s3Stub.objectExists("wh", "k")).thenReturn(true);
|
||||
Mockito.when(s3Stub.getObject("wh", "k")).thenReturn(
|
||||
new S3Object("wh", "k", "1|a\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
|
||||
|
||||
AtomicReference<Throwable> backendFailure = new AtomicReference<>();
|
||||
// fake backend: expect a fabricated Query, answer 'G', then after CopyDone answer 'C'+'Z'
|
||||
Thread backend = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
PostgresWireDecoder in = new PostgresWireDecoder(testBackendEnd.getInputStream());
|
||||
PostgresWireDecoder.FrontendMessage q = in.nextMessage();
|
||||
assertEquals('Q', q.type());
|
||||
assertTrue(q.getSql().contains("FROM STDIN"), q.getSql());
|
||||
OutputStream out = testBackendEnd.getOutputStream();
|
||||
out.write(new byte[]{'G', 0, 0, 0, 7, 0, 0, 0});
|
||||
out.flush();
|
||||
while (true) {
|
||||
PostgresWireDecoder.FrontendMessage m = in.nextMessage();
|
||||
if (m == null || m.type() == 'c') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
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 (Throwable t) {
|
||||
backendFailure.compareAndSet(null, t);
|
||||
}
|
||||
});
|
||||
|
||||
testClientEnd.getOutputStream().write(
|
||||
PostgresWireDecoder.encodeQuery("COPY t FROM 's3://wh/k'"));
|
||||
testClientEnd.getOutputStream().flush();
|
||||
|
||||
PostgresWireDecoder.FrontendMessage toClient =
|
||||
new PostgresWireDecoder(testClientEnd.getInputStream()).nextMessage();
|
||||
assertEquals('C', toClient.type());
|
||||
backend.join();
|
||||
if (backendFailure.get() != null) {
|
||||
throw new AssertionError("fake backend failed", backendFailure.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsOpenAndForwardsCopyWhenBackendHasAnOutstandingResponse() throws Exception {
|
||||
startBridge();
|
||||
// send a normal query first and never answer it, so outstandingResponses stays > 0
|
||||
testClientEnd.getOutputStream().write(PostgresWireDecoder.encodeQuery("SELECT 1"));
|
||||
testClientEnd.getOutputStream().flush();
|
||||
PostgresWireDecoder backendIn = new PostgresWireDecoder(testBackendEnd.getInputStream());
|
||||
assertEquals('Q', backendIn.nextMessage().type()); // SELECT 1 arrived, unanswered
|
||||
|
||||
testClientEnd.getOutputStream().write(PostgresWireDecoder.encodeQuery("COPY t FROM 's3://wh/k'"));
|
||||
testClientEnd.getOutputStream().flush();
|
||||
|
||||
// within the ~2s deadline the bridge gives up and forwards the COPY verbatim
|
||||
PostgresWireDecoder.FrontendMessage forwarded = backendIn.nextMessage();
|
||||
assertEquals('Q', forwarded.type());
|
||||
assertTrue(forwarded.getSql().contains("s3://wh/k"), forwarded.getSql());
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -27,7 +27,8 @@ class RedshiftProxyManagerTest {
|
||||
|
||||
private RedshiftProxyManager newManager() {
|
||||
return new RedshiftProxyManager(
|
||||
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
|
||||
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class),
|
||||
mock(io.github.hectorvent.floci.services.s3.S3Service.class));
|
||||
}
|
||||
|
||||
private static void start(RedshiftProxyManager manager, String key, int proxyPort) {
|
||||
|
||||
+549
@@ -0,0 +1,549 @@
|
||||
package io.github.hectorvent.floci.services.redshift.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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.concurrent.atomic.AtomicReference;
|
||||
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.assertNull;
|
||||
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.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class S3CopySimulatorTest {
|
||||
|
||||
private ServerSocket listener;
|
||||
private Socket simClient; // simulator's "client" end
|
||||
private Socket simBackend; // simulator's "backend" end
|
||||
private Socket testClient; // test reads ErrorResponse / CommandComplete here
|
||||
private Socket testBackend; // test plays PostgreSQL here
|
||||
private S3Service s3;
|
||||
|
||||
private final AtomicReference<Throwable> backendFailure = new AtomicReference<>();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
listener = new ServerSocket(0);
|
||||
simClient = new Socket("localhost", listener.getLocalPort());
|
||||
testClient = listener.accept();
|
||||
|
||||
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 s : new Socket[]{simClient, simBackend, testClient, testBackend}) {
|
||||
if (s != null && !s.isClosed()) {
|
||||
s.close();
|
||||
}
|
||||
}
|
||||
if (listener != null && !listener.isClosed()) {
|
||||
listener.close();
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface BackendScript {
|
||||
void run() throws IOException;
|
||||
}
|
||||
|
||||
/** Run a fake-backend script on a virtual thread, capturing any failure for the test thread. */
|
||||
private Thread backendThread(BackendScript script) {
|
||||
return Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
script.run();
|
||||
} catch (Throwable t) {
|
||||
backendFailure.compareAndSet(null, t);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void joinBackend(Thread t) throws InterruptedException {
|
||||
t.join();
|
||||
Throwable failure = backendFailure.get();
|
||||
if (failure != null) {
|
||||
throw new AssertionError("fake backend failed: " + failure, failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] gzip(String s) throws IOException {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try (GZIPOutputStream gz = new GZIPOutputStream(bytes)) {
|
||||
gz.write(s.getBytes(StandardCharsets.US_ASCII));
|
||||
}
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] intBytes(int v) {
|
||||
return new byte[]{(byte) (v >>> 24), (byte) (v >>> 16), (byte) (v >>> 8), (byte) v};
|
||||
}
|
||||
|
||||
private PostgresWireDecoder.FrontendMessage nextFromSimulatorToBackend() throws IOException {
|
||||
return new PostgresWireDecoder(testBackend.getInputStream()).nextMessage();
|
||||
}
|
||||
|
||||
/** 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();
|
||||
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
|
||||
PostgresWireDecoder.FrontendMessage query = in.nextMessage();
|
||||
assertEquals('Q', query.type());
|
||||
// CopyInResponse 'G': body = format(1) + columnCount(2) = 3 bytes, all zero => length 7
|
||||
out.write(new byte[]{'G', 0, 0, 0, 7, 0, 0, 0});
|
||||
out.flush();
|
||||
while (true) {
|
||||
PostgresWireDecoder.FrontendMessage m = in.nextMessage();
|
||||
if (m == null || m.type() == 'c') {
|
||||
break;
|
||||
}
|
||||
if (m.type() == 'd') {
|
||||
capturedCopyData.write(m.body());
|
||||
}
|
||||
}
|
||||
byte[] tag = "COPY 1\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 String captureFabricatedThenComplete() throws IOException {
|
||||
OutputStream out = testBackend.getOutputStream();
|
||||
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
|
||||
PostgresWireDecoder.FrontendMessage q = in.nextMessage();
|
||||
assertEquals('Q', q.type());
|
||||
out.write(new byte[]{'G', 0, 0, 0, 7, 0, 0, 0});
|
||||
out.flush();
|
||||
while (true) {
|
||||
PostgresWireDecoder.FrontendMessage m = in.nextMessage();
|
||||
if (m == null || m.type() == 'c') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out.write(new byte[]{'Z', 0, 0, 0, 5, 'I'});
|
||||
out.flush();
|
||||
return q.getSql();
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsSingleKeyAsPipeTextAndForwardsCommandComplete() throws Exception {
|
||||
when(s3.objectExists("wh", "d/a.txt")).thenReturn(true);
|
||||
when(s3.getObject("wh", "d/a.txt")).thenReturn(
|
||||
new S3Object("wh", "d/a.txt", "1|alice\n2|bob\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
|
||||
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"people", List.of(), "wh", "d/a.txt", "|", 0, false, false, null);
|
||||
|
||||
ByteArrayOutputStream copyData = new ByteArrayOutputStream();
|
||||
Thread backend = backendThread(() -> playHappyBackend(copyData));
|
||||
|
||||
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
|
||||
joinBackend(backend);
|
||||
|
||||
assertTrue(handled);
|
||||
assertEquals("1|alice\n2|bob\n", copyData.toString(StandardCharsets.US_ASCII));
|
||||
|
||||
PostgresWireDecoder.FrontendMessage toClient = new PostgresWireDecoder(testClient.getInputStream()).nextMessage();
|
||||
assertEquals('C', toClient.type());
|
||||
}
|
||||
|
||||
@Test
|
||||
void fabricatedQueryUsesTextFormatAndPipeDelimiterByDefault() throws Exception {
|
||||
when(s3.objectExists("wh", "k")).thenReturn(true);
|
||||
when(s3.getObject("wh", "k")).thenReturn(
|
||||
new S3Object("wh", "k", "x\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"t", List.of("a", "b"), "wh", "k", "|", 0, false, false, null);
|
||||
|
||||
AtomicReference<String> fabricated = new AtomicReference<>();
|
||||
Thread backend = backendThread(() -> fabricated.set(captureFabricatedThenComplete()));
|
||||
|
||||
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
|
||||
joinBackend(backend);
|
||||
|
||||
String sql = fabricated.get();
|
||||
assertTrue(sql.contains("COPY t (a, b) FROM STDIN"), sql);
|
||||
assertTrue(sql.toUpperCase().contains("FORMAT TEXT"), sql);
|
||||
assertTrue(sql.contains("DELIMITER '|'"), sql);
|
||||
assertFalse(sql.toUpperCase().contains("HEADER"), sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fabricatedQueryUsesCsvFormatAndCommaDelimiterByDefault() throws Exception {
|
||||
when(s3.objectExists("wh", "k")).thenReturn(true);
|
||||
when(s3.getObject("wh", "k")).thenReturn(
|
||||
new S3Object("wh", "k", "x\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"t", List.of("a", "b"), "wh", "k", null, 0, false, true, null);
|
||||
|
||||
AtomicReference<String> fabricated = new AtomicReference<>();
|
||||
Thread backend = backendThread(() -> fabricated.set(captureFabricatedThenComplete()));
|
||||
|
||||
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
|
||||
joinBackend(backend);
|
||||
|
||||
String sql = fabricated.get();
|
||||
assertTrue(sql.contains("COPY t (a, b) FROM STDIN"), sql);
|
||||
assertTrue(sql.toUpperCase().contains("FORMAT CSV"), sql);
|
||||
assertTrue(sql.contains("DELIMITER ','"), sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullAsBackslashNIsPassedThroughLiterally() throws Exception {
|
||||
when(s3.objectExists("wh", "k")).thenReturn(true);
|
||||
when(s3.getObject("wh", "k")).thenReturn(
|
||||
new S3Object("wh", "k", "x\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"t", List.of(), "wh", "k", "|", 0, false, false, "\\N");
|
||||
|
||||
AtomicReference<String> fabricated = new AtomicReference<>();
|
||||
Thread backend = backendThread(() -> fabricated.set(captureFabricatedThenComplete()));
|
||||
|
||||
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
|
||||
joinBackend(backend);
|
||||
|
||||
String sql = fabricated.get();
|
||||
assertTrue(sql.contains("NULL '\\N'"), sql);
|
||||
assertFalse(sql.contains("NULL '\\\\N'"), sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
void concatenatesPrefixObjectsInKeyOrderAndSkipsHeaderOnFirstOnly() throws Exception {
|
||||
when(s3.objectExists("wh", "p/")).thenReturn(false);
|
||||
when(s3.listObjectsWithPrefixes(eq("wh"), eq("p/"), isNull(), anyInt(), any(), any())).thenReturn(
|
||||
new S3Service.ListObjectsResult(List.of(
|
||||
new S3Object("wh", "p/1", "h1|h2\n1|a\n".getBytes(StandardCharsets.US_ASCII), "text/plain"),
|
||||
new S3Object("wh", "p/2", "2|b\n".getBytes(StandardCharsets.US_ASCII), "text/plain")),
|
||||
List.of(), false, null));
|
||||
when(s3.getObject("wh", "p/1")).thenReturn(
|
||||
new S3Object("wh", "p/1", "h1|h2\n1|a\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
|
||||
when(s3.getObject("wh", "p/2")).thenReturn(
|
||||
new S3Object("wh", "p/2", "2|b\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
|
||||
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"t", List.of(), "wh", "p/", "|", 1, false, false, null);
|
||||
|
||||
ByteArrayOutputStream copyData = new ByteArrayOutputStream();
|
||||
Thread backend = backendThread(() -> playHappyBackend(copyData));
|
||||
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
|
||||
joinBackend(backend);
|
||||
|
||||
assertEquals("1|a\n2|b\n", copyData.toString(StandardCharsets.US_ASCII));
|
||||
}
|
||||
|
||||
@Test
|
||||
void decompressesGzipObjects() throws Exception {
|
||||
when(s3.objectExists("wh", "k.gz")).thenReturn(true);
|
||||
when(s3.getObject("wh", "k.gz")).thenReturn(
|
||||
new S3Object("wh", "k.gz", gzip("1|a\n2|b\n"), "application/gzip"));
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"t", List.of(), "wh", "k.gz", "|", 0, true, false, null);
|
||||
|
||||
ByteArrayOutputStream copyData = new ByteArrayOutputStream();
|
||||
Thread backend = backendThread(() -> playHappyBackend(copyData));
|
||||
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
|
||||
joinBackend(backend);
|
||||
|
||||
assertEquals("1|a\n2|b\n", copyData.toString(StandardCharsets.US_ASCII));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniedBucketSendsInsufficientPrivilegeErrorResponse() throws Exception {
|
||||
doThrow(new AwsException("AccessDenied", "no", 403))
|
||||
.when(s3).authorizeAnonymousListBucket("wh");
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"t", List.of(), "wh", "k", "|", 0, false, false, null);
|
||||
|
||||
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
|
||||
assertTrue(handled);
|
||||
|
||||
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
|
||||
PostgresWireDecoder.FrontendMessage err = in.nextMessage();
|
||||
assertEquals('E', err.type());
|
||||
assertTrue(new String(err.body(), StandardCharsets.US_ASCII).contains("42501"));
|
||||
assertEquals('Z', in.nextMessage().type());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingKeySendsNotFoundErrorResponse() throws Exception {
|
||||
when(s3.objectExists("wh", "missing")).thenReturn(false);
|
||||
when(s3.listObjectsWithPrefixes(eq("wh"), eq("missing"), isNull(), anyInt(), any(), any())).thenReturn(
|
||||
new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"t", List.of(), "wh", "missing", "|", 0, false, false, null);
|
||||
|
||||
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
|
||||
assertTrue(handled);
|
||||
|
||||
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
|
||||
PostgresWireDecoder.FrontendMessage err = in.nextMessage();
|
||||
assertEquals('E', err.type());
|
||||
assertTrue(new String(err.body(), StandardCharsets.US_ASCII).contains("not found"));
|
||||
assertEquals('Z', in.nextMessage().type());
|
||||
}
|
||||
|
||||
@Test
|
||||
void backendErrorInsteadOfCopyInIsForwardedToClient() throws Exception {
|
||||
when(s3.objectExists("wh", "k")).thenReturn(true);
|
||||
when(s3.getObject("wh", "k")).thenReturn(
|
||||
new S3Object("wh", "k", "1\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"nosuch", List.of(), "wh", "k", "|", 0, false, false, null);
|
||||
|
||||
Thread backend = backendThread(() -> {
|
||||
new PostgresWireDecoder(testBackend.getInputStream()).nextMessage();
|
||||
byte[] msg = "SERROR\0C42P01\0Mrelation \"nosuch\" does not exist\0\0".getBytes(StandardCharsets.US_ASCII);
|
||||
OutputStream out = testBackend.getOutputStream();
|
||||
out.write('E');
|
||||
out.write(intBytes(4 + msg.length));
|
||||
out.write(msg);
|
||||
out.write(new byte[]{'Z', 0, 0, 0, 5, 'I'});
|
||||
out.flush();
|
||||
});
|
||||
|
||||
boolean handled = S3CopySimulator.runCopyFrom(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());
|
||||
}
|
||||
|
||||
@Test
|
||||
void midCopyFailureSendsExactlyOneErrorAndReadyForQuery() throws Exception {
|
||||
when(s3.objectExists("wh", "k")).thenReturn(true);
|
||||
when(s3.getObject("wh", "k")).thenThrow(new AwsException("InternalError", "boom", 500));
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"t", List.of(), "wh", "k", "|", 0, false, false, null);
|
||||
|
||||
Thread backend = backendThread(() -> {
|
||||
OutputStream out = testBackend.getOutputStream();
|
||||
PostgresWireDecoder in = new PostgresWireDecoder(testBackend.getInputStream());
|
||||
assertEquals('Q', in.nextMessage().type());
|
||||
out.write(new byte[]{'G', 0, 0, 0, 7, 0, 0, 0});
|
||||
out.flush();
|
||||
// wait for the simulator's CopyFail 'f'
|
||||
PostgresWireDecoder.FrontendMessage m;
|
||||
while ((m = in.nextMessage()) != null && m.type() != 'f') {
|
||||
// discard any CopyData already buffered
|
||||
}
|
||||
assertEquals('f', m == null ? 0 : m.type());
|
||||
byte[] err = "SERROR\0C57014\0MCOPY aborted\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.runCopyFrom(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(),
|
||||
"no second response should follow");
|
||||
}
|
||||
|
||||
@Test
|
||||
void backendEofBeforeCopyInResponseSendsErrorToClient() throws Exception {
|
||||
when(s3.objectExists("wh", "k")).thenReturn(true);
|
||||
when(s3.getObject("wh", "k")).thenReturn(
|
||||
new S3Object("wh", "k", "1\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"t", List.of(), "wh", "k", "|", 0, false, false, null);
|
||||
|
||||
Thread backend = backendThread(() -> {
|
||||
new PostgresWireDecoder(testBackend.getInputStream()).nextMessage();
|
||||
testBackend.close();
|
||||
});
|
||||
|
||||
boolean handled = S3CopySimulator.runCopyFrom(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());
|
||||
}
|
||||
|
||||
@Test
|
||||
void synthesizedErrorReportsFailedTransactionStatusWhenInABlock() throws Exception {
|
||||
when(s3.objectExists("wh", "missing")).thenReturn(false);
|
||||
when(s3.listObjectsWithPrefixes(eq("wh"), eq("missing"), isNull(), anyInt(), any(), any())).thenReturn(
|
||||
new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"t", List.of(), "wh", "missing", "|", 0, false, false, null);
|
||||
|
||||
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.runCopyFrom(simClient, simBackend, spec, s3, 'T');
|
||||
joinBackend(backend);
|
||||
|
||||
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
|
||||
assertEquals('E', in.nextMessage().type());
|
||||
PostgresWireDecoder.FrontendMessage ready = in.nextMessage();
|
||||
assertEquals('Z', ready.type());
|
||||
assertEquals('E', (char) ready.body()[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void paginatesPrefixListingAcrossMultiplePages() throws Exception {
|
||||
when(s3.objectExists("wh", "multi/")).thenReturn(false);
|
||||
when(s3.listObjectsWithPrefixes(eq("wh"), eq("multi/"), isNull(), anyInt(), isNull(), isNull())).thenReturn(
|
||||
new S3Service.ListObjectsResult(List.of(
|
||||
new S3Object("wh", "multi/1", "1|a\n".getBytes(StandardCharsets.US_ASCII), "text/plain")),
|
||||
List.of(), true, "tok-1"));
|
||||
when(s3.listObjectsWithPrefixes(eq("wh"), eq("multi/"), isNull(), anyInt(), eq("tok-1"), isNull())).thenReturn(
|
||||
new S3Service.ListObjectsResult(List.of(
|
||||
new S3Object("wh", "multi/2", "2|b\n".getBytes(StandardCharsets.US_ASCII), "text/plain")),
|
||||
List.of(), false, null));
|
||||
|
||||
when(s3.getObject("wh", "multi/1")).thenReturn(
|
||||
new S3Object("wh", "multi/1", "1|a\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
|
||||
when(s3.getObject("wh", "multi/2")).thenReturn(
|
||||
new S3Object("wh", "multi/2", "2|b\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
|
||||
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"t", List.of(), "wh", "multi/", "|", 0, false, false, null);
|
||||
|
||||
ByteArrayOutputStream copyData = new ByteArrayOutputStream();
|
||||
Thread backend = backendThread(() -> playHappyBackend(copyData));
|
||||
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
|
||||
joinBackend(backend);
|
||||
|
||||
assertEquals("1|a\n2|b\n", copyData.toString(StandardCharsets.US_ASCII));
|
||||
}
|
||||
|
||||
@Test
|
||||
void backendTimeoutAwaitingCopyInResponseClosesBackend() throws Exception {
|
||||
when(s3.objectExists("wh", "k")).thenReturn(true);
|
||||
when(s3.getObject("wh", "k")).thenReturn(
|
||||
new S3Object("wh", "k", "1\n".getBytes(StandardCharsets.US_ASCII), "text/plain"));
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"t", List.of(), "wh", "k", "|", 0, false, false, null);
|
||||
|
||||
simBackend.setSoTimeout(100);
|
||||
|
||||
Thread backend = backendThread(() -> {
|
||||
new PostgresWireDecoder(testBackend.getInputStream()).nextMessage();
|
||||
try {
|
||||
Thread.sleep(300);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
});
|
||||
|
||||
boolean handled = S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'I');
|
||||
joinBackend(backend);
|
||||
assertTrue(handled);
|
||||
|
||||
assertTrue(simBackend.isClosed(), "simBackend must be closed upon timeout");
|
||||
|
||||
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
|
||||
assertEquals('E', in.nextMessage().type());
|
||||
assertEquals('Z', in.nextMessage().type());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedBackendTransactionAbortClosesBackendAndClientWithoutReportingFailedTransaction() throws Exception {
|
||||
when(s3.objectExists("wh", "missing")).thenReturn(false);
|
||||
when(s3.listObjectsWithPrefixes(eq("wh"), eq("missing"), isNull(), anyInt(), any(), any())).thenReturn(
|
||||
new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"t", List.of(), "wh", "missing", "|", 0, false, false, null);
|
||||
|
||||
// Backend closes socket when abort query arrives, simulating dropped connection
|
||||
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"));
|
||||
testBackend.close();
|
||||
});
|
||||
|
||||
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'T');
|
||||
joinBackend(backend);
|
||||
|
||||
assertTrue(simBackend.isClosed(), "simBackend must be closed upon synchronization failure");
|
||||
assertTrue(simClient.isClosed(), "simClient must be closed upon synchronization failure");
|
||||
|
||||
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
|
||||
PostgresWireDecoder.FrontendMessage err = in.nextMessage();
|
||||
assertEquals('E', err.type());
|
||||
assertNull(in.nextMessage(), "Client must not receive an unconfirmed ReadyForQuery");
|
||||
}
|
||||
|
||||
@Test
|
||||
void backendReturnsNonETransactionStatusAfterAbortClosesBackendAndClient() throws Exception {
|
||||
when(s3.objectExists("wh", "missing")).thenReturn(false);
|
||||
when(s3.listObjectsWithPrefixes(eq("wh"), eq("missing"), isNull(), anyInt(), any(), any())).thenReturn(
|
||||
new S3Service.ListObjectsResult(List.of(), List.of(), false, null));
|
||||
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
|
||||
"t", List.of(), "wh", "missing", "|", 0, false, false, null);
|
||||
|
||||
// Fake backend returns ReadyForQuery with 'T' (e.g. abort query unexpectedly succeeded)
|
||||
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();
|
||||
out.write(new byte[]{'Z', 0, 0, 0, 5, 'T'});
|
||||
out.flush();
|
||||
});
|
||||
|
||||
S3CopySimulator.runCopyFrom(simClient, simBackend, spec, s3, 'T');
|
||||
joinBackend(backend);
|
||||
|
||||
assertTrue(simBackend.isClosed(), "simBackend must be closed when abort returns non-E status");
|
||||
assertTrue(simClient.isClosed(), "simClient must be closed when abort returns non-E status");
|
||||
|
||||
PostgresWireDecoder in = new PostgresWireDecoder(testClient.getInputStream());
|
||||
PostgresWireDecoder.FrontendMessage err = in.nextMessage();
|
||||
assertEquals('E', err.type());
|
||||
assertNull(in.nextMessage(), "Client must not receive an unconfirmed ReadyForQuery");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user