fix(redshift): run COPY ETL options on PostgreSQL 15 across protocols (#7514)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-06 08:50:21 -04:00
1 parent a0b39a4ad0
commit 576646aae7
30 files changed
+2282 -389

No files matched your search

@@ -0,0 +1,250 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.DockerAvailability;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class RedshiftCopyEtlIntegrationTest {
@Inject
RedshiftService redshift;
@Inject
S3Service s3;
private final String id = "copy-etl-" + UUID.randomUUID().toString().substring(0, 8);
private Cluster cluster;
private String url;
private String user;
@BeforeAll
void start() throws Exception {
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for a Redshift cluster");
cluster = redshift.createCluster(id, "dc2.large", "admin", "Secret123");
url = RedshiftConnections.jdbcUrl(cluster);
user = "admin";
s3.createBucket(id, "us-east-1");
}
@AfterAll
void stop() throws Exception {
if (cluster != null) {
redshift.deleteCluster(id);
}
}
private Connection connect(String mode) throws SQLException {
return RedshiftConnections.waitForConnection(url + "?sslmode=disable&gssEncMode=disable&preferQueryMode=" + mode,
user, "Secret123");
}
private String table() {
return "etl_" + UUID.randomUUID().toString().replace("-", "");
}
private String copy(String table, String key, String options) {
return "COPY " + table + " FROM 's3://" + id + "/" + key + "' " + options;
}
private void put(String key, String data) {
s3.putObject(id, key, data.getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
}
private static long count(Statement statement, String table) throws SQLException {
try (ResultSet rows = statement.executeQuery("SELECT count(*) FROM " + table)) {
assertTrue(rows.next());
return rows.getLong(1);
}
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
void maxErrorLoadsGoodRowsAndCountsErrorsAcrossObjects(String mode) throws Exception {
String table = table();
String prefix = table + "/";
put(prefix + "a", "id|name\n1|one\nbad|skip\n");
put(prefix + "b", "id|name\n2|two\n");
try (Connection connection = connect(mode); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE " + table + " (id int NOT NULL, name text)");
assertEquals(2, statement.executeUpdate(copy(table, prefix, "IGNOREHEADER 1 MAXERROR 2")));
assertEquals(2, count(statement, table));
put(prefix + "b", "id|name\n2|two\nnope|skip\n");
assertThrows(SQLException.class,
() -> statement.execute(copy(table, prefix, "IGNOREHEADER 1 MAXERROR 2")));
assertEquals(2, count(statement, table));
}
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
void metadataOptionsLoadTemporalAndMissingFields(String mode) throws Exception {
String table = table();
put(table, "1|31/10/2026|abcdef\n2|01/11/2026\n");
try (Connection connection = connect(mode); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE " + table + " (id int, day date, label varchar(3))");
assertEquals(2, statement.executeUpdate(copy(table, table,
"DATEFORMAT 'DD/MM/YYYY' FILLRECORD TRUNCATECOLUMNS")));
try (ResultSet rows = statement.executeQuery("SELECT day, label FROM " + table + " ORDER BY id")) {
assertTrue(rows.next());
assertEquals("2026-10-31", rows.getString(1));
assertEquals("abc", rows.getString(2));
assertTrue(rows.next());
assertEquals("2026-11-01", rows.getString(1));
assertEquals("", rows.getString(2));
}
}
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
void badTemporalFieldUsesTheSameErrorBudgetAsConversionErrors(String mode) throws Exception {
String table = table();
put(table, "1|31/10/2026\n2|bad-date\nbad-number|01/11/2026\n3|02/11/2026\n");
try (Connection connection = connect(mode); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE " + table + " (id int, day date)");
assertEquals(2, statement.executeUpdate(copy(table, table, "DATEFORMAT 'DD/MM/YYYY' MAXERROR 3")));
assertThrows(SQLException.class,
() -> statement.execute(copy(table, table, "DATEFORMAT 'DD/MM/YYYY' MAXERROR 2")));
assertEquals(2, count(statement, table));
}
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
void explicitTransactionRetainsTheCallersSavepointOnLoadFailure(String mode) throws Exception {
String table = table();
put(table, "1|good\nbad|first\nbad|second\n");
try (Connection connection = connect(mode); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE " + table + " (id int, name text)");
connection.setAutoCommit(false);
statement.execute("INSERT INTO " + table + " VALUES (99, 'before')");
Savepoint before = connection.setSavepoint();
assertThrows(SQLException.class, () -> statement.execute(copy(table, table, "MAXERROR 2")));
SQLException aborted = assertThrows(SQLException.class, () -> count(statement, table));
assertEquals("25P02", aborted.getSQLState());
connection.rollback(before);
assertEquals(1, count(statement, table));
connection.rollback();
}
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
void savedStatementDiscoversColumnsWhenItExecutesAgain(String mode) throws Exception {
String table = table();
put(table, "1|abcdef\n");
try (Connection connection = connect(mode); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE " + table + " (id int, name varchar(3))");
try (PreparedStatement prepared = connection.prepareStatement(copy(table, table, "TRUNCATECOLUMNS"))) {
for (int iteration = 0; iteration < 6; iteration++) {
assertEquals(1, prepared.executeUpdate());
}
statement.execute("ALTER TABLE " + table + " ALTER COLUMN name TYPE varchar(5)");
assertEquals(1, prepared.executeUpdate());
try (ResultSet rows = statement.executeQuery("SELECT max(length(name)) FROM " + table)) {
assertTrue(rows.next());
assertEquals(5, rows.getInt(1));
}
}
}
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
void jsonAutoDiscoversColumnsAndSkipsOnlyBadRecords(String mode) throws Exception {
String table = table();
put(table, "{\"id\":1,\"name\":\"one\"}\n{broken}\n{\"id\":2,\"name\":\"two\"}\n");
try (Connection connection = connect(mode); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE " + table + " (id int, name text)");
assertEquals(2, statement.executeUpdate(copy(table, table, "FORMAT JSON 'auto' MAXERROR 2")));
assertEquals(2, count(statement, table));
}
}
@ParameterizedTest
@ValueSource(strings = {"extended"})
void failedImplicitBatchRollsBackStatementsBeforeAndAfterCopy(String mode) throws Exception {
String table = table();
put(table, "1|one\nbad|skip\n");
try (Connection connection = connect(mode); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE " + table + " (id int, name text)");
statement.addBatch("INSERT INTO " + table + " VALUES (9, 'before')");
statement.addBatch(copy(table, table, "MAXERROR 2"));
statement.addBatch("INSERT INTO " + table + " VALUES ('bad', 'after')");
assertThrows(BatchUpdateException.class, statement::executeBatch);
assertEquals(0, count(statement, table));
}
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
void copyAndUnloadInTheSameBatchCommitAtTheFinalSync(String mode) throws Exception {
String table = table();
put(table, "1|one\nbad|skip\n");
try (Connection connection = connect(mode); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE " + table + " (id int, name text)");
statement.addBatch(copy(table, table, "MAXERROR 2"));
statement.addBatch("UNLOAD ('SELECT id FROM " + table + "') TO 's3://" + id + "/" + table + "-out/' PARALLEL OFF");
int[] counts = statement.executeBatch();
assertEquals(2, counts.length);
assertEquals(1, count(statement, table));
assertTrue(s3.objectExists(id, table + "-out/000"));
}
}
@ParameterizedTest
@ValueSource(strings = {"simple", "extended"})
void corruptGzipReturnsAnErrorWithoutDestroyingTheCallersSavepoint(String mode) throws Exception {
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
try (GZIPOutputStream output = new GZIPOutputStream(compressed)) {
output.write("1|one\n".getBytes(StandardCharsets.UTF_8));
}
byte[] truncated = Arrays.copyOf(compressed.toByteArray(), compressed.size() - 6);
for (byte[] content : List.of("not-gzip".getBytes(StandardCharsets.UTF_8), truncated)) {
for (int maxError : List.of(0, 2)) {
String table = table();
s3.putObject(id, table, content, "application/gzip", Map.of());
try (Connection connection = connect(mode); Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE " + table + " (id int, name text)");
connection.setAutoCommit(false);
statement.execute("INSERT INTO " + table + " VALUES (99, 'before')");
Savepoint before = connection.setSavepoint();
SQLException error = assertThrows(SQLException.class,
() -> statement.execute(copy(table, table, "GZIP MAXERROR " + maxError)));
assertFalse(error.getSQLState().startsWith("08"), "Bad S3 data must not disconnect the caller");
connection.rollback(before);
assertEquals(1, count(statement, table));
connection.rollback();
}
}
}
}
}
@@ -235,7 +235,7 @@ class RedshiftInterceptorIntegrationTest {
}
@Test
void copyTruncateColumnsOverExtendedQueryExplainsTheSimpleQueryRequirement() throws Exception {
void copyTruncateColumnsOverExtendedQueryTruncatesData() throws Exception {
String bucket = "redshift-copy-truncate-ext";
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "t.txt",
@@ -244,9 +244,11 @@ class RedshiftInterceptorIntegrationTest {
try (Connection connection = waitForConnection(sharedCluster, "admin", "Secret123");
Statement statement = connection.createStatement()) {
statement.execute("CREATE TABLE copy_trunc_ext (id int, name varchar(3))");
SQLException failure = assertThrows(SQLException.class, () -> statement.execute(
"COPY copy_trunc_ext FROM 's3://" + bucket + "/t.txt' TRUNCATECOLUMNS"));
assertTrue(failure.getMessage().contains("preferQueryMode=simple"), failure.getMessage());
statement.execute("COPY copy_trunc_ext FROM 's3://" + bucket + "/t.txt' TRUNCATECOLUMNS");
try (ResultSet rs = statement.executeQuery("SELECT name FROM copy_trunc_ext")) {
assertTrue(rs.next());
assertEquals("abc", rs.getString(1));
}
}
}
@@ -615,7 +617,7 @@ class RedshiftInterceptorIntegrationTest {
}
@Test
void copyFromS3JsonAutoWithoutColumnsOverExtendedQueryFailsClearly() throws Exception {
void copyFromS3JsonAutoWithoutColumnsOverExtendedQueryLoadsRows() throws Exception {
Cluster cluster = sharedCluster;
String bucket = "redshift-copy-json-auto-extended";
@@ -623,13 +625,15 @@ class RedshiftInterceptorIntegrationTest {
s3.putObject(bucket, "data/items.json",
"{\"id\": 1}\n".getBytes(StandardCharsets.UTF_8), "application/json", Map.of());
// Default connection: pgjdbc's default query mode is Extended even for a plain Statement,
// where the column list is fixed at Parse time and catalog discovery cannot run.
try (Connection c = waitForConnection(cluster, "admin", "Secret123")) {
c.createStatement().execute("CREATE TABLE ext_items (id int)");
SQLException ex = assertThrows(SQLException.class, () -> c.createStatement().execute(
"COPY ext_items FROM 's3://" + bucket + "/data/items.json' FORMAT AS JSON 'auto'"));
assertTrue(ex.getMessage().contains("explicit column list"));
c.createStatement().execute(
"COPY ext_items FROM 's3://" + bucket + "/data/items.json' FORMAT AS JSON 'auto'");
try (ResultSet rs = c.createStatement().executeQuery("SELECT count(*), max(id) FROM ext_items")) {
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertEquals(1, rs.getInt(2));
}
}
}
@@ -4,8 +4,6 @@ import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.DockerAvailability;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assumptions;
@@ -26,19 +24,11 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(RedshiftMaxErrorPostgres18IntegrationTest.Postgres18Profile.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class RedshiftMaxErrorPostgres18IntegrationTest {
class RedshiftMaxErrorIntegrationTest {
public static class Postgres18Profile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.redshift.image-version", "postgres:18-alpine");
}
}
private static final String CLUSTER_ID = "it-maxerror-pg18";
private static final String BUCKET = "it-maxerror-pg18-bucket";
private static final String CLUSTER_ID = "it-maxerror-pg15";
private static final String BUCKET = "it-maxerror-pg15-bucket";
@Inject
RedshiftService service;
@@ -79,7 +69,7 @@ class RedshiftMaxErrorPostgres18IntegrationTest {
Statement stmt = connection.createStatement()) {
stmt.execute("CREATE TABLE t_maxerror_two (id int, name text)");
// MAXERROR 2 tolerates 1 conversion error (REJECT_LIMIT 1) and loads the good rows past it
// MAXERROR 2 tolerates one bad record on the default PostgreSQL 15 backend.
stmt.execute("COPY t_maxerror_two (id, name) FROM 's3://" + BUCKET + "/one-error.txt' "
+ "DELIMITER '|' MAXERROR 2");
@@ -0,0 +1,83 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
class CopyRecordReaderTest {
private static CopyRecordReader reader(String content, String options) {
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY events FROM 's3://bucket/data' " + options);
return new CopyRecordReader(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)), spec);
}
private static String next(CopyRecordReader reader) throws IOException {
byte[] record = reader.next();
return record == null ? null : new String(record, StandardCharsets.UTF_8);
}
@Test
void csvQuotedNewlinesStayInTheSameRecord() throws IOException {
CopyRecordReader reader = reader("1,\"hello\nworld\"\r\n2,last", "CSV");
assertEquals("1,\"hello\nworld\"\r\n", next(reader));
assertEquals("2,last\n", next(reader));
assertNull(next(reader));
}
@Test
void csvDoubledQuotesDoNotEndAField() throws IOException {
CopyRecordReader reader = reader("1,\"a\"\"b\nnext\"\n2,c\n", "CSV");
assertEquals("1,\"a\"\"b\nnext\"\n", next(reader));
assertEquals("2,c\n", next(reader));
}
@Test
void csvQuotesCanStartWithinAField() throws IOException {
CopyRecordReader reader = reader("1,pre\"line\nbreak\"suffix\n2,x\n", "CSV");
assertEquals("1,pre\"line\nbreak\"suffix\n", next(reader));
assertEquals("2,x\n", next(reader));
}
@Test
void bareCarriageReturnsSeparateRecords() throws IOException {
CopyRecordReader reader = reader("1|a\r2|b\r", "DELIMITER '|'");
assertEquals("1|a\r", next(reader));
assertEquals("2|b\r", next(reader));
assertNull(next(reader));
}
@Test
void escapedTextNewlinesStayInTheSameRecord() throws IOException {
CopyRecordReader reader = reader("1|a\\\nb\n2|c\n", "DELIMITER '|'");
assertEquals("1|a\\\nb\n", next(reader));
assertEquals("2|c\n", next(reader));
}
@Test
void removeQuotesDoesNotCloseOnAnInteriorQuote() throws IOException {
CopyRecordReader reader = reader("1|'ab'cd\nef'\n2|g\n", "DELIMITER '|' REMOVEQUOTES");
assertEquals("1|'ab'cd\nef'\n", next(reader));
assertEquals("2|g\n", next(reader));
}
@Test
void unterminatedCsvQuoteAbortsInsteadOfGuessingTheNextRecord() {
CopyRecordReader reader = reader("1,\"bad\n2,still_bad\n", "CSV");
S3CopySimulator.S3TransferException error = assertThrows(
S3CopySimulator.S3TransferException.class, reader::next);
assertEquals("22P04", error.sqlState());
}
@Test
void jsonQuotesDoNotHideLineBoundaries() throws IOException {
CopyRecordReader reader = reader("{\"name\":\"bad}\n{\"name\":\"good\"}\n", "FORMAT JSON 'auto'");
assertEquals("{\"name\":\"bad}\n", next(reader));
assertEquals("{\"name\":\"good\"}\n", next(reader));
}
}
@@ -1,11 +1,17 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.core.common.PostgresWire;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -16,6 +22,7 @@ import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
@@ -24,10 +31,15 @@ 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.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@Timeout(10)
class ExtendedS3ExchangeTest {
private Socket simClient;
@@ -49,6 +61,9 @@ class ExtendedS3ExchangeTest {
simBackend = new Socket("localhost", backendListener.getLocalPort());
testBackend = backendListener.accept();
backendListener.close();
simBackend.setSoTimeout(3_000);
testBackend.setSoTimeout(3_000);
testClient.setSoTimeout(3_000);
s3 = mock(S3Service.class);
iamService = mock(IamService.class);
}
@@ -73,21 +88,76 @@ class ExtendedS3ExchangeTest {
BackendResponseCoordinator.Ticket ticket = coordinator.register(
BackendResponseCoordinator.Operation.EXECUTE, null);
ByteArrayOutputStream copied = new ByteArrayOutputStream();
writeSync();
Thread backend = backendThread(() -> playCopyIn(copied));
Thread backend = backendThread(() -> playEtlCopy(copied));
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), copy, s3, iamService, coordinator, ticket);
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), copy, s3, iamService,
null, List.of(), coordinator, ticket,
new CopyBackendSession(simBackend, response -> writeFrame(simClient.getOutputStream(),
response.type(), response.body())));
joinBackend(backend);
PostgresWireDecoder clientDecoder = new PostgresWireDecoder(testClient.getInputStream());
assertEquals('C', clientDecoder.nextMessage().type());
assertEquals("1|a\n", copied.toString(StandardCharsets.US_ASCII));
coordinator.register(BackendResponseCoordinator.Operation.SYNC, null);
coordinator.onBackendFrame('Z', new byte[]{'I'});
assertTrue(coordinator.awaitIdle(1, TimeUnit.SECONDS));
testClient.setSoTimeout(200);
assertThrows(SocketTimeoutException.class, () -> testClient.getInputStream().read());
}
@ParameterizedTest
@ValueSource(strings = {"", " MAXERROR 2"})
void jsonAutoNormalizesUnquotedColumnsAndPreservesQuotedColumns(String tolerance) throws Exception {
when(s3.objectExists("b", "in/data")).thenReturn(true);
when(s3.getObject("b", "in/data")).thenReturn(new S3Object("b", "in/data",
"{\"id\":1,\"ID\":99,\"MixedCase\":2,\"col one\":3}\n".getBytes(StandardCharsets.UTF_8),
"application/json"));
CopyStatementParser.S3CopyFrom copy = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY t (ID, \"MixedCase\", \"col one\") FROM 's3://b/in/data' JSON 'auto'" + tolerance);
ByteArrayOutputStream copied = new ByteArrayOutputStream();
Thread backend = backendThread(() -> new FakeCopyBackend(testBackend).serveUntilLoadComplete(copied));
long accepted = CopyEtlLoader.execute(new CopyBackendSession(simBackend, response -> { }),
copy, s3, iamService, null, List.of(), false);
joinBackend(backend);
assertEquals(1, accepted);
assertEquals("1,2,3\n", copied.toString(StandardCharsets.UTF_8));
}
@ParameterizedTest
@ValueSource(strings = {"", " MAXERROR 2"})
void copyRechecksRolePolicyAfterPreflightBeforeReadingObject(String tolerance) throws Exception {
String roleArn = "arn:aws:iam::000000000000:role/CopyRole";
IamRole role = mock(IamRole.class);
when(role.getArn()).thenReturn(roleArn);
when(iamService.findRole("000000000000", "CopyRole")).thenReturn(Optional.of(role));
when(iamService.resolvePrincipalContext(roleArn)).thenReturn(CallerContext.of(List.of(
"{\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}]}")));
when(s3.isAuthEnforced()).thenReturn(true);
when(s3.objectExists("b", "in/data")).thenReturn(true);
when(s3.getObject("b", "in/data")).thenReturn(new S3Object("b", "in/data",
"1\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
doAnswer(invocation -> {
when(iamService.resolvePrincipalContext(roleArn)).thenReturn(CallerContext.of(List.of()));
return null;
}).when(s3).authorizeSignedGetObject(any(), any(), eq("b"), eq("in/data"));
CopyStatementParser.S3CopyFrom copy = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY t FROM 's3://b/in/data' IAM_ROLE '" + roleArn + "'" + tolerance);
Thread backend = backendThread(() -> new FakeCopyBackend(testBackend).serveUntilSync(false, sql -> { }));
CopyBackendSession session = new CopyBackendSession(simBackend, response -> { });
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> CopyEtlLoader.execute(session, copy, s3, iamService, null, List.of(), false));
session.finish(true);
session.synchronize();
joinBackend(backend);
assertEquals("42501", error.sqlState());
verify(s3, never()).getObject("b", "in/data");
}
@Test
void copyOutWritesS3AndForwardsOnlyCommandComplete() throws Exception {
Map<String, byte[]> written = new ConcurrentHashMap<>();
@@ -101,15 +171,18 @@ class ExtendedS3ExchangeTest {
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, iamService, coordinator, ticket);
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), unload, s3, iamService,
null, List.of(), coordinator, ticket,
new CopyBackendSession(simBackend, response -> writeFrame(simClient.getOutputStream(),
response.type(), response.body())));
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.register(BackendResponseCoordinator.Operation.SYNC, null);
coordinator.onBackendFrame('Z', new byte[]{'I'});
assertTrue(coordinator.awaitIdle(1, TimeUnit.SECONDS));
testClient.setSoTimeout(200);
@@ -117,27 +190,67 @@ class ExtendedS3ExchangeTest {
}
@Test
void missingCopyInputSendsCopyFailAndWaitsForSyncRecovery() throws Exception {
void parquetUnloadDescribesColumnsAfterPendingParseAndBind() throws Exception {
CopyStatementParser.S3Unload unload = (CopyStatementParser.S3Unload) CopyStatementParser.parse(
"UNLOAD ('SELECT id FROM t') TO 's3://b/out/' FORMAT AS PARQUET ALLOWOVERWRITE");
RedshiftParquetWriter writer = mock(RedshiftParquetWriter.class);
byte[] parquet = "PAR1testPAR1".getBytes(StandardCharsets.US_ASCII);
List<RedshiftParquetWriter.Column> columns = List.of(new RedshiftParquetWriter.Column("id", "INTEGER"));
when(writer.convert(any(), eq(columns), any(), any(), anyLong())).thenReturn(List.of(parquet));
BackendResponseCoordinator coordinator = new BackendResponseCoordinator(new ExtendedQuerySession());
coordinator.register(BackendResponseCoordinator.Operation.PARSE, null);
coordinator.register(BackendResponseCoordinator.Operation.BIND, null);
BackendResponseCoordinator.Ticket ticket = coordinator.register(BackendResponseCoordinator.Operation.EXECUTE, null);
Thread backend = backendThread(() -> {
PostgresWireDecoder decoder = new PostgresWireDecoder(testBackend.getInputStream());
assertEquals('H', decoder.nextMessage().type());
OutputStream out = testBackend.getOutputStream();
PostgresWire.write(out, '1');
PostgresWire.write(out, '2');
out.flush();
assertEquals('P', decoder.nextMessage().type());
assertEquals('D', decoder.nextMessage().type());
assertEquals('C', decoder.nextMessage().type());
assertEquals('H', decoder.nextMessage().type());
PostgresWire.write(out, '1');
PostgresWire.write(out, 'T', new byte[]{0, 1}, PostgresWire.cStringBytes("id"),
PostgresWire.int32(0), new byte[2], PostgresWire.int32(23), new byte[]{0, 4},
PostgresWire.int32(-1), new byte[2]);
PostgresWire.write(out, '3');
out.flush();
playCopyOut();
});
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), unload, s3, iamService,
null, List.of(), coordinator, ticket,
new CopyBackendSession(simBackend, response -> {
throw new AssertionError("Unexpected asynchronous frame");
}), writer);
joinBackend(backend);
verify(s3).putObject(eq("b"), any(), eq(parquet), eq("application/octet-stream"), any());
PostgresWireDecoder clientDecoder = new PostgresWireDecoder(testClient.getInputStream());
assertEquals('1', clientDecoder.nextMessage().type());
assertEquals('2', clientDecoder.nextMessage().type());
assertEquals('C', clientDecoder.nextMessage().type());
coordinator.register(BackendResponseCoordinator.Operation.SYNC, null);
coordinator.onBackendFrame('Z', new byte[]{'I'});
assertTrue(coordinator.awaitIdle(1, TimeUnit.SECONDS));
}
@Test
void missingCopyInputReportsErrorBeforeClientSync() throws Exception {
CopyStatementParser.S3CopyFrom copy = new CopyStatementParser.S3CopyFrom(
"t", List.of(), "b", "missing", "|", 0, false, false, null, 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();
});
Thread backend = backendThread(() -> playEtlCopy(new ByteArrayOutputStream()));
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), copy, s3, iamService, coordinator, ticket);
ExtendedS3Exchange.execute(simClient, simBackend, executeFrame(), copy, s3, iamService,
null, List.of(), coordinator, ticket, new CopyBackendSession(simBackend, response -> {
throw new AssertionError("Unexpected asynchronous frame");
}));
joinBackend(backend);
testClient.setSoTimeout(1_000);
@@ -146,8 +259,10 @@ class ExtendedS3ExchangeTest {
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());
testClient.setSoTimeout(200);
assertThrows(SocketTimeoutException.class, () -> testClient.getInputStream().read());
coordinator.register(BackendResponseCoordinator.Operation.SYNC, null);
coordinator.onBackendFrame('Z', new byte[]{'I'});
assertTrue(coordinator.awaitIdle(1, TimeUnit.SECONDS));
}
@@ -155,33 +270,24 @@ class ExtendedS3ExchangeTest {
return new PostgresWireDecoder.FrontendMessage('E', new byte[]{0, 0, 0, 0, 0});
}
private void playCopyIn(ByteArrayOutputStream copied) throws IOException {
private void playEtlCopy(ByteArrayOutputStream copied) throws Exception {
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());
assertEquals('H', decoder.nextMessage().type());
writeCommandComplete();
new FakeCopyBackend(testBackend).serveUntilLoadComplete(copied);
}
private void playCopyOut() throws IOException {
PostgresWireDecoder decoder = new PostgresWireDecoder(testBackend.getInputStream());
assertEquals('E', decoder.nextMessage().type());
assertEquals('H', 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 {
@@ -189,15 +295,8 @@ class ExtendedS3ExchangeTest {
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);
PostgresWire.write(out, type, body);
}
private Thread backendThread(BackendScript script) {
@@ -211,7 +310,8 @@ class ExtendedS3ExchangeTest {
}
private void joinBackend(Thread backend) throws InterruptedException {
backend.join();
backend.join(5_000);
assertTrue(!backend.isAlive(), "Fake backend must finish");
Throwable failure = backendFailure.get();
if (failure != null) {
throw new AssertionError("fake backend failed", failure);
@@ -220,6 +320,6 @@ class ExtendedS3ExchangeTest {
@FunctionalInterface
private interface BackendScript {
void run() throws IOException;
void run() throws Exception;
}
}
@@ -0,0 +1,120 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.core.common.PostgresWire;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
/** Extended-query backend for COPY tests, including catalog discovery and transaction recovery. */
final class FakeCopyBackend {
private final Socket socket;
FakeCopyBackend(Socket socket) {
this.socket = socket;
}
void serveUntilLoadComplete(OutputStream copied) throws Exception {
serve(copied, true, false, sql -> { });
}
void serveUntilSync(boolean failCommit, StatementObserver observer) throws Exception {
serve(OutputStream.nullOutputStream(), false, failCommit, observer);
}
private void serve(OutputStream copied, boolean stopAfterLoad, boolean failCommit,
StatementObserver observer) throws Exception {
PostgresWireDecoder decoder = new PostgresWireDecoder(socket.getInputStream());
OutputStream out = socket.getOutputStream();
Map<String, String> statements = new HashMap<>();
Map<String, String> portals = new HashMap<>();
boolean transaction = false;
boolean failed = false;
boolean copyCompleted = false;
boolean finishing = false;
int closed = 0;
PostgresWireDecoder.FrontendMessage message;
while ((message = decoder.nextMessage()) != null) {
if (failed && message.type() != 'S') {
continue;
}
switch (message.type()) {
case 'P' -> {
PostgresWireDecoder.ParseMessage parsed = decoder.decodeParse(message);
statements.put(parsed.statementName(), parsed.sql());
PostgresWire.write(out, '1');
}
case 'B' -> {
PostgresWireDecoder.BindMessage bound = decoder.decodeBind(message);
portals.put(bound.portalName(), statements.get(bound.statementName()));
PostgresWire.write(out, '2');
}
case 'E' -> {
String sql = portals.get(decoder.decodeExecute(message).portalName());
if (sql.equals("BEGIN")) {
transaction = true;
} else if (sql.equals("COMMIT") || sql.equals("ROLLBACK")) {
transaction = false;
}
if (failCommit && sql.equals("COMMIT")) {
PostgresWire.write(out, 'E', S3CopySimulator.errorBody("23505", "deferred constraint violation"));
failed = true;
} else if (sql.startsWith("SAVEPOINT ") && !transaction) {
PostgresWire.write(out, 'E', S3CopySimulator.errorBody("25P01", "SAVEPOINT requires a transaction"));
failed = true;
} else if (sql.equals("SELECT 1 / 0")) {
PostgresWire.write(out, 'E', S3CopySimulator.errorBody("22012", "division by zero"));
failed = true;
} else if (sql.startsWith("COPY ")) {
PostgresWire.write(out, 'G', new byte[]{0, 0, 0});
} else {
if (sql.startsWith("SELECT a.attname")) {
PostgresWire.write(out, 'D', new byte[]{0, 3}, PostgresWire.int32(2), new byte[]{'i', 'd'},
PostgresWire.int32(-1), PostgresWire.int32(2), new byte[]{'2', '3'});
}
finishing = stopAfterLoad && copyCompleted && sql.startsWith("RELEASE SAVEPOINT floci_load_");
String tag = sql.startsWith("ROLLBACK") ? "ROLLBACK" : sql.split(" ")[0];
PostgresWire.write(out, 'C', PostgresWire.cStringBytes(tag));
out.flush();
observer.executed(sql);
}
}
case 'd' -> copied.write(message.body());
case 'c' -> {
PostgresWire.write(out, 'C', PostgresWire.cStringBytes("COPY 1"));
copyCompleted = true;
}
case 'f' -> {
PostgresWire.write(out, 'E', S3CopySimulator.errorBody("57014", "COPY input failed"));
failed = true;
}
case 'C' -> {
PostgresWire.write(out, '3');
if (finishing) {
closed++;
}
}
case 'S' -> {
PostgresWire.write(out, 'Z', new byte[]{(byte) (transaction ? 'T' : 'I')});
out.flush();
if (!failed) {
return;
}
failed = false;
}
case 'H' -> { }
default -> throw new AssertionError("Unexpected wire message " + message.type());
}
out.flush();
if (stopAfterLoad && (failed || message.type() == 'H' && finishing && closed == 2)) {
return;
}
}
}
@FunctionalInterface
interface StatementObserver {
void executed(String sql) throws Exception;
}
}
@@ -0,0 +1,317 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.core.common.PostgresWire;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
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.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
@Timeout(15)
class RedshiftCopyTransactionTest {
@Test
void readyForQueryClearsDiscardStateBeforeTheClientParsesRollback() throws Exception {
withBridgeSockets((client, bridgeClient, bridgeBackend, backend) -> {
CountDownLatch rollbackParsed = new CountDownLatch(1);
AtomicBoolean readyForwarded = new AtomicBoolean();
RedshiftInterceptingBridge.WireFrameTracker tracker = new RedshiftInterceptingBridge.WireFrameTracker(
(type, body) -> {
if (type == 'Z') {
readyForwarded.set(true);
}
});
OutputStream output = new FilterOutputStream(bridgeClient.getOutputStream()) {
@Override
public void write(byte[] bytes, int offset, int length) throws IOException {
out.write(bytes, offset, length);
tracker.consume(bytes, offset, length);
}
@Override
public void flush() throws IOException {
out.flush();
if (readyForwarded.compareAndSet(true, false)) {
try {
assertTrue(rollbackParsed.await(5, TimeUnit.SECONDS));
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
throw new IOException(exception);
}
}
}
};
Socket observedClient = spy(bridgeClient);
doReturn(output).when(observedClient).getOutputStream();
CompletableFuture<Void> server = CompletableFuture.runAsync(() -> {
try {
PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream());
assertEquals('P', decoder.nextMessage().type());
assertEquals('B', decoder.nextMessage().type());
PostgresWire.write(backend.getOutputStream(), '1');
PostgresWire.write(backend.getOutputStream(), '2');
backend.getOutputStream().flush();
assertEquals('P', decoder.nextMessage().type());
assertEquals('B', decoder.nextMessage().type());
assertEquals('E', decoder.nextMessage().type());
PostgresWire.write(backend.getOutputStream(), 'E',
S3CopySimulator.errorBody("25P02", "transaction is aborted"));
backend.getOutputStream().flush();
assertEquals('S', decoder.nextMessage().type());
PostgresWire.write(backend.getOutputStream(), 'Z', new byte[]{'E'});
backend.getOutputStream().flush();
PostgresWireDecoder.FrontendMessage rollback = decoder.nextMessage();
assertEquals('P', rollback.type());
assertEquals("ROLLBACK TO SAVEPOINT client_sp", decoder.decodeParse(rollback).sql());
rollbackParsed.countDown();
PostgresWire.write(backend.getOutputStream(), '1');
backend.getOutputStream().flush();
assertEquals('B', decoder.nextMessage().type());
assertEquals('E', decoder.nextMessage().type());
assertEquals('S', decoder.nextMessage().type(), "Rollback must not execute the previous COPY");
PostgresWire.write(backend.getOutputStream(), '2');
PostgresWire.write(backend.getOutputStream(), 'C', PostgresWire.cStringBytes("ROLLBACK"));
PostgresWire.write(backend.getOutputStream(), 'Z', new byte[]{'T'});
backend.getOutputStream().flush();
} catch (Exception exception) {
throw new AssertionError(exception);
}
});
Thread.ofVirtual().start(new RedshiftInterceptingBridge(observedClient, bridgeBackend,
mock(S3Service.class), mock(IamService.class))::run);
OutputStream frontend = client.getOutputStream();
PostgresWireDecoder responses = new PostgresWireDecoder(client.getInputStream());
frontend.write(PostgresWireDecoder.encodeParse(new PostgresWireDecoder.ParseMessage("",
"COPY events FROM 's3://bucket/data' MAXERROR 2", List.of()),
"COPY events FROM 's3://bucket/data' MAXERROR 2"));
PostgresWire.write(frontend, 'B', new byte[8]);
frontend.flush();
assertEquals('1', responses.nextMessage().type());
assertEquals('2', responses.nextMessage().type());
ByteArrayOutputStream failed = new ByteArrayOutputStream();
statement(failed, "", "SELECT count(*) FROM events");
frontend.write(failed.toByteArray());
frontend.flush();
assertEquals('E', responses.nextMessage().type());
PostgresWire.write(frontend, 'S');
frontend.flush();
assertEquals('Z', responses.nextMessage().type());
frontend.write(PostgresWireDecoder.encodeParse(new PostgresWireDecoder.ParseMessage("",
"ROLLBACK TO SAVEPOINT client_sp", List.of()), "ROLLBACK TO SAVEPOINT client_sp"));
frontend.flush();
assertEquals('1', responses.nextMessage().type());
PostgresWire.write(frontend, 'B', new byte[8]);
PostgresWire.write(frontend, 'E', new byte[5]);
PostgresWire.write(frontend, 'S');
frontend.flush();
server.get(5, TimeUnit.SECONDS);
assertEquals('2', responses.nextMessage().type());
assertEquals('C', responses.nextMessage().type());
assertEquals('T', responses.nextMessage().body()[0]);
});
}
@Test
void rollbackToSavepointRetainsOwnershipUntilClientSync() throws Exception {
runCycle(List.of(), List.of("SAVEPOINT client_sp", "ROLLBACK TO SAVEPOINT client_sp"), false);
}
@Test
void fullRollbackBeforeCopyStartsANewOwnedTransaction() throws Exception {
runCycle(List.of("BEGIN", "ROLLBACK"), List.of(), false);
}
@Test
void syncCompletionWaitsForTheRestOfAnAsynchronousFrame() throws Exception {
runCycle(List.of(), List.of("SAVEPOINT client_sp"), true);
}
@Test
void commitFailureAtClientSyncReturnsErrorWithoutDroppingSession() throws Exception {
withBridgeSockets((client, bridgeClient, bridgeBackend, backend) -> {
S3Service s3 = mock(S3Service.class);
when(s3.objectExists("bucket", "data")).thenReturn(true);
when(s3.getObject("bucket", "data")).thenReturn(new S3Object("bucket", "data",
"1\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
CompletableFuture<Void> server = CompletableFuture.runAsync(() -> {
try {
serve(backend, false, true, null);
} catch (Exception exception) {
throw new AssertionError(exception);
}
});
Thread.ofVirtual().start(new RedshiftInterceptingBridge(bridgeClient, bridgeBackend, s3,
mock(IamService.class))::run);
ByteArrayOutputStream pipeline = new ByteArrayOutputStream();
statement(pipeline, "copy", "COPY events FROM 's3://bucket/data' MAXERROR 2");
pipeline.writeBytes(PostgresWire.frame('S', new byte[0]));
client.getOutputStream().write(pipeline.toByteArray());
client.getOutputStream().flush();
PostgresWireDecoder decoder = new PostgresWireDecoder(client.getInputStream());
boolean sawError = false;
boolean sawReady = false;
while (true) {
PostgresWireDecoder.FrontendMessage response = decoder.nextMessage();
assertNotNull(response, "COPY must leave the connection usable");
if (response.type() == 'E') {
sawError = true;
} else if (response.type() == 'Z') {
sawReady = true;
assertEquals('I', response.body()[0], "The aborted cycle must report Idle at Sync");
break;
}
}
assertTrue(sawError, "Commit failure must report an error frame to the client");
assertTrue(sawReady, "The client must receive ReadyForQuery");
server.get(5, TimeUnit.SECONDS);
});
}
private void runCycle(List<String> before, List<String> after, boolean fragmentNotice) throws Exception {
withBridgeSockets((client, bridgeClient, bridgeBackend, backend) -> {
S3Service s3 = mock(S3Service.class);
when(s3.objectExists("bucket", "data")).thenReturn(true);
when(s3.getObject("bucket", "data")).thenReturn(new S3Object("bucket", "data",
"1\n".getBytes(StandardCharsets.UTF_8), "text/plain"));
Semaphore midFrameTimeout = new Semaphore(0);
Socket observedBackend = observePumpTimeout(bridgeBackend, midFrameTimeout);
CompletableFuture<Void> server = CompletableFuture.runAsync(() -> {
try {
serve(backend, fragmentNotice, false, midFrameTimeout);
} catch (Exception exception) {
throw new AssertionError(exception);
}
});
Thread.ofVirtual().start(new RedshiftInterceptingBridge(bridgeClient, observedBackend, s3,
mock(IamService.class))::run);
ByteArrayOutputStream pipeline = new ByteArrayOutputStream();
int index = 0;
for (String sql : before) {
statement(pipeline, "stmt" + index++, sql);
}
statement(pipeline, "copy", "COPY events FROM 's3://bucket/data' MAXERROR 2");
for (String sql : after) {
statement(pipeline, "stmt" + index++, sql);
}
if (!fragmentNotice) {
pipeline.writeBytes(PostgresWire.frame('S', new byte[0]));
}
client.getOutputStream().write(pipeline.toByteArray());
client.getOutputStream().flush();
if (fragmentNotice) {
assertTrue(midFrameTimeout.tryAcquire(5, TimeUnit.SECONDS),
"Pump must read the incomplete notice before client Sync");
PostgresWire.write(client.getOutputStream(), 'S');
client.getOutputStream().flush();
}
PostgresWireDecoder decoder = new PostgresWireDecoder(client.getInputStream());
int completed = 0;
while (true) {
PostgresWireDecoder.FrontendMessage response = decoder.nextMessage();
assertNotNull(response, "COPY must leave the connection usable");
assertFalse(response.type() == 'E', () -> "Unexpected COPY error: "
+ new String(response.body(), StandardCharsets.UTF_8));
if (response.type() == 'C') {
completed++;
} else if (response.type() == 'Z') {
assertEquals('I', response.body()[0], "The implicit cycle must finish at client Sync");
break;
}
}
assertEquals(before.size() + after.size() + 1, completed);
server.get(5, TimeUnit.SECONDS);
});
}
private static void withBridgeSockets(BridgeSocketTest test) throws Exception {
try (ServerSocket clients = new ServerSocket(0); ServerSocket backends = new ServerSocket(0);
Socket client = new Socket("127.0.0.1", clients.getLocalPort()); Socket bridgeClient = clients.accept();
Socket bridgeBackend = new Socket("127.0.0.1", backends.getLocalPort()); Socket backend = backends.accept()) {
client.setSoTimeout(5000);
backend.setSoTimeout(5000);
test.run(client, bridgeClient, bridgeBackend, backend);
}
}
@FunctionalInterface
private interface BridgeSocketTest {
void run(Socket client, Socket bridgeClient, Socket bridgeBackend, Socket backend) throws Exception;
}
private static void statement(ByteArrayOutputStream output, String name, String sql) throws IOException {
output.writeBytes(PostgresWireDecoder.encodeParse(new PostgresWireDecoder.ParseMessage(name, sql, List.of()), sql));
PostgresWire.write(output, 'B', PostgresWire.cStringBytes(name), PostgresWire.cStringBytes(name), new byte[6]);
PostgresWire.write(output, 'E', PostgresWire.cStringBytes(name), new byte[4]);
}
private static Socket observePumpTimeout(Socket backend, Semaphore midFrameTimeout) throws IOException {
InputStream input = new FilterInputStream(backend.getInputStream()) {
private final RedshiftInterceptingBridge.WireFrameTracker tracker =
new RedshiftInterceptingBridge.WireFrameTracker((type, body) -> {
// Only frame boundaries matter to the timeout observation.
});
@Override
public int read(byte[] bytes) throws IOException {
try {
int count = in.read(bytes);
if (count > 0) {
tracker.consume(bytes, 0, count);
}
return count;
} catch (SocketTimeoutException exception) {
if (!tracker.betweenMessages()) {
midFrameTimeout.release();
}
throw exception;
}
}
};
Socket observed = spy(backend);
doReturn(input).when(observed).getInputStream();
return observed;
}
private static void serve(Socket socket, boolean fragmentNotice, boolean failCommit,
Semaphore midFrameTimeout) throws Exception {
new FakeCopyBackend(socket).serveUntilSync(failCommit, sql -> {
if (fragmentNotice && sql.equals("SAVEPOINT client_sp")) {
byte[] notice = PostgresWire.frame('N', S3CopySimulator.errorBody("00000", "async notice"));
socket.getOutputStream().write(notice, 0, 3);
socket.getOutputStream().flush();
assertEquals('H', new PostgresWireDecoder(socket.getInputStream()).nextMessage().type(),
"Client Sync must request backend completion while the notice is incomplete");
midFrameTimeout.drainPermits();
assertTrue(midFrameTimeout.tryAcquire(5, TimeUnit.SECONDS),
"Pump must time out mid-notice while client Sync is pending");
socket.getOutputStream().write(notice, 3, notice.length - 3);
socket.getOutputStream().flush();
}
});
}
}
@@ -19,6 +19,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
@@ -29,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;
@@ -326,6 +328,7 @@ class RedshiftInterceptingBridgeTest {
}
@Test
@Timeout(15)
void pipelinedExtendedCopyPreservesResponseOrderAndSyncReadyForQuery() throws Exception {
startBridge();
Mockito.when(s3Stub.objectExists("b", "in/data")).thenReturn(true);
@@ -335,21 +338,62 @@ class RedshiftInterceptingBridgeTest {
Thread backend = Thread.ofVirtual().start(() -> {
try {
PostgresWireDecoder decoder = new PostgresWireDecoder(testBackendEnd.getInputStream());
assertEquals('C', decoder.nextMessage().type());
PostgresWireDecoder.ParseMessage parse = decoder.decodeParse(decoder.nextMessage());
assertTrue(parse.sql().contains("FROM STDIN"), parse.sql());
writeBackendFrame('1', new byte[0]);
assertEquals("DO $$BEGIN NULL; END$$", parse.sql());
assertEquals('B', decoder.nextMessage().type());
writeBackendFrame('2', new byte[0]);
assertEquals('D', decoder.nextMessage().type());
assertEquals('H', decoder.nextMessage().type());
writeBackendFrame('3', new byte[0]);
writeBackendFrame('1', new byte[0]);
writeBackendFrame('2', new byte[0]);
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('H', decoder.nextMessage().type());
writeBackendFrame('C', cString("DO"));
String command = "";
boolean inTransaction = false;
while (true) {
PostgresWireDecoder.FrontendMessage message = decoder.nextMessage();
switch (message.type()) {
case 'P' -> {
command = decoder.decodeParse(message).sql();
writeBackendFrame('1', new byte[0]);
}
case 'B' -> writeBackendFrame('2', new byte[0]);
case 'E' -> {
if (command.startsWith("COPY ")) {
assertTrue(command.contains("FROM STDIN"));
writeBackendFrame('G', new byte[]{0, 0, 0});
} else {
if (command.startsWith("SELECT a.attname")) {
ByteArrayOutputStream row = new ByteArrayOutputStream();
row.writeBytes(new byte[]{0, 3});
row.writeBytes(new byte[]{0, 0, 0, 2, 'i', 'd'});
row.writeBytes(new byte[]{-1, -1, -1, -1});
row.writeBytes(new byte[]{0, 0, 0, 2, '2', '3'});
writeBackendFrame('D', row.toByteArray());
}
if (command.equals("BEGIN")) {
inTransaction = true;
} else if (command.equals("COMMIT")) {
inTransaction = false;
}
writeBackendFrame('C', cString(command.equals("BEGIN") ? "BEGIN" : "OK"));
}
}
case 'd' -> assertEquals("1|a\n", new String(message.body(), StandardCharsets.US_ASCII));
case 'c' -> writeBackendFrame('C', cString("COPY 1"));
case 'C' -> writeBackendFrame('3', new byte[0]);
case 'S' -> {
assertFalse(inTransaction, "Only the client's final Sync may end this cycle");
writeBackendFrame('Z', new byte[]{'I'});
return;
}
case 'H' -> { }
default -> throw new AssertionError("Unexpected internal COPY message " + message.type());
}
}
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);
}
@@ -358,18 +402,24 @@ class RedshiftInterceptingBridgeTest {
PostgresWireDecoder.ParseMessage parse = new PostgresWireDecoder.ParseMessage(
"copy-s", "COPY t FROM 's3://b/in/data'", List.of());
ByteArrayOutputStream pipeline = new ByteArrayOutputStream();
pipeline.write(frame('C', concat(new byte[]{'S'}, cString("obsolete"))));
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('3', clientDecoder.nextMessage().type());
assertEquals('1', clientDecoder.nextMessage().type());
assertEquals('2', clientDecoder.nextMessage().type());
assertEquals('n', clientDecoder.nextMessage().type());
assertEquals('C', clientDecoder.nextMessage().type());
testClientEnd.setSoTimeout(200);
assertThrows(SocketTimeoutException.class, clientDecoder::nextMessage);
testClientEnd.setSoTimeout(5000);
testClientEnd.getOutputStream().write(frame('S', new byte[0]));
testClientEnd.getOutputStream().flush();
assertEquals('Z', clientDecoder.nextMessage().type());
backend.join();
if (backendFailure.get() != null) {
@@ -392,8 +442,9 @@ class RedshiftInterceptingBridgeTest {
assertTrue(parse.sql().startsWith("COPY (select id from t) TO STDOUT"), parse.sql());
assertEquals('B', decoder.nextMessage().type());
assertEquals('D', decoder.nextMessage().type());
assertEquals('H', decoder.nextMessage().type());
assertEquals('E', decoder.nextMessage().type());
assertEquals('S', decoder.nextMessage().type());
assertEquals('H', decoder.nextMessage().type());
writeBackendFrame('1', new byte[0]);
writeBackendFrame('2', new byte[0]);
writeBackendFrame('n', new byte[0]);
@@ -401,6 +452,7 @@ class RedshiftInterceptingBridgeTest {
writeBackendFrame('d', "1\n".getBytes(StandardCharsets.US_ASCII));
writeBackendFrame('c', new byte[0]);
writeBackendFrame('C', "COPY 1\0".getBytes(StandardCharsets.US_ASCII));
assertEquals('S', decoder.nextMessage().type());
writeBackendFrame('Z', new byte[]{'I'});
} catch (Throwable failure) {
backendFailure.compareAndSet(null, failure);
@@ -0,0 +1,32 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RedshiftInternalAuthTest {
@Test
void issuedTokenIsValidOnceAndSingleUse() {
String token = RedshiftInternalAuth.issueDataApiToken();
assertNotNull(token);
assertTrue(token.startsWith("floci-redshift-data:"));
// First consume must succeed
assertTrue(RedshiftInternalAuth.consumeDataApiToken(token));
// Replay of the same token must fail
assertFalse(RedshiftInternalAuth.consumeDataApiToken(token));
}
@Test
void unauthenticatedOrMalformedTokensAreRejected() {
assertFalse(RedshiftInternalAuth.consumeDataApiToken(null));
assertFalse(RedshiftInternalAuth.consumeDataApiToken(""));
assertFalse(RedshiftInternalAuth.consumeDataApiToken("floci-redshift-data"));
assertFalse(RedshiftInternalAuth.consumeDataApiToken("floci-redshift-data:unknown-uuid"));
assertFalse(RedshiftInternalAuth.consumeDataApiToken("other-app:token"));
}
}
@@ -56,6 +56,14 @@ import static org.mockito.Mockito.when;
class S3CopySimulatorTest {
@Test
void columnInfoQueryEscapesApostrophesAndBackslashesInTableNames() {
CopyStatementParser.S3CopyFrom copy = new CopyStatementParser.S3CopyFrom(
"\"o'brien\\new\"", List.of(), "b", "data", "|", 0, false, false, null, null);
assertTrue(S3CopySimulator.columnInfoQuery(copy).contains("to_regclass(E'\"o''brien\\\\new\"')"));
}
@Test
void parquetSlicesWaitForCompleteCsvRecordsAndManifestUsesConvertedLengths() throws Exception {
long previous = S3CopySimulator.UNLOAD_TARGET_FILE_BYTES;
@@ -1902,10 +1910,22 @@ class S3CopySimulatorTest {
}
@Test
void copyBackendSql_asksTheBackendToSkipConversionErrorsUpToMaxErrorMinusOne() {
assertTrue(backendCopy(10, false).endsWith(", ON_ERROR ignore, REJECT_LIMIT 9)"), backendCopy(10, false));
assertTrue(backendCopy(2, true).contains("FORMAT csv"), backendCopy(2, true));
assertTrue(backendCopy(2, true).endsWith(", ON_ERROR ignore, REJECT_LIMIT 1)"), backendCopy(2, true));
void corruptGzipInputIsACopyErrorRatherThanATransportFailure() {
CopyStatementParser.S3CopyFrom spec = (CopyStatementParser.S3CopyFrom) CopyStatementParser.parse(
"COPY t FROM 's3://bucket/broken' GZIP");
when(s3.objectExists("bucket", "broken")).thenReturn(true);
when(s3.getObject("bucket", "broken")).thenReturn(new S3Object("bucket", "broken",
"not-gzip".getBytes(StandardCharsets.UTF_8), "application/gzip"));
S3CopySimulator.CopyInput input = S3CopySimulator.prepareCopy(spec, s3, null);
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
() -> S3CopySimulator.streamCopyInput(input, new ByteArrayOutputStream()));
assertEquals("58030", error.sqlState());
}
@Test
void copyBackendSqlUsesPostgres15SyntaxWhenMaxErrorIsHandledByTheLoader() {
assertEquals("COPY t FROM STDIN WITH (FORMAT text, DELIMITER '|')", backendCopy(10, false));
assertEquals("COPY t FROM STDIN WITH (FORMAT csv, DELIMITER '|')", backendCopy(2, true));
}
@Test
@@ -1913,8 +1933,7 @@ class S3CopySimulatorTest {
CopyStatementParser.S3Statement parsed = CopyStatementParser.parse(
"COPY t FROM 's3://wh/k' DELIMITER '|' NULL AS 'x' GZIP IGNOREHEADER 1 MAXERROR AS 10");
assertEquals("COPY t FROM STDIN WITH (FORMAT text, DELIMITER '|', NULL 'x', ON_ERROR ignore, "
+ "REJECT_LIMIT 9)",
assertEquals("COPY t FROM STDIN WITH (FORMAT text, DELIMITER '|', NULL 'x')",
S3CopySimulator.copyBackendSql((CopyStatementParser.S3CopyFrom) parsed, null));
}
@@ -2155,7 +2174,7 @@ class S3CopySimulatorTest {
CopyStatementParser.S3CopyFrom spec = new CopyStatementParser.S3CopyFrom(
"users", List.of("\"col one\"", "Id"), "wh", "users.json", null, 0, false, false, null, null, true, false);
String ndjson = "{\"col one\": \"Alice\", \"Id\": 10}\n";
String ndjson = "{\"col one\": \"Alice\", \"id\": 10, \"Id\": 99}\n";
S3Object dataObj = new S3Object("wh", "users.json", ndjson.getBytes(StandardCharsets.UTF_8), "application/json");
when(s3.getObject("wh", "users.json")).thenReturn(dataObj);
@@ -2247,7 +2266,7 @@ class S3CopySimulatorTest {
@Test
void runCopyFrom_withQuotedAndMixedCaseColumns_passesThroughToBackendAndMatchesJsonKeys() throws Exception {
String ndjson = "{\"col one\": \"Alice\", \"MixedCase\": 10}\n";
String ndjson = "{\"col one\": \"Alice\", \"mixedcase\": 10, \"MixedCase\": 99}\n";
S3Object dataObj = new S3Object("wh", "users.json", ndjson.getBytes(StandardCharsets.UTF_8), "application/json");
when(s3.objectExists("wh", "users.json")).thenReturn(true);
when(s3.getObject("wh", "users.json")).thenReturn(dataObj);
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.redshiftdata;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.model.Parameter;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
@@ -24,8 +25,10 @@ import software.amazon.awssdk.services.redshiftdata.model.ExecuteStatementRespon
import software.amazon.awssdk.services.redshiftdata.model.ResourceNotFoundException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.hamcrest.Matchers.containsString;
@@ -46,6 +49,9 @@ class RedshiftDataApiIntegrationTest {
@Inject
RedshiftService redshift;
@Inject
S3Service s3;
@TestHTTPResource("/")
URI endpoint;
@@ -105,6 +111,49 @@ class RedshiftDataApiIntegrationTest {
return ((Number) value).intValue();
}
@Test
void sdkCopyEtlWorksInRetainedSessionsAndRollsBackAFailedBatch() {
String bucket = "data-copy-etl-" + UUID.randomUUID().toString().substring(0, 8);
s3.createBucket(bucket, "us-east-1");
s3.putObject(bucket, "data", "1|31/10/2026|abcdef\n2|bad-date|skip\n3|01/11/2026\n"
.getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
String copy = "COPY data_copy_etl FROM 's3://" + bucket
+ "/data' DATEFORMAT 'DD/MM/YYYY' FILLRECORD TRUNCATECOLUMNS MAXERROR 2";
try (RedshiftDataClient data = RedshiftDataClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))).build()) {
ExecuteStatementResponse created = data.executeStatement(request -> request.clusterIdentifier(clusterId)
.dbUser("admin").database("dev").sessionKeepAliveSeconds(60)
.sql("CREATE TEMP TABLE data_copy_etl(id int, day date, label varchar(3))"));
awaitFinished(created.id());
String session = created.sessionId();
String loaded = data.executeStatement(request -> request.sessionId(session).sql(copy)).id();
awaitFinished(loaded);
assertEquals(2L, data.describeStatement(request -> request.id(loaded)).resultRows());
String values = data.executeStatement(request -> request.sessionId(session)
.sql("SELECT day, label FROM data_copy_etl ORDER BY id")).id();
awaitFinished(values);
assertEquals("2026-10-31", data.getStatementResult(request -> request.id(values))
.records().getFirst().getFirst().stringValue());
assertEquals("abc", data.getStatementResult(request -> request.id(values))
.records().getFirst().get(1).stringValue());
String failed = data.batchExecuteStatement(request -> request.sessionId(session)
.sqls(copy, "INSERT INTO data_copy_etl(id) VALUES ('invalid')")).id();
Awaitility.await().atMost(Duration.ofSeconds(30)).until(() ->
"FAILED".equals(data.describeStatement(request -> request.id(failed)).statusAsString()));
awaitFinished(data.executeStatement(request -> request.sessionId(session).sql("BEGIN")).id());
awaitFinished(data.executeStatement(request -> request.sessionId(session).sql(copy)).id());
awaitFinished(data.executeStatement(request -> request.sessionId(session).sql("ROLLBACK")).id());
String count = data.executeStatement(request -> request.sessionId(session).sessionKeepAliveSeconds(0)
.sql("SELECT count(*) FROM data_copy_etl")).id();
awaitFinished(count);
assertEquals(2L, data.getStatementResult(request -> request.id(count))
.records().getFirst().getFirst().longValue());
} finally {
s3.deleteObject(bucket, "data");
s3.deleteBucket(bucket);
}
}
@Test
void sdkSessionPreservesPostgresTemporaryTablesAcrossExecuteAndBatch() {
try (RedshiftDataClient data = RedshiftDataClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
@@ -68,6 +68,70 @@ class RedshiftDataResourceResolverTest {
assertEquals("Secret123", target.password());
}
@Test
void resolvesClusterProxyPortWhenSessionOrCopyRequested() {
Cluster c = cluster();
c.setProxyPort(5439);
RedshiftService redshift = mock(RedshiftService.class);
when(redshift.describeClusters("wh")).thenReturn(List.of(c));
ObjectNode sessionReq = mapper.createObjectNode();
sessionReq.put("ClusterIdentifier", "wh");
sessionReq.put("DbUser", "admin");
sessionReq.put("Database", "dev");
sessionReq.put("SessionKeepAliveSeconds", 60);
RedshiftDataResourceResolver.DatabaseTarget sessionTarget =
resolver(redshift, mock(SecretsManagerService.class)).resolve(sessionReq, REGION);
assertEquals("127.0.0.1", sessionTarget.host());
assertEquals(5439, sessionTarget.port());
ObjectNode copyReq = mapper.createObjectNode();
copyReq.put("ClusterIdentifier", "wh");
copyReq.put("DbUser", "admin");
copyReq.put("Database", "dev");
copyReq.put("Sql", "COPY tbl FROM 's3://bucket/key' IAM_ROLE 'arn:aws:iam::000000000000:role/Role'");
RedshiftDataResourceResolver.DatabaseTarget copyTarget =
resolver(redshift, mock(SecretsManagerService.class)).resolve(copyReq, REGION);
assertEquals("127.0.0.1", copyTarget.host());
assertEquals(5439, copyTarget.port());
ObjectNode commentedCopy = mapper.createObjectNode();
commentedCopy.put("ClusterIdentifier", "wh");
commentedCopy.put("DbUser", "admin");
commentedCopy.put("Database", "dev");
commentedCopy.put("Sql", "/* leading comment */ COPY tbl FROM 's3://bucket/key' IAM_ROLE 'arn:aws:iam::000000000000:role/Role'");
RedshiftDataResourceResolver.DatabaseTarget commentedTarget =
resolver(redshift, mock(SecretsManagerService.class)).resolve(commentedCopy, REGION);
assertEquals("127.0.0.1", commentedTarget.host());
assertEquals(5439, commentedTarget.port());
}
@Test
void resolvesClusterContainerPortWhenNoProxyNeeded() {
Cluster c = cluster();
c.setProxyPort(5439);
RedshiftService redshift = mock(RedshiftService.class);
when(redshift.describeClusters("wh")).thenReturn(List.of(c));
ObjectNode req = mapper.createObjectNode();
req.put("ClusterIdentifier", "wh");
req.put("DbUser", "admin");
req.put("Database", "dev");
req.put("Sql", "SELECT 1");
RedshiftDataResourceResolver.DatabaseTarget target =
resolver(redshift, mock(SecretsManagerService.class)).resolve(req, REGION);
assertEquals(c.getContainerHost(), target.host());
assertEquals(c.getContainerPort(), target.port());
}
@Test
void aProvisionedClusterArnCarriesTheCallersAccount() {
RedshiftService redshift = mock(RedshiftService.class);
@@ -93,6 +93,17 @@ class RedshiftDataServiceTest {
return om.createObjectNode().put("Id", id);
}
@Test
void redshiftTableDdlIsRewrittenThroughTheDataApi() {
String id = service.executeStatement(req("CREATE TABLE events (id int) DISTSTYLE ALL"), REGION)
.path("Id").asText();
assertEquals("FINISHED", service.describeStatement(idOf(id)).path("Status").asText());
String queryId = service.executeStatement(req("SELECT count(*) FROM events"), REGION).path("Id").asText();
assertEquals("FINISHED", service.describeStatement(idOf(queryId)).path("Status").asText());
assertEquals(0, service.getStatementResult(idOf(queryId)).path("Records").get(0).get(0)
.path("longValue").asLong());
}
@Test
void copyJobListAndShowReadTheCatalogThroughTheDataApi() throws SQLException {
try (Connection connection = DriverManager.getConnection(jdbcUrl, "sa", "");