mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(redshift-data): emulate the Amazon Redshift Data API (#3186)
* feat(redshift-data): resource resolver, connection factory, statement store, service registration * feat(redshift-data): field mapper, column metadata, SQL parameter binding * feat(redshift-data): execute, describe, and paged result retrieval * feat(redshift-data): batch execution, list statements, cancel * feat(redshift-data): schema introspection operations * test(redshift-data): end-to-end Data API over a real cluster plus SDK compatibility test * docs(redshift-data): document the Redshift Data API surface * fix(redshift-data): address code review findings - rejectMultiStatement now reuses the SQL tokenizer so a semicolon inside a comment, string literal, or dollar-quoted block no longer rejects a valid single statement - GetStatementResultV2 gains unit coverage for the typed and CSV envelopes - CSV output is RFC 4180 quoted (embedded comma, quote, CR, LF) - batch rollback is asserted transactionally in the integration test - RedshiftDataFieldMapper logs a swallowed blob-read SQLException - RedshiftPid/RedshiftQueryId use a non-negative hash - NextToken that decodes to a negative offset is rejected - CancelStatement leaves a FAILED statement FAILED - DescribeTable paginates ColumnList and emits NextToken - DbUser is echoed on the SecretArn path - the statement store no longer builds its sweeper executor in the test constructor * fix(redshift-data): address PR #3186 review findings - SQL scanner handles PostgreSQL escape strings (E'...'): a backslash-escaped quote no longer ends the literal and mis-detects a following :name as a bind marker; plain '...' literals still treat backslash as an ordinary character - ListStatements clamps MaxResults to 1..100 so MaxResults=0 no longer emits the same NextToken forever - DescribeTable matches Table / Schema exactly (=) instead of LIKE, so a name containing _ or % cannot merge other tables' columns into ColumnList - register the service in the README category table - drop a stray em dash from the neighbouring services.yaml comment * fix(redshift-data): bind string parameters untyped so real PostgreSQL infers the column type CI ran the integration test against a real Redshift (PostgreSQL 15) cluster and parameterisedStatement failed: a string bound to an int column via setString raised "operator does not exist: integer = character varying". H2 in PostgreSQL mode coerces it, so the unit test missed it. - RedshiftDataConnectionFactory adds stringtype=unspecified to the JDBC URL, so setString sends the value untyped and the server infers the target type, matching how AWS binds Redshift Data API parameters - ListStatements now rejects MaxResults above 100 with ValidationException instead of silently clamping (PR #3186 re-review) - RedshiftDataOperationsTest uses JBoss Logging, not java.util.logging (PR #3186 re-review) * fix(redshift-data): back the statement store with StorageFactory The store held a bare ConcurrentHashMap outside the configured storage and lifecycle model. It now obtains an account-aware backend through StorageFactory ("redshift-data", statements.json), the same as Athena's query store, resolved to the global storage mode via the catalog descriptor. Default mode stays memory, so statements are still lost on restart as documented; the 24h TTL sweep now walks every account partition and deletes per account since the sweep thread has no request context. StoredStatement is annotated for reflection and field-visible serialization so persistent modes round-trip it. * test(redshift-data): cover StoredStatement serialization round-trip and values() The StorageFactory-backed store serializes StoredStatement in persistent modes. Adds a round-trip test through the exact mapper PersistentStorage builds, covering the ArrayNode, enum, Instant, and nested sub-statement fields plus the field-visibility annotation, and a values() test. * fix(redshift-data): register the nested Status enum for reflection PersistedModelReflectionTest walks every type reachable from a StorageFactory persistence root; StoredStatement.status pointed at an unregistered enum, so native-image deserialization of a persisted statement would fail on restart.
This commit is contained in:
1 parent
618f52e758
commit
b9039fef1d
30 files changed
+2805
-3
No files matched your search
@@ -631,6 +631,7 @@ public interface EmulatorConfig {
|
||||
RdsServiceConfig rds();
|
||||
RedshiftServiceConfig redshift();
|
||||
RdsDataServiceConfig rdsData();
|
||||
RedshiftDataServiceConfig redshiftData();
|
||||
EventBridgeServiceConfig eventbridge();
|
||||
CloudMapServiceConfig cloudmap();
|
||||
EmrServiceConfig emr();
|
||||
@@ -1263,6 +1264,14 @@ public interface EmulatorConfig {
|
||||
long transactionTtlSeconds();
|
||||
}
|
||||
|
||||
interface RedshiftDataServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@WithDefault("24")
|
||||
int resultTtlHours();
|
||||
}
|
||||
|
||||
interface NeptuneServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectReader;
|
||||
import io.github.hectorvent.floci.services.acm.AcmJsonHandler;
|
||||
import io.github.hectorvent.floci.services.athena.AthenaJsonHandler;
|
||||
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataJsonHandler;
|
||||
import io.github.hectorvent.floci.services.cloudhsmv2.CloudHsmV2JsonHandler;
|
||||
import io.github.hectorvent.floci.services.codebuild.CodeBuildJsonHandler;
|
||||
import io.github.hectorvent.floci.services.codedeploy.CodeDeployJsonHandler;
|
||||
@@ -98,6 +99,7 @@ public class AwsJson11Controller {
|
||||
private final EcrJsonHandler ecrJsonHandler;
|
||||
private final GlueJsonHandler glueJsonHandler;
|
||||
private final AthenaJsonHandler athenaJsonHandler;
|
||||
private final RedshiftDataJsonHandler redshiftDataJsonHandler;
|
||||
private final FirehoseJsonHandler firehoseJsonHandler;
|
||||
private final ResourceGroupsTaggingJsonHandler resourceGroupsTaggingJsonHandler;
|
||||
private final CodeBuildJsonHandler codeBuildJsonHandler;
|
||||
@@ -147,6 +149,7 @@ public class AwsJson11Controller {
|
||||
AcmJsonHandler acmJsonHandler, EcsJsonHandler ecsJsonHandler,
|
||||
EcrJsonHandler ecrJsonHandler, GlueJsonHandler glueJsonHandler,
|
||||
AthenaJsonHandler athenaJsonHandler,
|
||||
RedshiftDataJsonHandler redshiftDataJsonHandler,
|
||||
FirehoseJsonHandler firehoseJsonHandler,
|
||||
ResourceGroupsTaggingJsonHandler resourceGroupsTaggingJsonHandler,
|
||||
CodeBuildJsonHandler codeBuildJsonHandler,
|
||||
@@ -200,6 +203,7 @@ public class AwsJson11Controller {
|
||||
this.ecrJsonHandler = ecrJsonHandler;
|
||||
this.glueJsonHandler = glueJsonHandler;
|
||||
this.athenaJsonHandler = athenaJsonHandler;
|
||||
this.redshiftDataJsonHandler = redshiftDataJsonHandler;
|
||||
this.firehoseJsonHandler = firehoseJsonHandler;
|
||||
this.resourceGroupsTaggingJsonHandler = resourceGroupsTaggingJsonHandler;
|
||||
this.codeBuildJsonHandler = codeBuildJsonHandler;
|
||||
@@ -283,6 +287,7 @@ public class AwsJson11Controller {
|
||||
case "ecr" -> ecrJsonHandler.handle(action, request, region);
|
||||
case "glue" -> glueJsonHandler.handle(action, request, region);
|
||||
case "athena" -> athenaJsonHandler.handle(action, request, region);
|
||||
case "redshift-data" -> redshiftDataJsonHandler.handle(action, request, region);
|
||||
case "firehose" -> firehoseJsonHandler.handle(action, request, region);
|
||||
case "tagging" -> resourceGroupsTaggingJsonHandler.handle(action, request, region);
|
||||
case "codebuild" -> codeBuildJsonHandler.handle(action, request, region, regionResolver.getAccountId());
|
||||
|
||||
@@ -167,7 +167,12 @@ public class ResolvedServiceCatalog {
|
||||
5000L, AwsNamespaces.REDSHIFT, ServiceProtocol.QUERY,
|
||||
protocols(ServiceProtocol.QUERY),
|
||||
Set.of(), Set.of("redshift"), Set.of(), Set.of()),
|
||||
|
||||
descriptor("redshift-data", "redshift-data",
|
||||
config.services().redshift().enabled() && config.services().redshiftData().enabled(), true,
|
||||
"redshift-data", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
Set.of("RedshiftData."), Set.of("redshift-data"), Set.of(), Set.of()),
|
||||
|
||||
descriptor("events", "eventbridge", config.services().eventbridge().enabled(), true,
|
||||
"eventbridge", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Maps JDBC {@link ResultSetMetaData} onto the Redshift Data API
|
||||
* {@code ColumnMetadata} shape. Every documented field is emitted for each
|
||||
* column; {@code label} matters as much as {@code name} because AWS clients
|
||||
* commonly hydrate rows by the result-set label.
|
||||
*/
|
||||
final class RedshiftDataColumnMetadata {
|
||||
|
||||
private RedshiftDataColumnMetadata() {
|
||||
}
|
||||
|
||||
static ArrayNode toColumnMetadata(ObjectMapper om, ResultSetMetaData meta) throws SQLException {
|
||||
ArrayNode columns = om.createArrayNode();
|
||||
for (int i = 1; i <= meta.getColumnCount(); i++) {
|
||||
columns.add(column(om, meta, i));
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
|
||||
private static ObjectNode column(ObjectMapper om, ResultSetMetaData meta, int i) throws SQLException {
|
||||
String name = orEmpty(meta.getColumnName(i));
|
||||
String label = orEmpty(meta.getColumnLabel(i));
|
||||
ObjectNode column = om.createObjectNode();
|
||||
column.put("name", firstNonBlank(name, label));
|
||||
column.put("label", firstNonBlank(label, name));
|
||||
column.put("typeName", orEmpty(meta.getColumnTypeName(i)));
|
||||
column.put("nullable", meta.isNullable(i));
|
||||
column.put("length", meta.getColumnDisplaySize(i));
|
||||
column.put("precision", meta.getPrecision(i));
|
||||
column.put("scale", meta.getScale(i));
|
||||
column.put("isCaseSensitive", meta.isCaseSensitive(i));
|
||||
column.put("isCurrency", meta.isCurrency(i));
|
||||
column.put("isSigned", meta.isSigned(i));
|
||||
column.put("schemaName", orEmpty(meta.getSchemaName(i)));
|
||||
column.put("tableName", orEmpty(meta.getTableName(i)));
|
||||
column.putNull("columnDefault");
|
||||
return column;
|
||||
}
|
||||
|
||||
private static String firstNonBlank(String preferred, String fallback) {
|
||||
return preferred != null && !preferred.isBlank() ? preferred : orEmpty(fallback);
|
||||
}
|
||||
|
||||
private static String orEmpty(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Properties;
|
||||
|
||||
@ApplicationScoped
|
||||
class RedshiftDataConnectionFactory {
|
||||
|
||||
Connection open(RedshiftDataResourceResolver.DatabaseTarget target) throws SQLException {
|
||||
// stringtype=unspecified: Redshift Data API parameter values are always strings on the
|
||||
// wire, so every bind goes through PreparedStatement.setString. With the default
|
||||
// (varchar) the driver stamps an explicit type OID and the server refuses
|
||||
// "integer = character varying"; unspecified sends the value untyped and lets the
|
||||
// server infer the column's type from context, matching how AWS binds parameters.
|
||||
String url = "jdbc:postgresql://" + target.host() + ":" + target.port() + "/" + target.database()
|
||||
+ "?sslmode=disable&stringtype=unspecified";
|
||||
Properties props = new Properties();
|
||||
props.setProperty("user", target.user());
|
||||
props.setProperty("password", target.password());
|
||||
props.setProperty("connectTimeout", "5");
|
||||
return DriverManager.getConnection(url, props);
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Blob;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Maps a JDBC value onto the Redshift Data API {@code Field} union: exactly one
|
||||
* of {@code stringValue}, {@code longValue}, {@code doubleValue},
|
||||
* {@code booleanValue}, {@code blobValue}, or {@code isNull}.
|
||||
*/
|
||||
final class RedshiftDataFieldMapper {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftDataFieldMapper.class);
|
||||
|
||||
private RedshiftDataFieldMapper() {
|
||||
}
|
||||
|
||||
static ObjectNode toField(ObjectMapper om, Object value, int sqlType, boolean wasNull) {
|
||||
ObjectNode field = om.createObjectNode();
|
||||
if (wasNull || value == null) {
|
||||
field.put("isNull", true);
|
||||
return field;
|
||||
}
|
||||
switch (sqlType) {
|
||||
case Types.BIT, Types.BOOLEAN -> field.put("booleanValue", toBoolean(value));
|
||||
case Types.TINYINT, Types.SMALLINT, Types.INTEGER, Types.BIGINT ->
|
||||
field.put("longValue", coerceNumber(value).longValue());
|
||||
case Types.REAL, Types.FLOAT, Types.DOUBLE ->
|
||||
field.put("doubleValue", coerceNumber(value).doubleValue());
|
||||
case Types.NUMERIC, Types.DECIMAL -> field.put("stringValue", toPlainString(value));
|
||||
case Types.BINARY, Types.VARBINARY, Types.LONGVARBINARY, Types.BLOB -> field.put("blobValue", toBytes(value));
|
||||
default -> field.put("stringValue", value.toString());
|
||||
}
|
||||
return field;
|
||||
}
|
||||
|
||||
static List<ArrayNode> rows(ObjectMapper om, ResultSet rs) throws SQLException {
|
||||
ResultSetMetaData meta = rs.getMetaData();
|
||||
int columns = meta.getColumnCount();
|
||||
List<ArrayNode> materialised = new ArrayList<>();
|
||||
while (rs.next()) {
|
||||
ArrayNode row = om.createArrayNode();
|
||||
for (int i = 1; i <= columns; i++) {
|
||||
Object value = rs.getObject(i);
|
||||
row.add(toField(om, value, meta.getColumnType(i), rs.wasNull()));
|
||||
}
|
||||
materialised.add(row);
|
||||
}
|
||||
return materialised;
|
||||
}
|
||||
|
||||
static long serializedSize(List<ArrayNode> rows) {
|
||||
long total = 0;
|
||||
for (ArrayNode row : rows) {
|
||||
for (Iterator<JsonNode> it = row.elements(); it.hasNext(); ) {
|
||||
JsonNode field = it.next();
|
||||
if (field.has("stringValue")) {
|
||||
total += field.get("stringValue").asText().getBytes(StandardCharsets.UTF_8).length;
|
||||
} else if (field.has("blobValue")) {
|
||||
total += field.get("blobValue").asText().length();
|
||||
} else if (field.has("longValue")) {
|
||||
total += Long.toString(field.get("longValue").asLong()).length();
|
||||
} else if (field.has("doubleValue")) {
|
||||
total += Double.toString(field.get("doubleValue").asDouble()).length();
|
||||
} else if (field.has("booleanValue")) {
|
||||
total += Boolean.toString(field.get("booleanValue").asBoolean()).length();
|
||||
}
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
private static boolean toBoolean(Object value) {
|
||||
if (value instanceof Boolean b) {
|
||||
return b;
|
||||
}
|
||||
if (value instanceof Number n) {
|
||||
return n.longValue() != 0;
|
||||
}
|
||||
return Boolean.parseBoolean(value.toString());
|
||||
}
|
||||
|
||||
private static Number coerceNumber(Object value) {
|
||||
if (value instanceof Number n) {
|
||||
return n;
|
||||
}
|
||||
return new BigDecimal(value.toString());
|
||||
}
|
||||
|
||||
private static String toPlainString(Object value) {
|
||||
if (value instanceof BigDecimal d) {
|
||||
return d.toPlainString();
|
||||
}
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
private static byte[] toBytes(Object value) {
|
||||
if (value instanceof byte[] bytes) {
|
||||
return bytes;
|
||||
}
|
||||
if (value instanceof Blob blob) {
|
||||
try {
|
||||
return blob.getBytes(1, Math.toIntExact(blob.length()));
|
||||
} catch (SQLException e) {
|
||||
LOG.warnv("Could not read blob value for a Redshift Data API field, returning empty bytes: {0}",
|
||||
e.getMessage());
|
||||
return new byte[0];
|
||||
}
|
||||
}
|
||||
return value.toString().getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
@ApplicationScoped
|
||||
public class RedshiftDataJsonHandler {
|
||||
|
||||
private final RedshiftDataService service;
|
||||
|
||||
@Inject
|
||||
public RedshiftDataJsonHandler(RedshiftDataService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
return switch (action) {
|
||||
case "ExecuteStatement" -> Response.ok(service.executeStatement(request, region)).build();
|
||||
case "BatchExecuteStatement" -> Response.ok(service.batchExecuteStatement(request, region)).build();
|
||||
case "DescribeStatement" -> Response.ok(service.describeStatement(request)).build();
|
||||
case "GetStatementResult" -> Response.ok(service.getStatementResult(request)).build();
|
||||
case "GetStatementResultV2" -> Response.ok(service.getStatementResultV2(request)).build();
|
||||
case "ListStatements" -> Response.ok(service.listStatements(request)).build();
|
||||
case "CancelStatement" -> Response.ok(service.cancelStatement(request)).build();
|
||||
case "ListDatabases" -> Response.ok(service.listDatabases(request, region)).build();
|
||||
case "ListSchemas" -> Response.ok(service.listSchemas(request, region)).build();
|
||||
case "ListTables" -> Response.ok(service.listTables(request, region)).build();
|
||||
case "DescribeTable" -> Response.ok(service.describeTable(request, region)).build();
|
||||
case "ExecuteSql", "BatchExecuteSql" -> throw new AwsException("ValidationException",
|
||||
action + " is a deprecated operation and is not supported.", 400);
|
||||
default -> throw new AwsException("ValidationException",
|
||||
"Operation " + action + " is not supported by the Floci Redshift Data API.", 400);
|
||||
};
|
||||
}
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@ApplicationScoped
|
||||
class RedshiftDataResourceResolver {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftDataResourceResolver.class);
|
||||
|
||||
private final RedshiftService redshiftService;
|
||||
private final SecretsManagerService secretsManagerService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
RedshiftDataResourceResolver(RedshiftService redshiftService,
|
||||
SecretsManagerService secretsManagerService,
|
||||
ObjectMapper objectMapper) {
|
||||
this.redshiftService = redshiftService;
|
||||
this.secretsManagerService = secretsManagerService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
DatabaseTarget resolve(JsonNode request, String region) {
|
||||
if (hasText(request, "WorkgroupName")) {
|
||||
throw validation("Redshift Serverless (WorkgroupName) is not emulated by Floci.");
|
||||
}
|
||||
String database = requiredText(request, "Database");
|
||||
|
||||
if (hasText(request, "SecretArn")) {
|
||||
return resolveViaSecret(request, region, database);
|
||||
}
|
||||
return resolveViaDbUser(request, database);
|
||||
}
|
||||
|
||||
private DatabaseTarget resolveViaSecret(JsonNode request, String region, String database) {
|
||||
String secretArn = request.get("SecretArn").asText();
|
||||
try {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(secretArn);
|
||||
if (region != null && !region.isBlank() && !region.equals(arn.region())) {
|
||||
throw validation("SecretArn is outside the request region.");
|
||||
}
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw validation("SecretArn is not a valid ARN: " + secretArn);
|
||||
}
|
||||
String clusterId = requiredText(request, "ClusterIdentifier");
|
||||
Cluster cluster = cluster(clusterId);
|
||||
SecretVersion secret;
|
||||
try {
|
||||
secret = secretsManagerService.getSecretValue(secretArn, null, null, region);
|
||||
} catch (AwsException e) {
|
||||
throw validation("SecretArn does not resolve to a local secret: " + secretArn);
|
||||
}
|
||||
Credentials creds = parseCredentials(secret.getSecretString());
|
||||
if (creds == null) {
|
||||
throw validation("Secret " + secretArn + " does not contain username and password fields.");
|
||||
}
|
||||
return target(clusterArn(clusterId, region), cluster, database, creds.username(), creds.password());
|
||||
}
|
||||
|
||||
private DatabaseTarget resolveViaDbUser(JsonNode request, String database) {
|
||||
String clusterId = requiredText(request, "ClusterIdentifier");
|
||||
String dbUser = requiredText(request, "DbUser");
|
||||
Cluster cluster = cluster(clusterId);
|
||||
if (!dbUser.equals(cluster.getMasterUsername())) {
|
||||
throw validation("DbUser " + dbUser + " is not the cluster master; create it first or use "
|
||||
+ "GetClusterCredentials (not yet emulated).");
|
||||
}
|
||||
return target(clusterArn(clusterId, null), cluster, database, dbUser, cluster.getMasterPassword());
|
||||
}
|
||||
|
||||
private Cluster cluster(String clusterId) {
|
||||
try {
|
||||
return redshiftService.describeClusters(clusterId).get(0);
|
||||
} catch (AwsException e) {
|
||||
throw validation("Cluster " + clusterId + " was not found.");
|
||||
}
|
||||
}
|
||||
|
||||
private static DatabaseTarget target(String arn, Cluster cluster, String database, String user, String password) {
|
||||
String host = cluster.getContainerHost();
|
||||
int port = cluster.getContainerPort();
|
||||
if (host == null || host.isBlank() || port <= 0) {
|
||||
throw validation("Cluster runtime is not available for Data API execution.");
|
||||
}
|
||||
return new DatabaseTarget(arn, host, port, database, user, password);
|
||||
}
|
||||
|
||||
private Credentials parseCredentials(String secretString) {
|
||||
if (secretString == null || secretString.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
JsonNode node = objectMapper.readTree(secretString);
|
||||
String username = text(node, "username");
|
||||
if (username == null) {
|
||||
username = text(node, "user");
|
||||
}
|
||||
String password = text(node, "password");
|
||||
if (username != null && password != null) {
|
||||
return new Credentials(username, password);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not parse Redshift Data API secret: {0}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String clusterArn(String clusterId, String region) {
|
||||
String r = (region == null || region.isBlank()) ? "us-east-1" : region;
|
||||
return "arn:aws:redshift:" + r + ":000000000000:cluster:" + clusterId;
|
||||
}
|
||||
|
||||
private static AwsException validation(String message) {
|
||||
return new AwsException("ValidationException", message, 400);
|
||||
}
|
||||
|
||||
private static boolean hasText(JsonNode node, String field) {
|
||||
String value = text(node, field);
|
||||
return value != null && !value.isBlank();
|
||||
}
|
||||
|
||||
private static String requiredText(JsonNode node, String field) {
|
||||
String value = text(node, field);
|
||||
if (value == null || value.isBlank()) {
|
||||
throw validation(field + " is required.");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String field) {
|
||||
JsonNode value = node.get(field);
|
||||
return value == null || value.isNull() ? null : value.asText();
|
||||
}
|
||||
|
||||
record DatabaseTarget(String arn, String host, int port, String database, String user, String password) {
|
||||
}
|
||||
|
||||
private record Credentials(String username, String password) {
|
||||
}
|
||||
}
|
||||
+666
@@ -0,0 +1,666 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@ApplicationScoped
|
||||
public class RedshiftDataService implements Resettable {
|
||||
|
||||
private static final int PAGE_SIZE = 1000;
|
||||
|
||||
private final RedshiftDataResourceResolver resolver;
|
||||
private final RedshiftDataConnectionFactory connectionFactory;
|
||||
private final RedshiftDataStatementStore store;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public RedshiftDataService(RedshiftDataResourceResolver resolver,
|
||||
RedshiftDataConnectionFactory connectionFactory,
|
||||
RedshiftDataStatementStore store,
|
||||
ObjectMapper objectMapper) {
|
||||
this.resolver = resolver;
|
||||
this.connectionFactory = connectionFactory;
|
||||
this.store = store;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
store.clear();
|
||||
}
|
||||
|
||||
// ── ExecuteStatement ────────────────────────────────────────────────────
|
||||
|
||||
public ObjectNode executeStatement(JsonNode request, String region) {
|
||||
String sql = requiredText(request, "Sql");
|
||||
rejectMultiStatement(sql);
|
||||
Map<String, String> parameters = RedshiftDataSqlParameters.parseParameters(request, "Parameters");
|
||||
|
||||
RedshiftDataResourceResolver.DatabaseTarget target = resolver.resolve(request, region);
|
||||
|
||||
RedshiftDataStatementStore.StoredStatement stored = newStatement(request);
|
||||
stored.sql = sql;
|
||||
stored.sqls = List.of(sql);
|
||||
stored.clusterIdentifier = clusterIdentifierOrNull(request);
|
||||
stored.dbUser = target.user();
|
||||
stored.database = target.database();
|
||||
stored.resultFormat = request.path("ResultFormat").asText("JSON");
|
||||
|
||||
runStatement(stored, target, sql, parameters);
|
||||
store.put(stored);
|
||||
return executeResponse(stored);
|
||||
}
|
||||
|
||||
private void runStatement(RedshiftDataStatementStore.StoredStatement stored,
|
||||
RedshiftDataResourceResolver.DatabaseTarget target,
|
||||
String sql, Map<String, String> parameters) {
|
||||
try (Connection connection = connectionFactory.open(target)) {
|
||||
runOnConnection(stored, connection, sql, parameters);
|
||||
} catch (SQLException e) {
|
||||
stored.status = RedshiftDataStatementStore.Status.FAILED;
|
||||
stored.error = e.getMessage();
|
||||
}
|
||||
stored.updatedAt = Instant.now();
|
||||
}
|
||||
|
||||
private void runOnConnection(RedshiftDataStatementStore.StoredStatement stored,
|
||||
Connection connection, String sql, Map<String, String> parameters)
|
||||
throws SQLException {
|
||||
RedshiftDataSqlParameters.ParsedSql parsed = RedshiftDataSqlParameters.parse(sql);
|
||||
long t0 = System.nanoTime();
|
||||
try (PreparedStatement statement = connection.prepareStatement(parsed.sql())) {
|
||||
RedshiftDataSqlParameters.bind(statement, parsed.parameterOrder(), parameters);
|
||||
boolean hasResultSet = statement.execute();
|
||||
if (hasResultSet) {
|
||||
try (ResultSet rs = statement.getResultSet()) {
|
||||
stored.columnMetadata = RedshiftDataColumnMetadata.toColumnMetadata(objectMapper, rs.getMetaData());
|
||||
stored.rows = RedshiftDataFieldMapper.rows(objectMapper, rs);
|
||||
stored.hasResultSet = true;
|
||||
stored.resultRows = stored.rows.size();
|
||||
stored.resultSize = RedshiftDataFieldMapper.serializedSize(stored.rows);
|
||||
}
|
||||
} else {
|
||||
stored.hasResultSet = false;
|
||||
stored.resultRows = Math.max(statement.getUpdateCount(), 0);
|
||||
}
|
||||
}
|
||||
stored.durationNanos = System.nanoTime() - t0;
|
||||
stored.status = RedshiftDataStatementStore.Status.FINISHED;
|
||||
}
|
||||
|
||||
private ObjectNode executeResponse(RedshiftDataStatementStore.StoredStatement stored) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("Id", stored.id);
|
||||
if (stored.clusterIdentifier != null) {
|
||||
response.put("ClusterIdentifier", stored.clusterIdentifier);
|
||||
} else {
|
||||
response.putNull("ClusterIdentifier");
|
||||
}
|
||||
response.put("CreatedAt", epochSeconds(stored.createdAt));
|
||||
response.put("Database", stored.database);
|
||||
if (stored.dbUser != null) {
|
||||
response.put("DbUser", stored.dbUser);
|
||||
}
|
||||
response.putArray("DbGroups");
|
||||
response.putNull("WorkgroupName");
|
||||
response.put("HasResultSet", stored.hasResultSet);
|
||||
response.putNull("SessionId");
|
||||
return response;
|
||||
}
|
||||
|
||||
// ── DescribeStatement ───────────────────────────────────────────────────
|
||||
|
||||
public ObjectNode describeStatement(JsonNode request) {
|
||||
RedshiftDataStatementStore.StoredStatement stored = require(request);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("Id", stored.id);
|
||||
response.put("Status", stored.status.name());
|
||||
response.put("CreatedAt", epochSeconds(stored.createdAt));
|
||||
response.put("UpdatedAt", epochSeconds(stored.updatedAt));
|
||||
response.put("Duration", stored.durationNanos);
|
||||
if (stored.error != null) {
|
||||
response.put("Error", stored.error);
|
||||
}
|
||||
response.put("QueryString", stored.sql);
|
||||
int stableId = stored.id.hashCode() & Integer.MAX_VALUE;
|
||||
response.put("RedshiftPid", stableId);
|
||||
response.put("RedshiftQueryId", (long) stableId);
|
||||
response.put("ResultRows", stored.resultRows);
|
||||
response.put("ResultSize", stored.resultSize);
|
||||
response.put("HasResultSet", stored.hasResultSet);
|
||||
if (stored.clusterIdentifier != null) {
|
||||
response.put("ClusterIdentifier", stored.clusterIdentifier);
|
||||
}
|
||||
response.put("Database", stored.database);
|
||||
if (stored.dbUser != null) {
|
||||
response.put("DbUser", stored.dbUser);
|
||||
}
|
||||
response.putNull("WorkgroupName");
|
||||
response.put("ResultFormat", stored.resultFormat);
|
||||
if (stored.batch && stored.subStatements != null) {
|
||||
ArrayNode subs = response.putArray("SubStatements");
|
||||
for (RedshiftDataStatementStore.StoredStatement sub : stored.subStatements) {
|
||||
ObjectNode s = subs.addObject();
|
||||
s.put("Id", sub.id);
|
||||
s.put("Status", sub.status.name());
|
||||
s.put("QueryString", sub.sql);
|
||||
s.put("Duration", sub.durationNanos);
|
||||
s.put("ResultRows", sub.resultRows);
|
||||
s.put("ResultSize", sub.resultSize);
|
||||
s.put("HasResultSet", sub.hasResultSet);
|
||||
if (sub.error != null) {
|
||||
s.put("Error", sub.error);
|
||||
}
|
||||
}
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
// ── GetStatementResult / GetStatementResultV2 ───────────────────────────
|
||||
|
||||
public ObjectNode getStatementResult(JsonNode request) {
|
||||
RedshiftDataStatementStore.StoredStatement stored = resultBearing(request);
|
||||
int offset = decodeToken(textOrNull(request, "NextToken"));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("ColumnMetadata", stored.columnMetadata);
|
||||
ArrayNode records = response.putArray("Records");
|
||||
int end = Math.min(offset + PAGE_SIZE, stored.rows.size());
|
||||
for (int i = offset; i < end; i++) {
|
||||
records.add(stored.rows.get(i));
|
||||
}
|
||||
response.put("TotalNumRows", (long) stored.rows.size());
|
||||
if (end < stored.rows.size()) {
|
||||
response.put("NextToken", encodeToken(end));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
public ObjectNode getStatementResultV2(JsonNode request) {
|
||||
RedshiftDataStatementStore.StoredStatement stored = resultBearing(request);
|
||||
int offset = decodeToken(textOrNull(request, "NextToken"));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("ColumnMetadata", stored.columnMetadata);
|
||||
int end = Math.min(offset + PAGE_SIZE, stored.rows.size());
|
||||
boolean csv = "CSV".equalsIgnoreCase(stored.resultFormat);
|
||||
ArrayNode records = response.putArray("Records");
|
||||
for (int i = offset; i < end; i++) {
|
||||
if (csv) {
|
||||
records.addObject().put("CSVRecords", toCsvLine(stored.rows.get(i)));
|
||||
} else {
|
||||
records.add(stored.rows.get(i));
|
||||
}
|
||||
}
|
||||
response.put("ResultFormat", csv ? "CSV" : "JSON");
|
||||
response.put("TotalNumRows", (long) stored.rows.size());
|
||||
if (end < stored.rows.size()) {
|
||||
response.put("NextToken", encodeToken(end));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
private static String toCsvLine(ArrayNode row) {
|
||||
StringBuilder line = new StringBuilder();
|
||||
for (int i = 0; i < row.size(); i++) {
|
||||
if (i > 0) {
|
||||
line.append(',');
|
||||
}
|
||||
JsonNode field = row.get(i);
|
||||
if (field.path("isNull").asBoolean(false)) {
|
||||
continue;
|
||||
}
|
||||
line.append(csvCell(fieldText(field)));
|
||||
}
|
||||
return line.toString();
|
||||
}
|
||||
|
||||
private static String fieldText(JsonNode field) {
|
||||
if (field.has("stringValue")) {
|
||||
return field.get("stringValue").asText();
|
||||
}
|
||||
if (field.has("longValue")) {
|
||||
return Long.toString(field.get("longValue").asLong());
|
||||
}
|
||||
if (field.has("doubleValue")) {
|
||||
return Double.toString(field.get("doubleValue").asDouble());
|
||||
}
|
||||
if (field.has("booleanValue")) {
|
||||
return Boolean.toString(field.get("booleanValue").asBoolean());
|
||||
}
|
||||
if (field.has("blobValue")) {
|
||||
return field.get("blobValue").asText();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// RFC 4180: quote a field that contains a comma, quote, CR, or LF, doubling embedded quotes.
|
||||
private static String csvCell(String value) {
|
||||
if (value.indexOf(',') < 0 && value.indexOf('"') < 0
|
||||
&& value.indexOf('\n') < 0 && value.indexOf('\r') < 0) {
|
||||
return value;
|
||||
}
|
||||
return '"' + value.replace("\"", "\"\"") + '"';
|
||||
}
|
||||
|
||||
// ── BatchExecuteStatement ──────────────────────────────────────────────
|
||||
|
||||
public ObjectNode batchExecuteStatement(JsonNode request, String region) {
|
||||
JsonNode sqlsNode = request.get("Sqls");
|
||||
if (sqlsNode == null || !sqlsNode.isArray() || sqlsNode.isEmpty()) {
|
||||
throw new AwsException("ValidationException", "Sqls must be a non-empty array of SQL statements.", 400);
|
||||
}
|
||||
List<String> sqls = new ArrayList<>();
|
||||
for (JsonNode n : sqlsNode) {
|
||||
sqls.add(n.asText());
|
||||
}
|
||||
|
||||
RedshiftDataResourceResolver.DatabaseTarget target = resolver.resolve(request, region);
|
||||
|
||||
RedshiftDataStatementStore.StoredStatement parent = newStatement(request);
|
||||
parent.batch = true;
|
||||
parent.sql = String.join("; ", sqls);
|
||||
parent.sqls = sqls;
|
||||
parent.clusterIdentifier = clusterIdentifierOrNull(request);
|
||||
parent.dbUser = target.user();
|
||||
parent.database = target.database();
|
||||
parent.resultFormat = request.path("ResultFormat").asText("JSON");
|
||||
parent.subStatements = new ArrayList<>();
|
||||
|
||||
long totalDuration = 0;
|
||||
try (Connection connection = connectionFactory.open(target)) {
|
||||
connection.setAutoCommit(false);
|
||||
boolean failed = false;
|
||||
for (int n = 0; n < sqls.size(); n++) {
|
||||
RedshiftDataStatementStore.StoredStatement sub = new RedshiftDataStatementStore.StoredStatement();
|
||||
sub.id = parent.id + ":" + (n + 1);
|
||||
sub.sql = sqls.get(n);
|
||||
sub.sqls = List.of(sqls.get(n));
|
||||
sub.clusterIdentifier = parent.clusterIdentifier;
|
||||
sub.database = parent.database;
|
||||
sub.dbUser = parent.dbUser;
|
||||
sub.resultFormat = parent.resultFormat;
|
||||
Instant now = Instant.now();
|
||||
sub.createdAt = now;
|
||||
sub.updatedAt = now;
|
||||
try {
|
||||
runOnConnection(sub, connection, sqls.get(n), Map.of());
|
||||
} catch (SQLException e) {
|
||||
sub.status = RedshiftDataStatementStore.Status.FAILED;
|
||||
sub.error = e.getMessage();
|
||||
sub.updatedAt = Instant.now();
|
||||
parent.subStatements.add(sub);
|
||||
store.put(sub);
|
||||
totalDuration += sub.durationNanos;
|
||||
parent.status = RedshiftDataStatementStore.Status.FAILED;
|
||||
parent.error = e.getMessage();
|
||||
connection.rollback();
|
||||
failed = true;
|
||||
break;
|
||||
}
|
||||
sub.updatedAt = Instant.now();
|
||||
parent.subStatements.add(sub);
|
||||
store.put(sub);
|
||||
totalDuration += sub.durationNanos;
|
||||
}
|
||||
if (!failed) {
|
||||
connection.commit();
|
||||
parent.status = RedshiftDataStatementStore.Status.FINISHED;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
parent.status = RedshiftDataStatementStore.Status.FAILED;
|
||||
parent.error = e.getMessage();
|
||||
}
|
||||
|
||||
for (int i = parent.subStatements.size() - 1; i >= 0; i--) {
|
||||
RedshiftDataStatementStore.StoredStatement sub = parent.subStatements.get(i);
|
||||
if (sub.hasResultSet) {
|
||||
parent.hasResultSet = true;
|
||||
parent.columnMetadata = sub.columnMetadata;
|
||||
parent.rows = sub.rows;
|
||||
parent.resultRows = sub.resultRows;
|
||||
parent.resultSize = sub.resultSize;
|
||||
break;
|
||||
}
|
||||
}
|
||||
parent.durationNanos = totalDuration;
|
||||
parent.updatedAt = Instant.now();
|
||||
store.put(parent);
|
||||
return executeResponse(parent);
|
||||
}
|
||||
|
||||
// ── ListStatements ─────────────────────────────────────────────────────
|
||||
|
||||
public ObjectNode listStatements(JsonNode request) {
|
||||
String nameFilter = textOrNull(request, "StatementName");
|
||||
String statusFilter = textOrNull(request, "Status");
|
||||
// AWS treats 0 or absent as the default and rejects anything above the documented
|
||||
// maximum of 100. Clamping 0 up also stops a follower looping on a static NextToken.
|
||||
int maxResults = request.path("MaxResults").asInt(100);
|
||||
if (maxResults <= 0) {
|
||||
maxResults = 100;
|
||||
} else if (maxResults > 100) {
|
||||
throw new AwsException("ValidationException", "MaxResults must not exceed 100.", 400);
|
||||
}
|
||||
int offset = decodeToken(textOrNull(request, "NextToken"));
|
||||
|
||||
List<RedshiftDataStatementStore.StoredStatement> all = store.values().stream()
|
||||
.filter(s -> s.id.indexOf(':') < 0)
|
||||
.filter(s -> nameFilter == null || nameFilter.equals(s.statementName))
|
||||
.filter(s -> statusFilter == null || statusFilter.equalsIgnoreCase(s.status.name()))
|
||||
.sorted(Comparator.comparing((RedshiftDataStatementStore.StoredStatement s) -> s.createdAt).reversed())
|
||||
.toList();
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode statements = response.putArray("Statements");
|
||||
int end = Math.min(offset + maxResults, all.size());
|
||||
for (int i = offset; i < end; i++) {
|
||||
RedshiftDataStatementStore.StoredStatement s = all.get(i);
|
||||
ObjectNode node = statements.addObject();
|
||||
node.put("Id", s.id);
|
||||
node.put("QueryString", s.sql);
|
||||
ArrayNode queryStrings = node.putArray("QueryStrings");
|
||||
for (String sql : s.sqls != null ? s.sqls : List.of(s.sql)) {
|
||||
queryStrings.add(sql);
|
||||
}
|
||||
node.put("Status", s.status.name());
|
||||
node.put("CreatedAt", epochSeconds(s.createdAt));
|
||||
node.put("UpdatedAt", epochSeconds(s.updatedAt));
|
||||
if (s.statementName != null) {
|
||||
node.put("StatementName", s.statementName);
|
||||
}
|
||||
node.put("IsBatchStatement", s.batch);
|
||||
node.put("ResultRows", s.resultRows);
|
||||
node.put("ResultSize", s.resultSize);
|
||||
node.put("Duration", s.durationNanos);
|
||||
}
|
||||
if (end < all.size()) {
|
||||
response.put("NextToken", encodeToken(end));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
// ── CancelStatement ────────────────────────────────────────────────────
|
||||
|
||||
public ObjectNode cancelStatement(JsonNode request) {
|
||||
RedshiftDataStatementStore.StoredStatement stored = require(request);
|
||||
if (stored.status != RedshiftDataStatementStore.Status.FINISHED
|
||||
&& stored.status != RedshiftDataStatementStore.Status.FAILED) {
|
||||
stored.status = RedshiftDataStatementStore.Status.ABORTED;
|
||||
stored.updatedAt = Instant.now();
|
||||
}
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("Status", true);
|
||||
return response;
|
||||
}
|
||||
|
||||
// ── Schema introspection ───────────────────────────────────────────────
|
||||
|
||||
public ObjectNode listDatabases(JsonNode request, String region) {
|
||||
RedshiftDataResourceResolver.DatabaseTarget target = resolver.resolve(request, region);
|
||||
List<String> names = new ArrayList<>();
|
||||
try (Connection c = connectionFactory.open(target);
|
||||
PreparedStatement ps = c.prepareStatement(
|
||||
"SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname");
|
||||
ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
names.add(rs.getString(1));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw databaseError(e);
|
||||
}
|
||||
return pageStrings(request, "Databases", names);
|
||||
}
|
||||
|
||||
public ObjectNode listSchemas(JsonNode request, String region) {
|
||||
RedshiftDataResourceResolver.DatabaseTarget target = resolver.resolve(request, region);
|
||||
String pattern = orLike(textOrNull(request, "SchemaPattern"));
|
||||
List<String> names = new ArrayList<>();
|
||||
try (Connection c = connectionFactory.open(target);
|
||||
PreparedStatement ps = c.prepareStatement(
|
||||
"SELECT schema_name FROM information_schema.schemata "
|
||||
+ "WHERE schema_name LIKE ? ORDER BY schema_name")) {
|
||||
ps.setString(1, pattern);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
names.add(rs.getString(1));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw databaseError(e);
|
||||
}
|
||||
return pageStrings(request, "Schemas", names);
|
||||
}
|
||||
|
||||
public ObjectNode listTables(JsonNode request, String region) {
|
||||
RedshiftDataResourceResolver.DatabaseTarget target = resolver.resolve(request, region);
|
||||
String schemaPattern = orLike(textOrNull(request, "SchemaPattern"));
|
||||
String tablePattern = orLike(textOrNull(request, "TablePattern"));
|
||||
List<ObjectNode> tables = new ArrayList<>();
|
||||
try (Connection c = connectionFactory.open(target);
|
||||
PreparedStatement ps = c.prepareStatement(
|
||||
"SELECT table_schema, table_name, table_type FROM information_schema.tables "
|
||||
+ "WHERE table_schema LIKE ? AND table_name LIKE ? "
|
||||
+ "ORDER BY table_schema, table_name")) {
|
||||
ps.setString(1, schemaPattern);
|
||||
ps.setString(2, tablePattern);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
ObjectNode t = objectMapper.createObjectNode();
|
||||
t.put("schema", rs.getString(1));
|
||||
t.put("name", rs.getString(2));
|
||||
t.put("type", "VIEW".equalsIgnoreCase(rs.getString(3)) ? "VIEW" : "TABLE");
|
||||
tables.add(t);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw databaseError(e);
|
||||
}
|
||||
return pageObjects(request, "Tables", tables);
|
||||
}
|
||||
|
||||
public ObjectNode describeTable(JsonNode request, String region) {
|
||||
RedshiftDataResourceResolver.DatabaseTarget target = resolver.resolve(request, region);
|
||||
String schema = textOrNull(request, "Schema");
|
||||
String table = requiredText(request, "Table");
|
||||
boolean withSchema = schema != null && !schema.isBlank();
|
||||
// Table and Schema name a specific table, not a pattern: match exactly so a name
|
||||
// containing '_' or '%' cannot pull columns from other tables into ColumnList.
|
||||
String sql = "SELECT column_name, data_type, character_maximum_length, is_nullable, "
|
||||
+ "numeric_precision, numeric_scale, column_default, table_schema, table_name "
|
||||
+ "FROM information_schema.columns WHERE table_name = ? "
|
||||
+ (withSchema ? "AND table_schema = ? " : "")
|
||||
+ "ORDER BY ordinal_position";
|
||||
|
||||
List<ObjectNode> columns = new ArrayList<>();
|
||||
try (Connection c = connectionFactory.open(target);
|
||||
PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, table);
|
||||
if (withSchema) {
|
||||
ps.setString(2, schema);
|
||||
}
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
ObjectNode col = objectMapper.createObjectNode();
|
||||
String columnName = rs.getString("column_name");
|
||||
col.put("name", columnName);
|
||||
col.put("label", columnName);
|
||||
col.put("typeName", rs.getString("data_type"));
|
||||
col.put("length", rs.getInt("character_maximum_length"));
|
||||
col.put("nullable", "YES".equalsIgnoreCase(rs.getString("is_nullable")) ? 1 : 0);
|
||||
// information_schema does not carry these per-column flags. They are
|
||||
// fixed at emulation-friendly defaults rather than driver-derived as in
|
||||
// GetStatementResult's ColumnMetadata, which reads a live ResultSetMetaData.
|
||||
col.put("isCaseSensitive", false);
|
||||
col.put("isCurrency", false);
|
||||
col.put("isSigned", true);
|
||||
col.put("precision", rs.getInt("numeric_precision"));
|
||||
col.put("scale", rs.getInt("numeric_scale"));
|
||||
col.put("schemaName", rs.getString("table_schema"));
|
||||
col.put("tableName", rs.getString("table_name"));
|
||||
String columnDefault = rs.getString("column_default");
|
||||
if (columnDefault != null) {
|
||||
col.put("columnDefault", columnDefault);
|
||||
} else {
|
||||
col.putNull("columnDefault");
|
||||
}
|
||||
columns.add(col);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw databaseError(e);
|
||||
}
|
||||
|
||||
int max = pageSize(request);
|
||||
int offset = decodeToken(textOrNull(request, "NextToken"));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("TableName", table);
|
||||
ArrayNode list = response.putArray("ColumnList");
|
||||
int end = Math.min(offset + max, columns.size());
|
||||
for (int i = offset; i < end; i++) {
|
||||
list.add(columns.get(i));
|
||||
}
|
||||
if (end < columns.size()) {
|
||||
response.put("NextToken", encodeToken(end));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
private ObjectNode pageStrings(JsonNode request, String key, List<String> values) {
|
||||
int max = pageSize(request);
|
||||
int offset = decodeToken(textOrNull(request, "NextToken"));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode arr = response.putArray(key);
|
||||
int end = Math.min(offset + max, values.size());
|
||||
for (int i = offset; i < end; i++) {
|
||||
arr.add(values.get(i));
|
||||
}
|
||||
if (end < values.size()) {
|
||||
response.put("NextToken", encodeToken(end));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
private ObjectNode pageObjects(JsonNode request, String key, List<ObjectNode> values) {
|
||||
int max = pageSize(request);
|
||||
int offset = decodeToken(textOrNull(request, "NextToken"));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode arr = response.putArray(key);
|
||||
int end = Math.min(offset + max, values.size());
|
||||
for (int i = offset; i < end; i++) {
|
||||
arr.add(values.get(i));
|
||||
}
|
||||
if (end < values.size()) {
|
||||
response.put("NextToken", encodeToken(end));
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
private static int pageSize(JsonNode request) {
|
||||
int max = request.path("MaxResults").asInt(PAGE_SIZE);
|
||||
return max > 0 ? max : PAGE_SIZE;
|
||||
}
|
||||
|
||||
private static String orLike(String value) {
|
||||
return value == null || value.isBlank() ? "%" : value;
|
||||
}
|
||||
|
||||
private static AwsException databaseError(SQLException e) {
|
||||
return new AwsException("ValidationException", e.getMessage(), 400);
|
||||
}
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────
|
||||
|
||||
private RedshiftDataStatementStore.StoredStatement newStatement(JsonNode request) {
|
||||
RedshiftDataStatementStore.StoredStatement stored = new RedshiftDataStatementStore.StoredStatement();
|
||||
stored.id = UUID.randomUUID().toString();
|
||||
stored.statementName = textOrNull(request, "StatementName");
|
||||
Instant now = Instant.now();
|
||||
stored.createdAt = now;
|
||||
stored.updatedAt = now;
|
||||
stored.status = RedshiftDataStatementStore.Status.STARTED;
|
||||
return stored;
|
||||
}
|
||||
|
||||
private RedshiftDataStatementStore.StoredStatement require(JsonNode request) {
|
||||
String id = requiredText(request, "Id");
|
||||
RedshiftDataStatementStore.StoredStatement stored = store.get(id);
|
||||
if (stored == null) {
|
||||
throw new AwsException("ResourceNotFoundException", "Statement " + id + " was not found.", 400);
|
||||
}
|
||||
return stored;
|
||||
}
|
||||
|
||||
private RedshiftDataStatementStore.StoredStatement resultBearing(JsonNode request) {
|
||||
RedshiftDataStatementStore.StoredStatement stored = require(request);
|
||||
if (!stored.hasResultSet || stored.rows == null) {
|
||||
throw new AwsException("ValidationException", "Statement has no result set", 400);
|
||||
}
|
||||
return stored;
|
||||
}
|
||||
|
||||
private static void rejectMultiStatement(String sql) {
|
||||
if (RedshiftDataSqlParameters.isMultiStatement(sql)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"A single Sql statement is required; use BatchExecuteStatement for multiple.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static String encodeToken(int offset) {
|
||||
return Base64.getEncoder().encodeToString(Integer.toString(offset).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static int decodeToken(String token) {
|
||||
if (token == null || token.isBlank()) {
|
||||
return 0;
|
||||
}
|
||||
int offset;
|
||||
try {
|
||||
offset = Integer.parseInt(new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8));
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("ValidationException", "NextToken is not valid.", 400);
|
||||
}
|
||||
if (offset < 0) {
|
||||
throw new AwsException("ValidationException", "NextToken is not valid.", 400);
|
||||
}
|
||||
return offset;
|
||||
}
|
||||
|
||||
private static double epochSeconds(Instant instant) {
|
||||
return instant.toEpochMilli() / 1000.0;
|
||||
}
|
||||
|
||||
private String clusterIdentifierOrNull(JsonNode request) {
|
||||
return textOrNull(request, "ClusterIdentifier");
|
||||
}
|
||||
|
||||
private static String requiredText(JsonNode request, String name) {
|
||||
String value = textOrNull(request, name);
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new AwsException("ValidationException", name + " is required.", 400);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String textOrNull(JsonNode request, String name) {
|
||||
JsonNode node = request.get(name);
|
||||
return node == null || node.isNull() ? null : node.asText();
|
||||
}
|
||||
}
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Translates Redshift Data API {@code SqlParameter} bindings into JDBC
|
||||
* {@link PreparedStatement} bindings.
|
||||
*
|
||||
* <p>The Data API uses named placeholders ({@code :name}); JDBC uses positional
|
||||
* {@code ?}. {@link #parse(String)} rewrites the SQL to positional form while
|
||||
* recording the placeholder order. Redshift Data API parameter values are always
|
||||
* strings on the wire, so {@link #bind} binds every placeholder with
|
||||
* {@link PreparedStatement#setString}; PostgreSQL coerces to the column type.
|
||||
*/
|
||||
final class RedshiftDataSqlParameters {
|
||||
|
||||
private RedshiftDataSqlParameters() {
|
||||
}
|
||||
|
||||
record ParsedSql(String sql, List<String> parameterOrder) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrites {@code :name} placeholders to positional {@code ?}, skipping over
|
||||
* string literals, quoted identifiers, line and block comments, PostgreSQL
|
||||
* {@code ::} casts, and dollar-quoted strings so a colon inside any of those
|
||||
* is left untouched. Backslash is not treated as a string-literal escape
|
||||
* (the PostgreSQL default with {@code standard_conforming_strings} on).
|
||||
*/
|
||||
static ParsedSql parse(String sql) {
|
||||
StringBuilder out = new StringBuilder(sql.length());
|
||||
List<String> order = new ArrayList<>();
|
||||
int len = sql.length();
|
||||
int i = 0;
|
||||
while (i < len) {
|
||||
char c = sql.charAt(i);
|
||||
if (c == '-' && i + 1 < len && sql.charAt(i + 1) == '-') {
|
||||
int end = sql.indexOf('\n', i);
|
||||
end = end < 0 ? len : end;
|
||||
out.append(sql, i, end);
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
if (c == '/' && i + 1 < len && sql.charAt(i + 1) == '*') {
|
||||
int end = sql.indexOf("*/", i + 2);
|
||||
end = end < 0 ? len : end + 2;
|
||||
out.append(sql, i, end);
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
if (c == '\'' || c == '"') {
|
||||
i = copyQuoted(sql, i, c, out);
|
||||
continue;
|
||||
}
|
||||
if (c == '$') {
|
||||
int consumed = copyDollarQuoted(sql, i, out);
|
||||
if (consumed > i) {
|
||||
i = consumed;
|
||||
continue;
|
||||
}
|
||||
out.append(c);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (c == ':') {
|
||||
if (i + 1 < len && sql.charAt(i + 1) == ':') {
|
||||
out.append("::");
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (i + 1 < len && isNameStart(sql.charAt(i + 1))) {
|
||||
int j = i + 1;
|
||||
while (j < len && isNamePart(sql.charAt(j))) {
|
||||
j++;
|
||||
}
|
||||
order.add(sql.substring(i + 1, j));
|
||||
out.append('?');
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.append(c);
|
||||
i++;
|
||||
}
|
||||
return new ParsedSql(out.toString(), order);
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds each positional placeholder from {@code order} with the matching
|
||||
* value in {@code valuesByName}.
|
||||
*
|
||||
* @throws AwsException if a placeholder has no supplied value
|
||||
*/
|
||||
static void bind(PreparedStatement statement, List<String> order, Map<String, String> valuesByName)
|
||||
throws SQLException {
|
||||
for (int position = 0; position < order.size(); position++) {
|
||||
String name = order.get(position);
|
||||
if (!valuesByName.containsKey(name)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"SQL references parameter :" + name + " but no matching value was supplied.", 400);
|
||||
}
|
||||
String value = valuesByName.get(name);
|
||||
if (value == null) {
|
||||
statement.setNull(position + 1, Types.NULL);
|
||||
} else {
|
||||
statement.setString(position + 1, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a Data API {@code {name, value}} array into an insertion-ordered map.
|
||||
*/
|
||||
static Map<String, String> parseParameters(JsonNode request, String field) {
|
||||
JsonNode array = request.get(field);
|
||||
if (array == null || array.isNull()) {
|
||||
return Map.of();
|
||||
}
|
||||
if (!array.isArray()) {
|
||||
throw new AwsException("ValidationException", field + " must be an array of {name, value} objects.", 400);
|
||||
}
|
||||
Map<String, String> byName = new LinkedHashMap<>();
|
||||
for (JsonNode parameter : array) {
|
||||
if (parameter == null || !parameter.isObject() || !parameter.hasNonNull("name")) {
|
||||
throw new AwsException("ValidationException", "Each parameter must be an object with a name.", 400);
|
||||
}
|
||||
String name = parameter.get("name").asText();
|
||||
JsonNode value = parameter.get("value");
|
||||
String text = value == null || value.isNull() ? null : value.asText();
|
||||
if (byName.putIfAbsent(name, text) != null) {
|
||||
throw new AwsException("ValidationException", "Duplicate parameter name :" + name + ".", 400);
|
||||
}
|
||||
}
|
||||
return byName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code sql} holds more than one statement, applying the same
|
||||
* literal / identifier / comment / dollar-quote skipping as {@link #parse}
|
||||
* so a {@code ;} inside any of those is not counted. Trailing {@code ;}
|
||||
* characters (with only whitespace after) are permitted.
|
||||
*/
|
||||
static boolean isMultiStatement(String sql) {
|
||||
int len = sql.length();
|
||||
int i = 0;
|
||||
boolean sawSemicolon = false;
|
||||
while (i < len) {
|
||||
char c = sql.charAt(i);
|
||||
if (c == '-' && i + 1 < len && sql.charAt(i + 1) == '-') {
|
||||
int end = sql.indexOf('\n', i);
|
||||
i = end < 0 ? len : end;
|
||||
continue;
|
||||
}
|
||||
if (c == '/' && i + 1 < len && sql.charAt(i + 1) == '*') {
|
||||
int end = sql.indexOf("*/", i + 2);
|
||||
i = end < 0 ? len : end + 2;
|
||||
continue;
|
||||
}
|
||||
if (c == '\'' || c == '"') {
|
||||
i = skipQuoted(sql, i, c, isEscapeStringStart(sql, i, c));
|
||||
continue;
|
||||
}
|
||||
if (c == '$') {
|
||||
int consumed = skipDollarQuoted(sql, i);
|
||||
if (consumed > i) {
|
||||
i = consumed;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (c == ';') {
|
||||
sawSemicolon = true;
|
||||
} else if (sawSemicolon && !Character.isWhitespace(c)) {
|
||||
return true;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the quote at {@code quotePos} opens a PostgreSQL escape string
|
||||
* ({@code E'...'} / {@code e'...'}), inside which a backslash escapes the
|
||||
* next character. Plain {@code '...'} literals do not process backslashes
|
||||
* under {@code standard_conforming_strings}.
|
||||
*/
|
||||
private static boolean isEscapeStringStart(String sql, int quotePos, char quote) {
|
||||
if (quote != '\'' || quotePos == 0) {
|
||||
return false;
|
||||
}
|
||||
char prefix = sql.charAt(quotePos - 1);
|
||||
if (prefix != 'e' && prefix != 'E') {
|
||||
return false;
|
||||
}
|
||||
return quotePos - 1 == 0 || !isNamePart(sql.charAt(quotePos - 2));
|
||||
}
|
||||
|
||||
private static int skipQuoted(String sql, int start, char quote, boolean backslashEscapes) {
|
||||
int len = sql.length();
|
||||
int i = start + 1;
|
||||
while (i < len) {
|
||||
char c = sql.charAt(i);
|
||||
if (backslashEscapes && c == '\\' && i + 1 < len) {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (c == quote) {
|
||||
if (i + 1 < len && sql.charAt(i + 1) == quote) {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
return i + 1;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
private static int skipDollarQuoted(String sql, int start) {
|
||||
int len = sql.length();
|
||||
int tagEnd = start + 1;
|
||||
while (tagEnd < len && isNamePart(sql.charAt(tagEnd))) {
|
||||
tagEnd++;
|
||||
}
|
||||
if (tagEnd >= len || sql.charAt(tagEnd) != '$') {
|
||||
return start;
|
||||
}
|
||||
String tag = sql.substring(start, tagEnd + 1);
|
||||
int close = sql.indexOf(tag, tagEnd + 1);
|
||||
return close < 0 ? len : close + tag.length();
|
||||
}
|
||||
|
||||
private static int copyQuoted(String sql, int start, char quote, StringBuilder out) {
|
||||
int end = skipQuoted(sql, start, quote, isEscapeStringStart(sql, start, quote));
|
||||
out.append(sql, start, end);
|
||||
return end;
|
||||
}
|
||||
|
||||
private static int copyDollarQuoted(String sql, int start, StringBuilder out) {
|
||||
int end = skipDollarQuoted(sql, start);
|
||||
if (end > start) {
|
||||
out.append(sql, start, end);
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
private static boolean isNameStart(char c) {
|
||||
return Character.isLetter(c) || c == '_';
|
||||
}
|
||||
|
||||
private static boolean isNamePart(char c) {
|
||||
return Character.isLetterOrDigit(c) || c == '_';
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@ApplicationScoped
|
||||
class RedshiftDataStatementStore {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftDataStatementStore.class);
|
||||
|
||||
@RegisterForReflection
|
||||
enum Status { PICKED, STARTED, FINISHED, FAILED, ABORTED }
|
||||
|
||||
// Statements live in the configured storage backend like every other service's state
|
||||
// (memory mode by default, so they are still lost on restart as documented). The TTL
|
||||
// sweep below evicts entries the emulator would otherwise keep forever.
|
||||
private final AccountAwareStorageBackend<StoredStatement> statements;
|
||||
private final Duration ttl;
|
||||
private final Clock clock;
|
||||
// Created by the CDI lifecycle in start(); the test constructor never starts it, so unit
|
||||
// tests that build the store directly drive sweep() by hand and spawn no background thread.
|
||||
private ScheduledExecutorService sweeper;
|
||||
|
||||
@Inject
|
||||
RedshiftDataStatementStore(StorageFactory storageFactory, EmulatorConfig config) {
|
||||
this.statements = storageFactory.create("redshift-data", "statements.json",
|
||||
new TypeReference<Map<String, StoredStatement>>() {});
|
||||
this.ttl = Duration.ofHours(Math.max(1, config.services().redshiftData().resultTtlHours()));
|
||||
this.clock = Clock.systemUTC();
|
||||
}
|
||||
|
||||
RedshiftDataStatementStore(int resultTtlHours, Clock clock) {
|
||||
this.statements = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
this.ttl = Duration.ofHours(Math.max(1, resultTtlHours));
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void start() {
|
||||
sweeper = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "redshift-data-statement-sweep");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
sweeper.scheduleAtFixedRate(this::sweepSafely, 30, 30, TimeUnit.MINUTES);
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void stop() {
|
||||
if (sweeper != null) {
|
||||
sweeper.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
void put(StoredStatement statement) {
|
||||
statements.put(statement.id, statement);
|
||||
}
|
||||
|
||||
StoredStatement get(String id) {
|
||||
return statements.get(id).orElse(null);
|
||||
}
|
||||
|
||||
List<StoredStatement> values() {
|
||||
return statements.scan(k -> true);
|
||||
}
|
||||
|
||||
void clear() {
|
||||
statements.clear();
|
||||
}
|
||||
|
||||
void sweep() {
|
||||
Instant cutoff = Instant.now(clock).minus(ttl);
|
||||
// The sweep thread has no request context, so it iterates every account's partition
|
||||
// and deletes per account rather than through the current-account view.
|
||||
for (AccountAwareStorageBackend.AccountEntry<StoredStatement> entry
|
||||
: statements.scanAllAccountEntries(k -> true)) {
|
||||
if (entry.value().createdAt.isBefore(cutoff)) {
|
||||
statements.deleteForAccount(entry.accountId(), entry.key());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void sweepSafely() {
|
||||
try {
|
||||
sweep();
|
||||
} catch (Exception e) {
|
||||
LOG.warn("Failed to sweep expired Redshift Data API statements", e);
|
||||
}
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
|
||||
static final class StoredStatement {
|
||||
String id;
|
||||
String sql;
|
||||
List<String> sqls;
|
||||
boolean batch;
|
||||
String statementName;
|
||||
String clusterIdentifier;
|
||||
String database;
|
||||
String dbUser;
|
||||
String resultFormat = "JSON";
|
||||
Status status;
|
||||
String error;
|
||||
Instant createdAt;
|
||||
Instant updatedAt;
|
||||
long durationNanos;
|
||||
boolean hasResultSet;
|
||||
long resultRows;
|
||||
long resultSize;
|
||||
ArrayNode columnMetadata;
|
||||
List<ArrayNode> rows;
|
||||
List<StoredStatement> subStatements;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user