diff --git a/compatibility-tests/sdk-test-java/src/test/java/io/github/hectorvent/floci/compat/RedshiftSpectrumTest.java b/compatibility-tests/sdk-test-java/src/test/java/io/github/hectorvent/floci/compat/RedshiftSpectrumTest.java new file mode 100644 index 0000000000..2f2b97cf5d --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/io/github/hectorvent/floci/compat/RedshiftSpectrumTest.java @@ -0,0 +1,124 @@ +package io.github.hectorvent.floci.compat; + +import com.floci.test.TestFixtures; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.redshift.RedshiftClient; +import software.amazon.awssdk.services.redshift.model.Cluster; +import software.amazon.awssdk.services.redshift.model.CreateClusterRequest; +import software.amazon.awssdk.services.redshift.model.DeleteClusterRequest; +import software.amazon.awssdk.services.redshift.model.DescribeClustersRequest; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.time.Instant; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class RedshiftSpectrumTest { + + @Test + @DisplayName("queries an S3 CSV external table through the Redshift JDBC wire") + void queriesCsvExternalTable() throws Exception { + String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + String clusterId = "spectrum-" + suffix; + String bucket = "spectrum-" + suffix; + RedshiftClient redshift = TestFixtures.redshiftClient(); + S3Client s3 = TestFixtures.s3Client(); + boolean bucketCreated = false; + boolean clusterCreated = false; + + try { + s3.createBucket(CreateBucketRequest.builder().bucket(bucket).build()); + bucketCreated = true; + s3.putObject(PutObjectRequest.builder().bucket(bucket).key("events/part-1.csv") + .contentType("text/csv").build(), + RequestBody.fromString("id,name\n1,Alice\n2,Bob\n")); + redshift.createCluster(CreateClusterRequest.builder().clusterIdentifier(clusterId) + .nodeType("dc2.large").masterUsername("admin").masterUserPassword("Password123") + .build()); + clusterCreated = true; + + Cluster cluster = waitForCluster(redshift, clusterId); + String jdbcUrl = "jdbc:postgresql://" + cluster.endpoint().address() + ":" + + cluster.endpoint().port() + "/dev"; + try (Connection connection = waitForConnection(jdbcUrl); + Statement statement = connection.createStatement()) { + statement.execute("CREATE EXTERNAL SCHEMA analytics FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'"); + statement.execute("CREATE EXTERNAL TABLE analytics.events (id INTEGER, name VARCHAR) " + + "STORED AS TEXTFILE LOCATION 's3://" + bucket + "/events/' " + + "TBLPROPERTIES ('skip.header.line.count'='1')"); + try (ResultSet rows = statement.executeQuery("SELECT id, name FROM analytics.events")) { + assertTrue(rows.next()); + assertEquals(1, rows.getInt("id")); + assertEquals("Alice", rows.getString("name")); + assertTrue(rows.next()); + assertEquals(2, rows.getInt("id")); + assertEquals("Bob", rows.getString("name")); + assertTrue(!rows.next()); + } + } + } finally { + try { + if (!clusterCreated) { + return; + } + redshift.deleteCluster(DeleteClusterRequest.builder().clusterIdentifier(clusterId).build()); + } finally { + if (bucketCreated) { + s3.deleteObject(DeleteObjectRequest.builder().bucket(bucket).key("events/part-1.csv").build()); + s3.deleteBucket(DeleteBucketRequest.builder().bucket(bucket).build()); + } + redshift.close(); + s3.close(); + } + } + } + + private static Cluster waitForCluster(RedshiftClient redshift, String clusterId) throws InterruptedException { + Instant deadline = Instant.now().plus(Duration.ofSeconds(30)); + while (Instant.now().isBefore(deadline)) { + try { + Cluster cluster = redshift.describeClusters(DescribeClustersRequest.builder() + .clusterIdentifier(clusterId).build()).clusters().get(0); + if (cluster.endpoint() != null && cluster.endpoint().port() > 0) { + return cluster; + } + } catch (RuntimeException ignored) { + // The control-plane response may briefly precede endpoint publication. + } + Thread.sleep(500); + } + throw new IllegalStateException("Timed out waiting for Redshift cluster endpoint"); + } + + private static Connection waitForConnection(String jdbcUrl) throws InterruptedException, SQLException { + Instant deadline = Instant.now().plus(Duration.ofSeconds(30)); + SQLException last = null; + while (Instant.now().isBefore(deadline)) { + try { + Connection connection = DriverManager.getConnection(jdbcUrl, "admin", "Password123"); + if (connection.isValid(5)) { + return connection; + } + connection.close(); + } catch (SQLException exception) { + last = exception; + } + Thread.sleep(500); + } + throw last == null ? new SQLException("Timed out waiting for Redshift JDBC connection") : last; + } +} diff --git a/docs/services/redshift.md b/docs/services/redshift.md index caa8ceaee3..8996fabcbf 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -233,6 +233,41 @@ Floci's Redshift auth proxy inspects frontend queries on the PostgreSQL wire pro - The rewrite only runs when the statement's first keyword is `CREATE TABLE` or `ALTER TABLE`. A `SELECT`, `INSERT`, function body, or string literal that merely contains one of these keywords is forwarded byte-for-byte. Single-quoted and dollar-quoted string literals are masked before the rewrite, so a keyword inside a quoted value (including in a later statement of a multi-statement query) is preserved. - Columns legitimately named `distkey`, `sortkey`, or `encode` survive. +### Redshift Spectrum Phase 1 + +The PostgreSQL wire proxy supports a bounded Spectrum subset for CSV data in S3. The supported +statements are: + +```sql +CREATE EXTERNAL SCHEMA + FROM DATA CATALOG DATABASE '' IAM_ROLE ''; + +CREATE EXTERNAL TABLE . ( , ...) + STORED AS TEXTFILE LOCATION 's3:////' + TBLPROPERTIES ('skip.header.line.count'=''); +``` + +Supported column types are `VARCHAR`, `CHAR`, `INTEGER`, `BIGINT`, `DECIMAL`, `BOOLEAN`, `DATE`, +and `TIMESTAMP`. CSV reads support `DELIMITER`, `QUOTE`, `ESCAPE`, `NULL AS`, and +`skip.header.line.count`. Objects under the location are read in lexicographic key order. + +The query path supports `SELECT *`, explicit column projections, and simple `WHERE` predicates +over one external table. Queries with joins, grouping, ordering, subqueries, parameters, or +multiple statements are outside Phase 1 and are forwarded to PostgreSQL, which returns its own +error. Rows are materialized into a connection-local temporary table (`CREATE TEMP TABLE`) before +the rewritten query is sent to PostgreSQL. The temporary table is not visible to another +connection. Under the Extended Query protocol, the temporary table is dropped eagerly once +the cursor is exhausted or closed. Under the Simple Query protocol, the table remains +session-scoped and is cleaned up when the connection terminates, avoiding race conditions +with the streaming backend-to-client pump. Each query materializes its own table, so a +long-lived or pooled connection holds one copy per query until it closes. + +`IAM_ROLE` is parsed and retained in the external schema metadata. Phase 1 does not yet assume +the role or evaluate its IAM policy for Spectrum reads. S3 authorization therefore follows the +current S3 emulator authorization mode, and role-specific Spectrum access enforcement is a +future phase. Parquet, JSON, Avro, ORC, partition discovery, `ALTER`, and `DROP` lifecycle +operations are not supported in Phase 1. + ### COPY from S3 `COPY
[()] FROM 's3:///' [options]` sent over the Simple @@ -356,7 +391,7 @@ These views expose the documented Redshift column names, types, and ordering map ## Out of Scope -- Real Redshift SQL semantics: the data plane is stock PostgreSQL. Redshift-only table DDL keywords (DISTSTYLE / DISTKEY / SORTKEY / ENCODE) are stripped so CREATE TABLE / ALTER TABLE executes (see [SQL Interceptor](#sql-interceptor)), but the distribution/sort behavior they request is not; SUPER/SPECTRUM are not emulated. +- Real Redshift SQL semantics: the data plane is stock PostgreSQL. Redshift-only table DDL keywords (DISTSTYLE / DISTKEY / SORTKEY / ENCODE) are stripped so CREATE TABLE / ALTER TABLE executes (see [SQL Interceptor](#sql-interceptor)), but the distribution/sort behavior they request is not; SUPER and Spectrum features outside the documented [Phase 1 subset](#redshift-spectrum-phase-1) are not emulated. - Multi-node clusters: `NodeType` and `NumberOfNodes` are stored as metadata; every cluster is a single PostgreSQL container. - Parameter groups apply no real engine settings; values are stored and echoed back only. - Subnet groups, VPC routing, and security groups are metadata only. diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/ExtendedSpectrumExchange.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/ExtendedSpectrumExchange.java new file mode 100644 index 0000000000..9f1e6a34e0 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/ExtendedSpectrumExchange.java @@ -0,0 +1,225 @@ +package io.github.hectorvent.floci.services.redshift.proxy; + +import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor; +import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumMaterializer; +import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumReadException; +import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumSqlException; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.Map; + +/** + * Runs a Spectrum {@code Plan} for one Extended Query Execute. + * + *

Results are sent to the client immediately and this method then returns without waiting for + * Flush or Sync: PostgreSQL lets a frontend pipeline any number of Parse/Bind/Execute steps before + * a single trailing Sync, and Execute itself never produces {@code ReadyForQuery}. The client's + * eventual Sync is handled generically by {@link RedshiftInterceptingBridge#run()}, which forwards + * it to the real backend; the backend's own {@code ReadyForQuery} for that Sync is then relayed to + * the client by the ordinary backend-to-client pump. Waiting here for Sync (or even just Flush) + * before producing output would deadlock a client that reads Execute's result before deciding + * whether to send more commands or Sync. + * + *

A Spectrum SELECT cannot be paused and resumed on the real backend (it runs as a single Simple + * Query against the materialized temp table), so {@code Execute}'s {@code maxRows} is honored by + * buffering the full row set once per portal in a {@link PortalCursor} and doling it out across + * however many Execute calls the client makes, exactly like a real suspended portal: once the + * buffer is empty this sends {@code CommandComplete}, otherwise {@code PortalSuspended}. + */ +final class ExtendedSpectrumExchange { + + private static final Logger LOG = Logger.getLogger(ExtendedSpectrumExchange.class); + + private ExtendedSpectrumExchange() { + } + + static void execute(Socket client, Socket backend, SpectrumInterceptor.Plan plan, + SpectrumInterceptor interceptor, String accountId, String database, + BackendResponseCoordinator coordinator, BackendResponseCoordinator.Ticket ticket, + String portalName, int maxRows, Map cursors) throws IOException { + boolean failed = true; + try { + PortalCursor cursor = cursors.get(portalName); + if (cursor == null) { + SpectrumInterceptor.Decision decision = interceptor.execute(plan, accountId, database, backend); + if (decision instanceof SpectrumInterceptor.Decision.Handled) { + forward(client, commandComplete("CREATE EXTERNAL")); + failed = false; + return; + } + if (decision instanceof SpectrumInterceptor.Decision.Rewritten rewritten) { + cursor = new PortalCursor(rewritten.materialization(), + bufferRows(backend, rewritten.sql())); + cursors.put(portalName, cursor); + } else { + throw new SpectrumSqlException("0A000", "Spectrum plan did not produce an executable statement"); + } + } + deliverRows(client, cursor, maxRows); + failed = false; + if (cursor.exhausted()) { + cursors.remove(portalName); + cleanup(interceptor, backend, cursor.materialization()); + } + } catch (RuntimeException e) { + PortalCursor abandoned = cursors.remove(portalName); + if (abandoned != null) { + cleanup(interceptor, backend, abandoned.materialization()); + } + forward(client, error(e)); + } finally { + coordinator.completeOwnedExecute(ticket, failed); + } + } + + /** Drops a cursor's temp table, e.g. when its portal is closed before the client exhausts it. */ + static void abandon(SpectrumInterceptor interceptor, Socket backend, PortalCursor cursor) { + cleanup(interceptor, backend, cursor.materialization()); + } + + private static void cleanup(SpectrumInterceptor interceptor, Socket backend, + SpectrumMaterializer.Materialization materialization) { + try { + interceptor.cleanup(backend, materialization); + } catch (RuntimeException cleanupFailure) { + LOG.warnv(cleanupFailure, "Unable to clean up Spectrum materialization {0}", + materialization.identifier()); + } + } + + private static Deque bufferRows(Socket backend, String sql) + throws IOException { + OutputStream backendOut = backend.getOutputStream(); + backendOut.write(PostgresWireDecoder.encodeQuery(sql)); + backendOut.flush(); + + PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream()); + Deque rows = new ArrayDeque<>(); + while (true) { + PostgresWireDecoder.FrontendMessage message = decoder.nextMessage(); + if (message == null) { + throw new IOException("Backend closed during Spectrum Execute"); + } + switch (message.type()) { + case 'Z' -> { + return rows; + } + case 'T', 'C' -> { + // RowDescription was already sent from catalog metadata at Describe time; the + // backend's own CommandComplete tag is discarded in favor of one reflecting the + // buffered row count, since rows are delivered across possibly several Executes. + } + case 'E' -> throw new SpectrumSqlException("22000", + "PostgreSQL rejected the rewritten Spectrum query: " + describeError(message)); + default -> rows.add(message); + } + } + } + + private static String describeError(PostgresWireDecoder.FrontendMessage errorResponse) { + byte[] body = errorResponse.body(); + if (body == null) { + return "unknown error"; + } + int offset = 0; + while (offset < body.length && body[offset] != 0) { + if (body[offset] == 'M') { + int start = offset + 1; + int end = start; + while (end < body.length && body[end] != 0) { + end++; + } + return new String(body, start, end - start, StandardCharsets.UTF_8); + } + while (offset < body.length && body[offset] != 0) { + offset++; + } + offset++; + } + return "unknown error"; + } + + private static void deliverRows(Socket client, PortalCursor cursor, int maxRows) throws IOException { + int delivered = 0; + while ((maxRows <= 0 || delivered < maxRows) && !cursor.rows().isEmpty()) { + forward(client, cursor.rows().pollFirst()); + delivered++; + } + cursor.delivered(delivered); + if (cursor.rows().isEmpty()) { + forward(client, commandComplete("SELECT " + cursor.totalDelivered())); + } else { + forward(client, portalSuspended()); + } + } + + private static PostgresWireDecoder.FrontendMessage commandComplete(String tag) { + return new PostgresWireDecoder.FrontendMessage('C', (tag + '\0').getBytes(StandardCharsets.UTF_8)); + } + + private static PostgresWireDecoder.FrontendMessage portalSuspended() { + return new PostgresWireDecoder.FrontendMessage('s', new byte[0]); + } + + private static PostgresWireDecoder.FrontendMessage error(RuntimeException exception) { + return new PostgresWireDecoder.FrontendMessage('E', + S3CopySimulator.errorBody(sqlState(exception), exception.getMessage())); + } + + private static String sqlState(RuntimeException exception) { + if (exception instanceof SpectrumSqlException spectrumSqlException) { + return spectrumSqlException.sqlState(); + } + if (exception instanceof SpectrumReadException spectrumReadException) { + return spectrumReadException.sqlState(); + } + return "22023"; + } + + private static void forward(Socket client, PostgresWireDecoder.FrontendMessage message) throws IOException { + OutputStream output = client.getOutputStream(); + output.write(message.toPacketBytes()); + output.flush(); + } + + /** The buffered, not-yet-delivered rows of one Spectrum SELECT bound to a portal, and the temp + * table they came from. Rows are removed as they are delivered; {@link #exhausted()} is true + * once every row has been sent to the client across one or more {@code Execute} calls. */ + static final class PortalCursor { + private final SpectrumMaterializer.Materialization materialization; + private final Deque rows; + private long totalDelivered; + + PortalCursor(SpectrumMaterializer.Materialization materialization, + Deque rows) { + this.materialization = materialization; + this.rows = rows; + } + + SpectrumMaterializer.Materialization materialization() { + return materialization; + } + + Deque rows() { + return rows; + } + + void delivered(int count) { + totalDelivered += count; + } + + long totalDelivered() { + return totalDelivered; + } + + boolean exhausted() { + return rows.isEmpty(); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java index ea7011783b..ff323c6d1d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.rds.proxy.PostgresProtocolHandler; import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates; import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator; import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor; import org.jboss.logging.Logger; import java.io.IOException; @@ -38,6 +39,7 @@ public class RedshiftAuthProxy { private final PasswordValidator passwordValidator; private final S3Service s3Service; private final IamService iamService; + private final SpectrumInterceptor spectrumInterceptor; private final String clusterAccountId; private volatile List iamRoleArns; private final int handshakeTimeoutMillis; @@ -57,7 +59,7 @@ public class RedshiftAuthProxy { this(clusterKey, backendHost, backendPort, masterUsername, masterPassword, dbName, sigV4, tlsCertificates, passwordValidator, s3Service, iamService, null, List.of(), - handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections); + handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections, null); } public RedshiftAuthProxy(String clusterKey, String backendHost, int backendPort, @@ -69,6 +71,20 @@ public class RedshiftAuthProxy { List iamRoleArns, int handshakeTimeoutMillis, int backendConnectTimeoutMillis, int maxConnections) { + this(clusterKey, backendHost, backendPort, masterUsername, masterPassword, dbName, sigV4, + tlsCertificates, passwordValidator, s3Service, iamService, clusterAccountId, iamRoleArns, + handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections, null); + } + + public RedshiftAuthProxy(String clusterKey, String backendHost, int backendPort, + String masterUsername, String masterPassword, String dbName, + RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates, + PasswordValidator passwordValidator, + S3Service s3Service, IamService iamService, + String clusterAccountId, + List iamRoleArns, + int handshakeTimeoutMillis, int backendConnectTimeoutMillis, + int maxConnections, SpectrumInterceptor spectrumInterceptor) { this.clusterKey = clusterKey; this.backendHost = backendHost; this.backendPort = backendPort; @@ -80,6 +96,7 @@ public class RedshiftAuthProxy { this.passwordValidator = passwordValidator; this.s3Service = s3Service; this.iamService = iamService; + this.spectrumInterceptor = spectrumInterceptor; this.clusterAccountId = clusterAccountId; this.iamRoleArns = iamRoleArns == null ? List.of() : List.copyOf(iamRoleArns); this.handshakeTimeoutMillis = handshakeTimeoutMillis; @@ -205,7 +222,7 @@ public class RedshiftAuthProxy { // Redshift-only DDL (DISTKEY/SORTKEY/ENCODE/...) is rewritten for the plain // PostgreSQL backend on the way through; every other message is relayed verbatim. new RedshiftInterceptingBridge(session.client(), session.backend(), s3Service, iamService, - clusterAccountId, iamRoleArns).run(); + clusterAccountId, iamRoleArns, spectrumInterceptor).run(); } } catch (Exception e) { LOG.debugv("Redshift connection error for cluster {0}: {1}", clusterKey, e.getMessage()); diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftInterceptingBridge.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftInterceptingBridge.java index 553b75bd2b..bfd1085f85 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftInterceptingBridge.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftInterceptingBridge.java @@ -1,15 +1,26 @@ package io.github.hectorvent.floci.services.redshift.proxy; import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumColumn; +import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor; +import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumQueryRewriter; +import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumReadException; +import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumSqlException; import io.github.hectorvent.floci.services.s3.S3Service; import org.jboss.logging.Logger; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.SocketTimeoutException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; import java.util.List; +import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.LockSupport; import java.util.concurrent.locks.ReentrantLock; @@ -33,6 +44,8 @@ public class RedshiftInterceptingBridge { private static final Logger LOG = Logger.getLogger(RedshiftInterceptingBridge.class); + private static final byte[] EMPTY_BODY = new byte[0]; + private static final int PUMP_READ_TIMEOUT_MS = 200; private static final int CLIENT_READ_TIMEOUT_MS = 10_000; private static final long PUMP_PARK_WAIT_MS = 2_000L; @@ -46,12 +59,17 @@ public class RedshiftInterceptingBridge { private final IamService iamService; private final String clusterAccountId; private final List iamRoleArns; + private final SpectrumInterceptor spectrumInterceptor; private final ExtendedQuerySession session = new ExtendedQuerySession(); + private final Map spectrumStatements = new HashMap<>(); + private final Map spectrumPortals = new HashMap<>(); + private final Map spectrumCursors = new HashMap<>(); private final BackendResponseCoordinator coordinator = new BackendResponseCoordinator(session); private final ReentrantLock backendLock = new ReentrantLock(true); private volatile boolean pumpBetweenMessages = true; private volatile boolean pumpFinished = false; + private boolean extendedSpectrumError; public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService) { this(client, backend, s3Service, iamService, null); @@ -63,13 +81,20 @@ public class RedshiftInterceptingBridge { } public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService, - String clusterAccountId, List iamRoleArns) { + String clusterAccountId, List iamRoleArns) { + this(client, backend, s3Service, iamService, clusterAccountId, iamRoleArns, null); + } + + public RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService, + String clusterAccountId, List iamRoleArns, + SpectrumInterceptor spectrumInterceptor) { this.client = client; this.backend = backend; this.s3Service = s3Service; this.iamService = iamService; this.clusterAccountId = clusterAccountId; this.iamRoleArns = iamRoleArns == null ? List.of() : List.copyOf(iamRoleArns); + this.spectrumInterceptor = spectrumInterceptor; } @FunctionalInterface @@ -123,6 +148,9 @@ public class RedshiftInterceptingBridge { } continue; } + if (extendedSpectrumError && msg.type() != 'S' && msg.type() != 'X') { + continue; + } switch (msg.type()) { case 'Q' -> handleSimpleQuery(msg, backendOut); case 'P' -> handleParse(decoder, msg, backendOut); @@ -131,6 +159,7 @@ public class RedshiftInterceptingBridge { case 'E' -> handleExecute(decoder, msg, backendOut); case 'C' -> handleClose(decoder, msg, backendOut); case 'S' -> { + extendedSpectrumError = false; coordinator.register(BackendResponseCoordinator.Operation.SYNC, null); write(backendOut, msg.toPacketBytes()); } @@ -151,6 +180,36 @@ public class RedshiftInterceptingBridge { private void handleSimpleQuery(PostgresWireDecoder.FrontendMessage message, OutputStream backendOut) throws IOException { String sql = message.getSql(); + if (spectrumInterceptor != null) { + SpectrumInterceptor.Decision[] decision = new SpectrumInterceptor.Decision[1]; + boolean intercepted; + try { + intercepted = runWithBackendOwned(() -> { + decision[0] = spectrumInterceptor.intercept(sql, clusterAccountId, "dev", backend); + return true; + }); + } catch (SpectrumSqlException | SpectrumReadException | IllegalArgumentException exception) { + writeSimpleSpectrumError(exception); + return; + } + if (intercepted && decision[0] instanceof SpectrumInterceptor.Decision.Handled) { + coordinator.register(BackendResponseCoordinator.Operation.SIMPLE_QUERY, null); + write(client.getOutputStream(), commandComplete("CREATE EXTERNAL\0")); + write(client.getOutputStream(), readyForQuery('I')); + coordinator.onBackendFrame('Z', new byte[]{'I'}); + return; + } + if (intercepted && decision[0] instanceof SpectrumInterceptor.Decision.Rewritten rewritten) { + // The response streams back to the client through the async backend->client pump + // (see class docs), so the materialized temp table cannot be dropped synchronously + // here without racing that pump; it is cleaned up implicitly when the underlying + // PostgreSQL session ends (CREATE TEMP TABLE is session-scoped). The Extended Query + // path (ExtendedSpectrumExchange) owns the whole round trip and can clean up eagerly. + coordinator.register(BackendResponseCoordinator.Operation.SIMPLE_QUERY, null); + write(backendOut, PostgresWireDecoder.encodeQuery(rewritten.sql())); + return; + } + } CopyStatementParser.S3Statement parsed = parseS3Statement(sql); if (parsed != null) { CopyStatementParser.S3Statement statement = parsed; @@ -183,6 +242,24 @@ public class RedshiftInterceptingBridge { private void handleParse(PostgresWireDecoder decoder, PostgresWireDecoder.FrontendMessage message, OutputStream backendOut) throws IOException { PostgresWireDecoder.ParseMessage parse = decoder.decodeParse(message); + // A Parse with an already-used statement name (the unnamed statement, "", above all) redefines + // it, per protocol; without this, a later non-Spectrum statement reusing that name would still + // resolve to the stale Spectrum plan in handleBind/handleDescribe/handleExecute. + spectrumStatements.remove(parse.statementName()); + if (spectrumInterceptor != null && parse.parameterTypeOids().isEmpty()) { + try { + SpectrumInterceptor.Plan plan = spectrumInterceptor.plan(parse.sql(), clusterAccountId, "dev"); + if (plan instanceof SpectrumInterceptor.Plan.Ddl || plan instanceof SpectrumInterceptor.Plan.Query) { + awaitPriorBackendResponses(); + spectrumStatements.put(parse.statementName(), plan); + write(client.getOutputStream(), backendFrame('1', EMPTY_BODY)); + return; + } + } catch (SpectrumSqlException | SpectrumReadException | IllegalArgumentException exception) { + writeParseSpectrumError(exception); + return; + } + } CopyStatementParser.S3Statement statement = parse.parameterTypeOids().isEmpty() ? parseS3Statement(parse.sql()) : null; ExtendedQuerySession.Mutation mutation = session.stageParse(parse.statementName(), statement); @@ -208,6 +285,14 @@ public class RedshiftInterceptingBridge { private void handleBind(PostgresWireDecoder decoder, PostgresWireDecoder.FrontendMessage message, OutputStream backendOut) throws IOException { PostgresWireDecoder.BindMessage bind = decoder.decodeBind(message); + SpectrumInterceptor.Plan spectrumPlan = spectrumStatements.get(bind.statementName()); + if (spectrumPlan != null) { + awaitPriorBackendResponses(); + spectrumPortals.put(bind.portalName(), spectrumPlan); + write(client.getOutputStream(), backendFrame('2', EMPTY_BODY)); + return; + } + spectrumPortals.remove(bind.portalName()); ExtendedQuerySession.Mutation mutation = session.stageBind(bind.portalName(), bind.statementName()); coordinator.register(BackendResponseCoordinator.Operation.BIND, mutation); write(backendOut, message.toPacketBytes()); @@ -216,6 +301,25 @@ public class RedshiftInterceptingBridge { private void handleDescribe(PostgresWireDecoder decoder, PostgresWireDecoder.FrontendMessage message, OutputStream backendOut) throws IOException { PostgresWireDecoder.TargetMessage describe = decoder.decodeDescribe(message); + SpectrumInterceptor.Plan spectrumPlan = describe.targetType() == 'S' + ? spectrumStatements.get(describe.name()) + : spectrumPortals.get(describe.name()); + if (spectrumPlan != null) { + try { + awaitPriorBackendResponses(); + if (describe.targetType() == 'S') { + // Describe(Statement) must answer with ParameterDescription before RowDescription + // or NoData; every Spectrum-owned Parse has zero parameters (handleParse only + // takes this path when parse.parameterTypeOids() is empty), so this is always 0. + write(client.getOutputStream(), backendFrame('t', new byte[]{0, 0})); + } + byte[] response = spectrumDescribeResponse(spectrumPlan); + write(client.getOutputStream(), response); + } catch (SpectrumSqlException | SpectrumReadException | IllegalArgumentException exception) { + writeParseSpectrumError(exception); + } + return; + } BackendResponseCoordinator.Operation operation = describe.targetType() == 'S' ? BackendResponseCoordinator.Operation.DESCRIBE_STATEMENT : BackendResponseCoordinator.Operation.DESCRIBE_PORTAL; @@ -223,9 +327,53 @@ public class RedshiftInterceptingBridge { write(backendOut, message.toPacketBytes()); } + /** {@code RowDescription} for a Spectrum SELECT, or {@code NoData} for a DDL statement, computed + * entirely from catalog metadata so Describe never has to round-trip the real backend. */ + private static byte[] spectrumDescribeResponse(SpectrumInterceptor.Plan plan) { + if (plan instanceof SpectrumInterceptor.Plan.Query query) { + return rowDescription(SpectrumQueryRewriter.outputColumns(query.query(), query.table())); + } + return backendFrame('n', EMPTY_BODY); + } + + private static byte[] rowDescription(List columns) { + ByteArrayOutputStream body = new ByteArrayOutputStream(); + body.write((columns.size() >>> 8) & 0xFF); + body.write(columns.size() & 0xFF); + for (SpectrumColumn column : columns) { + writeCString(body, column.name()); + writeInt32(body, 0); + writeInt16(body, 0); + writeInt32(body, column.type().postgresTypeOid()); + writeInt16(body, column.type().postgresTypeLength()); + writeInt32(body, -1); + writeInt16(body, 0); + } + return backendFrame('T', body.toByteArray()); + } + + private static void writeInt32(ByteArrayOutputStream out, int value) { + out.write((value >>> 24) & 0xFF); + out.write((value >>> 16) & 0xFF); + out.write((value >>> 8) & 0xFF); + out.write(value & 0xFF); + } + + private static void writeInt16(ByteArrayOutputStream out, int value) { + out.write((value >>> 8) & 0xFF); + out.write(value & 0xFF); + } + private void handleExecute(PostgresWireDecoder decoder, PostgresWireDecoder.FrontendMessage message, OutputStream backendOut) throws IOException { PostgresWireDecoder.ExecuteMessage execute = decoder.decodeExecute(message); + SpectrumInterceptor.Plan spectrumPlan = spectrumPortals.get(execute.portalName()); + if (spectrumPlan != null) { + BackendResponseCoordinator.Ticket ticket = coordinator.register( + BackendResponseCoordinator.Operation.EXECUTE, null); + runExtendedSpectrumWithBackendOwned(spectrumPlan, execute.portalName(), execute.maxRows(), ticket); + return; + } BackendResponseCoordinator.Ticket ticket = coordinator.register( BackendResponseCoordinator.Operation.EXECUTE, null); CopyStatementParser.S3Statement statement = session.portal(execute.portalName()).orElse(null); @@ -236,14 +384,117 @@ public class RedshiftInterceptingBridge { runExtendedWithBackendOwned(message, statement, ticket); } + private void runExtendedSpectrumWithBackendOwned(SpectrumInterceptor.Plan plan, String portalName, int maxRows, + BackendResponseCoordinator.Ticket ticket) throws IOException { + BackendResponseCoordinator.GateResult gate; + try { + gate = coordinator.awaitExtendedExecuteTurn(ticket); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Interrupted while awaiting Spectrum Execute turn", e); + } + if (gate != BackendResponseCoordinator.GateResult.READY) { + return; + } + + long deadlineNanos = System.nanoTime() + PUMP_PARK_WAIT_MS * 1_000_000L; + boolean locked = false; + while (!pumpFinished && System.nanoTime() < deadlineNanos) { + try { + long remainingMillis = Math.max(1L, + TimeUnit.NANOSECONDS.toMillis(deadlineNanos - System.nanoTime())); + locked = backendLock.tryLock(Math.min(PUMP_PARK_WAIT_MS, remainingMillis), TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Interrupted while acquiring Spectrum Execute ownership", e); + } + if (!locked) { + continue; + } + if (pumpBetweenMessages) { + break; + } + backendLock.unlock(); + locked = false; + } + if (!locked || !pumpBetweenMessages || pumpFinished) { + if (locked) { + backendLock.unlock(); + } + throw new IOException("Could not take backend ownership for Spectrum Execute"); + } + try { + backend.setSoTimeout(EXCHANGE_READ_TIMEOUT_MS); + ExtendedSpectrumExchange.execute(client, backend, plan, spectrumInterceptor, clusterAccountId, "dev", + coordinator, ticket, portalName, maxRows, spectrumCursors); + } finally { + try { + backend.setSoTimeout(PUMP_READ_TIMEOUT_MS); + } catch (IOException e) { + LOG.debugv(e, "could not restore backend read timeout (socket closing)"); + } + backendLock.unlock(); + } + } + private void handleClose(PostgresWireDecoder decoder, PostgresWireDecoder.FrontendMessage message, OutputStream backendOut) throws IOException { PostgresWireDecoder.TargetMessage close = decoder.decodeClose(message); + boolean spectrumOwned; + if (close.targetType() == 'S') { + SpectrumInterceptor.Plan closedPlan = spectrumStatements.remove(close.name()); + spectrumOwned = closedPlan != null; + if (closedPlan != null) { + abandonStatementPortals(closedPlan); + } + } else { + spectrumOwned = spectrumPortals.remove(close.name()) != null; + ExtendedSpectrumExchange.PortalCursor cursor = spectrumCursors.remove(close.name()); + if (cursor != null) { + // The portal is closed before the client exhausted it (fetch-size cursor abandoned + // mid-stream): the temp table has no other owner and would otherwise leak until the + // backend session ends, so drop it now. + runWithBackendOwned(() -> { + ExtendedSpectrumExchange.abandon(spectrumInterceptor, backend, cursor); + return true; + }); + } + } + if (spectrumOwned) { + // Parse/Bind for a spectrum-owned statement or portal never reached the real backend + // (they are synthesized locally, see handleParse/handleBind), so the backend has never + // heard of this name either: forwarding Close would draw a spurious "does not exist" error. + awaitPriorBackendResponses(); + write(client.getOutputStream(), backendFrame('3', EMPTY_BODY)); + return; + } ExtendedQuerySession.Mutation mutation = session.stageClose(close.targetType(), close.name()); coordinator.register(BackendResponseCoordinator.Operation.CLOSE, mutation); write(backendOut, message.toPacketBytes()); } + /** Closing a prepared statement also closes every portal created from it. */ + private void abandonStatementPortals(SpectrumInterceptor.Plan closedPlan) throws IOException { + List abandoned = new ArrayList<>(); + Iterator> portals = spectrumPortals.entrySet().iterator(); + while (portals.hasNext()) { + Map.Entry portal = portals.next(); + if (portal.getValue() == closedPlan) { + portals.remove(); + ExtendedSpectrumExchange.PortalCursor cursor = spectrumCursors.remove(portal.getKey()); + if (cursor != null) { + abandoned.add(cursor); + } + } + } + for (ExtendedSpectrumExchange.PortalCursor cursor : abandoned) { + runWithBackendOwned(() -> { + ExtendedSpectrumExchange.abandon(spectrumInterceptor, backend, cursor); + return true; + }); + } + } + private CopyStatementParser.S3Statement parseS3Statement(String sql) { try { return CopyStatementParser.parse(sql); @@ -311,6 +562,90 @@ public class RedshiftInterceptingBridge { out.flush(); } + private static byte[] commandComplete(String tag) { + return backendFrame('C', tag.getBytes(StandardCharsets.UTF_8)); + } + + private static byte[] readyForQuery(char status) { + return backendFrame('Z', new byte[]{(byte) status}); + } + + private static byte[] errorResponse(String sqlState, String message) { + ByteArrayOutputStream body = new ByteArrayOutputStream(); + body.write('S'); + writeCString(body, "ERROR"); + body.write('C'); + writeCString(body, sqlState); + body.write('M'); + writeCString(body, message == null ? "Spectrum statement failed" : message); + body.write(0); + return backendFrame('E', body.toByteArray()); + } + + private static byte[] backendFrame(char type, byte[] body) { + int length = body.length + 4; + byte[] frame = new byte[body.length + 5]; + frame[0] = (byte) type; + frame[1] = (byte) (length >>> 24); + frame[2] = (byte) (length >>> 16); + frame[3] = (byte) (length >>> 8); + frame[4] = (byte) length; + System.arraycopy(body, 0, frame, 5, body.length); + return frame; + } + + private static void writeCString(ByteArrayOutputStream out, String value) { + out.writeBytes(value.getBytes(StandardCharsets.UTF_8)); + out.write(0); + } + + private void writeSimpleSpectrumError(RuntimeException exception) throws IOException { + coordinator.register(BackendResponseCoordinator.Operation.SIMPLE_QUERY, null); + write(client.getOutputStream(), errorResponse(spectrumSqlState(exception), exception.getMessage())); + write(client.getOutputStream(), readyForQuery('I')); + coordinator.onBackendFrame('Z', new byte[]{'I'}); + } + + private void writeParseSpectrumError(RuntimeException exception) throws IOException { + session.clear(); + extendedSpectrumError = true; + awaitPriorBackendResponses(); + write(client.getOutputStream(), errorResponse(spectrumSqlState(exception), exception.getMessage())); + } + + /** + * Waits until any earlier pipelined backend query (such as a {@code BEGIN} dispatched by + * {@code setAutoCommit(false)}) has finished streaming its response to the client. This + * prevents synthesized Spectrum responses (e.g. {@code ParseComplete}, {@code BindComplete}, + * {@code RowDescription}) from racing and overtaking earlier backend responses on the wire. + */ + private void awaitPriorBackendResponses() throws IOException { + long deadlineNanos = System.nanoTime() + PUMP_PARK_WAIT_MS * 1_000_000L; + while (!pumpFinished) { + try { + if (coordinator.awaitIdle(PUMP_READ_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { + return; + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("Interrupted while waiting for prior backend responses", e); + } + if (System.nanoTime() >= deadlineNanos) { + throw new IOException("Backend did not go idle in time before local Spectrum response"); + } + } + } + + private static String spectrumSqlState(RuntimeException exception) { + if (exception instanceof SpectrumSqlException spectrumSqlException) { + return spectrumSqlException.sqlState(); + } + if (exception instanceof SpectrumReadException spectrumReadException) { + return spectrumReadException.sqlState(); + } + return "22023"; + } + /** * Take exclusive ownership of an idle backend at a wire-message boundary, run {@code exchange}, * then release it. Returns {@code false} if the backend could not be caught idle within diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java index 644b949701..0fafb683d5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator; import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates; import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator; import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumInterceptor; import io.quarkus.runtime.ShutdownEvent; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.event.Observes; @@ -30,6 +31,7 @@ public class RedshiftProxyManager { private final RdsProxyTlsCertificates tlsCertificates; private final S3Service s3Service; private final IamService iamService; + private final SpectrumInterceptor spectrumInterceptor; private final EmulatorConfig config; private final ConcurrentHashMap proxies = new ConcurrentHashMap<>(); /** @@ -40,13 +42,20 @@ public class RedshiftProxyManager { */ private final ConcurrentHashMap unclosableProxies = new ConcurrentHashMap<>(); - @Inject public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates, S3Service s3Service, IamService iamService, EmulatorConfig config) { + this(sigV4Validator, tlsCertificates, s3Service, iamService, config, null); + } + + @Inject + public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates, + S3Service s3Service, IamService iamService, EmulatorConfig config, + SpectrumInterceptor spectrumInterceptor) { this.sigV4Validator = sigV4Validator; this.tlsCertificates = tlsCertificates; this.s3Service = s3Service; this.iamService = iamService; + this.spectrumInterceptor = spectrumInterceptor; this.config = config; } @@ -75,7 +84,7 @@ public class RedshiftProxyManager { clusterAccountId, iamRoleArns, redshiftConfig.proxyHandshakeTimeoutMillis(), redshiftConfig.proxyBackendConnectTimeoutMillis(), - redshiftConfig.proxyMaxConnections()); + redshiftConfig.proxyMaxConnections(), spectrumInterceptor); try { proxy.start(proxyPort); } catch (IOException | RuntimeException e) { diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumCatalog.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumCatalog.java new file mode 100644 index 0000000000..69b0f38e5c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumCatalog.java @@ -0,0 +1,76 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.Resettable; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import jakarta.enterprise.context.ApplicationScoped; + +import java.util.Comparator; +import java.util.List; +import java.util.Optional; + +@ApplicationScoped +public class SpectrumCatalog implements Resettable { + + private final AccountAwareStorageBackend schemas; + private final AccountAwareStorageBackend tables; + + public SpectrumCatalog(StorageFactory storageFactory) { + schemas = storageFactory.create("redshift", "redshift-spectrum-schemas.json", + new TypeReference<>() {}); + tables = storageFactory.create("redshift", "redshift-spectrum-tables.json", + new TypeReference<>() {}); + } + + public synchronized void createSchema(SpectrumExternalSchema schema) { + String key = schemaKey(schema.accountId(), schema.databaseName(), schema.schemaName()); + if (schemas.getForAccount(schema.accountId(), key).isPresent()) { + throw new SpectrumSqlException("42P06", "Spectrum external schema already exists: " + schema.schemaName()); + } + schemas.putForAccount(schema.accountId(), key, schema); + schemas.flush(); + } + + public synchronized void createTable(SpectrumExternalTable table) { + String key = tableKey(table.accountId(), table.databaseName(), table.schemaName(), table.tableName()); + if (tables.getForAccount(table.accountId(), key).isPresent()) { + throw new SpectrumSqlException("42P07", "Spectrum external table already exists: " + table.tableName()); + } + tables.putForAccount(table.accountId(), key, table); + tables.flush(); + } + + public Optional schema(String accountId, String databaseName, String schemaName) { + return schemas.getForAccount(accountId, schemaKey(accountId, databaseName, schemaName)); + } + + public Optional table(String accountId, String databaseName, + String schemaName, String tableName) { + return tables.getForAccount(accountId, tableKey(accountId, databaseName, schemaName, tableName)); + } + + public List tablesForSchema(String accountId, String databaseName, String schemaName) { + String prefix = accountId + ":" + databaseName + ":" + schemaName + ":"; + return tables.scanForAccount(accountId, key -> key.startsWith(prefix)) + .stream() + .sorted(Comparator.comparing(SpectrumExternalTable::tableName)) + .toList(); + } + + @Override + public synchronized void clear() { + schemas.clear(); + tables.clear(); + schemas.flush(); + tables.flush(); + } + + private static String schemaKey(String accountId, String databaseName, String schemaName) { + return accountId + ":" + databaseName + ":" + schemaName; + } + + private static String tableKey(String accountId, String databaseName, String schemaName, String tableName) { + return accountId + ":" + databaseName + ":" + schemaName + ":" + tableName; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumColumn.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumColumn.java new file mode 100644 index 0000000000..5427eae299 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumColumn.java @@ -0,0 +1,92 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.Locale; + +@RegisterForReflection(targets = SpectrumColumn.Type.class) +public record SpectrumColumn(String name, Type type) { + + public SpectrumColumn { + if (name == null || name.isBlank()) { + throw new IllegalArgumentException("Spectrum column name is required"); + } + if (type == null) { + throw new IllegalArgumentException("Spectrum column type is required"); + } + if (!name.equals(name.trim())) { + throw new IllegalArgumentException("Spectrum column name must not contain surrounding whitespace"); + } + } + + @RegisterForReflection + public enum Type { + VARCHAR, + CHAR, + INTEGER, + BIGINT, + DECIMAL, + BOOLEAN, + DATE, + TIMESTAMP; + + public static Type fromSql(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Spectrum column type is required"); + } + String normalized = value.trim().toUpperCase(Locale.ROOT); + return switch (normalized) { + case "VARCHAR" -> VARCHAR; + case "CHAR" -> CHAR; + case "INTEGER", "INT" -> INTEGER; + case "BIGINT" -> BIGINT; + case "DECIMAL", "NUMERIC" -> DECIMAL; + case "BOOLEAN", "BOOL" -> BOOLEAN; + case "DATE" -> DATE; + case "TIMESTAMP" -> TIMESTAMP; + default -> throw new IllegalArgumentException("Unsupported Spectrum column type: " + value); + }; + } + + public String postgresType() { + return switch (this) { + case VARCHAR -> "VARCHAR"; + case CHAR -> "CHAR"; + case INTEGER -> "INTEGER"; + case BIGINT -> "BIGINT"; + case DECIMAL -> "DECIMAL"; + case BOOLEAN -> "BOOLEAN"; + case DATE -> "DATE"; + case TIMESTAMP -> "TIMESTAMP"; + }; + } + + /** + * The well-known PostgreSQL {@code pg_type} OID for this column's Postgres type, needed to + * synthesize a wire-accurate {@code RowDescription} for an Extended Query Describe response + * without a backend round trip. + */ + public int postgresTypeOid() { + return switch (this) { + case VARCHAR -> 1043; + case CHAR -> 1042; + case INTEGER -> 23; + case BIGINT -> 20; + case DECIMAL -> 1700; + case BOOLEAN -> 16; + case DATE -> 1082; + case TIMESTAMP -> 1114; + }; + } + + /** The fixed on-wire type length for this Postgres type, or {@code -1} for a variable-length type. */ + public short postgresTypeLength() { + return switch (this) { + case VARCHAR, CHAR, DECIMAL -> -1; + case INTEGER, DATE -> 4; + case BIGINT, TIMESTAMP -> 8; + case BOOLEAN -> 1; + }; + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumExternalSchema.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumExternalSchema.java new file mode 100644 index 0000000000..441600ccb0 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumExternalSchema.java @@ -0,0 +1,39 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public record SpectrumExternalSchema( + String accountId, + String databaseName, + String schemaName, + String location, + String iamRoleArn) { + + public SpectrumExternalSchema { + requireText(accountId, "accountId"); + requireText(databaseName, "databaseName"); + requireText(schemaName, "schemaName"); + validateS3Location(location); + if (iamRoleArn != null && iamRoleArn.isBlank()) { + throw new IllegalArgumentException("iamRoleArn must not be blank"); + } + } + + private static void requireText(String value, String field) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(field + " is required"); + } + } + + static void validateS3Location(String value) { + if (value == null || !value.startsWith("s3://") || value.length() <= "s3://".length()) { + throw new IllegalArgumentException("Spectrum location must be an s3:// URI"); + } + String path = value.substring("s3://".length()); + int slash = path.indexOf('/'); + if (slash <= 0 || slash == path.length() - 1) { + throw new IllegalArgumentException("Spectrum location must include a bucket and key or prefix"); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumExternalTable.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumExternalTable.java new file mode 100644 index 0000000000..194e45f694 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumExternalTable.java @@ -0,0 +1,55 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; + +@RegisterForReflection +public record SpectrumExternalTable( + String accountId, + String databaseName, + String schemaName, + String tableName, + List columns, + String location, + char delimiter, + char quote, + char escape, + String nullValue, + int headerLines) { + + public SpectrumExternalTable { + requireText(accountId, "accountId"); + requireText(databaseName, "databaseName"); + requireText(schemaName, "schemaName"); + requireText(tableName, "tableName"); + SpectrumExternalSchema.validateS3Location(location); + if (columns == null || columns.isEmpty()) { + throw new IllegalArgumentException("Spectrum external table requires columns"); + } + columns = List.copyOf(columns); + if (delimiter == '\0' || quote == '\0' || escape == '\0') { + throw new IllegalArgumentException("Spectrum CSV delimiters must be valid characters"); + } + if (nullValue == null) { + throw new IllegalArgumentException("Spectrum nullValue is required"); + } + if (headerLines < 0) { + throw new IllegalArgumentException("Spectrum headerLines must not be negative"); + } + for (int i = 0; i < columns.size(); i++) { + String left = columns.get(i).name(); + for (int j = i + 1; j < columns.size(); j++) { + if (left.equalsIgnoreCase(columns.get(j).name())) { + throw new IllegalArgumentException("Duplicate Spectrum column: " + left); + } + } + } + } + + private static void requireText(String value, String field) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(field + " is required"); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumInterceptor.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumInterceptor.java new file mode 100644 index 0000000000..13820d901b --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumInterceptor.java @@ -0,0 +1,121 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import jakarta.enterprise.context.ApplicationScoped; + +import java.net.Socket; +import java.util.Optional; + +@ApplicationScoped +public final class SpectrumInterceptor { + + private final SpectrumCatalog catalog; + private final SpectrumStatementParser statementParser; + private final SpectrumQueryClassifier queryClassifier; + private final SpectrumQueryRewriter queryRewriter; + private final SpectrumS3Reader reader; + private final SpectrumMaterializer materializer; + + public SpectrumInterceptor(SpectrumCatalog catalog, SpectrumStatementParser statementParser, + SpectrumQueryClassifier queryClassifier, SpectrumQueryRewriter queryRewriter, + SpectrumS3Reader reader, SpectrumMaterializer materializer) { + this.catalog = catalog; + this.statementParser = statementParser; + this.queryClassifier = queryClassifier; + this.queryRewriter = queryRewriter; + this.reader = reader; + this.materializer = materializer; + } + + public Decision intercept(String sql, String accountId, String databaseName, Socket backend) { + Plan plan = plan(sql, accountId, databaseName); + return execute(plan, accountId, databaseName, backend); + } + + public Plan plan(String sql, String accountId, String databaseName) { + Optional statement = statementParser.parse(sql); + if (statement.isPresent()) { + return new Plan.Ddl(statement.get()); + } + + Optional query = queryClassifier.classify(sql, 0); + if (query.isEmpty() || query.get().schemaName() == null) { + return new Plan.Forward(); + } + SpectrumQuery externalQuery = query.get(); + Optional table = catalog.table( + accountId, databaseName, externalQuery.schemaName(), externalQuery.tableName()); + if (table.isEmpty()) { + return new Plan.Forward(); + } + SpectrumExternalSchema schema = catalog.schema(accountId, databaseName, externalQuery.schemaName()) + .orElseThrow(() -> new SpectrumSqlException("0A000", "External schema is not defined")); + return new Plan.Query(externalQuery, table.get(), schema, materializer.nextIdentifier()); + } + + public Decision execute(Plan plan, String accountId, String databaseName, Socket backend) { + switch (plan) { + case Plan.Ddl(SpectrumStatement parsed) -> { + switch (parsed) { + case SpectrumStatement.CreateSchema schema -> catalog.createSchema(new SpectrumExternalSchema( + accountId, schema.databaseName(), schema.schemaName(), + "s3://spectrum/" + schema.schemaName() + "/", schema.iamRoleArn())); + case SpectrumStatement.CreateTable table -> catalog.createTable(new SpectrumExternalTable( + accountId, databaseName, table.schemaName(), table.tableName(), table.columns(), + table.location(), table.delimiter(), table.quote(), table.escape(), table.nullValue(), + table.headerLines())); + } + return new Decision.Handled(); + } + case Plan.Query(SpectrumQuery query, SpectrumExternalTable table, SpectrumExternalSchema schema, String identifier) -> { + SpectrumMaterializer.Materialization materialized = materializer.materialize(backend, table, schema, reader, identifier); + return new Decision.Rewritten(queryRewriter.rewrite(query, materialized.identifier()), materialized); + } + case Plan.Forward ignored -> { + return new Decision.Forward(); + } + } + } + + /** + * Drops the temp table a {@link Decision.Rewritten} materialized, once the client has finished + * reading its rows (or failed while doing so). + *

+ * This eager cleanup is used by execution paths that manage the query round-trip explicitly, such + * as the Extended Query path in {@code ExtendedSpectrumExchange}. Under the Simple Query protocol, + * the temp table is session-scoped (via PostgreSQL {@code CREATE TEMP TABLE}) and cleaned up when + * the connection terminates, avoiding race conditions with the streaming backend-to-client pump. + * Each query materializes its own table, so a long-lived or pooled connection holds one copy per + * query until it closes. + */ + public void cleanup(Socket backend, SpectrumMaterializer.Materialization materialization) { + materializer.cleanup(backend, materialization); + } + + public sealed interface Plan permits Plan.Ddl, Plan.Forward, Plan.Query { + record Ddl(SpectrumStatement statement) implements Plan { + } + + record Forward() implements Plan { + } + + record Query(SpectrumQuery query, SpectrumExternalTable table, SpectrumExternalSchema schema, + String identifier) implements Plan { + } + } + + public sealed interface Decision permits Decision.Handled, Decision.Forward, Decision.Rewritten { + record Handled() implements Decision { + } + + record Forward() implements Decision { + } + + /** + * A Spectrum query rewritten into an executable SQL statement querying a temporary table. + * The materialized table is dropped eagerly via {@link SpectrumInterceptor#cleanup} on the + * Extended Query protocol, or released at session termination on the Simple Query protocol. + */ + record Rewritten(String sql, SpectrumMaterializer.Materialization materialization) implements Decision { + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumMaterializer.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumMaterializer.java new file mode 100644 index 0000000000..5d38129689 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumMaterializer.java @@ -0,0 +1,221 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import jakarta.enterprise.context.ApplicationScoped; + +import io.github.hectorvent.floci.services.redshift.proxy.PostgresWireDecoder; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.HexFormat; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@ApplicationScoped +public final class SpectrumMaterializer { + + private static final SecureRandom RANDOM = new SecureRandom(); + private static final String SQLSTATE_DATA = "22000"; + + public Materialization materialize(Socket backend, SpectrumExternalTable table, + SpectrumExternalSchema schema, SpectrumS3Reader reader) { + return materialize(backend, table, schema, reader, nextIdentifier()); + } + + public Materialization materialize(Socket backend, SpectrumExternalTable table, + SpectrumExternalSchema schema, SpectrumS3Reader reader, String identifier) { + Materialization materialization = new Materialization(identifier, table.columns()); + OutputStream output = null; + boolean tableCreated = false; + boolean copyInProgress = false; + try { + output = backend.getOutputStream(); + sendQuery(output, createTableSql(identifier, table)); + awaitReady(backend); + tableCreated = true; + sendQuery(output, copySql(identifier, table)); + awaitCopyIn(backend); + copyInProgress = true; + try (Stream rows = reader.read(schema, table)) { + Iterator iterator = rows.iterator(); + while (iterator.hasNext()) { + writeCopyData(output, encodeRow(iterator.next())); + } + } + writeCopyDone(output); + copyInProgress = false; + awaitReady(backend); + return materialization; + } catch (SpectrumReadException exception) { + recoverFromFailure(backend, materialization, output, tableCreated, copyInProgress, exception); + throw exception; + } catch (IOException exception) { + SpectrumReadException readException = new SpectrumReadException( + SQLSTATE_DATA, "Unable to materialize Spectrum rows", exception); + recoverFromFailure(backend, materialization, output, tableCreated, copyInProgress, readException); + throw readException; + } + } + + public String nextIdentifier() { + return "spectrum_tmp_" + HexFormat.of().formatHex(randomBytes(12)); + } + + public void cleanup(Socket backend, Materialization materialization) { + try { + OutputStream output = backend.getOutputStream(); + sendQuery(output, "DROP TABLE IF EXISTS \"" + quoteIdentifier(materialization.identifier()) + "\""); + awaitReady(backend); + } catch (IOException exception) { + throw new SpectrumReadException(SQLSTATE_DATA, "Unable to clean up Spectrum materialization", exception); + } + } + + private static String createTableSql(String identifier, SpectrumExternalTable table) { + StringBuilder sql = new StringBuilder("CREATE TEMP TABLE \"") + .append(quoteIdentifier(identifier)).append("\" ("); + for (int i = 0; i < table.columns().size(); i++) { + if (i > 0) { + sql.append(", "); + } + SpectrumColumn column = table.columns().get(i); + sql.append('"').append(quoteIdentifier(column.name())).append("\" ").append(column.type().postgresType()); + } + return sql.append(')').toString(); + } + + private static String copySql(String identifier, SpectrumExternalTable table) { + return "COPY \"" + quoteIdentifier(identifier) + "\" (" + + table.columns().stream().map(column -> "\"" + quoteIdentifier(column.name()) + "\"") + .collect(Collectors.joining(", ")) + + ") FROM STDIN"; + } + + private static byte[] encodeRow(SpectrumRow row) { + StringBuilder line = new StringBuilder(); + for (int i = 0; i < row.values().size(); i++) { + if (i > 0) { + line.append('\t'); + } + String value = row.values().get(i); + if (value == null) { + line.append("\\N"); + } else { + line.append(value.replace("\\", "\\\\").replace("\t", "\\t") + .replace("\n", "\\n").replace("\r", "\\r")); + } + } + line.append('\n'); + return line.toString().getBytes(StandardCharsets.UTF_8); + } + + private static void sendQuery(OutputStream output, String sql) throws IOException { + output.write(PostgresWireDecoder.encodeQuery(sql)); + output.flush(); + } + + private static void writeCopyData(OutputStream output, byte[] data) throws IOException { + output.write('d'); + writeInt32(output, data.length + 4); + output.write(data); + } + + private static void writeCopyDone(OutputStream output) throws IOException { + output.write('c'); + writeInt32(output, 4); + output.flush(); + } + + private static void writeCopyFail(OutputStream output, String reason) throws IOException { + byte[] body = (reason == null ? "Spectrum row conversion failed" : reason).getBytes(StandardCharsets.UTF_8); + output.write('f'); + writeInt32(output, body.length + 5); + output.write(body); + output.write(0); + output.flush(); + } + + private static void writeInt32(OutputStream output, int value) throws IOException { + output.write((value >>> 24) & 0xFF); + output.write((value >>> 16) & 0xFF); + output.write((value >>> 8) & 0xFF); + output.write(value & 0xFF); + } + + private static void awaitCopyIn(Socket backend) throws IOException { + PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream()); + PostgresWireDecoder.FrontendMessage message; + SpectrumReadException backendFailure = null; + while ((message = decoder.nextMessage()) != null) { + if (message.type() == 'G') { + return; + } + if (message.type() == 'E') { + backendFailure = new SpectrumReadException(SQLSTATE_DATA, "PostgreSQL rejected Spectrum COPY"); + } + if (message.type() == 'Z' && backendFailure != null) { + throw backendFailure; + } + } + throw new IOException("PostgreSQL closed before CopyInResponse"); + } + + private static void awaitReady(Socket backend) throws IOException { + PostgresWireDecoder decoder = new PostgresWireDecoder(backend.getInputStream()); + PostgresWireDecoder.FrontendMessage message; + SpectrumReadException backendFailure = null; + while ((message = decoder.nextMessage()) != null) { + if (message.type() == 'Z') { + if (backendFailure != null) { + throw backendFailure; + } + return; + } + if (message.type() == 'E') { + backendFailure = new SpectrumReadException(SQLSTATE_DATA, "PostgreSQL rejected Spectrum statement"); + } + } + throw new IOException("PostgreSQL closed before ReadyForQuery"); + } + + private void recoverFromFailure(Socket backend, Materialization materialization, OutputStream output, + boolean tableCreated, boolean copyInProgress, + SpectrumReadException original) { + if (copyInProgress && output != null) { + try { + writeCopyFail(output, original.getMessage()); + awaitReady(backend); + } catch (IOException | SpectrumReadException cleanupFailure) { + original.addSuppressed(cleanupFailure); + } + } + if (tableCreated) { + try { + cleanup(backend, materialization); + } catch (RuntimeException cleanupFailure) { + original.addSuppressed(cleanupFailure); + } + } + } + + private static String quoteIdentifier(String value) { + return value.replace("\"", "\"\""); + } + + private static byte[] randomBytes(int length) { + byte[] bytes = new byte[length]; + RANDOM.nextBytes(bytes); + return bytes; + } + + public record Materialization(String identifier, List columns) { + public Materialization { + columns = List.copyOf(columns); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQuery.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQuery.java new file mode 100644 index 0000000000..4b5d8850e7 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQuery.java @@ -0,0 +1,9 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +public record SpectrumQuery( + String schemaName, + String tableName, + String projectionSql, + String predicateSql, + boolean selectStar) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryClassifier.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryClassifier.java new file mode 100644 index 0000000000..e8f4e5f9fc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryClassifier.java @@ -0,0 +1,120 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import jakarta.enterprise.context.ApplicationScoped; + +import java.util.Locale; +import java.util.Optional; + +@ApplicationScoped +public final class SpectrumQueryClassifier { + + public Optional classify(String sql, int parameterCount) { + String normalized = sql == null ? "" : sql.trim(); + if (!startsWithKeyword(normalized, "SELECT")) { + return Optional.empty(); + } + if (parameterCount > 0 || containsOutsideQuotes(normalized, '?')) { + return Optional.empty(); + } + String statement = stripTrailingSemicolon(normalized); + if (statement.indexOf(';') >= 0 || hasParenthesesOutsideQuotes(statement)) { + return Optional.empty(); + } + String lower = statement.toLowerCase(Locale.ROOT); + for (String keyword : new String[]{" join ", " group ", " order ", " having ", " union ", " intersect ", + " except ", " limit ", " offset ", " distinct "}) { + if (lower.contains(keyword)) { + return Optional.empty(); + } + } + int from = keywordIndex(statement, "from", 6); + if (from < 0) { + return Optional.empty(); + } + String projection = statement.substring(6, from).trim(); + if (projection.isEmpty() || projection.contains(",") && projection.contains("(")) { + return Optional.empty(); + } + String source = statement.substring(from + 4).trim(); + int where = keywordIndex(source, "where", 0); + String tablePart = where < 0 ? source : source.substring(0, where).trim(); + String predicate = where < 0 ? null : source.substring(where + 5).trim(); + if (!isIdentifierPath(tablePart) || (predicate != null && !simplePredicate(predicate))) { + return Optional.empty(); + } + String[] identifiers = tablePart.split("\\.", -1); + String schema = identifiers.length == 2 ? identifier(identifiers[0]) : null; + String table = identifier(identifiers[identifiers.length - 1]); + boolean star = "*".equals(projection); + if (!star && !isProjection(projection)) { + return Optional.empty(); + } + return Optional.of(new SpectrumQuery(schema, table, projection, predicate, star)); + } + + private static boolean simplePredicate(String predicate) { + String lower = predicate.toLowerCase(Locale.ROOT); + return !lower.contains(" or ") && !lower.contains(" in ") && !lower.contains(" like ") + && !lower.contains(" is ") && predicate.matches("[\\w\\\".]+\\s*(=|<>|!=|<=|>=|<|>)\\s*('[^']*(?:''[^']*)*'|-?\\d+(?:\\.\\d+)?)" + + "(?:\\s+AND\\s+[\\w\\\".]+\\s*(?:=|<>|!=|<=|>=|<|>)\\s*(?:'[^']*(?:''[^']*)*'|-?\\d+(?:\\.\\d+)?))*"); + } + + private static boolean isProjection(String projection) { + for (String part : projection.split(",")) { + if (!isIdentifierPath(part.trim())) { + return false; + } + } + return true; + } + + private static boolean isIdentifierPath(String value) { + return value.matches("(?:[A-Za-z_][A-Za-z0-9_$]*|\"(?:\"\"|[^\"])+\")(?:\\.(?:[A-Za-z_][A-Za-z0-9_$]*|\"(?:\"\"|[^\"])+\")){0,1}"); + } + + private static String identifier(String value) { + String trimmed = value.trim(); + if (trimmed.startsWith("\"") && trimmed.endsWith("\"")) { + return trimmed.substring(1, trimmed.length() - 1).replace("\"\"", "\""); + } + return trimmed.toLowerCase(Locale.ROOT); + } + + private static int keywordIndex(String sql, String keyword, int start) { + String lower = sql.toLowerCase(Locale.ROOT); + for (int i = start; i <= lower.length() - keyword.length(); i++) { + if (lower.regionMatches(i, keyword, 0, keyword.length()) + && (i == 0 || Character.isWhitespace(lower.charAt(i - 1))) + && (i + keyword.length() == lower.length() || Character.isWhitespace(lower.charAt(i + keyword.length())))) { + return i; + } + } + return -1; + } + + private static boolean startsWithKeyword(String sql, String keyword) { + return sql.regionMatches(true, 0, keyword, 0, keyword.length()) + && (sql.length() == keyword.length() || Character.isWhitespace(sql.charAt(keyword.length()))); + } + + private static String stripTrailingSemicolon(String sql) { + return sql.endsWith(";") ? sql.substring(0, sql.length() - 1).trim() : sql; + } + + private static boolean containsOutsideQuotes(String sql, char target) { + boolean quoted = false; + for (int i = 0; i < sql.length(); i++) { + char current = sql.charAt(i); + if (current == '\'') { + quoted = !quoted; + } else if (!quoted && current == target) { + return true; + } + } + return false; + } + + private static boolean hasParenthesesOutsideQuotes(String sql) { + return containsOutsideQuotes(sql, '(') || containsOutsideQuotes(sql, ')'); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryRewriter.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryRewriter.java new file mode 100644 index 0000000000..259e2426db --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryRewriter.java @@ -0,0 +1,58 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import jakarta.enterprise.context.ApplicationScoped; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +@ApplicationScoped +public final class SpectrumQueryRewriter { + + public SpectrumQueryRewriter() { + } + + public static String rewrite(SpectrumQuery query, String materializedIdentifier) { + if (materializedIdentifier == null || materializedIdentifier.isBlank()) { + throw new IllegalArgumentException("materializedIdentifier is required"); + } + String projection = query.selectStar() ? "*" : query.projectionSql(); + StringBuilder sql = new StringBuilder("SELECT ").append(projection) + .append(" FROM \"").append(materializedIdentifier.replace("\"", "\"\"")) + .append('"'); + if (query.predicateSql() != null && !query.predicateSql().isBlank()) { + sql.append(" WHERE ").append(query.predicateSql()); + } + return sql.toString(); + } + + /** + * The columns {@code query} projects from {@code table}, in output order. {@link SpectrumQueryClassifier} + * only ever accepts {@code *} or a comma-separated list of plain (optionally schema-qualified) + * identifiers as a projection, so this is a complete, exact mapping, not a heuristic: it is what + * an Extended Query Describe response is built from without a backend round trip. + */ + public static List outputColumns(SpectrumQuery query, SpectrumExternalTable table) { + if (query.selectStar()) { + return table.columns(); + } + List columns = new ArrayList<>(); + for (String part : query.projectionSql().split(",")) { + String name = normalizeIdentifier(part.trim()); + columns.add(table.columns().stream() + .filter(column -> column.name().equalsIgnoreCase(name)) + .findFirst() + .orElseThrow(() -> new SpectrumSqlException("42703", + "column \"" + name + "\" does not exist on external table"))); + } + return columns; + } + + private static String normalizeIdentifier(String value) { + String local = value.substring(value.lastIndexOf('.') + 1); + if (local.length() >= 2 && local.startsWith("\"") && local.endsWith("\"")) { + return local.substring(1, local.length() - 1).replace("\"\"", "\""); + } + return local.toLowerCase(Locale.ROOT); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumReadException.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumReadException.java new file mode 100644 index 0000000000..55aebc20e8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumReadException.java @@ -0,0 +1,20 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +public class SpectrumReadException extends RuntimeException { + + private final String sqlState; + + public SpectrumReadException(String sqlState, String message) { + super(message); + this.sqlState = sqlState; + } + + public SpectrumReadException(String sqlState, String message, Throwable cause) { + super(message, cause); + this.sqlState = sqlState; + } + + public String sqlState() { + return sqlState; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumRow.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumRow.java new file mode 100644 index 0000000000..6dc72c2429 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumRow.java @@ -0,0 +1,12 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public record SpectrumRow(List values) { + + public SpectrumRow { + values = Collections.unmodifiableList(new ArrayList<>(values)); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumS3Reader.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumS3Reader.java new file mode 100644 index 0000000000..aff800e436 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumS3Reader.java @@ -0,0 +1,275 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +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 io.github.hectorvent.floci.services.s3.model.S3Object; +import jakarta.enterprise.context.ApplicationScoped; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Spliterators; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +@ApplicationScoped +public final class SpectrumS3Reader { + + private static final String SQLSTATE_AUTHORIZATION = "42501"; + private static final String SQLSTATE_DATA = "22000"; + private static final String SQLSTATE_INTERNAL = "XX000"; + + private final S3Service s3Service; + // Stored in the schema now so role-aware Spectrum authorization can be added without changing metadata. + @SuppressWarnings("unused") + private final IamService iamService; + + public SpectrumS3Reader(S3Service s3Service, IamService iamService) { + this.s3Service = s3Service; + this.iamService = iamService; + } + + public Stream read(SpectrumExternalSchema schema, SpectrumExternalTable table) { + Location location = Location.parse(table.location()); + try { + s3Service.authorizeAnonymousListBucket(location.bucket()); + List objects = new ArrayList<>(); + String continuationToken = null; + do { + S3Service.ListObjectsResult result = s3Service.listObjectsWithPrefixes( + location.bucket(), location.key(), "", 1000, continuationToken, null); + objects.addAll(result.objects()); + continuationToken = result.isTruncated() ? result.nextContinuationToken() : null; + } while (continuationToken != null); + List keys = objects.stream() + .map(S3Object::getKey) + .sorted(Comparator.naturalOrder()) + .toList(); + return StreamSupport.stream(Spliterators.spliteratorUnknownSize( + new RowIterator(location.bucket(), keys.iterator(), table), 0), false); + } catch (AwsException exception) { + throw mapAwsException(location, exception); + } + } + + private SpectrumReadException mapAwsException(Location location, AwsException exception) { + String state = switch (exception.getErrorCode()) { + case "AccessDenied", "Unauthorized", "Forbidden" -> SQLSTATE_AUTHORIZATION; + default -> SQLSTATE_INTERNAL; + }; + return new SpectrumReadException(state, + "Unable to read Spectrum location " + location.uri(), exception); + } + + private final class RowIterator implements Iterator { + private final String bucket; + private final Iterator keys; + private final SpectrumExternalTable table; + private BufferedReader reader; + private SpectrumRow next; + private boolean finished; + private String currentKey; + + private RowIterator(String bucket, Iterator keys, SpectrumExternalTable table) { + this.bucket = bucket; + this.keys = keys; + this.table = table; + } + + @Override + public boolean hasNext() { + if (next == null && !finished) { + advance(); + } + return next != null; + } + + @Override + public SpectrumRow next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + SpectrumRow result = next; + next = null; + return result; + } + + private void advance() { + try { + while (true) { + if (reader == null) { + if (!keys.hasNext()) { + finished = true; + return; + } + currentKey = keys.next(); + s3Service.authorizeAnonymousGetObject(bucket, currentKey); + S3Object object = s3Service.getObject(bucket, currentKey); + reader = new BufferedReader(new InputStreamReader( + new ByteArrayInputStream(object.getData()), StandardCharsets.UTF_8)); + skipHeaders(); + } + String record = readRecord(reader, table.quote(), table.escape()); + if (record == null) { + reader.close(); + reader = null; + continue; + } + if (record.isEmpty()) { + continue; + } + next = convert(record, table); + return; + } + } catch (AwsException exception) { + throw mapAwsException(new Location(bucket, currentKey), exception); + } catch (IOException exception) { + throw new SpectrumReadException(SQLSTATE_INTERNAL, "Unable to close Spectrum object", exception); + } + } + + private void skipHeaders() throws IOException { + for (int i = 0; i < table.headerLines(); i++) { + if (readRecord(reader, table.quote(), table.escape()) == null) { + return; + } + } + } + } + + private static SpectrumRow convert(String record, SpectrumExternalTable table) { + List fields = parseFields(record, table.delimiter(), table.quote(), table.escape()); + if (fields.size() != table.columns().size()) { + throw new SpectrumReadException(SQLSTATE_DATA, + "Spectrum row has " + fields.size() + " fields, expected " + table.columns().size()); + } + List converted = new ArrayList<>(fields.size()); + for (int i = 0; i < fields.size(); i++) { + String value = fields.get(i); + converted.add(value.equals(table.nullValue()) ? null : convertValue(value, table.columns().get(i).type())); + } + return new SpectrumRow(converted); + } + + private static String convertValue(String value, SpectrumColumn.Type type) { + try { + return switch (type) { + case VARCHAR, CHAR -> value; + case INTEGER -> Integer.toString(Integer.parseInt(value)); + case BIGINT -> Long.toString(Long.parseLong(value)); + case DECIMAL -> new BigDecimal(value).toString(); + case BOOLEAN -> parseBoolean(value); + case DATE -> LocalDate.parse(value).toString(); + case TIMESTAMP -> parseTimestamp(value); + }; + } catch (NumberFormatException | DateTimeParseException exception) { + throw new SpectrumReadException(SQLSTATE_DATA, "Invalid " + type + " value", exception); + } + } + + private static String parseBoolean(String value) { + if ("true".equalsIgnoreCase(value)) { + return "true"; + } + if ("false".equalsIgnoreCase(value)) { + return "false"; + } + throw new SpectrumReadException(SQLSTATE_DATA, "Invalid BOOLEAN value"); + } + + private static String parseTimestamp(String value) { + try { + return LocalDateTime.parse(value).toString(); + } catch (DateTimeParseException ignored) { + return OffsetDateTime.parse(value).toLocalDateTime().toString(); + } + } + + private static List parseFields(String record, char delimiter, char quote, char escape) { + List fields = new ArrayList<>(); + StringBuilder field = new StringBuilder(); + boolean quoted = false; + for (int i = 0; i < record.length(); i++) { + char current = record.charAt(i); + if (current == escape && quoted && i + 1 < record.length()) { + field.append(record.charAt(++i)); + } else if (current == quote) { + if (quoted && i + 1 < record.length() && record.charAt(i + 1) == quote) { + field.append(quote); + i++; + } else { + quoted = !quoted; + } + } else if (current == delimiter && !quoted) { + fields.add(field.toString()); + field.setLength(0); + } else { + field.append(current); + } + } + if (quoted) { + throw new SpectrumReadException(SQLSTATE_DATA, "Unterminated quoted CSV field"); + } + fields.add(field.toString()); + return fields; + } + + private static String readRecord(BufferedReader reader, char quote, char escape) throws IOException { + StringBuilder record = new StringBuilder(); + boolean quoted = false; + int value; + while ((value = reader.read()) != -1) { + char current = (char) value; + if (current == escape && !quoted) { + record.append(current); + int next = reader.read(); + if (next == -1) { + break; + } + record.append((char) next); + } else if (current == quote) { + quoted = !quoted; + record.append(current); + } else if (current == '\n' && !quoted) { + break; + } else if (current != '\r') { + record.append(current); + } + } + if (value == -1 && record.isEmpty()) { + return null; + } + return record.toString(); + } + + private record Location(String bucket, String key) { + private static Location parse(String uri) { + if (uri == null || !uri.startsWith("s3://")) { + throw new SpectrumReadException(SQLSTATE_INTERNAL, "Spectrum location must use s3://"); + } + String path = uri.substring(5); + int slash = path.indexOf('/'); + if (slash <= 0) { + throw new SpectrumReadException(SQLSTATE_INTERNAL, "Spectrum location must include a bucket and key"); + } + return new Location(path.substring(0, slash), path.substring(slash + 1)); + } + + private String uri() { + return "s3://" + bucket + "/" + key; + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumSqlException.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumSqlException.java new file mode 100644 index 0000000000..e4693e309d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumSqlException.java @@ -0,0 +1,15 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +public class SpectrumSqlException extends RuntimeException { + + private final String sqlState; + + public SpectrumSqlException(String sqlState, String message) { + super(message); + this.sqlState = sqlState; + } + + public String sqlState() { + return sqlState; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumStatement.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumStatement.java new file mode 100644 index 0000000000..36e4f619e9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumStatement.java @@ -0,0 +1,25 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import java.util.List; + +public sealed interface SpectrumStatement permits SpectrumStatement.CreateSchema, SpectrumStatement.CreateTable { + + record CreateSchema(String schemaName, String databaseName, String iamRoleArn) implements SpectrumStatement { + } + + record CreateTable( + String schemaName, + String tableName, + List columns, + String location, + char delimiter, + char quote, + char escape, + String nullValue, + int headerLines) implements SpectrumStatement { + + public CreateTable { + columns = List.copyOf(columns); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumStatementParser.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumStatementParser.java new file mode 100644 index 0000000000..3bb5107a94 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumStatementParser.java @@ -0,0 +1,330 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import jakarta.enterprise.context.ApplicationScoped; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +@ApplicationScoped +public final class SpectrumStatementParser { + + private static final String UNSUPPORTED = "0A000"; + private static final String INVALID_VALUE = "22023"; + + public Optional parse(String sql) { + List tokens = new Tokenizer(sql).tokenize(); + Cursor cursor = new Cursor(tokens); + if (cursor.peekKeyword("CREATE") && cursor.peekKeyword(1, "EXTERNAL") && cursor.peekKeyword(2, "SCHEMA")) { + return Optional.of(parseSchema(cursor)); + } + if (cursor.peekKeyword("CREATE") && cursor.peekKeyword(1, "EXTERNAL") && cursor.peekKeyword(2, "TABLE")) { + return Optional.of(parseTable(cursor)); + } + if (cursor.peekKeyword("CREATE") && cursor.peekKeyword(1, "EXTERNAL")) { + throw unsupported("unsupported CREATE EXTERNAL statement"); + } + return Optional.empty(); + } + + private SpectrumStatement.CreateSchema parseSchema(Cursor cursor) { + cursor.expectKeyword("CREATE"); + cursor.expectKeyword("EXTERNAL"); + cursor.expectKeyword("SCHEMA"); + String schema = cursor.identifier(); + cursor.expectKeyword("FROM"); + cursor.expectKeyword("DATA"); + cursor.expectKeyword("CATALOG"); + cursor.expectKeyword("DATABASE"); + String database = cursor.stringLiteral(); + cursor.expectKeyword("IAM_ROLE"); + String role = cursor.stringLiteral(); + if (cursor.peekKeyword("CREATE")) { + cursor.expectKeyword("CREATE"); + cursor.expectKeyword("EXTERNAL"); + cursor.expectKeyword("DATABASE"); + cursor.expectKeyword("IF"); + cursor.expectKeyword("NOT"); + cursor.expectKeyword("EXISTS"); + } + cursor.finish(); + return new SpectrumStatement.CreateSchema(schema, database, role); + } + + private SpectrumStatement.CreateTable parseTable(Cursor cursor) { + cursor.expectKeyword("CREATE"); + cursor.expectKeyword("EXTERNAL"); + cursor.expectKeyword("TABLE"); + String schema = cursor.identifier(); + cursor.expectSymbol('.'); + String table = cursor.identifier(); + cursor.expectSymbol('('); + List columns = new ArrayList<>(); + while (!cursor.peekSymbol(')')) { + String name = cursor.identifier(); + String type = cursor.identifier(); + try { + columns.add(new SpectrumColumn(name, SpectrumColumn.Type.fromSql(type))); + } catch (IllegalArgumentException exception) { + throw new SpectrumSqlException(INVALID_VALUE, exception.getMessage()); + } + if (!cursor.consumeSymbol(',')) { + break; + } + } + cursor.expectSymbol(')'); + cursor.expectKeyword("STORED"); + cursor.expectKeyword("AS"); + if (!cursor.consumeKeyword("TEXTFILE")) { + throw unsupported("only STORED AS TEXTFILE is supported"); + } + cursor.expectKeyword("LOCATION"); + String location = cursor.stringLiteral(); + String nullValue = "\\N"; + char delimiter = ','; + char quote = '"'; + char escape = '\\'; + int headerLines = 0; + if (cursor.consumeKeyword("TBLPROPERTIES")) { + cursor.expectSymbol('('); + Map properties = new HashMap<>(); + while (!cursor.peekSymbol(')')) { + String name = cursor.stringLiteral(); + cursor.expectSymbol('='); + String value = cursor.stringLiteral(); + if (properties.put(name, value) != null) { + throw unsupported("duplicate Spectrum table property: " + name); + } + if (!SetOfProperties.SUPPORTED.contains(name)) { + throw unsupported("unsupported Spectrum table property: " + name); + } + if (!cursor.consumeSymbol(',')) { + break; + } + } + cursor.expectSymbol(')'); + try { + if (properties.containsKey("skip.header.line.count")) { + headerLines = Integer.parseInt(properties.get("skip.header.line.count")); + if (headerLines < 0) { + throw new IllegalArgumentException("skip.header.line.count must not be negative"); + } + } + delimiter = oneCharacter(properties, "field.delim", delimiter); + char serialization = oneCharacter(properties, "serialization.format", delimiter); + if (properties.containsKey("field.delim") && properties.containsKey("serialization.format") + && serialization != delimiter) { + throw new IllegalArgumentException("field.delim and serialization.format must match"); + } + delimiter = serialization; + quote = oneCharacter(properties, "quoteChar", quote); + escape = oneCharacter(properties, "escapeChar", escape); + nullValue = properties.getOrDefault("serialization.null.format", nullValue); + } catch (IllegalArgumentException exception) { + throw new SpectrumSqlException(INVALID_VALUE, exception.getMessage()); + } + } + cursor.finish(); + try { + SpectrumExternalSchema.validateS3Location(location); + } catch (IllegalArgumentException exception) { + throw new SpectrumSqlException(INVALID_VALUE, exception.getMessage()); + } + return new SpectrumStatement.CreateTable(schema, table, columns, location, delimiter, quote, escape, nullValue, + headerLines); + } + + private static char oneCharacter(Map properties, String name, char defaultValue) { + String value = properties.get(name); + if (value == null) { + return defaultValue; + } + if (value.length() != 1) { + throw new IllegalArgumentException(name + " must contain exactly one character"); + } + return value.charAt(0); + } + + private static SpectrumSqlException unsupported(String message) { + return new SpectrumSqlException(UNSUPPORTED, message); + } + + private static final class SetOfProperties { + private static final Set SUPPORTED = Set.of( + "skip.header.line.count", "field.delim", "serialization.format", "quoteChar", "escapeChar", + "serialization.null.format"); + + private SetOfProperties() { + } + } + + private record Token(Kind kind, String text, boolean quoted) { + private enum Kind { IDENTIFIER, STRING, SYMBOL, END } + } + + private static final class Cursor { + private final List tokens; + private int position; + + private Cursor(List tokens) { + this.tokens = tokens; + } + + private boolean peekKeyword(String value) { + return peekKeyword(0, value); + } + + private boolean peekKeyword(int offset, String value) { + Token token = tokens.get(Math.min(position + offset, tokens.size() - 1)); + return token.kind() == Token.Kind.IDENTIFIER && !token.quoted() + && token.text().equalsIgnoreCase(value); + } + + private boolean consumeKeyword(String value) { + if (!peekKeyword(value)) { + return false; + } + position++; + return true; + } + + private void expectKeyword(String value) { + if (!consumeKeyword(value)) { + throw unsupported("expected keyword " + value); + } + } + + private String identifier() { + Token token = current(); + if (token.kind() != Token.Kind.IDENTIFIER) { + throw unsupported("expected identifier"); + } + position++; + return token.text(); + } + + private String stringLiteral() { + Token token = current(); + if (token.kind() != Token.Kind.STRING) { + throw unsupported("expected string literal"); + } + position++; + return token.text(); + } + + private void expectSymbol(char symbol) { + if (!consumeSymbol(symbol)) { + throw unsupported("expected symbol " + symbol); + } + } + + private boolean consumeSymbol(char symbol) { + Token token = current(); + if (token.kind() == Token.Kind.SYMBOL && token.text().charAt(0) == symbol) { + position++; + return true; + } + return false; + } + + private boolean peekSymbol(char symbol) { + Token token = current(); + return token.kind() == Token.Kind.SYMBOL && token.text().charAt(0) == symbol; + } + + private void finish() { + if (consumeSymbol(';')) { + if (current().kind() != Token.Kind.END) { + throw unsupported("trailing SQL is not supported"); + } + return; + } + if (current().kind() != Token.Kind.END) { + throw unsupported("trailing SQL is not supported"); + } + } + + private Token current() { + return tokens.get(position); + } + } + + private static final class Tokenizer { + private final String sql; + private int position; + + private Tokenizer(String sql) { + this.sql = sql == null ? "" : sql; + } + + private List tokenize() { + List tokens = new ArrayList<>(); + while (position < sql.length()) { + char current = sql.charAt(position); + if (Character.isWhitespace(current)) { + position++; + } else if (current == '-' && position + 1 < sql.length() && sql.charAt(position + 1) == '-') { + skipComment(); + } else if (current == '\'') { + tokens.add(new Token(Token.Kind.STRING, readQuoted('\''), true)); + } else if (current == '"') { + tokens.add(new Token(Token.Kind.IDENTIFIER, readQuoted('"'), true)); + } else if (isSymbol(current)) { + tokens.add(new Token(Token.Kind.SYMBOL, String.valueOf(current), false)); + position++; + } else { + tokens.add(new Token(Token.Kind.IDENTIFIER, readIdentifier(), false)); + } + } + tokens.add(new Token(Token.Kind.END, "", false)); + return tokens; + } + + private void skipComment() { + position += 2; + while (position < sql.length() && sql.charAt(position) != '\n') { + position++; + } + } + + private String readQuoted(char delimiter) { + position++; + StringBuilder value = new StringBuilder(); + while (position < sql.length()) { + char current = sql.charAt(position++); + if (current == delimiter) { + if (position < sql.length() && sql.charAt(position) == delimiter) { + value.append(delimiter); + position++; + } else { + return value.toString(); + } + } else { + value.append(current); + } + } + throw unsupported("unterminated quoted value"); + } + + private String readIdentifier() { + int start = position; + while (position < sql.length()) { + char current = sql.charAt(position); + if (Character.isWhitespace(current) || isSymbol(current) || current == '\'') { + break; + } + position++; + } + String value = sql.substring(start, position); + return value.toLowerCase(Locale.ROOT); + } + + private static boolean isSymbol(char value) { + return value == '(' || value == ')' || value == ',' || value == '.' || value == ';' || value == '='; + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index d56daeb328..cc819ebd0c 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -109,6 +109,7 @@ quarkus: - --initialize-at-run-time=io.github.hectorvent.floci.services.ecs.container.EcsTaskRoleCredentials - --initialize-at-run-time=io.github.hectorvent.floci.services.ssoportal.SsoPortalService - --initialize-at-run-time=io.github.hectorvent.floci.services.redshift.proxy.S3CopySimulator + - --initialize-at-run-time=io.github.hectorvent.floci.services.redshift.spectrum.SpectrumMaterializer - --initialize-at-run-time=io.github.hectorvent.floci.services.ecs.exec.EcsExecSessionRegistry # snappy-java (Firehose Snappy/HADOOP_SNAPPY delivery) extracts and loads a # bundled JNI library from the static initializers of these two classes. diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumIntegrationTest.java new file mode 100644 index 0000000000..4a82ef3a37 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumIntegrationTest.java @@ -0,0 +1,196 @@ +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.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class RedshiftSpectrumIntegrationTest { + + @Inject + RedshiftService redshiftService; + + @Inject + S3Service s3Service; + + private String clusterId; + private String bucket; + + @BeforeAll + static void requireDocker() { + Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for Redshift Spectrum integration tests"); + } + + private static boolean isDockerAvailable() { + try { + Process process = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}") + .redirectErrorStream(true) + .start(); + int exit = process.waitFor(); + return exit == 0; + } catch (Exception ignored) { + return false; + } + } + + @AfterEach + void cleanUp() { + if (clusterId != null) { + redshiftService.deleteCluster(clusterId); + } + if (bucket != null) { + s3Service.deleteObject(bucket, "events/part-1.csv"); + s3Service.deleteObject(bucket, "invalid/part-1.csv"); + s3Service.deleteBucket(bucket); + } + } + + @Test + @Timeout(60) + void queriesCsvExternalTableThroughRedshiftWireProxy() throws SQLException { + bucket = "spectrum-it-" + System.nanoTime(); + s3Service.createBucket(bucket, "us-east-1"); + s3Service.putObject(bucket, "events/part-1.csv", + "id,name\n1,Alice\n2,Bob\n".getBytes(StandardCharsets.UTF_8), "text/csv", null); + clusterId = "it-spectrum-" + System.nanoTime(); + Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123"); + + try (Connection connection = waitForConnection(cluster, "admin", "Secret123"); + Statement statement = connection.createStatement()) { + statement.execute("CREATE EXTERNAL SCHEMA analytics FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'"); + SQLException duplicateSchema = assertThrows(SQLException.class, () -> statement.execute( + "CREATE EXTERNAL SCHEMA analytics FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'")); + assertEquals("42P06", duplicateSchema.getSQLState()); + statement.execute("CREATE EXTERNAL TABLE analytics.events (id INTEGER, name VARCHAR) " + + "STORED AS TEXTFILE LOCATION 's3://" + bucket + "/events/' " + + "TBLPROPERTIES ('skip.header.line.count'='1')"); + try (ResultSet rows = statement.executeQuery("SELECT id, name FROM analytics.events")) { + assertTrue(rows.next()); + assertEquals(1, rows.getInt("id")); + assertEquals("Alice", rows.getString("name")); + assertTrue(rows.next()); + assertEquals(2, rows.getInt("id")); + assertEquals("Bob", rows.getString("name")); + assertTrue(!rows.next()); + } + s3Service.putObject(bucket, "invalid/part-1.csv", "invalid,Bad\n".getBytes(StandardCharsets.UTF_8), + "text/csv", null); + statement.execute("CREATE EXTERNAL TABLE analytics.invalid_events (id INTEGER, name VARCHAR) " + + "STORED AS TEXTFILE LOCATION 's3://" + bucket + "/invalid/'"); + SQLException invalidRow = assertThrows(SQLException.class, + () -> statement.executeQuery("SELECT * FROM analytics.invalid_events")); + assertEquals("22000", invalidRow.getSQLState()); + try (ResultSet healthCheck = statement.executeQuery("SELECT 1")) { + assertTrue(healthCheck.next()); + assertEquals(1, healthCheck.getInt(1)); + } + } + } + + @Test + @Timeout(60) + void queriesCsvExternalTableThroughExtendedQueryProtocol() throws SQLException { + bucket = "spectrum-it-ext-" + System.nanoTime(); + s3Service.createBucket(bucket, "us-east-1"); + s3Service.putObject(bucket, "events/part-1.csv", + "id,name\n1,Alice\n2,Bob\n".getBytes(StandardCharsets.UTF_8), "text/csv", null); + clusterId = "it-spectrum-ext-" + System.nanoTime(); + Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123"); + + String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort() + + "/dev?socketTimeout=20&loginTimeout=20"; + try (Connection connection = Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO) + .pollInterval(Duration.ofMillis(500)).ignoreExceptions() + .until(() -> DriverManager.getConnection(url, "admin", "Secret123"), Objects::nonNull); + Statement setup = connection.createStatement()) { + setup.execute("CREATE EXTERNAL SCHEMA analytics_ext FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'"); + setup.execute("CREATE EXTERNAL TABLE analytics_ext.events (id INTEGER, name VARCHAR) " + + "STORED AS TEXTFILE LOCATION 's3://" + bucket + "/events/' " + + "TBLPROPERTIES ('skip.header.line.count'='1')"); + // Phase 1 does not support bind-parameterized Spectrum predicates (SpectrumQueryClassifier + // rejects them), so this exercises Extended Query with a literal predicate: pgjdbc still + // uses Parse/Bind/Describe/Execute/Sync for PreparedStatement even without a '?'. + try (java.sql.PreparedStatement prepared = connection.prepareStatement( + "SELECT id, name FROM analytics_ext.events WHERE id = 1")) { + // Forces pgjdbc to send Describe('S', ...) (Describe Statement, not just Describe + // Portal): the response must be ParameterDescription followed by RowDescription/NoData. + assertEquals(0, prepared.getParameterMetaData().getParameterCount()); + try (ResultSet rows = prepared.executeQuery()) { + assertTrue(rows.next()); + assertEquals(1, rows.getInt("id")); + assertEquals("Alice", rows.getString("name")); + assertTrue(!rows.next()); + } + } + } + } + + @Test + @Timeout(60) + void pagesSpectrumRowsAcrossMultipleExecutesWhenFetchSizeIsSet() throws SQLException { + bucket = "spectrum-it-fetch-" + System.nanoTime(); + s3Service.createBucket(bucket, "us-east-1"); + s3Service.putObject(bucket, "events/part-1.csv", + "id,name\n1,Alice\n2,Bob\n3,Carol\n4,Dave\n5,Eve\n".getBytes(StandardCharsets.UTF_8), + "text/csv", null); + clusterId = "it-spectrum-fetch-" + System.nanoTime(); + Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123"); + + String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort() + + "/dev?socketTimeout=20&loginTimeout=20"; + try (Connection connection = Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO) + .pollInterval(Duration.ofMillis(500)).ignoreExceptions() + .until(() -> DriverManager.getConnection(url, "admin", "Secret123"), Objects::nonNull); + Statement setup = connection.createStatement()) { + setup.execute("CREATE EXTERNAL SCHEMA analytics_fetch FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'"); + setup.execute("CREATE EXTERNAL TABLE analytics_fetch.events (id INTEGER, name VARCHAR) " + + "STORED AS TEXTFILE LOCATION 's3://" + bucket + "/events/' " + + "TBLPROPERTIES ('skip.header.line.count'='1')"); + + // Fetch size only becomes a real server-side cursor (Execute with maxRows > 0, answered + // with PortalSuspended) in pgjdbc when autoCommit is off. + connection.setAutoCommit(false); + try (java.sql.PreparedStatement prepared = connection.prepareStatement( + "SELECT id, name FROM analytics_fetch.events")) { + prepared.setFetchSize(2); + List ids = new ArrayList<>(); + try (ResultSet rows = prepared.executeQuery()) { + while (rows.next()) { + ids.add(rows.getInt("id")); + } + } + assertEquals(List.of(1, 2, 3, 4, 5), ids); + } + connection.commit(); + } + } + + private static Connection waitForConnection(Cluster cluster, String username, String password) throws SQLException { + String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort() + "/dev"; + return Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO) + .pollInterval(Duration.ofMillis(500)).ignoreExceptions() + .until(() -> DriverManager.getConnection(url, username, password), Objects::nonNull); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumCatalogTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumCatalogTest.java new file mode 100644 index 0000000000..ddd2ff831a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumCatalogTest.java @@ -0,0 +1,92 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class SpectrumCatalogTest { + + private static final String ACCOUNT = "000000000000"; + private SpectrumCatalog catalog; + + @BeforeEach + void setUp() { + StorageFactory factory = mock(StorageFactory.class); + when(factory.create(eq("redshift"), eq("redshift-spectrum-schemas.json"), any(TypeReference.class))) + .thenReturn(AccountAwareStorageBackend.inMemory(ACCOUNT)); + when(factory.create(eq("redshift"), eq("redshift-spectrum-tables.json"), any(TypeReference.class))) + .thenReturn(AccountAwareStorageBackend.inMemory(ACCOUNT)); + catalog = new SpectrumCatalog(factory); + } + + @Test + void createsAndLooksUpExternalSchema() { + SpectrumExternalSchema schema = new SpectrumExternalSchema( + ACCOUNT, "dev", "analytics", "s3://warehouse/root/", null); + + catalog.createSchema(schema); + + assertEquals(java.util.Optional.of(schema), catalog.schema(ACCOUNT, "dev", "analytics")); + } + + @Test + void createsAndListsExternalTablesInStableNameOrder() { + SpectrumExternalTable second = table("zebra"); + SpectrumExternalTable first = table("alpha"); + + catalog.createTable(second); + catalog.createTable(first); + + assertEquals(List.of(first, second), catalog.tablesForSchema(ACCOUNT, "dev", "analytics")); + } + + @Test + void rejectsDuplicateTableAndDuplicateColumnNames() { + catalog.createTable(table("events")); + + SpectrumSqlException duplicate = assertThrows(SpectrumSqlException.class, + () -> catalog.createTable(table("events"))); + assertEquals("42P07", duplicate.sqlState()); + assertThrows(IllegalArgumentException.class, () -> new SpectrumExternalTable( + ACCOUNT, "dev", "analytics", "duplicate", + List.of(new SpectrumColumn("id", SpectrumColumn.Type.BIGINT), + new SpectrumColumn("id", SpectrumColumn.Type.VARCHAR)), + "s3://warehouse/events/", ',', '"', '\\', "\\N", 0)); + } + + @Test + void isolatesLookupsByAccountAndClearsState() { + SpectrumExternalTable table = table("events"); + catalog.createTable(table); + + assertTrue(catalog.table("111111111111", "dev", "analytics", "events").isEmpty()); + catalog.clear(); + assertTrue(catalog.tablesForSchema(ACCOUNT, "dev", "analytics").isEmpty()); + } + + @Test + void validatesLocationAndColumnType() { + assertThrows(IllegalArgumentException.class, () -> new SpectrumExternalSchema( + ACCOUNT, "dev", "analytics", "https://example.invalid/data", null)); + assertThrows(IllegalArgumentException.class, () -> new SpectrumColumn("id", null)); + } + + private static SpectrumExternalTable table(String name) { + return new SpectrumExternalTable( + ACCOUNT, "dev", "analytics", name, + List.of(new SpectrumColumn("id", SpectrumColumn.Type.BIGINT)), + "s3://warehouse/events/", ',', '"', '\\', "\\N", 1); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumInterceptorTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumInterceptorTest.java new file mode 100644 index 0000000000..bc397bf366 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumInterceptorTest.java @@ -0,0 +1,74 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.net.Socket; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class SpectrumInterceptorTest { + + private SpectrumCatalog catalog; + private SpectrumMaterializer materializer; + private SpectrumInterceptor interceptor; + + @BeforeEach + void setUp() { + catalog = mock(SpectrumCatalog.class); + materializer = mock(SpectrumMaterializer.class); + interceptor = new SpectrumInterceptor(catalog, new SpectrumStatementParser(), new SpectrumQueryClassifier(), + null, mock(SpectrumS3Reader.class), materializer); + } + + @Test + void storesExternalSchemaAndTableDdl() { + SpectrumInterceptor.Decision schema = interceptor.intercept( + "CREATE EXTERNAL SCHEMA analytics FROM DATA CATALOG DATABASE 'dev' IAM_ROLE 'role'", + "000000000000", "dev", null); + SpectrumInterceptor.Decision table = interceptor.intercept( + "CREATE EXTERNAL TABLE analytics.events (id INTEGER) STORED AS TEXTFILE LOCATION 's3://b/events/'", + "000000000000", "dev", null); + + assertInstanceOf(SpectrumInterceptor.Decision.Handled.class, schema); + assertInstanceOf(SpectrumInterceptor.Decision.Handled.class, table); + } + + @Test + void forwardsLocalQueryAndRewritesCatalogResolvedExternalQuery() { + SpectrumExternalTable table = new SpectrumExternalTable("000000000000", "dev", "analytics", "events", + List.of(new SpectrumColumn("id", SpectrumColumn.Type.INTEGER)), "s3://b/events/", ',', '"', '\\', "\\N", 0); + SpectrumExternalSchema schema = new SpectrumExternalSchema("000000000000", "dev", "analytics", + "s3://b/root/", null); + SpectrumMaterializer.Materialization materialization = new SpectrumMaterializer.Materialization( + "spectrum_tmp_x", table.columns()); + when(catalog.table("000000000000", "dev", "analytics", "events")).thenReturn(java.util.Optional.of(table)); + when(catalog.schema("000000000000", "dev", "analytics")).thenReturn(java.util.Optional.of(schema)); + when(materializer.nextIdentifier()).thenReturn("spectrum_tmp_x"); + when(materializer.materialize(any(), any(), any(), any(), eq("spectrum_tmp_x"))).thenReturn(materialization); + + assertInstanceOf(SpectrumInterceptor.Decision.Forward.class, + interceptor.intercept("SELECT * FROM local.events", "000000000000", "dev", null)); + SpectrumInterceptor.Decision decision = interceptor.intercept( + "SELECT * FROM analytics.events", "000000000000", "dev", null); + SpectrumInterceptor.Decision.Rewritten rewritten = assertInstanceOf( + SpectrumInterceptor.Decision.Rewritten.class, decision); + assertEquals("SELECT * FROM \"spectrum_tmp_x\"", rewritten.sql()); + } + + @Test + void delegatesCleanupToMaterializer() { + Socket backend = mock(Socket.class); + SpectrumMaterializer.Materialization materialization = new SpectrumMaterializer.Materialization( + "spectrum_tmp_x", List.of()); + interceptor.cleanup(backend, materialization); + verify(materializer).cleanup(backend, materialization); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumMaterializerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumMaterializerTest.java new file mode 100644 index 0000000000..9c633066e7 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumMaterializerTest.java @@ -0,0 +1,110 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Arrays; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class SpectrumMaterializerTest { + + @Test + void materializesRowsWithGeneratedIdentifierAndCopyFraming() throws Exception { + try (ServerSocket listener = new ServerSocket(0); Socket backend = new Socket("localhost", listener.getLocalPort())) { + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future captured = executor.submit(() -> serve(listener)); + SpectrumS3Reader reader = mock(SpectrumS3Reader.class); + when(reader.read(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) + .thenReturn(Stream.of(new SpectrumRow(Arrays.asList("1", null)), new SpectrumRow(List.of("two", "x")))); + SpectrumExternalTable table = new SpectrumExternalTable("000000000000", "dev", "analytics", "events", + List.of(new SpectrumColumn("id", SpectrumColumn.Type.INTEGER), + new SpectrumColumn("value", SpectrumColumn.Type.VARCHAR)), + "s3://warehouse/events/", ',', '"', '\\', "\\N", 0); + + SpectrumMaterializer.Materialization materialization = new SpectrumMaterializer() + .materialize(backend, table, null, reader); + new SpectrumMaterializer().cleanup(backend, materialization); + + byte[] copy = captured.get(); + assertTrue(materialization.identifier().startsWith("spectrum_tmp_")); + assertFalse(materialization.identifier().contains("events")); + assertTrue(new String(copy, StandardCharsets.UTF_8).contains("1\t\\N\ntwo\tx\n")); + executor.shutdownNow(); + } + } + + private static byte[] serve(ServerSocket listener) throws IOException { + try (Socket socket = listener.accept()) { + InputStream input = socket.getInputStream(); + OutputStream output = socket.getOutputStream(); + ByteArrayOutputStream copyRows = new ByteArrayOutputStream(); + readQuery(input); + send(output, 'C', "CREATE 0\0".getBytes(StandardCharsets.UTF_8)); + send(output, 'Z', new byte[]{'I'}); + readQuery(input); + send(output, 'G', new byte[]{0, 0, 0}); + while (true) { + Frame frame = readFrame(input); + if (frame.type() == 'c') { + break; + } + if (frame.type() == 'd') { + copyRows.write(frame.body()); + } + } + send(output, 'C', "COPY 2\0".getBytes(StandardCharsets.UTF_8)); + send(output, 'Z', new byte[]{'I'}); + readQuery(input); + send(output, 'C', "DROP TABLE\0".getBytes(StandardCharsets.UTF_8)); + send(output, 'Z', new byte[]{'I'}); + return copyRows.toByteArray(); + } + } + + private static void readQuery(InputStream input) throws IOException { + Frame frame = readFrame(input); + if (frame.type() != 'Q') { + throw new IOException("expected query"); + } + } + + private static Frame readFrame(InputStream input) throws IOException { + int type = input.read(); + if (type < 0) { + throw new IOException("unexpected EOF"); + } + byte[] length = input.readNBytes(4); + int size = ((length[0] & 0xff) << 24) | ((length[1] & 0xff) << 16) + | ((length[2] & 0xff) << 8) | (length[3] & 0xff); + return new Frame((char) type, input.readNBytes(size - 4)); + } + + private static void send(OutputStream output, char type, byte[] body) throws IOException { + int size = body.length + 4; + output.write(type); + output.write((size >>> 24) & 0xff); + output.write((size >>> 16) & 0xff); + output.write((size >>> 8) & 0xff); + output.write(size & 0xff); + output.write(body); + output.flush(); + } + + private record Frame(char type, byte[] body) { + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryClassifierTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryClassifierTest.java new file mode 100644 index 0000000000..0ee21c6c8f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryClassifierTest.java @@ -0,0 +1,41 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SpectrumQueryClassifierTest { + + private final SpectrumQueryClassifier classifier = new SpectrumQueryClassifier(); + + @Test + void classifiesProjectionAndSimplePredicates() { + SpectrumQuery query = classifier.classify( + "SELECT id, name FROM analytics.events WHERE id >= 2 AND name <> 'x'", 0).orElseThrow(); + + assertEquals("analytics", query.schemaName()); + assertEquals("events", query.tableName()); + assertEquals("id, name", query.projectionSql()); + assertEquals("id >= 2 AND name <> 'x'", query.predicateSql()); + } + + @Test + void classifiesSelectStarAndReturnsEmptyForNonSelectSql() { + SpectrumQuery query = classifier.classify("SELECT * FROM events", 0).orElseThrow(); + assertTrue(query.selectStar()); + assertTrue(classifier.classify("SHOW TABLES", 0).isEmpty()); + assertTrue(classifier.classify("SELECT 1", 0).isEmpty()); + } + + @Test + void rejectsParametersAndUnsupportedExternalShapes() { + assertTrue(classifier.classify("SELECT * FROM analytics.events", 1).isEmpty()); + assertTrue(classifier.classify( + "SELECT * FROM analytics.events JOIN analytics.users ON events.id = users.id", 0).isEmpty()); + assertTrue(classifier.classify( + "SELECT count(*) FROM analytics.events", 0).isEmpty()); + assertTrue(classifier.classify( + "SELECT * FROM analytics.events; SELECT 1", 0).isEmpty()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryRewriterTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryRewriterTest.java new file mode 100644 index 0000000000..2ede55967e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumQueryRewriterTest.java @@ -0,0 +1,18 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SpectrumQueryRewriterTest { + + @Test + void rewritesOnlyTheSourceTableAndQuotesGeneratedIdentifier() { + SpectrumQuery query = new SpectrumQuery("analytics", "events", "id, name", "id >= 2 AND name <> 'x'", false); + + assertEquals("SELECT id, name FROM \"spectrum_tmp_abc\" WHERE id >= 2 AND name <> 'x'", + SpectrumQueryRewriter.rewrite(query, "spectrum_tmp_abc")); + assertEquals("SELECT * FROM \"tmp\"\"unsafe\"", SpectrumQueryRewriter.rewrite( + new SpectrumQuery("analytics", "events", "*", null, true), "tmp\"unsafe")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumS3ReaderTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumS3ReaderTest.java new file mode 100644 index 0000000000..a9e6034c52 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumS3ReaderTest.java @@ -0,0 +1,122 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.s3.model.S3Object; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class SpectrumS3ReaderTest { + + @Test + void readsCsvRowsWithHeadersNullsAndTypes() { + S3Service s3 = mock(S3Service.class); + S3Object data = object("events/data.csv", "" + + "id,name,active,amount,date\n" + + "1,alice,true,12.50,2026-01-02\n" + + "2,\\N,false,3.00,2026-01-03\n"); + when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null)) + .thenReturn(new S3Service.ListObjectsResult(List.of(data), List.of(), false, null)); + when(s3.getObject("warehouse", "events/data.csv")).thenReturn(data); + SpectrumExternalTable table = new SpectrumExternalTable("000000000000", "dev", "analytics", "events", + List.of( + new SpectrumColumn("id", SpectrumColumn.Type.INTEGER), + new SpectrumColumn("name", SpectrumColumn.Type.VARCHAR), + new SpectrumColumn("active", SpectrumColumn.Type.BOOLEAN), + new SpectrumColumn("amount", SpectrumColumn.Type.DECIMAL), + new SpectrumColumn("date", SpectrumColumn.Type.DATE)), + "s3://warehouse/events/", ',', '"', '\\', "\\N", 1); + + List rows = new SpectrumS3Reader(s3, null).read(schema(), table).toList(); + + assertEquals(List.of( + new SpectrumRow(List.of("1", "alice", "true", "12.50", "2026-01-02")), + new SpectrumRow(Arrays.asList("2", null, "false", "3.00", "2026-01-03"))), rows); + } + + @Test + void readsPrefixObjectsInSortedKeyOrder() { + S3Service s3 = mock(S3Service.class); + S3Object z = object("events/z.csv", "z\n"); + S3Object a = object("events/a.csv", "a\n"); + when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null)) + .thenReturn(new S3Service.ListObjectsResult(List.of(z, a), List.of(), false, null)); + when(s3.getObject("warehouse", "events/z.csv")).thenReturn(z); + when(s3.getObject("warehouse", "events/a.csv")).thenReturn(a); + SpectrumExternalTable table = table(SpectrumColumn.Type.VARCHAR); + + List rows = new SpectrumS3Reader(s3, null).read(schema(), table).toList(); + + assertEquals(List.of(new SpectrumRow(List.of("a")), new SpectrumRow(List.of("z"))), rows); + } + + @Test + void rejectsRowWidthAndTypeConversionErrors() { + S3Service s3 = mock(S3Service.class); + S3Object data = object("events/data.csv", "bad,extra\n"); + when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null)) + .thenReturn(new S3Service.ListObjectsResult(List.of(data), List.of(), false, null)); + when(s3.getObject("warehouse", "events/data.csv")).thenReturn(data); + SpectrumExternalTable table = new SpectrumExternalTable("000000000000", "dev", "analytics", "events", + List.of(new SpectrumColumn("id", SpectrumColumn.Type.INTEGER)), + "s3://warehouse/events/", ',', '"', '\\', "\\N", 0); + + assertThrows(SpectrumReadException.class, () -> new SpectrumS3Reader(s3, null).read(schema(), table).toList()); + } + + @Test + void pagesThroughMoreThanOneThousandObjects() { + S3Service s3 = mock(S3Service.class); + S3Object first = object("events/000.csv", "1\n"); + S3Object second = object("events/001.csv", "2\n"); + when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null)) + .thenReturn(new S3Service.ListObjectsResult(List.of(first), List.of(), true, "page-2")); + when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, "page-2", null)) + .thenReturn(new S3Service.ListObjectsResult(List.of(second), List.of(), false, null)); + when(s3.getObject("warehouse", "events/000.csv")).thenReturn(first); + when(s3.getObject("warehouse", "events/001.csv")).thenReturn(second); + SpectrumExternalTable table = table(SpectrumColumn.Type.VARCHAR); + + List rows = new SpectrumS3Reader(s3, null).read(schema(), table).toList(); + + assertEquals(List.of(new SpectrumRow(List.of("1")), new SpectrumRow(List.of("2"))), rows); + } + + @Test + void mapsDeniedGetObjectToAuthorizationSqlState() { + S3Service s3 = mock(S3Service.class); + S3Object data = object("events/data.csv", "value\n"); + when(s3.listObjectsWithPrefixes("warehouse", "events/", "", 1000, null, null)) + .thenReturn(new S3Service.ListObjectsResult(List.of(data), List.of(), false, null)); + doThrow(new AwsException("AccessDenied", "Access Denied", 403)) + .when(s3).authorizeAnonymousGetObject("warehouse", "events/data.csv"); + SpectrumExternalTable table = table(SpectrumColumn.Type.VARCHAR); + + SpectrumReadException exception = assertThrows(SpectrumReadException.class, + () -> new SpectrumS3Reader(s3, null).read(schema(), table).toList()); + + assertEquals("42501", exception.sqlState()); + } + + private static SpectrumExternalSchema schema() { + return new SpectrumExternalSchema("000000000000", "dev", "analytics", "s3://warehouse/root/", null); + } + + private static SpectrumExternalTable table(SpectrumColumn.Type type) { + return new SpectrumExternalTable("000000000000", "dev", "analytics", "events", + List.of(new SpectrumColumn("value", type)), "s3://warehouse/events/", ',', '"', '\\', "\\N", 0); + } + + private static S3Object object(String key, String content) { + return new S3Object("warehouse", key, content.getBytes(StandardCharsets.UTF_8), "text/csv"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumSqlParserTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumSqlParserTest.java new file mode 100644 index 0000000000..ad5d87f685 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/SpectrumSqlParserTest.java @@ -0,0 +1,82 @@ +package io.github.hectorvent.floci.services.redshift.spectrum; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SpectrumSqlParserTest { + + private final SpectrumStatementParser parser = new SpectrumStatementParser(); + + @Test + void parsesExternalSchemaAndNormalizesUnquotedIdentifiers() { + SpectrumStatement statement = parser.parse( + "CREATE EXTERNAL SCHEMA Analytics FROM DATA CATALOG DATABASE 'warehouse' IAM_ROLE 'arn:aws:iam::000000000000:role/Reader'") + .orElseThrow(); + + SpectrumStatement.CreateSchema schema = assertInstanceOf(SpectrumStatement.CreateSchema.class, statement); + assertEquals("analytics", schema.schemaName()); + assertEquals("warehouse", schema.databaseName()); + assertEquals("arn:aws:iam::000000000000:role/Reader", schema.iamRoleArn()); + } + + @Test + void parsesQuotedIdentifiersEscapedLiteralsAndCsvProperties() { + SpectrumStatement statement = parser.parse("" + + "-- define the table\n" + + "CREATE EXTERNAL TABLE \"Sales\".\"Order\"\"Items\" (" + + "order_id BIGINT, description VARCHAR, active BOOLEAN, created DATE) " + + "STORED AS TEXTFILE LOCATION 's3://bucket/a''b/' " + + "TBLPROPERTIES (" + + "'skip.header.line.count'='1', 'field.delim'='|', " + + "'serialization.format'='|', 'quoteChar'='\"', 'escapeChar'='\\', " + + "'serialization.null.format'='NULL')").orElseThrow(); + + SpectrumStatement.CreateTable table = assertInstanceOf(SpectrumStatement.CreateTable.class, statement); + assertEquals("Sales", table.schemaName()); + assertEquals("Order\"Items", table.tableName()); + assertEquals(List.of( + new SpectrumColumn("order_id", SpectrumColumn.Type.BIGINT), + new SpectrumColumn("description", SpectrumColumn.Type.VARCHAR), + new SpectrumColumn("active", SpectrumColumn.Type.BOOLEAN), + new SpectrumColumn("created", SpectrumColumn.Type.DATE)), table.columns()); + assertEquals("s3://bucket/a'b/", table.location()); + assertEquals('|', table.delimiter()); + assertEquals('"', table.quote()); + assertEquals('\\', table.escape()); + assertEquals("NULL", table.nullValue()); + assertEquals(1, table.headerLines()); + } + + @Test + void acceptsOptionalExternalDatabaseClauseAndTrailingSemicolon() { + SpectrumStatement statement = parser.parse( + "CREATE EXTERNAL SCHEMA s FROM DATA CATALOG DATABASE 'db' IAM_ROLE 'role' " + + "CREATE EXTERNAL DATABASE IF NOT EXISTS;").orElseThrow(); + + SpectrumStatement.CreateSchema schema = assertInstanceOf(SpectrumStatement.CreateSchema.class, statement); + assertEquals("s", schema.schemaName()); + } + + @Test + void returnsEmptyForNonSpectrumSql() { + assertTrue(parser.parse("SELECT 1").isEmpty()); + } + + @Test + void rejectsTrailingStatementsDuplicatePropertiesAndUnsupportedFormat() { + assertThrows(SpectrumSqlException.class, () -> parser.parse( + "CREATE EXTERNAL SCHEMA s FROM DATA CATALOG DATABASE 'db' IAM_ROLE 'role'; SELECT 1")); + assertThrows(SpectrumSqlException.class, () -> parser.parse( + "CREATE EXTERNAL TABLE s.t (id INTEGER) STORED AS PARQUET LOCATION 's3://b/p'")); + assertThrows(SpectrumSqlException.class, () -> parser.parse( + "CREATE EXTERNAL TABLE s.t (id INTEGER) STORED AS TEXTFILE LOCATION 's3://b/p' " + + "TBLPROPERTIES ('field.delim'=',', 'field.delim'='|')")); + assertThrows(SpectrumSqlException.class, () -> parser.parse("CREATE EXTERNAL VIEW v AS SELECT 1")); + } +}