mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(redshift): run COPY ETL options on PostgreSQL 15 across protocols (#7514)
This commit is contained in:
1 parent
a0b39a4ad0
commit
576646aae7
30 files changed
+2282
-389
No files matched your search
+23
-27
@@ -857,13 +857,10 @@ order) through its own S3 service and streams the rows into the backing PostgreS
|
||||
sensitivity. `FORMAT AS JSON 'auto ignorecase'` performs case-insensitive key matching. Input
|
||||
objects can be separated by any whitespace, including multiline pretty-printed JSON. Non-object root
|
||||
values abort the load. When columns are not specified in the COPY statement, table column names and
|
||||
order are automatically discovered from the database catalog, but only over the **Simple Query
|
||||
protocol**. Over Extended Query (the default for a JDBC `PreparedStatement`, and for a plain
|
||||
`Statement` under recent pgjdbc versions) the column list is fixed by the time `Parse` is sent,
|
||||
before any backend round trip is possible, so catalog discovery cannot run there: omitting the column
|
||||
list fails the COPY with a clear error instead of silently guessing. Specify the column list explicitly
|
||||
for Extended Query, or connect with `preferQueryMode=simple` to use discovery. Nested objects and
|
||||
arrays are serialized as JSON strings.
|
||||
order are automatically discovered from the database catalog when the statement executes, through
|
||||
Simple Query, Extended Query and the Data API. Nested objects and arrays are serialized as JSON strings.
|
||||
With `MAXERROR` greater than 1, input is processed as JSON lines so a malformed line can be skipped;
|
||||
multiline pretty-printed JSON is supported only without error tolerance.
|
||||
- `MANIFEST` resolves file keys from a JSON manifest file (`{"entries": [{"url": "s3://...", "mandatory": boolean}]}`),
|
||||
compatible with output from `UNLOAD ... MANIFEST`. Missing files marked `mandatory: true` abort the load.
|
||||
When `mandatory` is omitted, it defaults to `false`. All entries in the manifest must reside in the same S3
|
||||
@@ -895,8 +892,8 @@ order) through its own S3 service and streams the rows into the backing PostgreS
|
||||
mode and an empty unquoted field in CSV mode. `TRUNCATECOLUMNS` cuts a value to the declared
|
||||
`CHAR`/`VARCHAR` length in bytes (Redshift's meaning of the declared length, so `éééé` into
|
||||
`VARCHAR(3)` loads `é`), never inside a multi-byte character or a backslash escape. Its column
|
||||
lengths come from the database catalog, so it works only over the **Simple Query protocol** (`preferQueryMode=simple`);
|
||||
over Extended Query the COPY fails with an error that names this requirement. A field-level option
|
||||
lengths come from the database catalog at execution, through Simple Query, Extended Query and the Data API.
|
||||
A field-level option
|
||||
buffers each decompressed object in memory, so an object over 64 MiB, or a heap budget shared
|
||||
across connections that is used up, fails the COPY instead of exhausting the emulator.
|
||||
- `DATEFORMAT [AS] 'format'` reads the fields of `DATE` columns and `TIMEFORMAT [AS] 'format'` those of
|
||||
@@ -905,8 +902,8 @@ order) through its own S3 service and streams the rows into the backing PostgreS
|
||||
`TIMEFORMAT` also takes `'epochsecs'` and `'epochmillisecs'`, read as UTC. A `DATEFORMAT` may name a time
|
||||
of day, which is dropped; a `TIMEFORMAT` without one gives midnight. A format that names a time zone, or
|
||||
any other text, is not recognized and the statement is forwarded to PostgreSQL. A value that does not
|
||||
match its format fails the COPY, whatever `MAXERROR` says; the message names the column and the format, and
|
||||
Floci writes no `stl_load_errors` row. `ACCEPTANYDATE` loads such a value as
|
||||
match its format is a record error counted against `MAXERROR`; the message names the column and the format,
|
||||
and Floci writes no `stl_load_errors` row. `ACCEPTANYDATE` loads such a value as
|
||||
`NULL` instead; when no format is given it reads the ISO form of a date, with an optional time of day, and
|
||||
turns anything else into `NULL`. An empty unquoted field of a `DATE`, `TIMESTAMP` or other non-character column
|
||||
is loaded as `NULL`, as in AWS, without requiring `ACCEPTANYDATE` or `EMPTYASNULL`. Numeric parts with no
|
||||
@@ -914,8 +911,8 @@ order) through its own S3 service and streams the rows into the backing PostgreS
|
||||
full width, a part may be named once, and `HH12` needs `AM` or `PM`; any other format string is not
|
||||
recognized.
|
||||
Like `TRUNCATECOLUMNS`, these and the empty non-character rule read column types from the catalog, so
|
||||
they apply only with the options that query column types (`DATEFORMAT`, `TIMEFORMAT`, `FILLRECORD`), over the
|
||||
Simple Query protocol, and are not combined with `FORMAT AS JSON`; a plain `COPY` without those options does
|
||||
they apply only with the options that query column types (`DATEFORMAT`, `TIMEFORMAT`, `FILLRECORD`), through
|
||||
Simple Query, Extended Query and the Data API, and are not combined with `FORMAT AS JSON`; a plain `COPY` without those options does
|
||||
not read the catalog. Floci deviations: `'auto'` is accepted but converts
|
||||
nothing, leaving every value to PostgreSQL, which reads ISO 8601, Julian and `YYYYMMDD HHMISS` but not every
|
||||
form Redshift recognizes (for example `BC` dates and `YYYY.DDD`), and with it `ACCEPTANYDATE` cannot turn a
|
||||
@@ -928,21 +925,20 @@ order) through its own S3 service and streams the rows into the backing PostgreS
|
||||
too. A column that does not allow `NULL` fails the COPY as it would without `FILLRECORD`, and a record with
|
||||
too many fields still fails. The number and types of the columns come from the catalog (generated columns
|
||||
left out), or from the column list, in which a name that matches no column counts as a non-character column.
|
||||
A domain over a character type counts as a non-character column. It works only over the Simple Query
|
||||
protocol, and it is not combined with `FORMAT AS JSON`.
|
||||
A domain over a character type counts as a non-character column. It works through Simple Query,
|
||||
Extended Query and the Data API, and is not combined with `FORMAT AS JSON`.
|
||||
- `MAXERROR [AS] n` (0 to 100000) lets the load go on past records that cannot be converted. With `n` of 0 or 1 the
|
||||
COPY fails at the first error, as it does without the option. With a larger `n` Floci asks the backend to skip
|
||||
the failing records (`ON_ERROR ignore`) and to fail the COPY, rolling it back, once `n` of them have been
|
||||
skipped (`REJECT_LIMIT n - 1`). This uses the PostgreSQL `COPY` options of the same names, so it needs a
|
||||
PostgreSQL 18 backend (set `floci.services.redshift.image-version`, for example `postgres:18-alpine`); the
|
||||
default backend rejects the option as unknown and the COPY fails with that error. The COPY fails when the
|
||||
`n`-th record is rejected, counted across all the files of the load. Floci deviations: only a value that the
|
||||
backend cannot convert to its column type is skipped, whereas Redshift also skips a record with too many or too
|
||||
few fields, a `NOT NULL` violation and other errors, which still fail the COPY here. So do a value that does
|
||||
not match a `DATEFORMAT` or `TIMEFORMAT` (use `ACCEPTANYDATE` to load it as `NULL`), a quoted field without its
|
||||
closing quote under `REMOVEQUOTES`, and a line that `FORMAT AS JSON 'auto'` cannot read, since Floci rejects
|
||||
those before the backend sees them. The backend reports the count of skipped records in its own notice, not
|
||||
Redshift's `Load into table ... completed` message, and no `stl_load_errors` row is written.
|
||||
COPY fails at the first error, as it does without the option. A larger `n` loads logical records under
|
||||
savepoints on the default PostgreSQL 15 backend, through Simple Query, Extended Query and the Data API.
|
||||
Conversion, date/time format, field-count, encoding, string-length and `NOT NULL` errors can be skipped.
|
||||
The `n`-th record error, counted across all source objects, rolls back the entire COPY; earlier statements
|
||||
in an explicit transaction remain subject to the caller's transaction and savepoints. Access denied,
|
||||
cancellation, storage and unexpected internal errors are never ignored. An unterminated CSV quote or
|
||||
unreadable compressed object aborts the load because the next record boundary cannot be established.
|
||||
The returned `COPY` count includes accepted rows only. Floci deviations: tolerant loads use one COPY
|
||||
per record, which costs more round trips and runs PostgreSQL statement triggers per record; PostgreSQL
|
||||
deferred-constraint timing is not promised as Redshift behavior. Tolerant records are buffered within
|
||||
the transform size and shared memory limits. No `stl_load_errors` row or Redshift load-summary message is written.
|
||||
- Any other clause (`FIXEDWIDTH`, `PARQUET`, `AVRO`, `ORC`,
|
||||
`ENCODING`, `ESCAPE`, `ENCRYPTED`, `MASTER_SYMMETRIC_KEY`,
|
||||
`KMS_KEY_ID`, and so on) is not recognized: the statement is forwarded unchanged and PostgreSQL
|
||||
|
||||
+27
-3
@@ -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;
|
||||
|
||||
+42
@@ -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 {
|
||||
|
||||
+239
@@ -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);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
+103
@@ -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);
|
||||
}
|
||||
}
|
||||
+6
-6
@@ -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);
|
||||
}
|
||||
}
|
||||
+52
@@ -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);
|
||||
}
|
||||
}
|
||||
+102
-185
@@ -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());
|
||||
}
|
||||
|
||||
+1
-1
@@ -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() {
|
||||
}
|
||||
|
||||
+8
-4
@@ -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();
|
||||
|
||||
+89
-8
@@ -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();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+48
@@ -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);
|
||||
}
|
||||
}
|
||||
+54
-51
@@ -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);
|
||||
|
||||
+4
-1
@@ -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);
|
||||
}
|
||||
|
||||
+51
-14
@@ -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();
|
||||
|
||||
+3
-1
@@ -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);
|
||||
|
||||
+250
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-10
@@ -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
-14
@@ -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");
|
||||
|
||||
+83
@@ -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));
|
||||
}
|
||||
}
|
||||
+145
-45
@@ -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;
|
||||
}
|
||||
}
|
||||
+120
@@ -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;
|
||||
}
|
||||
}
|
||||
+317
@@ -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();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+63
-11
@@ -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);
|
||||
|
||||
+32
@@ -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"));
|
||||
}
|
||||
}
|
||||
+27
-8
@@ -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);
|
||||
|
||||
+49
@@ -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)
|
||||
|
||||
+64
@@ -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);
|
||||
|
||||
+11
@@ -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", "");
|
||||
|
||||
Reference in new issue
Block a user