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

@@ -60,7 +60,17 @@ public class PostgresProtocolHandler {
* An authenticated client connection ready to be bridged. {@code iamRole} is the role an IAM
* token named and the session was handed over to, or {@code null} for every other login.
*/
public record AuthenticatedSession(Socket client, Socket backend, String iamRole) {}
public record AuthenticatedSession(Socket client, Socket backend, String iamRole,
Map<String, String> startupParameters) {
public AuthenticatedSession(Socket client, Socket backend, String iamRole) {
this(client, backend, iamRole, Map.of());
}
}
@FunctionalInterface
public interface StartupObserver {
void onStartup(String username, String database, Map<String, String> parameters);
}
/** The username/password the proxy opens the backend PostgreSQL connection with. */
record BackendLogin(String user, String password) {}
@@ -153,6 +163,19 @@ public class PostgresProtocolHandler {
PasswordValidator passwordValidator, int handshakeTimeoutMillis,
boolean forwardStartupParameters, boolean databaseIamAuthentication,
BiConsumer<String, String> startupObserver) throws IOException {
return authenticate(client, backendConnector, masterUsername, masterPassword, dbName,
iamEnabled, sigV4, binding, tlsCertificates, passwordValidator,
handshakeTimeoutMillis, forwardStartupParameters, databaseIamAuthentication,
(username, database, parameters) -> startupObserver.accept(username, database));
}
public static AuthenticatedSession authenticate(Socket client, BackendConnector backendConnector,
String masterUsername, String masterPassword, String dbName,
boolean iamEnabled, RdsSigV4Validator sigV4,
RdsProxyBinding binding, RdsProxyTlsCertificates tlsCertificates,
PasswordValidator passwordValidator, int handshakeTimeoutMillis,
boolean forwardStartupParameters, boolean databaseIamAuthentication,
StartupObserver startupObserver) throws IOException {
client.setSoTimeout(handshakeTimeoutMillis);
@@ -165,7 +188,8 @@ public class PostgresProtocolHandler {
}
client = startup.socket();
String clientUsername = startup.username();
startupObserver.accept(clientUsername, resolveEffectiveDbName(startup.database(), dbName));
startupObserver.onStartup(clientUsername, resolveEffectiveDbName(startup.database(), dbName),
startup.parameters());
InputStream clientIn = client.getInputStream();
// PgBouncer rejects partial login packets; keep the challenge together until flush().
// https://github.com/pgbouncer/pgbouncer/blob/pgbouncer_1_24_0/src/server.c#L116-L119
@@ -481,7 +505,7 @@ public class PostgresProtocolHandler {
client.setSoTimeout(0);
backend.setSoTimeout(0);
return new AuthenticatedSession(client, backend, iamRole);
return new AuthenticatedSession(client, backend, iamRole, startup.parameters());
} catch (IOException | RuntimeException e) {
closeQuietly(backend);
throw e;
@@ -109,6 +109,26 @@ final class BackendResponseCoordinator {
}
}
boolean awaitSyncTurn(Ticket ticket, long timeout, TimeUnit unit) throws InterruptedException {
long remaining = unit.toNanos(timeout);
lock.lockInterruptibly();
try {
while (!closed) {
PendingOperation head = pending.peekFirst();
if (head != null && head.ticket().equals(ticket)) {
return true;
}
if (remaining <= 0) {
return false;
}
remaining = changed.awaitNanos(remaining);
}
return false;
} finally {
lock.unlock();
}
}
void onBackendFrame(char type, byte[] body) {
lock.lock();
try {
@@ -182,6 +202,17 @@ final class BackendResponseCoordinator {
}
}
void discardUntilSync() {
lock.lock();
try {
discardingUntilSync = true;
discardQueuedOperationsBeforeSync();
changed.signalAll();
} finally {
lock.unlock();
}
}
boolean isDiscardingUntilSync() {
lock.lock();
try {
@@ -200,6 +231,17 @@ final class BackendResponseCoordinator {
}
}
void transactionEnded() {
lock.lock();
try {
lastReadyStatus = 'I';
session.transactionEnded();
changed.signalAll();
} finally {
lock.unlock();
}
}
void close() {
lock.lock();
try {
@@ -0,0 +1,239 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.core.common.PostgresWire;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql;
import io.github.hectorvent.floci.services.redshift.proxy.S3CopySimulator.S3TransferException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/** Internal COPY commands use named extended statements so client statements and portals survive. */
final class CopyBackendSession {
private final Socket backend;
private final FrameSink asynchronous;
private final String prefix = "floci_copy_" + UUID.randomUUID().toString().replace("-", "");
private long sequence;
private volatile boolean ownsTransaction;
private boolean failed;
private String activeStatement;
private boolean parsed;
private char readyStatus = 'I';
CopyBackendSession(Socket backend, FrameSink asynchronous) {
this.backend = backend;
this.asynchronous = asynchronous;
}
char readyStatus() {
return readyStatus;
}
boolean ownsTransaction() {
return ownsTransaction;
}
boolean requiresCompletion() {
return ownsTransaction || (failed && activeStatement != null);
}
void begin(boolean callerTransaction) throws IOException {
if (!callerTransaction && !ownsTransaction) {
execute("BEGIN");
ownsTransaction = true;
}
}
void onClientCommand(String sql, String tag) {
boolean fullRollback = tag.equals("ROLLBACK") && RedshiftAuditSql.savepoint(sql) == null;
if (tag.equals("BEGIN") || tag.equals("COMMIT") || fullRollback) {
ownsTransaction = false;
}
}
void onBackendError() {
failed = true;
}
void onClientReady(char status) {
failed = false;
activeStatement = null;
parsed = false;
if (status == 'I') {
ownsTransaction = false;
}
}
void finish(boolean cycleFailed) throws IOException {
recover();
if (!ownsTransaction) {
return;
}
try {
execute(cycleFailed ? "ROLLBACK" : "COMMIT");
} finally {
ownsTransaction = false;
}
}
void recover() throws IOException {
if (!failed) {
return;
}
synchronize();
if (parsed && activeStatement != null) {
write('C', new byte[]{'S'}, PostgresWire.cStringBytes(activeStatement));
flush();
while (read().type() != '3') {
// A failed command's prepared statement survives transaction rollback.
}
}
activeStatement = null;
parsed = false;
}
void synchronize() throws IOException {
write('S', new byte[0]);
backend.getOutputStream().flush();
while (true) {
PostgresWireDecoder.FrontendMessage response = read();
if (response.type() == 'Z') {
readyStatus = (char) response.body()[0];
break;
}
}
failed = false;
}
void failTransaction() throws IOException {
try {
execute("SELECT 1 / 0");
} catch (S3TransferException expected) {
// Preserve COPY's original error while leaving an explicit transaction failed.
if (!"22012".equals(expected.sqlState()) && !"25P02".equals(expected.sqlState())) {
throw expected;
}
}
}
void execute(String sql) throws IOException {
query(sql);
}
List<List<String>> query(String sql) throws IOException {
String name = start(sql);
List<List<String>> rows = new ArrayList<>();
while (true) {
PostgresWireDecoder.FrontendMessage response = read();
if (response.type() == 'D') {
rows.add(S3CopySimulator.parseDataRow(response.body()));
} else if (response.type() == 'C' || response.type() == 'I') {
close(name);
return rows;
}
}
}
long copy(String sql, CopyStream stream) throws IOException {
String name = start(sql);
while (read().type() != 'G') {
// ParseComplete and BindComplete precede CopyInResponse.
}
try {
stream.write(backend.getOutputStream());
} catch (IOException | RuntimeException exception) {
write('f', PostgresWire.cStringBytes("S3 COPY input failed"));
backend.getOutputStream().flush();
try {
while (read().type() != 'E') {
// CopyFail must be consumed before recovery can issue an internal Sync.
}
} catch (S3TransferException expected) {
exception.addSuppressed(expected);
}
throw exception;
}
write('c', new byte[0]);
flush();
while (true) {
PostgresWireDecoder.FrontendMessage response = read();
if (response.type() == 'C') {
String tag = new String(response.body(), StandardCharsets.UTF_8).replace("\0", "");
close(name);
return Long.parseLong(tag.substring(tag.lastIndexOf(' ') + 1));
}
}
}
private String start(String sql) throws IOException {
String name = prefix + "_" + sequence++;
activeStatement = name;
parsed = false;
write('P', PostgresWire.cStringBytes(name), PostgresWire.cStringBytes(sql), new byte[2]);
write('B', PostgresWire.cStringBytes(name), PostgresWire.cStringBytes(name), new byte[6]);
write('E', PostgresWire.cStringBytes(name), new byte[4]);
flush();
return name;
}
private void close(String name) throws IOException {
write('C', new byte[]{'P'}, PostgresWire.cStringBytes(name));
write('C', new byte[]{'S'}, PostgresWire.cStringBytes(name));
flush();
for (int closed = 0; closed < 2;) {
if (read().type() == '3') {
closed++;
}
}
activeStatement = null;
parsed = false;
}
private PostgresWireDecoder.FrontendMessage read() throws IOException {
PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream());
while (true) {
PostgresWireDecoder.FrontendMessage response = decoder.nextMessage();
if (response == null) {
throw new IOException("Backend closed during COPY execution");
}
if (response.type() == 'N' || response.type() == 'A' || response.type() == 'S') {
asynchronous.accept(response);
continue;
}
if (response.type() == 'E') {
failed = true;
Map<Character, String> fields = PostgresWire.parseFields(response.body(), 0);
throw new S3TransferException(fields.getOrDefault('C', "XX000"),
fields.getOrDefault('M', "COPY backend command failed"), null);
}
if (response.type() == '1') {
parsed = true;
}
return response;
}
}
private void flush() throws IOException {
write('H', new byte[0]);
backend.getOutputStream().flush();
}
private void write(char type, byte[]... parts) throws IOException {
PostgresWire.write(backend.getOutputStream(), type, parts);
}
@FunctionalInterface
interface CopyStream {
void write(OutputStream output) throws IOException;
}
@FunctionalInterface
interface FrameSink {
void accept(PostgresWireDecoder.FrontendMessage response) throws IOException;
}
}
@@ -0,0 +1,251 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PostgresWire;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.redshift.proxy.S3CopySimulator.ColumnInfo;
import io.github.hectorvent.floci.services.redshift.proxy.S3CopySimulator.CopyInput;
import io.github.hectorvent.floci.services.redshift.proxy.S3CopySimulator.S3TransferException;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.function.IntConsumer;
/** Executes COPY transformations and error tolerance on the caller's PostgreSQL 15 session. */
final class CopyEtlLoader {
private static final Set<String> RECORD_ERRORS = Set.of(
"22P02", "22003", "22007", "22008", "22001", "22021", "22P04", "23502");
private CopyEtlLoader() {
}
static boolean runSimple(Socket client, Socket socket, CopyStatementParser.S3CopyFrom spec,
S3Service s3, IamService iam, String account, List<String> roles,
char status, IntConsumer onStatusChange) throws IOException {
CopyBackendSession backend = new CopyBackendSession(socket, response -> {
client.getOutputStream().write(response.toPacketBytes());
client.getOutputStream().flush();
});
long accepted = 0;
S3TransferException failure = null;
try {
accepted = execute(backend, spec, s3, iam, account, roles, status != 'I');
} catch (S3TransferException exception) {
failure = exception;
} catch (AwsException exception) {
failure = new S3TransferException("42501", "S3 COPY access denied", exception);
} catch (RuntimeException exception) {
failure = new S3TransferException("XX000", "S3 COPY failed", exception);
}
backend.recover();
try {
backend.finish(failure != null);
} catch (S3TransferException e) {
backend.recover();
if (failure == null) {
failure = e;
}
}
backend.synchronize();
if (failure == null) {
client.getOutputStream().write(PostgresWire.frame('C',
PostgresWire.cStringBytes("COPY " + accepted)));
} else {
client.getOutputStream().write(PostgresWire.frame('E',
S3CopySimulator.errorBody(failure.sqlState(), failure.getMessage())));
}
client.getOutputStream().write(PostgresWire.frame('Z', new byte[]{(byte) backend.readyStatus()}));
client.getOutputStream().flush();
if (onStatusChange != null) {
onStatusChange.accept(backend.readyStatus());
}
return true;
}
static long execute(CopyBackendSession backend, CopyStatementParser.S3CopyFrom spec,
S3Service s3, IamService iam, String account, List<String> roles,
boolean callerTransaction) throws IOException {
backend.begin(callerTransaction);
String savepoint = "floci_load_" + UUID.randomUUID().toString().replace("-", "");
backend.execute("SAVEPOINT " + savepoint);
try {
long rows = load(backend, spec, s3, iam, account, roles);
backend.execute("RELEASE SAVEPOINT " + savepoint);
return rows;
} catch (IOException | RuntimeException exception) {
try {
backend.recover();
backend.execute("ROLLBACK TO SAVEPOINT " + savepoint);
backend.execute("RELEASE SAVEPOINT " + savepoint);
backend.failTransaction();
} catch (IOException | RuntimeException recoveryFailure) {
IOException failure = new IOException("Unable to recover failed COPY", recoveryFailure);
failure.addSuppressed(exception);
throw failure;
}
throw exception;
}
}
private static long load(CopyBackendSession backend, CopyStatementParser.S3CopyFrom spec,
S3Service s3, IamService iam, String account, List<String> roles) throws IOException {
List<ColumnInfo> catalog = columns(backend, spec);
List<String> discovered = spec.jsonAuto() && (spec.columns() == null || spec.columns().isEmpty())
? catalog.stream().map(ColumnInfo::name).toList() : null;
List<Integer> widths = spec.transforms().truncateColumns() ? S3CopySimulator.alignMaxBytes(spec, catalog) : null;
List<CopyRecordTransformer.ColumnKind> kinds = spec.transforms().needsColumnTypes()
? S3CopySimulator.alignKinds(spec, catalog) : null;
CopyInput input = S3CopySimulator.prepareCopy(spec, s3, iam, account, roles);
try {
if (!spec.transforms().toleratesErrors()) {
return backend.copy(S3CopySimulator.copyBackendSql(spec, discovered),
output -> S3CopySimulator.streamCopyInput(input, discovered, widths, kinds, output));
}
try {
return RequestScopes.callAsChecked(S3CopySimulator.keyAccount(spec, s3, iam),
() -> loadRecords(backend, input, discovered, widths, kinds));
} catch (IOException | RuntimeException exception) {
throw exception;
} catch (Exception exception) {
throw new IOException("Unable to read COPY input", exception);
}
} finally {
S3CopySimulator.releaseCopySession(input);
}
}
private static List<ColumnInfo> columns(CopyBackendSession backend, CopyStatementParser.S3CopyFrom spec)
throws IOException {
List<ColumnInfo> catalog = new ArrayList<>();
for (List<String> row : backend.query(S3CopySimulator.columnInfoQuery(spec))) {
catalog.add(S3CopySimulator.columnInfo(row));
}
if (catalog.isEmpty()) {
throw new S3TransferException("42P01", "COPY target has no loadable columns", null);
}
return catalog;
}
private static void acquireTransformHeap(int[] heldMib, int wantedMib) {
while (heldMib[0] < wantedMib) {
if (!S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.tryAcquire(1)) {
throw new S3TransferException("53400", "COPY memory budget exhausted; retry shortly", null);
}
heldMib[0]++;
}
}
private static long loadRecords(CopyBackendSession backend, CopyInput input, List<String> discovered,
List<Integer> widths, List<CopyRecordTransformer.ColumnKind> kinds)
throws IOException {
CopyStatementParser.S3CopyFrom spec = input.spec();
List<String> jsonColumns = S3CopySimulator.jsonColumns(spec, discovered);
String sql = S3CopySimulator.copyBackendSql(spec, discovered);
String rowSavepoint = "floci_row_" + UUID.randomUUID().toString().replace("-", "");
long accepted = 0;
int rejected = 0;
for (String key : input.keys()) {
S3CopySimulator.authorizeCopyObject(spec, input.s3(), input.iamService(), input.roleSession(), key);
S3Object object = input.s3().getObject(spec.bucket(), key);
byte[] data = object != null && object.getData() != null ? object.getData() : new byte[0];
try (InputStream raw = new ByteArrayInputStream(data);
InputStream source = CopySourceInputStream.open(raw, spec.gzip())) {
S3CopySimulator.skipLines(source, spec.headerLines());
CopyRecordReader records = new CopyRecordReader(source, spec);
int[] heldMib = new int[]{0};
try {
byte[] record;
while ((record = records.next(wantedMib -> acquireTransformHeap(heldMib, wantedMib))) != null) {
backend.execute("SAVEPOINT " + rowSavepoint);
try {
acquireTransformHeap(heldMib, (int) ((record.length * 2L) / (1024 * 1024)) + 1);
byte[] transformed = transform(spec, record, jsonColumns, widths, kinds, heldMib);
accepted += backend.copy(sql, output -> {
for (int offset = 0; offset < transformed.length; offset += 8192) {
int length = Math.min(8192, transformed.length - offset);
byte[] chunk = new byte[length];
System.arraycopy(transformed, offset, chunk, 0, length);
S3CopySimulator.writeCopyData(output, chunk, length);
}
});
} catch (S3TransferException exception) {
backend.recover();
backend.execute("ROLLBACK TO SAVEPOINT " + rowSavepoint);
if (!RECORD_ERRORS.contains(exception.sqlState()) || ++rejected >= spec.transforms().maxError()) {
throw exception;
}
} finally {
if (heldMib[0] > 0) {
S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.release(heldMib[0]);
heldMib[0] = 0;
}
}
backend.execute("RELEASE SAVEPOINT " + rowSavepoint);
}
} finally {
if (heldMib[0] > 0) {
S3CopySimulator.COPY_TRANSFORM_HEAP_MIB.release(heldMib[0]);
heldMib[0] = 0;
}
}
}
}
return accepted;
}
private static byte[] transform(CopyStatementParser.S3CopyFrom spec, byte[] record, List<String> jsonColumns,
List<Integer> widths, List<CopyRecordTransformer.ColumnKind> kinds,
int[] heldMib) throws IOException {
if (spec.jsonAuto()) {
ByteArrayOutputStream csv = new ByteArrayOutputStream();
OutputStream bounded = new OutputStream() {
private long count = 0;
@Override
public void write(int b) throws IOException {
count++;
check();
csv.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
count += len;
check();
csv.write(b, off, len);
}
private void check() {
if (count > S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES) {
throw new S3TransferException("54000", "COPY transformed record exceeds the size limit", null);
}
if (heldMib != null) {
acquireTransformHeap(heldMib, (int) ((record.length + 2L * count) / (1024 * 1024)) + 1);
}
}
};
JsonLinesToCsvConverter.convert(new ByteArrayInputStream(record), jsonColumns, bounded, spec.jsonAutoIgnoreCase());
return csv.toByteArray();
}
return new CopyRecordTransformer(spec, widths, kinds).apply(record, bytes -> {
if (bytes > S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES) {
throw new S3TransferException("54000", "COPY transformed record exceeds the size limit", null);
}
if (heldMib != null) {
acquireTransformHeap(heldMib, (int) ((record.length + 2L * bytes) / (1024 * 1024)) + 1);
}
});
}
}
@@ -0,0 +1,103 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.nio.charset.StandardCharsets;
import java.util.function.IntConsumer;
/** Reads one logical COPY record, retaining CSV newlines inside quoted fields. */
final class CopyRecordReader {
private final PushbackInputStream input;
private final boolean csv;
private final boolean removeQuotes;
private final boolean json;
private final int delimiter;
CopyRecordReader(InputStream input, CopyStatementParser.S3CopyFrom spec) {
this.input = new PushbackInputStream(input, 1);
csv = spec.csv();
json = spec.jsonAuto();
removeQuotes = spec.transforms().removeQuotes();
String separator = spec.delimiter() != null ? spec.delimiter() : (csv ? "," : "|");
delimiter = separator.getBytes(StandardCharsets.UTF_8)[0] & 0xff;
}
byte[] next() throws IOException {
return next(null);
}
byte[] next(IntConsumer memoryTracker) throws IOException {
ByteArrayOutputStream record = new ByteArrayOutputStream();
int quote = 0;
boolean fieldStart = true;
int value;
while ((value = input.read()) != -1) {
append(record, value, memoryTracker);
if (json) {
if (value == '\n') {
return record.toByteArray();
}
continue;
}
if (!csv && value == '\\') {
int escaped = input.read();
if (escaped != -1) {
append(record, escaped, memoryTracker);
}
fieldStart = false;
continue;
}
if (quote != 0) {
if (value == quote) {
int following = input.read();
if (csv && following == quote) {
append(record, following, memoryTracker);
} else {
if (csv || following == -1 || following == delimiter || following == '\n' || following == '\r') {
quote = 0;
}
if (following != -1) {
input.unread(following);
}
}
}
} else if ((csv && value == '"')
|| (fieldStart && removeQuotes && (value == '"' || value == '\''))) {
quote = value;
fieldStart = false;
} else if (value == '\n' || value == '\r') {
if (value == '\r') {
int following = input.read();
if (following == '\n') {
append(record, following, memoryTracker);
} else if (following != -1) {
input.unread(following);
}
}
return record.toByteArray();
} else {
fieldStart = value == delimiter;
}
}
if (quote != 0) {
throw new S3CopySimulator.S3TransferException("22P04", "COPY quoted field has no closing quote", null);
}
if (record.size() == 0) {
return null;
}
append(record, '\n', memoryTracker);
return record.toByteArray();
}
private static void append(ByteArrayOutputStream record, int value, IntConsumer memoryTracker) {
if (record.size() >= S3CopySimulator.COPY_TRANSFORM_MAX_OBJECT_BYTES) {
throw new S3CopySimulator.S3TransferException("54000", "COPY record exceeds the transform size limit", null);
}
if (memoryTracker != null && (record.size() % (1024 * 1024) == 0)) {
memoryTracker.accept((record.size() / (1024 * 1024)) + 1);
}
record.write(value);
}
}
@@ -13,7 +13,7 @@ import java.util.function.IntConsumer;
*/
final class CopyRecordTransformer {
private static final String SQLSTATE_INTERNAL = "XX000";
private static final String SQLSTATE_INVALID_COPY = "22P04";
private static final byte NEWLINE = '\n';
private static final byte CARRIAGE_RETURN = '\r';
private static final byte BACKSLASH = '\\';
@@ -291,8 +291,7 @@ final class CopyRecordTransformer {
/**
* Rewrites a DATE or TIMESTAMP field from the DATEFORMAT or TIMEFORMAT to the ISO text PostgreSQL reads.
* Returns the field as it is when no format applies to its column, and null when ACCEPTANYDATE turns a
* value that does not match into NULL; without it such a value fails the COPY, whatever MAXERROR says,
* because it never reaches the backend that skips records under MAXERROR.
* value that does not match into NULL; otherwise it is a record error counted by MAXERROR.
*/
private byte[] convertTemporal(byte[] value, int column) {
if (!transforms.temporal() || columnKinds == null || column >= columnKinds.size()) {
@@ -315,8 +314,9 @@ final class CopyRecordTransformer {
if (transforms.acceptAnyDate()) {
return null;
}
throw malformed("invalid " + (kind == ColumnKind.DATE ? "date" : "timestamp") + " in column "
+ (column + 1) + ": " + e.getMessage());
throw new S3CopySimulator.S3TransferException("22007",
"COPY invalid " + (kind == ColumnKind.DATE ? "date" : "timestamp") + " in column "
+ (column + 1) + ": " + e.getMessage(), e);
}
}
@@ -463,6 +463,6 @@ final class CopyRecordTransformer {
}
private static S3CopySimulator.S3TransferException malformed(String detail) {
return new S3CopySimulator.S3TransferException(SQLSTATE_INTERNAL, "COPY failed: " + detail, null);
return new S3CopySimulator.S3TransferException(SQLSTATE_INVALID_COPY, "COPY failed: " + detail, null);
}
}
@@ -0,0 +1,52 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
/** S3 decoding errors are COPY errors; backend transport errors must remain IOExceptions. */
final class CopySourceInputStream extends FilterInputStream {
private CopySourceInputStream(InputStream input) {
super(input);
}
static InputStream open(InputStream input, boolean gzip) {
try {
return new CopySourceInputStream(gzip ? new GZIPInputStream(input) : input);
} catch (IOException exception) {
throw failure(exception);
}
}
@Override
public int read() {
try {
return in.read();
} catch (IOException exception) {
throw failure(exception);
}
}
@Override
public int read(byte[] buffer, int offset, int length) {
try {
return in.read(buffer, offset, length);
} catch (IOException exception) {
throw failure(exception);
}
}
@Override
public void close() {
try {
in.close();
} catch (IOException exception) {
throw failure(exception);
}
}
private static S3CopySimulator.S3TransferException failure(IOException exception) {
return new S3CopySimulator.S3TransferException("58030", "Unable to read or decompress S3 COPY data", exception);
}
}
@@ -1,33 +1,35 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.s3.S3Service;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;
final class ExtendedS3Exchange {
private record CopyResult(boolean succeeded, byte[] deferredReadyForQuery) {
}
private ExtendedS3Exchange() {
}
static void execute(Socket client, Socket backend,
PostgresWireDecoder.FrontendMessage executeFrame,
CopyStatementParser.S3Statement statement, S3Service s3Service, IamService iamService,
BackendResponseCoordinator coordinator, BackendResponseCoordinator.Ticket ticket) throws IOException {
execute(client, backend, executeFrame, statement, s3Service, iamService, null, List.of(), coordinator, ticket, null);
String clusterAccountId, List<String> iamRoleArns, BackendResponseCoordinator coordinator,
BackendResponseCoordinator.Ticket ticket, CopyBackendSession copyBackend) throws IOException {
execute(client, backend, executeFrame, statement, s3Service, iamService, clusterAccountId, iamRoleArns,
coordinator, ticket, copyBackend, null);
}
static void execute(Socket client, Socket backend,
PostgresWireDecoder.FrontendMessage executeFrame,
CopyStatementParser.S3Statement statement, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns, BackendResponseCoordinator coordinator,
BackendResponseCoordinator.Ticket ticket, RedshiftParquetWriter parquetWriter) throws IOException {
BackendResponseCoordinator.Ticket ticket, CopyBackendSession copyBackend,
RedshiftParquetWriter parquetWriter) throws IOException {
BackendResponseCoordinator.GateResult gate;
try {
gate = coordinator.awaitExtendedExecuteTurn(ticket);
@@ -40,22 +42,13 @@ final class ExtendedS3Exchange {
}
boolean failed = true;
byte[] deferredReadyForQuery = null;
try {
switch (statement) {
case CopyStatementParser.S3CopyFrom copy -> {
CopyResult result = runCopy(client, backend, executeFrame, copy, s3Service, iamService,
clusterAccountId, iamRoleArns, coordinator);
failed = !result.succeeded();
deferredReadyForQuery = result.deferredReadyForQuery();
}
case CopyStatementParser.S3Unload unload -> {
CopyResult result = runUnload(client, backend, executeFrame, unload, s3Service, iamService,
clusterAccountId, iamRoleArns, coordinator, ticket, parquetWriter);
failed = !result.succeeded();
deferredReadyForQuery = result.deferredReadyForQuery();
}
}
failed = !switch (statement) {
case CopyStatementParser.S3CopyFrom copy -> runEtlCopy(client, backend, executeFrame, copy,
s3Service, iamService, clusterAccountId, iamRoleArns, coordinator, copyBackend);
case CopyStatementParser.S3Unload unload -> runOwnedUnload(client, backend, executeFrame, unload,
s3Service, iamService, clusterAccountId, iamRoleArns, coordinator, ticket, copyBackend, parquetWriter);
};
} catch (IOException | RuntimeException e) {
closeQuietly(client);
closeQuietly(backend);
@@ -63,72 +56,18 @@ final class ExtendedS3Exchange {
} finally {
coordinator.completeOwnedExecute(ticket, failed);
}
if (deferredReadyForQuery != null) {
coordinator.onBackendFrame('Z', deferredReadyForQuery);
}
}
private static CopyResult runCopy(Socket client, Socket backend,
PostgresWireDecoder.FrontendMessage executeFrame,
CopyStatementParser.S3CopyFrom spec, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns, BackendResponseCoordinator coordinator) throws IOException {
OutputStream backendOut = backend.getOutputStream();
backendOut.write(executeFrame.toPacketBytes());
backendOut.flush();
PostgresWireDecoder.FrontendMessage sync = readClientSync(client, backendOut);
PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream());
PostgresWireDecoder.FrontendMessage first = nextOwnedFrame(client, decoder, coordinator);
if (first.type() == 'E') {
forward(client, first);
forwardClientSyncToBackend(sync, backendOut, coordinator);
return new CopyResult(false, null);
}
if (first.type() != 'G') {
throw unexpected(first, "CopyInResponse");
}
S3CopySimulator.CopyInput input;
try {
input = S3CopySimulator.prepareCopy(spec, s3Service, iamService, clusterAccountId, iamRoleArns);
} catch (S3CopySimulator.S3TransferException e) {
S3CopySimulator.writeCopyFail(backendOut, e.getMessage());
forwardClientSyncToBackend(sync, backendOut, coordinator);
drainExecute(client, decoder, coordinator, false);
sendError(client, e.sqlState(), e.getMessage());
return new CopyResult(false, drainReadyForQuery(client, decoder, coordinator));
}
try {
S3CopySimulator.streamCopyInput(input, backendOut);
backendOut.write(new byte[]{'c', 0, 0, 0, 4});
backendOut.flush();
} catch (RuntimeException | IOException e) {
S3CopySimulator.writeCopyFail(backendOut, e.getMessage());
forwardClientSyncToBackend(sync, backendOut, coordinator);
drainExecute(client, decoder, coordinator, false);
String detail = e.getMessage() != null ? e.getMessage() : e.toString();
sendError(client, "XX000", "S3 COPY failed: " + detail);
return new CopyResult(false, drainReadyForQuery(client, decoder, coordinator));
} finally {
S3CopySimulator.releaseCopySession(input);
}
forwardClientSyncToBackend(sync, backendOut, coordinator);
PostgresWireDecoder.FrontendMessage terminal = drainExecute(client, decoder, coordinator, true);
return new CopyResult(terminal.type() != 'E', null);
}
private static CopyResult runUnload(Socket client, Socket backend,
PostgresWireDecoder.FrontendMessage executeFrame,
CopyStatementParser.S3Unload spec, S3Service s3Service, IamService iamService,
String clusterAccountId, List<String> iamRoleArns, BackendResponseCoordinator coordinator,
BackendResponseCoordinator.Ticket ticket, RedshiftParquetWriter parquetWriter) throws IOException {
OutputStream backendOut = backend.getOutputStream();
private static boolean runOwnedUnload(Socket client, Socket backend,
PostgresWireDecoder.FrontendMessage executeFrame, CopyStatementParser.S3Unload spec,
S3Service s3, IamService iam, String account, List<String> roles,
BackendResponseCoordinator coordinator, BackendResponseCoordinator.Ticket ticket,
CopyBackendSession copyBackend, RedshiftParquetWriter parquetWriter) throws IOException {
OutputStream output = backend.getOutputStream();
List<RedshiftParquetWriter.Column> columns = List.of();
if (spec.parquet()) {
backendOut.write(new byte[]{'H', 0, 0, 0, 4});
backendOut.flush();
output.write(new byte[]{'H', 0, 0, 0, 4});
output.flush();
PostgresWireDecoder preamble = new PostgresWireDecoder(backend.getInputStream());
while (!coordinator.isFirstPending(ticket)) {
PostgresWireDecoder.FrontendMessage message = preamble.nextMessage();
@@ -138,106 +77,115 @@ final class ExtendedS3Exchange {
coordinator.onBackendFrame(message.type(), message.body());
forward(client, message);
if (message.type() == 'E') {
forwardClientSyncToBackend(client, backendOut, coordinator);
return new CopyResult(false, drainReadyForQuery(client, preamble, coordinator));
copyBackend.onBackendError();
return false;
}
}
RedshiftParquetWriter.Description description = RedshiftParquetWriter.describe(client, backend, spec.selectQuery());
if (description.error() != null) {
copyBackend.onBackendError();
forward(client, description.error());
forwardClientSyncToBackend(client, backendOut, coordinator);
return new CopyResult(false, drainReadyForQuery(client,
new PostgresWireDecoder(backend.getInputStream()), coordinator));
return false;
}
columns = description.columns();
}
backendOut.write(executeFrame.toPacketBytes());
backendOut.flush();
forwardClientSyncToBackend(client, backendOut, coordinator);
output.write(executeFrame.toPacketBytes());
output.write(new byte[]{'H', 0, 0, 0, 4});
output.flush();
PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream());
PostgresWireDecoder.FrontendMessage first = nextOwnedFrame(client, decoder, coordinator);
if (first.type() == 'E') {
copyBackend.onBackendError();
forward(client, first);
return new CopyResult(false, drainReadyForQuery(client, decoder, coordinator));
return false;
}
if (first.type() != 'H') {
throw unexpected(first, "CopyOutResponse");
}
S3CopySimulator.UnloadCollector collector;
S3CopySimulator.UnloadCollector collector = null;
S3CopySimulator.S3TransferException failure = null;
try {
collector = S3CopySimulator.prepareUnload(spec, s3Service, iamService, clusterAccountId, iamRoleArns, parquetWriter);
collector.columns(columns);
} catch (S3CopySimulator.S3TransferException e) {
S3CopySimulator.writeCopyFail(backendOut, e.getMessage());
drainExecute(client, decoder, coordinator, false);
sendError(client, e.sqlState(), e.getMessage());
return new CopyResult(false, drainReadyForQuery(client, decoder, coordinator));
}
try (collector) {
try {
collector = S3CopySimulator.prepareUnload(spec, s3, iam, account, roles, parquetWriter);
collector.columns(columns);
} catch (S3CopySimulator.S3TransferException exception) {
failure = exception;
}
while (true) {
PostgresWireDecoder.FrontendMessage message = nextOwnedFrame(client, decoder, coordinator);
if (message.type() == 'd') {
PostgresWireDecoder.FrontendMessage response = nextOwnedFrame(client, decoder, coordinator);
if (response.type() == 'd' && failure == null && collector != null) {
try {
collector.accept(message.body());
} catch (S3CopySimulator.S3TransferException e) {
collector.accept(response.body());
} catch (S3CopySimulator.S3TransferException exception) {
failure = exception;
collector.abort();
S3CopySimulator.writeCopyFail(backendOut, e.getMessage());
drainExecute(client, decoder, coordinator, false);
sendError(client, e.sqlState(), e.getMessage());
return new CopyResult(false, drainReadyForQuery(client, decoder, coordinator));
}
} else if (message.type() == 'c') {
continue;
} else if (message.type() == 'E') {
} else if (response.type() == 'E') {
copyBackend.onBackendError();
forward(client, response);
return false;
} else if (response.type() == 'C') {
if (failure == null && collector != null) {
try {
collector.complete();
} catch (S3CopySimulator.S3TransferException exception) {
failure = exception;
}
}
if (failure == null) {
forward(client, response);
return true;
}
copyBackend.begin(coordinator.lastReadyStatus() != 'I');
copyBackend.failTransaction();
sendError(client, failure.sqlState(), failure.getMessage());
return false;
}
}
} finally {
if (collector != null) {
if (failure != null) {
collector.abort();
forward(client, message);
return new CopyResult(false, drainReadyForQuery(client, decoder, coordinator));
} else if (message.type() == 'C') {
try {
collector.complete();
} catch (S3CopySimulator.S3TransferException e) {
S3CopySimulator.writeCopyFail(backendOut, e.getMessage());
sendError(client, e.sqlState(), e.getMessage());
return new CopyResult(false, drainReadyForQuery(client, decoder, coordinator));
}
forward(client, message);
return new CopyResult(true, null);
} else {
throw unexpected(message, "CopyData, CopyDone, or CommandComplete");
}
collector.close();
}
}
}
private static PostgresWireDecoder.FrontendMessage drainExecute(Socket client,
PostgresWireDecoder decoder, BackendResponseCoordinator coordinator,
boolean forwardTerminal) throws IOException {
while (true) {
PostgresWireDecoder.FrontendMessage message = nextOwnedFrame(client, decoder, coordinator);
char type = message.type();
if (type == 'C' || type == 'E' || type == 'I' || type == 's') {
if (forwardTerminal) {
forward(client, message);
}
return message;
}
if (type != 'd' && type != 'c') {
throw unexpected(message, "CopyData, CopyDone, or an Execute terminal response");
}
private static boolean runEtlCopy(Socket client, Socket backend,
PostgresWireDecoder.FrontendMessage executeFrame, CopyStatementParser.S3CopyFrom spec,
S3Service s3, IamService iam, String account, List<String> roles,
BackendResponseCoordinator coordinator, CopyBackendSession copyBackend) throws IOException {
OutputStream output = backend.getOutputStream();
output.write(executeFrame.toPacketBytes());
output.write(new byte[]{'H', 0, 0, 0, 4});
output.flush();
PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream());
PostgresWireDecoder.FrontendMessage response = nextOwnedFrame(client, decoder, coordinator);
if (response.type() == 'E') {
copyBackend.onBackendError();
forward(client, response);
return false;
}
}
private static byte[] drainReadyForQuery(Socket client, PostgresWireDecoder decoder,
BackendResponseCoordinator coordinator) throws IOException {
PostgresWireDecoder.FrontendMessage message = nextOwnedFrame(client, decoder, coordinator);
if (message.type() != 'Z') {
throw unexpected(message, "ReadyForQuery");
if (response.type() != 'C') {
throw unexpected(response, "COPY execution placeholder completion");
}
try {
long count = CopyEtlLoader.execute(copyBackend, spec, s3, iam, account, roles,
coordinator.lastReadyStatus() != 'I');
forward(client, new PostgresWireDecoder.FrontendMessage('C',
("COPY " + count + "\0").getBytes(StandardCharsets.UTF_8)));
return true;
} catch (S3CopySimulator.S3TransferException exception) {
sendError(client, exception.sqlState(), exception.getMessage());
return false;
} catch (AwsException exception) {
sendError(client, "42501", "S3 COPY access denied");
return false;
} catch (RuntimeException exception) {
sendError(client, "XX000", "S3 COPY execution failed");
return false;
}
forward(client, message);
return message.body();
}
private static PostgresWireDecoder.FrontendMessage nextOwnedFrame(Socket client,
@@ -262,37 +210,6 @@ final class ExtendedS3Exchange {
}
}
private static PostgresWireDecoder.FrontendMessage readClientSync(Socket client, OutputStream backendOut)
throws IOException {
PostgresWireDecoder decoder = new PostgresWireDecoder(client.getInputStream());
while (true) {
PostgresWireDecoder.FrontendMessage message = decoder.nextMessage();
if (message == null) {
throw new IOException("Client closed during an Extended Query S3 exchange");
}
if (message.type() == 'S') {
return message;
}
if (message.type() != 'H') {
throw new IOException("Expected Flush or Sync after an Extended Query S3 Execute");
}
backendOut.write(message.toPacketBytes());
backendOut.flush();
}
}
private static void forwardClientSyncToBackend(Socket client, OutputStream backendOut,
BackendResponseCoordinator coordinator) throws IOException {
forwardClientSyncToBackend(readClientSync(client, backendOut), backendOut, coordinator);
}
private static void forwardClientSyncToBackend(PostgresWireDecoder.FrontendMessage sync, OutputStream backendOut,
BackendResponseCoordinator coordinator) throws IOException {
coordinator.register(BackendResponseCoordinator.Operation.SYNC, null);
backendOut.write(sync.toPacketBytes());
backendOut.flush();
}
private static IOException unexpected(PostgresWireDecoder.FrontendMessage message, String expected) {
return new IOException("Expected " + expected + " but backend sent " + message.type());
}
@@ -15,7 +15,7 @@ import java.util.Map;
final class JsonLinesToCsvConverter {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String SQLSTATE_INTERNAL = "XX000";
private static final String SQLSTATE_INTERNAL = "22P04";
private JsonLinesToCsvConverter() {
}
@@ -267,18 +267,21 @@ public class RedshiftAuthProxy {
session = PostgresProtocolHandler.authenticate(
client, connector, masterUsername, masterPassword, dbName,
false, sigV4, null, tlsCertificates, passwordValidator,
handshakeTimeoutMillis, false, true, (user, database) -> {
handshakeTimeoutMillis, false, true, (user, database, params) -> {
login.username = user;
login.database = database;
login.dataApi = RedshiftInternalAuth.consumeDataApiToken(params.get("application_name"));
});
if (session != null) {
publishConnection(client, login, "authenticated");
// Redshift-only DDL (DISTKEY/SORTKEY/ENCODE/...) is rewritten for the plain
// PostgreSQL backend on the way through; every other message is relayed verbatim.
RoleConfiguration roles = roleConfiguration;
RedshiftAuditLogPublisher bridgeAudit = login.dataApi ? null : auditLogPublisher;
SpectrumInterceptor bridgeSpectrum = login.dataApi ? null : spectrumInterceptor;
new RedshiftInterceptingBridge(session.client(), session.backend(), s3Service, iamService,
clusterAccountId, roles.iamRoleArns(), spectrumInterceptor, clusterKey, login.database,
roles.defaultIamRoleArn(), auditLogPublisher, login.username, parquetWriter).run();
clusterAccountId, roles.iamRoleArns(), bridgeSpectrum, clusterKey, login.database,
roles.defaultIamRoleArn(), bridgeAudit, login.username, parquetWriter).run();
publishConnection(client, login, "disconnection");
} else {
publishConnection(client, login, login.backendUnavailable ? "connection_error" : "authentication failure");
@@ -304,10 +307,11 @@ public class RedshiftAuthProxy {
private String username;
private String database;
private boolean backendUnavailable;
private boolean dataApi;
}
private void publishConnection(Socket client, LoginAttempt login, String event) {
if (auditLogPublisher == null || login.username == null) {
if (auditLogPublisher == null || login.username == null || login.dataApi) {
return;
}
String remoteAddress = client.getInetAddress() == null ? null : client.getInetAddress().getHostAddress();
@@ -1,10 +1,12 @@
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.redshift.RedshiftAuditLogPublisher;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.UserChange;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.UserChanges;
import io.github.hectorvent.floci.services.redshift.proxy.S3CopySimulator.S3TransferException;
import io.github.hectorvent.floci.services.redshift.spectrum.PostgresExtendedBackendSession;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumColumn;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor;
@@ -82,6 +84,7 @@ public class RedshiftInterceptingBridge {
private final Map<String, SpectrumInterceptor.Plan> spectrumPortals = new HashMap<>();
private final Map<String, ExtendedSpectrumExchange.PortalCursor> spectrumCursors = new HashMap<>();
private final BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session);
private final CopyBackendSession copyBackend;
private final ReentrantLock backendLock;
/** Budget of {@link #runWithBackendOwned} only; the Extended Query paths keep {@link #PUMP_PARK_WAIT_MS}. */
@@ -169,6 +172,8 @@ public class RedshiftInterceptingBridge {
this.auditLogPublisher = auditLogPublisher;
this.databaseUser = databaseUser;
this.relationalBackend = new PostgresExtendedBackendSession(backend);
this.copyBackend = new CopyBackendSession(backend,
response -> write(client.getOutputStream(), response.toPacketBytes()));
this.backendLock = backendLock;
this.ownershipWaitMillis = ownershipWaitMillis;
}
@@ -241,7 +246,11 @@ public class RedshiftInterceptingBridge {
case 'C' -> handleClose(decoder, msg, backendOut);
case 'S' -> {
extendedSpectrumError = false;
coordinator.register(BackendResponseCoordinator.Operation.SYNC, null);
BackendResponseCoordinator.Ticket sync = coordinator.register(
BackendResponseCoordinator.Operation.SYNC, null);
if (copyBackend.requiresCompletion()) {
finishCopyCycle(sync, backendOut);
}
write(backendOut, msg.toPacketBytes());
}
default -> write(backendOut, msg.toPacketBytes());
@@ -263,6 +272,10 @@ public class RedshiftInterceptingBridge {
private void handleSimpleQuery(PostgresWireDecoder.FrontendMessage message, OutputStream backendOut)
throws IOException {
if (copyBackend.requiresCompletion()) {
BackendResponseCoordinator.Ticket sync = coordinator.register(BackendResponseCoordinator.Operation.SYNC, null);
finishCopyCycle(sync, backendOut, true);
}
String sql = message.getSql();
publishActivity(sql);
if (spectrumInterceptor != null) {
@@ -381,7 +394,7 @@ public class RedshiftInterceptingBridge {
String rewritten = parse.sql();
if (statement instanceof CopyStatementParser.S3CopyFrom copy) {
rewritten = S3CopySimulator.copyBackendSql(copy);
rewritten = "DO $$BEGIN NULL; END$$";
} else if (statement instanceof CopyStatementParser.S3Unload unload) {
rewritten = S3CopySimulator.unloadBackendSql(unload);
} else {
@@ -657,6 +670,7 @@ public class RedshiftInterceptingBridge {
private void runExtendedWithBackendOwned(PostgresWireDecoder.FrontendMessage executeFrame,
CopyStatementParser.S3Statement statement, BackendResponseCoordinator.Ticket ticket) throws IOException {
write(backend.getOutputStream(), new byte[]{'H', 0, 0, 0, 4});
BackendResponseCoordinator.GateResult gate;
try {
gate = coordinator.awaitExtendedExecuteTurn(ticket);
@@ -697,7 +711,7 @@ public class RedshiftInterceptingBridge {
try {
backend.setSoTimeout(EXCHANGE_READ_TIMEOUT_MS);
ExtendedS3Exchange.execute(client, backend, executeFrame, statement, s3Service, iamService,
clusterAccountId, iamRoleArns, coordinator, ticket, parquetWriter);
clusterAccountId, iamRoleArns, coordinator, ticket, copyBackend, parquetWriter);
} finally {
try {
backend.setSoTimeout(PUMP_READ_TIMEOUT_MS);
@@ -708,6 +722,61 @@ public class RedshiftInterceptingBridge {
}
}
private void finishCopyCycle(BackendResponseCoordinator.Ticket sync, OutputStream output) throws IOException {
finishCopyCycle(sync, output, false);
}
private void finishCopyCycle(BackendResponseCoordinator.Ticket sync, OutputStream output, boolean consumeSync)
throws IOException {
write(output, new byte[]{'H', 0, 0, 0, 4});
try {
if (!coordinator.awaitSyncTurn(sync, EXCHANGE_READ_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
throw new IOException("Timed out awaiting prior COPY cycle responses");
}
long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(EXCHANGE_READ_TIMEOUT_MS);
while (true) {
long remaining = deadline - System.nanoTime();
if (remaining <= 0 || !backendLock.tryLock(remaining, TimeUnit.NANOSECONDS)) {
throw new IOException("Timed out awaiting COPY transaction completion");
}
if (pumpBetweenMessages) {
break;
}
backendLock.unlock();
LockSupport.parkNanos(BUSY_BACKOFF_NANOS);
}
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted awaiting COPY transaction completion", exception);
}
try {
backend.setSoTimeout(EXCHANGE_READ_TIMEOUT_MS);
boolean failed = coordinator.isDiscardingUntilSync();
try {
copyBackend.finish(failed);
} catch (S3TransferException e) {
copyBackend.recover();
coordinator.discardUntilSync();
write(client.getOutputStream(), PostgresWire.frame('E',
S3CopySimulator.errorBody(e.sqlState(), e.getMessage())));
}
if (consumeSync) {
copyBackend.synchronize();
byte[] status = new byte[]{(byte) copyBackend.readyStatus()};
coordinator.onBackendFrame('Z', status);
copyBackend.onClientReady((char) status[0]);
relationalBackend.onSync();
completeUserChanges(status);
}
} finally {
try {
backend.setSoTimeout(PUMP_READ_TIMEOUT_MS);
} finally {
backendLock.unlock();
}
}
}
private static void write(OutputStream out, byte[] packet) throws IOException {
out.write(packet);
out.flush();
@@ -902,10 +971,14 @@ public class RedshiftInterceptingBridge {
}
if (type == 'E') {
auditCycleFailed = true;
copyBackend.onBackendError();
}
coordinator.onBackendFrame(type, body);
if (type == 'Z') {
relationalBackend.onSync();
if (body.length > 0) {
copyBackend.onClientReady((char) body[0]);
}
completeUserChanges(body);
}
});
@@ -925,10 +998,11 @@ public class RedshiftInterceptingBridge {
if (read == -1) {
break;
}
clientOut.write(buffer, 0, read);
clientOut.flush();
// The client can send its next Parse as soon as ReadyForQuery reaches it.
tracker.consume(buffer, 0, read);
pumpBetweenMessages = tracker.betweenMessages();
clientOut.write(buffer, 0, read);
clientOut.flush();
} finally {
backendLock.unlock();
}
@@ -939,6 +1013,7 @@ public class RedshiftInterceptingBridge {
Thread.currentThread().interrupt();
} finally {
pumpFinished = true;
coordinator.close();
closeQuietly(client, "client");
closeQuietly(backend, "backend");
}
@@ -955,7 +1030,7 @@ public class RedshiftInterceptingBridge {
private BiConsumer<Character, byte[]> auditResponses(String sql) {
ArrayDeque<String> commands = new ArrayDeque<>(RedshiftAuditSql.statements(sql));
return (type, body) -> {
if (type != 'C' || auditLogPublisher == null) {
if (type != 'C') {
return;
}
String command = commands.pollFirst();
@@ -963,8 +1038,14 @@ public class RedshiftInterceptingBridge {
return;
}
String tag = new String(body, StandardCharsets.UTF_8).replace("\0", "");
auditUserChanges.complete(command, tag);
publishCompletedUserChanges();
copyBackend.onClientCommand(command, tag);
if (tag.equals("ROLLBACK") && RedshiftAuditSql.savepoint(command) == null) {
coordinator.transactionEnded();
}
if (auditLogPublisher != null) {
auditUserChanges.complete(command, tag);
publishCompletedUserChanges();
}
};
}
@@ -0,0 +1,48 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Registry for short-lived, single-use authentication tokens used to identify internal
* connections originating from trusted Floci services (such as Redshift Data API) through the proxy.
*/
public final class RedshiftInternalAuth {
private static final String DATA_API_PREFIX = "floci-redshift-data:";
private static final long TICKET_EXPIRY_MILLIS = 30_000L;
private static final Map<String, Long> ACTIVE_TICKETS = new ConcurrentHashMap<>();
private RedshiftInternalAuth() {
}
/**
* Issues a single-use token identifying an internal Data API connection.
* The returned value is formatted as the PostgreSQL {@code application_name}.
*/
public static String issueDataApiToken() {
cleanExpiredTickets();
String ticket = UUID.randomUUID().toString();
ACTIVE_TICKETS.put(ticket, System.currentTimeMillis() + TICKET_EXPIRY_MILLIS);
return DATA_API_PREFIX + ticket;
}
/**
* Validates and consumes a single-use token from the connection's startup parameters.
* Returns {@code true} only if the token matches a valid registered ticket that has not expired.
*/
public static boolean consumeDataApiToken(String applicationName) {
if (applicationName == null || !applicationName.startsWith(DATA_API_PREFIX)) {
return false;
}
String ticket = applicationName.substring(DATA_API_PREFIX.length());
Long expiry = ACTIVE_TICKETS.remove(ticket);
return expiry != null && expiry >= System.currentTimeMillis();
}
private static void cleanExpiredTickets() {
long now = System.currentTimeMillis();
ACTIVE_TICKETS.entrySet().removeIf(entry -> entry.getValue() < now);
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PostgresWire;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.s3.S3Service;
@@ -26,7 +27,6 @@ import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
@@ -133,13 +133,7 @@ public final class S3CopySimulator {
try {
try {
if (spec.manifest()) {
if (roleSession != null) {
RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(),
"s3:GetObject", copyObjectArn(spec, s3, spec.keyOrPrefix()));
s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), spec.keyOrPrefix());
} else {
s3.authorizeAnonymousGetObject(spec.bucket(), spec.keyOrPrefix());
}
authorizeCopyObject(spec, s3, iamService, roleSession, spec.keyOrPrefix());
} else {
if (roleSession != null) {
RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(),
@@ -169,13 +163,7 @@ public final class S3CopySimulator {
try {
for (String key : keys) {
if (roleSession != null) {
RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(),
"s3:GetObject", copyObjectArn(spec, s3, key));
s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key);
} else {
s3.authorizeAnonymousGetObject(spec.bucket(), key);
}
authorizeCopyObject(spec, s3, iamService, roleSession, key);
}
} catch (AwsException e) {
throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
@@ -230,7 +218,7 @@ public final class S3CopySimulator {
}
/** Null when no key is in play, which {@link RequestScopes} reads as "stay in the current account". */
private static String keyAccount(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService) {
static String keyAccount(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService) {
if (spec.iamRoleArn() != null || spec.accessKeys() == null || !s3.isAuthEnforced()) {
return null;
}
@@ -392,6 +380,10 @@ public final class S3CopySimulator {
CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
String clusterAccountId, List<String> associatedRoleArns,
char txStatus, IntConsumer onStatusChange) throws IOException {
if (spec.transforms().toleratesErrors()) {
return CopyEtlLoader.runSimple(client, backend, spec, s3, iamService, clusterAccountId,
associatedRoleArns, txStatus, onStatusChange);
}
CopyInput input;
try {
input = prepareCopy(spec, s3, iamService, clusterAccountId, associatedRoleArns);
@@ -532,21 +524,35 @@ public final class S3CopySimulator {
if (spec.nullAs() != null) {
sql.append(", NULL '").append(quoteLiteral(spec.nullAs())).append("'");
}
if (spec.transforms().toleratesErrors()) {
// MAXERROR fails the load at the error_count-th error; REJECT_LIMIT tolerates that many errors, not
// more. Both options need a PostgreSQL 18 backend, which an older one rejects as an unknown option.
sql.append(", ON_ERROR ignore, REJECT_LIMIT ").append(spec.transforms().maxError() - 1);
}
sql.append(")");
return sql.toString();
}
private static String unquoteIdentifier(String identifier) {
static List<String> jsonColumns(CopyStatementParser.S3CopyFrom spec, List<String> discoveredColumns) {
if (discoveredColumns != null && !discoveredColumns.isEmpty()) {
return discoveredColumns;
}
return spec.columns() == null ? List.of()
: spec.columns().stream().map(S3CopySimulator::normalizeColumnName).toList();
}
private static String normalizeColumnName(String identifier) {
if (identifier != null && identifier.length() >= 2
&& identifier.startsWith("\"") && identifier.endsWith("\"")) {
return identifier.substring(1, identifier.length() - 1).replace("\"\"", "\"");
}
return identifier;
return identifier == null ? null : identifier.toLowerCase(Locale.ROOT);
}
static void authorizeCopyObject(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
RedshiftRoleAccess.RoleSession roleSession, String key) {
if (roleSession != null) {
RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(),
"s3:GetObject", copyObjectArn(spec, s3, key));
s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key);
} else {
s3.authorizeAnonymousGetObject(spec.bucket(), key);
}
}
/**
@@ -576,23 +582,13 @@ public final class S3CopySimulator {
}
byte[] buffer = new byte[CHUNK];
for (int i = 0; i < keys.size(); i++) {
if (roleSession != null) {
RedshiftRoleAccess.authorizeSessionAction(s3, iamService, roleSession, spec.iamRoleArn(),
"s3:GetObject", copyObjectArn(spec, s3, keys.get(i)));
s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), keys.get(i));
} else {
s3.authorizeAnonymousGetObject(spec.bucket(), keys.get(i));
}
authorizeCopyObject(spec, s3, iamService, roleSession, keys.get(i));
S3Object object = s3.getObject(spec.bucket(), keys.get(i));
byte[] data = object != null && object.getData() != null ? object.getData() : new byte[0];
InputStream rawIn = new ByteArrayInputStream(data);
try (InputStream in = spec.gzip() ? new GZIPInputStream(rawIn) : rawIn) {
try (InputStream in = CopySourceInputStream.open(rawIn, spec.gzip())) {
if (spec.jsonAuto()) {
List<String> targetCols = (discoveredColumns != null && !discoveredColumns.isEmpty())
? discoveredColumns
: (spec.columns() != null
? spec.columns().stream().map(S3CopySimulator::unquoteIdentifier).toList()
: List.of());
List<String> targetCols = jsonColumns(spec, discoveredColumns);
CopyDataOutputStream copyDataOut = new CopyDataOutputStream(backendOut);
JsonLinesToCsvConverter.convert(in, targetCols, copyDataOut, spec.jsonAutoIgnoreCase());
copyDataOut.flush();
@@ -711,7 +707,7 @@ public final class S3CopySimulator {
}
List<T> aligned = new ArrayList<>();
for (String column : spec.columns()) {
String key = column.startsWith("\"") ? unquoteIdentifier(column) : column.toLowerCase(Locale.ROOT);
String key = normalizeColumnName(column);
aligned.add(byName.get(key));
}
return aligned;
@@ -739,7 +735,7 @@ public final class S3CopySimulator {
return CopyRecordTransformer.ColumnKind.OTHER;
}
private static List<String> parseDataRow(byte[] body) {
static List<String> parseDataRow(byte[] body) {
int count = ((body[0] & 0xFF) << 8) | (body[1] & 0xFF);
List<String> values = new ArrayList<>(count);
int offset = 2;
@@ -757,15 +753,26 @@ public final class S3CopySimulator {
return values;
}
static String columnInfoQuery(CopyStatementParser.S3CopyFrom spec) {
// 1042 = bpchar, 1043 = varchar; atttypmod carries the declared length plus a 4-byte header.
return "SELECT a.attname, CASE WHEN a.atttypid IN (1042, 1043) AND a.atttypmod > 4 "
+ "THEN a.atttypmod - 4 END, a.atttypid FROM pg_catalog.pg_attribute a "
+ "WHERE a.attrelid = to_regclass(" + PostgresWire.quoteLiteral(spec.targetTable()) + ") "
+ "AND a.attnum > 0 AND NOT a.attisdropped AND a.attgenerated = '' "
+ "ORDER BY a.attnum";
}
static ColumnInfo columnInfo(List<String> values) {
Integer maxBytes = values.size() >= 2 && values.get(1) != null
? Integer.valueOf(values.get(1)) : null;
String typeOid = values.size() >= 3 ? values.get(2) : null;
return new ColumnInfo(values.get(0), maxBytes, kindOf(typeOid));
}
private static List<ColumnInfo> discoverColumnInfo(Socket client, Socket backend,
CopyStatementParser.S3CopyFrom spec,
char txStatus, IntConsumer onStatusChange) throws IOException {
// 1042 = bpchar, 1043 = varchar; atttypmod carries the declared length plus a 4-byte header.
String query = "SELECT a.attname, CASE WHEN a.atttypid IN (1042, 1043) AND a.atttypmod > 4 "
+ "THEN a.atttypmod - 4 END, a.atttypid FROM pg_catalog.pg_attribute a "
+ "WHERE a.attrelid = to_regclass('" + quoteLiteral(spec.targetTable()) + "') "
+ "AND a.attnum > 0 AND NOT a.attisdropped AND a.attgenerated = '' "
+ "ORDER BY a.attnum";
String query = columnInfoQuery(spec);
OutputStream backendOut = backend.getOutputStream();
backendOut.write(PostgresWireDecoder.encodeQuery(query));
@@ -779,11 +786,7 @@ public final class S3CopySimulator {
if (type == 'D') {
List<String> values = parseDataRow(msg.body());
if (!values.isEmpty() && values.get(0) != null) {
Integer maxBytes = values.size() >= 2 && values.get(1) != null
? Integer.valueOf(values.get(1))
: null;
String typeOid = values.size() >= 3 ? values.get(2) : null;
cols.add(new ColumnInfo(values.get(0), maxBytes, kindOf(typeOid)));
cols.add(columnInfo(values));
}
} else if (type == 'E') {
forward(client, msg);
@@ -855,7 +858,7 @@ public final class S3CopySimulator {
}
}
private static void skipLines(InputStream in, int lines) throws IOException {
static void skipLines(InputStream in, int lines) throws IOException {
int seen = 0;
int b;
while (seen < lines && (b = in.read()) != -1) {
@@ -865,7 +868,7 @@ public final class S3CopySimulator {
}
}
private static void writeCopyData(OutputStream out, byte[] buf, int len) throws IOException {
static void writeCopyData(OutputStream out, byte[] buf, int len) throws IOException {
out.write('d');
out.write(intBytes(4 + len));
out.write(buf, 0, len);
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshiftdata;
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftInternalAuth;
import jakarta.enterprise.context.ApplicationScoped;
import org.postgresql.Driver;
@@ -18,11 +19,13 @@ class RedshiftDataConnectionFactory {
// (varchar) the driver stamps an explicit type OID and the server refuses
// "integer = character varying"; unspecified sends the value untyped and lets the
// server infer the column's type from context, matching how AWS binds parameters.
String applicationName = RedshiftInternalAuth.issueDataApiToken();
String url = "jdbc:postgresql://" + target.host() + ":" + target.port() + "/" + target.database()
+ "?sslmode=disable&stringtype=unspecified";
+ "?sslmode=disable&stringtype=unspecified&ApplicationName=" + applicationName;
Properties props = new Properties();
props.setProperty("user", target.user());
props.setProperty("password", target.password());
props.setProperty("ApplicationName", applicationName);
props.setProperty("connectTimeout", "5");
return driver.connect(url, props);
}
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.redshift.RedshiftCredentialBroker;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.proxy.CopyStatementParser;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumSession;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessRuntime;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService;
@@ -60,14 +61,15 @@ class RedshiftDataResourceResolver {
DatabaseTarget resolve(JsonNode request, String region) {
String database = requiredText(request, "Database");
boolean needsProxy = needsProxy(request);
if (hasText(request, "WorkgroupName")) {
return resolveWorkgroup(request, region, database);
return resolveWorkgroup(request, region, database, needsProxy);
}
if (hasText(request, "SecretArn")) {
return resolveViaSecret(request, region, database);
return resolveViaSecret(request, region, database, needsProxy);
}
return resolveViaDbUser(request, region, database);
return resolveViaDbUser(request, region, database, needsProxy);
}
/**
@@ -75,7 +77,7 @@ class RedshiftDataResourceResolver {
* database user AWS derives from the signing identity. Floci connects the IAM path as the
* namespace admin, the same stand-in GetClusterCredentialsWithIAM uses for a cluster.
*/
private DatabaseTarget resolveWorkgroup(JsonNode request, String region, String database) {
private DatabaseTarget resolveWorkgroup(JsonNode request, String region, String database, boolean needsProxy) {
if (hasText(request, "ClusterIdentifier")) {
throw validation("ClusterIdentifier and WorkgroupName cannot both be specified.");
}
@@ -89,8 +91,12 @@ class RedshiftDataResourceResolver {
throw validation("Database " + database + " does not exist in workgroup " + workgroup.workgroupName()
+ "; the only database is " + workgroup.database() + ".");
}
int proxyPort = workgroup.endpoint() != null ? workgroup.endpoint().getPort() : 0;
boolean hasProxy = needsProxy && proxyPort > 0;
String host = hasProxy ? "127.0.0.1" : workgroup.host();
int port = hasProxy ? proxyPort : workgroup.port();
if (!hasText(request, "SecretArn")) {
return new DatabaseTarget(workgroup.arn(), workgroup.host(), workgroup.port(), database,
return new DatabaseTarget(workgroup.arn(), host, port, database,
workgroup.masterUsername(), workgroup.masterPassword(), spectrum, null,
workgroup.masterUsername(), workgroup.workgroupName());
}
@@ -100,7 +106,7 @@ class RedshiftDataResourceResolver {
if (isManagedAdminSecret(secretArn, workgroup.adminPasswordSecretArn(), region)) {
user = workgroup.masterUsername();
}
return new DatabaseTarget(workgroup.arn(), workgroup.host(), workgroup.port(), database,
return new DatabaseTarget(workgroup.arn(), host, port, database,
user, creds.password(), spectrum, null, user, workgroup.workgroupName());
}
@@ -138,22 +144,22 @@ class RedshiftDataResourceResolver {
}
}
private DatabaseTarget resolveViaSecret(JsonNode request, String region, String database) {
private DatabaseTarget resolveViaSecret(JsonNode request, String region, String database, boolean needsProxy) {
String secretArn = request.get("SecretArn").asText();
validateSecretRegion(secretArn, region);
String clusterId = requiredText(request, "ClusterIdentifier");
Cluster cluster = cluster(clusterId);
DatabaseSecretCredentials creds = secretCredentials(secretArn, region);
return target(clusterArn(clusterId, region), cluster, database, creds.username(), creds.password());
return target(clusterArn(clusterId, region), cluster, database, creds.username(), creds.password(), needsProxy);
}
private DatabaseTarget resolveViaDbUser(JsonNode request, String region, String database) {
private DatabaseTarget resolveViaDbUser(JsonNode request, String region, String database, boolean needsProxy) {
String clusterId = requiredText(request, "ClusterIdentifier");
String dbUser = requiredText(request, "DbUser");
Cluster cluster = cluster(clusterId);
if (dbUser.equals(cluster.getMasterUsername())) {
return target(clusterArn(clusterId, region), cluster, database, dbUser, cluster.getMasterPassword());
return target(clusterArn(clusterId, region), cluster, database, dbUser, cluster.getMasterPassword(), needsProxy);
}
boolean liveCredential = credentialBroker
.resolve(regionResolver.getAccountId(), clusterId, dbUser)
@@ -161,7 +167,7 @@ class RedshiftDataResourceResolver {
if (liveCredential) {
// The minted DbUser is nominal: connect as the cluster master.
DatabaseTarget backend = target(clusterArn(clusterId, region), cluster, database,
cluster.getMasterUsername(), cluster.getMasterPassword());
cluster.getMasterUsername(), cluster.getMasterPassword(), needsProxy);
return new DatabaseTarget(backend.arn(), backend.host(), backend.port(), backend.database(), backend.user(),
backend.password(), backend.spectrum(), cluster, dbUser);
}
@@ -176,9 +182,12 @@ class RedshiftDataResourceResolver {
}
}
private static DatabaseTarget target(String arn, Cluster cluster, String database, String user, String password) {
String host = cluster.getContainerHost();
int port = cluster.getContainerPort();
private static DatabaseTarget target(String arn, Cluster cluster, String database, String user, String password,
boolean needsProxy) {
int proxyPort = cluster.getProxyPort();
boolean hasProxy = needsProxy && proxyPort > 0;
String host = hasProxy ? "127.0.0.1" : cluster.getContainerHost();
int port = hasProxy ? proxyPort : cluster.getContainerPort();
if (host == null || host.isBlank() || port <= 0) {
throw validation("Cluster runtime is not available for Data API execution.");
}
@@ -188,6 +197,34 @@ class RedshiftDataResourceResolver {
return new DatabaseTarget(arn, host, port, database, user, password, spectrum, cluster);
}
private static boolean needsProxy(JsonNode request) {
if (request == null) {
return false;
}
if (request.has("SessionId") || request.path("SessionKeepAliveSeconds").asInt() > 0) {
return true;
}
if (hasText(request, "Sql") && isS3CopyOrUnload(request.get("Sql").asText())) {
return true;
}
JsonNode sqls = request.get("Sqls");
if (sqls != null && sqls.isArray()) {
for (JsonNode item : sqls) {
if (item.isTextual() && isS3CopyOrUnload(item.asText())) {
return true;
}
}
}
return false;
}
private static boolean isS3CopyOrUnload(String sql) {
if (sql == null || sql.isBlank()) {
return false;
}
return CopyStatementParser.parse(sql) != null;
}
private String clusterArn(String clusterId, String region) {
String r = (region == null || region.isBlank()) ? regionResolver.getDefaultRegion() : region;
return AwsArnUtils.Arn.of("redshift", r, regionResolver.getAccountId(), "cluster:" + clusterId).toString();
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.UserChange;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.UserChanges;
import io.github.hectorvent.floci.services.redshift.proxy.CopyJobSql;
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftSqlInterceptor;
import io.github.hectorvent.floci.services.redshift.spectrum.BackendSql;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumQueryPreparation;
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumReadException;
@@ -683,7 +684,8 @@ public class RedshiftDataService implements Resettable, StoredResourceArns {
throw new SQLException("External query preparation failed: " + exception.getMessage(), "58030", exception);
}
}
ParsedSql parsed = RedshiftDataSqlParameters.parse(CopyJobSql.rewrite(sql, !autoCommit || !connection.getAutoCommit()));
String rewritten = CopyJobSql.rewrite(sql, !autoCommit || !connection.getAutoCommit());
ParsedSql parsed = RedshiftDataSqlParameters.parse(RedshiftSqlInterceptor.rewrite(rewritten));
execution.checkCancellation();
if (!autoCommit) {
connection.setAutoCommit(false);