mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(redshift-data): add async execution and statement status events (#5383)
* feat(redshift-data): add async execution and statement status events
* fix(redshift-data): address review findings on async Data API
- Mark a statement FAILED when its worker dies unexpectedly instead of leaving it active
- Let unexpected publisher errors propagate; the delivery pool logs them at error level
- Run CREATE/DROP INDEX CONCURRENTLY, REINDEX CONCURRENTLY, ALTER SYSTEM and tablespace DDL outside a transaction
- Drop WaitTimeSeconds from Scheduler targets so the shared dispatcher thread never blocks
- Share result rows and column metadata between snapshots; ListStatements no longer copies results
- Replace the global monitor with a ReentrantReadWriteLock for status writes and reset
* fix(redshift-data): reject CancelStatement on terminal statements
- Throw ValidationException ("Could not cancel a query that is already in <STATE> state.") instead of returning Status false, as AWS does
- Use WaitTimeSeconds instead of 30 s polling in the Serverless compatibility test and the Spectrum integration test
* fix(redshift-data): match AWS CancelStatement message and tidy test signature
- Append "with ID: <id>" to the terminal-state ValidationException message
- Drop the unused throws InterruptedException from workgroupLifecycleUsesAwsSdk
This commit is contained in:
1 parent
641bf980d0
commit
ae75a653d6
27 files changed
+1756
-198
No files matched your search
@@ -1706,6 +1706,15 @@ public interface EmulatorConfig {
|
||||
|
||||
@WithDefault("24")
|
||||
int resultTtlHours();
|
||||
|
||||
@WithDefault("10")
|
||||
int maxConcurrentStatements();
|
||||
|
||||
@WithDefault("100")
|
||||
int queueCapacity();
|
||||
|
||||
@WithDefault("10")
|
||||
int shutdownTimeoutSeconds();
|
||||
}
|
||||
|
||||
interface RedshiftServerlessServiceConfig {
|
||||
|
||||
+19
-1
@@ -12,15 +12,30 @@ import java.sql.Statement;
|
||||
|
||||
final class RedshiftDataBackendSql implements BackendSql {
|
||||
private final Connection connection;
|
||||
private final RedshiftDataExecution execution;
|
||||
|
||||
RedshiftDataBackendSql(Connection connection) {
|
||||
this(connection, null);
|
||||
}
|
||||
|
||||
RedshiftDataBackendSql(Connection connection, RedshiftDataExecution execution) {
|
||||
this.connection = connection;
|
||||
this.execution = execution;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(String sql) {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.execute(sql);
|
||||
if (execution != null) {
|
||||
execution.track(statement);
|
||||
}
|
||||
try {
|
||||
statement.execute(sql);
|
||||
} finally {
|
||||
if (execution != null) {
|
||||
execution.untrack(statement);
|
||||
}
|
||||
}
|
||||
} catch (SQLException exception) {
|
||||
throw failure(exception);
|
||||
}
|
||||
@@ -29,6 +44,9 @@ final class RedshiftDataBackendSql implements BackendSql {
|
||||
@Override
|
||||
public long copyIn(String copySql, InputStream data) {
|
||||
try {
|
||||
if (execution != null) {
|
||||
execution.checkCancellation();
|
||||
}
|
||||
return connection.unwrap(PGConnection.class).getCopyAPI().copyIn(copySql, data);
|
||||
} catch (SQLException exception) {
|
||||
throw failure(exception);
|
||||
|
||||
+4
-2
@@ -1,15 +1,17 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.postgresql.Driver;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Properties;
|
||||
|
||||
@ApplicationScoped
|
||||
class RedshiftDataConnectionFactory {
|
||||
|
||||
private final Driver driver = new Driver();
|
||||
|
||||
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
|
||||
@@ -22,6 +24,6 @@ class RedshiftDataConnectionFactory {
|
||||
props.setProperty("user", target.user());
|
||||
props.setProperty("password", target.password());
|
||||
props.setProperty("connectTimeout", "5");
|
||||
return DriverManager.getConnection(url, props);
|
||||
return driver.connect(url, props);
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.ServiceRegistry;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@ApplicationScoped
|
||||
class RedshiftDataEventPublisher {
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftDataEventPublisher.class);
|
||||
|
||||
private final EventBridgeService events;
|
||||
private final ObjectMapper mapper;
|
||||
private final ServiceRegistry registry;
|
||||
|
||||
@Inject
|
||||
RedshiftDataEventPublisher(EventBridgeService events, ObjectMapper mapper, ServiceRegistry registry) {
|
||||
this.events = events;
|
||||
this.mapper = mapper;
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
void publish(RedshiftDataStatementStore.StoredStatement statement) {
|
||||
try {
|
||||
if (!registry.isServiceEnabled("eventbridge")) {
|
||||
LOG.warnv("EventBridge disabled for statement {0}, account {1}, region {2}",
|
||||
statement.id, statement.accountId, statement.region);
|
||||
return;
|
||||
}
|
||||
ObjectNode detail = mapper.createObjectNode();
|
||||
detail.put("statementId", statement.id);
|
||||
if (statement.statementName != null) {
|
||||
detail.put("statementName", statement.statementName);
|
||||
}
|
||||
if (statement.principal != null) {
|
||||
detail.put("principal", statement.principal);
|
||||
}
|
||||
detail.put("redshiftQueryId", (long) (statement.id.hashCode() & Integer.MAX_VALUE));
|
||||
detail.put("state", statement.status.name());
|
||||
detail.put("rows", statement.resultRows);
|
||||
detail.put("expireAt", statement.expiresAt.getEpochSecond());
|
||||
Map<String, Object> entry = new HashMap<>();
|
||||
entry.put("Source", "aws.redshift-data");
|
||||
entry.put("DetailType", "Redshift Data Statement Status Change");
|
||||
entry.put("Detail", detail.toString());
|
||||
entry.put("EventBusName", "default");
|
||||
entry.put("Resources", mapper.createArrayNode().add(statement.resourceArn));
|
||||
EventBridgeService.PutEventsResult result = events.putEvents(List.of(entry), statement.region, statement.accountId);
|
||||
if (result.failedCount() > 0) {
|
||||
LOG.warnv("EventBridge rejected event for statement {0}, account {1}, region {2}: {3}",
|
||||
statement.id, statement.accountId, statement.region, result.entries());
|
||||
}
|
||||
} catch (AwsException rejected) {
|
||||
LOG.warnv(rejected, "EventBridge refused event for statement {0}, account {1}, region {2}",
|
||||
statement.id, statement.accountId, statement.region);
|
||||
}
|
||||
}
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import org.jboss.logging.Logger;
|
||||
import org.postgresql.PGConnection;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
final class RedshiftDataExecution {
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftDataExecution.class);
|
||||
|
||||
private final CountDownLatch done = new CountDownLatch(1);
|
||||
private final long generation;
|
||||
private Statement statement;
|
||||
private Connection connection;
|
||||
private boolean cancellationRequested;
|
||||
private boolean committed;
|
||||
private boolean committing;
|
||||
private boolean terminal;
|
||||
private volatile boolean valid = true;
|
||||
private Runnable task;
|
||||
|
||||
RedshiftDataExecution(long generation) {
|
||||
this.generation = generation;
|
||||
}
|
||||
|
||||
long generation() {
|
||||
return generation;
|
||||
}
|
||||
|
||||
synchronized void track(Connection active) throws SQLException {
|
||||
checkCancellation();
|
||||
connection = active;
|
||||
}
|
||||
|
||||
synchronized void track(Statement active) throws SQLException {
|
||||
checkCancellation();
|
||||
statement = active;
|
||||
}
|
||||
|
||||
synchronized void untrack(Statement active) {
|
||||
if (statement == active) {
|
||||
statement = null;
|
||||
}
|
||||
}
|
||||
|
||||
synchronized void checkCancellation() throws SQLException {
|
||||
if (cancellationRequested || !valid) {
|
||||
throw new SQLException("Statement cancelled", "57014");
|
||||
}
|
||||
}
|
||||
|
||||
void commit(SqlAction action) throws SQLException {
|
||||
synchronized (this) {
|
||||
checkCancellation();
|
||||
committing = true;
|
||||
}
|
||||
try {
|
||||
action.run();
|
||||
synchronized (this) {
|
||||
committed = true;
|
||||
}
|
||||
} finally {
|
||||
synchronized (this) {
|
||||
committing = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
boolean cancel() {
|
||||
if (!requestCancellation()) {
|
||||
return false;
|
||||
}
|
||||
signalCancellation();
|
||||
Thread.startVirtualThread(() -> {
|
||||
while (isCancellationRequested() && !isDone()) {
|
||||
await(Duration.ofMillis(100));
|
||||
if (!isDone()) {
|
||||
signalCancellation();
|
||||
}
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
synchronized boolean requestCancellation() {
|
||||
if (terminal || committed || committing || cancellationRequested) {
|
||||
return false;
|
||||
}
|
||||
cancellationRequested = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
void signalCancellation() {
|
||||
Statement activeStatement;
|
||||
Connection activeConnection;
|
||||
synchronized (this) {
|
||||
activeStatement = statement;
|
||||
activeConnection = connection;
|
||||
}
|
||||
try {
|
||||
if (activeStatement != null) {
|
||||
activeStatement.cancel();
|
||||
} else if (activeConnection != null && activeConnection.isWrapperFor(PGConnection.class)) {
|
||||
activeConnection.unwrap(PGConnection.class).cancelQuery();
|
||||
}
|
||||
} catch (SQLException failure) {
|
||||
// The worker still observes cancellation before commit and rolls back its transaction.
|
||||
LOG.warnv(failure, "Unable to signal JDBC cancellation; worker will abort before commit");
|
||||
}
|
||||
}
|
||||
|
||||
synchronized boolean isCancellationRequested() {
|
||||
return cancellationRequested;
|
||||
}
|
||||
|
||||
synchronized void terminal() {
|
||||
terminal = true;
|
||||
statement = null;
|
||||
connection = null;
|
||||
}
|
||||
|
||||
void completed() {
|
||||
terminal();
|
||||
done.countDown();
|
||||
}
|
||||
|
||||
void await(Duration timeout) {
|
||||
try {
|
||||
done.await(timeout.toNanos(), TimeUnit.NANOSECONDS);
|
||||
} catch (InterruptedException expected) {
|
||||
// End the bounded wait and preserve interruption for the caller.
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
boolean isDone() {
|
||||
return done.getCount() == 0;
|
||||
}
|
||||
|
||||
boolean isValid() {
|
||||
return valid;
|
||||
}
|
||||
|
||||
void invalidate() {
|
||||
valid = false;
|
||||
}
|
||||
|
||||
void task(Runnable runnable) {
|
||||
task = runnable;
|
||||
}
|
||||
|
||||
Runnable task() {
|
||||
return task;
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
interface SqlAction {
|
||||
void run() throws SQLException;
|
||||
}
|
||||
}
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
@ApplicationScoped
|
||||
class RedshiftDataExecutor implements AutoCloseable {
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftDataExecutor.class);
|
||||
|
||||
private final ThreadPoolExecutor workers;
|
||||
private final ThreadPoolExecutor deliveries;
|
||||
private final Map<String, RedshiftDataExecution> executions = new HashMap<>();
|
||||
private final int shutdownSeconds;
|
||||
// Status writes hold the read lock; reset holds the write lock, so no write lands after a reset.
|
||||
private final ReentrantReadWriteLock resetLock = new ReentrantReadWriteLock();
|
||||
private volatile boolean closed;
|
||||
private volatile long generation;
|
||||
|
||||
@Inject
|
||||
RedshiftDataExecutor(EmulatorConfig config) {
|
||||
this(config.services().redshiftData().maxConcurrentStatements(),
|
||||
config.services().redshiftData().queueCapacity(),
|
||||
config.services().redshiftData().shutdownTimeoutSeconds());
|
||||
}
|
||||
|
||||
RedshiftDataExecutor(int concurrency, int capacity, int shutdownSeconds) {
|
||||
if (concurrency <= 0 || capacity <= 0 || shutdownSeconds < 0) {
|
||||
throw new IllegalArgumentException("Invalid Redshift Data executor limits");
|
||||
}
|
||||
this.shutdownSeconds = shutdownSeconds;
|
||||
workers = pool(concurrency, capacity, "redshift-data-sql");
|
||||
deliveries = pool(2, capacity, "redshift-data-events");
|
||||
}
|
||||
|
||||
private static ThreadPoolExecutor pool(int concurrency, int capacity, String name) {
|
||||
return new ThreadPoolExecutor(concurrency, concurrency, 0, TimeUnit.SECONDS,
|
||||
new ArrayBlockingQueue<>(capacity), runnable -> {
|
||||
Thread thread = new Thread(runnable, name);
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
}, new ThreadPoolExecutor.AbortPolicy());
|
||||
}
|
||||
|
||||
RedshiftDataExecution submit(String account, String region, String id,
|
||||
Consumer<RedshiftDataExecution> work) {
|
||||
return submit(account, region, id, () -> { }, work, (execution, failure) -> { });
|
||||
}
|
||||
|
||||
/**
|
||||
* Admits a statement. {@code admit} runs under the reset read lock, so a reset cannot slip
|
||||
* between persisting the statement and registering its execution. {@code onFailure} runs when
|
||||
* the worker dies with an unexpected exception, so the statement can still reach a terminal state.
|
||||
*/
|
||||
RedshiftDataExecution submit(String account, String region, String id, Runnable admit,
|
||||
Consumer<RedshiftDataExecution> work,
|
||||
BiConsumer<RedshiftDataExecution, RuntimeException> onFailure) {
|
||||
resetLock.readLock().lock();
|
||||
try {
|
||||
if (closed) {
|
||||
throw new AwsException("ActiveStatementsExceededException", "Data API is shutting down", 400);
|
||||
}
|
||||
String key = account + ":" + id;
|
||||
RedshiftDataExecution execution = new RedshiftDataExecution(generation);
|
||||
Runnable task = () -> {
|
||||
try {
|
||||
RequestScopes.runAs(account, region, () -> work.accept(execution));
|
||||
} catch (RuntimeException failure) {
|
||||
LOG.errorv(failure, "Redshift Data worker failed for statement {0} in account {1}", id, account);
|
||||
recover(execution, failure, onFailure, id, account, region);
|
||||
} finally {
|
||||
execution.completed();
|
||||
synchronized (this) {
|
||||
executions.remove(key, execution);
|
||||
}
|
||||
}
|
||||
};
|
||||
execution.task(task);
|
||||
admit.run();
|
||||
synchronized (this) {
|
||||
executions.put(key, execution);
|
||||
}
|
||||
try {
|
||||
workers.execute(task);
|
||||
} catch (RejectedExecutionException failure) {
|
||||
synchronized (this) {
|
||||
executions.remove(key, execution);
|
||||
}
|
||||
throw new AwsException("ActiveStatementsExceededException", "Too many active statements", 400);
|
||||
}
|
||||
return execution;
|
||||
} finally {
|
||||
resetLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private static void recover(RedshiftDataExecution execution, RuntimeException failure,
|
||||
BiConsumer<RedshiftDataExecution, RuntimeException> onFailure,
|
||||
String id, String account, String region) {
|
||||
try {
|
||||
RequestScopes.runAs(account, region, () -> onFailure.accept(execution, failure));
|
||||
} catch (RuntimeException secondary) {
|
||||
LOG.errorv(secondary, "Unable to mark statement {0} in account {1} failed after a worker error", id, account);
|
||||
}
|
||||
}
|
||||
|
||||
boolean cancel(String account, String id) {
|
||||
RedshiftDataExecution execution;
|
||||
synchronized (this) {
|
||||
execution = executions.get(account + ":" + id);
|
||||
}
|
||||
if (execution == null || !execution.cancel()) {
|
||||
return false;
|
||||
}
|
||||
if (workers.remove(execution.task())) {
|
||||
execution.task().run();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void publish(RedshiftDataExecution execution, Runnable write) {
|
||||
resetLock.readLock().lock();
|
||||
try {
|
||||
if (execution.isValid() && execution.generation() == generation) {
|
||||
write.run();
|
||||
}
|
||||
} finally {
|
||||
resetLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
void deliver(RedshiftDataExecution execution, String account, String region,
|
||||
String id, Runnable delivery) {
|
||||
resetLock.readLock().lock();
|
||||
try {
|
||||
if (!execution.isValid() || execution.generation() != generation) {
|
||||
return;
|
||||
}
|
||||
// Delivery runs outside the lock so a slow EventBridge call cannot block a reset.
|
||||
deliveries.execute(() -> RequestScopes.runAs(account, region, () -> {
|
||||
if (execution.isValid() && execution.generation() == generation) {
|
||||
try {
|
||||
delivery.run();
|
||||
} catch (RuntimeException failure) {
|
||||
// The SQL outcome is already stored; log the lost event at error level and keep the pool alive.
|
||||
LOG.errorv(failure, "Event delivery failed for statement {0}, account {1}, region {2}",
|
||||
id, account, region);
|
||||
}
|
||||
}
|
||||
}));
|
||||
} catch (RejectedExecutionException failure) {
|
||||
LOG.warnv("Event delivery rejected for statement {0}, account {1}, region {2}", id, account, region);
|
||||
} finally {
|
||||
resetLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
void clear(Runnable clearStorage) {
|
||||
List<RedshiftDataExecution> active;
|
||||
resetLock.writeLock().lock();
|
||||
try {
|
||||
generation++;
|
||||
synchronized (this) {
|
||||
active = new ArrayList<>(executions.values());
|
||||
executions.clear();
|
||||
}
|
||||
for (RedshiftDataExecution execution : active) {
|
||||
execution.invalidate();
|
||||
}
|
||||
clearStorage.run();
|
||||
} finally {
|
||||
resetLock.writeLock().unlock();
|
||||
}
|
||||
for (RedshiftDataExecution execution : active) {
|
||||
if (execution.requestCancellation()) {
|
||||
Thread.startVirtualThread(execution::signalCancellation);
|
||||
}
|
||||
if (workers.remove(execution.task())) {
|
||||
execution.completed();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@PreDestroy
|
||||
public void close() {
|
||||
synchronized (this) {
|
||||
closed = true;
|
||||
}
|
||||
long deadline = System.nanoTime() + Duration.ofSeconds(shutdownSeconds).toNanos();
|
||||
workers.shutdown();
|
||||
waitUntil(workers, deadline);
|
||||
List<RedshiftDataExecution> active;
|
||||
synchronized (this) {
|
||||
active = new ArrayList<>(executions.values());
|
||||
}
|
||||
for (RedshiftDataExecution execution : active) {
|
||||
if (execution.requestCancellation()) {
|
||||
Thread.startVirtualThread(execution::signalCancellation);
|
||||
}
|
||||
}
|
||||
for (Runnable queued : workers.shutdownNow()) {
|
||||
queued.run();
|
||||
}
|
||||
deliveries.shutdown();
|
||||
waitUntil(deliveries, deadline);
|
||||
deliveries.shutdownNow();
|
||||
}
|
||||
|
||||
private static void waitUntil(ThreadPoolExecutor pool, long deadline) {
|
||||
try {
|
||||
pool.awaitTermination(Math.max(0, deadline - System.nanoTime()), TimeUnit.NANOSECONDS);
|
||||
} catch (InterruptedException expected) {
|
||||
// Continue shutdown cleanup while preserving the caller's interruption.
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
+212
-67
@@ -4,9 +4,12 @@ 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.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.common.SqlParameterParser.ParsedSql;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.BackendSql;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumQueryPreparation;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumReadException;
|
||||
@@ -21,6 +24,7 @@ import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
@@ -28,59 +32,161 @@ import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class RedshiftDataService implements Resettable {
|
||||
|
||||
private static final int PAGE_SIZE = 1000;
|
||||
static final Pattern AUTO_COMMIT_SQL = Pattern.compile(
|
||||
"(?is)\\A(?:\\s+|--[^\\r\\n]*(?:\\r?\\n|$)|/\\*.*?\\*/)*"
|
||||
+ "(?:VACUUM\\b|(?:CREATE|DROP)\\s+(?:DATABASE|TABLESPACE)\\b|ALTER\\s+SYSTEM\\b"
|
||||
+ "|CREATE\\s+(?:UNIQUE\\s+)?INDEX\\s+CONCURRENTLY\\b|DROP\\s+INDEX\\s+CONCURRENTLY\\b"
|
||||
+ "|REINDEX\\b[^;]*?\\bCONCURRENTLY\\b)");
|
||||
|
||||
private final RedshiftDataResourceResolver resolver;
|
||||
private final RedshiftDataConnectionFactory connectionFactory;
|
||||
private final RedshiftDataStatementStore store;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final SpectrumQueryPreparation preparation;
|
||||
private final RedshiftDataExecutor executor;
|
||||
private final RedshiftDataEventPublisher publisher;
|
||||
private final RequestContext requestContext;
|
||||
private final IamService iamService;
|
||||
|
||||
public RedshiftDataService(RedshiftDataResourceResolver resolver,
|
||||
RedshiftDataConnectionFactory connectionFactory,
|
||||
RedshiftDataStatementStore store,
|
||||
ObjectMapper objectMapper) {
|
||||
this(resolver, connectionFactory, store, objectMapper, null);
|
||||
RedshiftDataService(RedshiftDataResourceResolver resolver, RedshiftDataConnectionFactory connectionFactory,
|
||||
RedshiftDataStatementStore store, ObjectMapper objectMapper, SpectrumQueryPreparation preparation,
|
||||
RedshiftDataExecutor executor, RedshiftDataEventPublisher publisher) {
|
||||
this(resolver, connectionFactory, store, objectMapper, preparation, executor, publisher, null, null);
|
||||
}
|
||||
|
||||
@Inject
|
||||
public RedshiftDataService(RedshiftDataResourceResolver resolver,
|
||||
RedshiftDataConnectionFactory connectionFactory,
|
||||
RedshiftDataStatementStore store, ObjectMapper objectMapper,
|
||||
SpectrumQueryPreparation preparation) {
|
||||
public RedshiftDataService(RedshiftDataResourceResolver resolver, RedshiftDataConnectionFactory connectionFactory,
|
||||
RedshiftDataStatementStore store, ObjectMapper objectMapper, SpectrumQueryPreparation preparation,
|
||||
RedshiftDataExecutor executor, RedshiftDataEventPublisher publisher,
|
||||
RequestContext requestContext, IamService iamService) {
|
||||
this.resolver = resolver;
|
||||
this.connectionFactory = connectionFactory;
|
||||
this.store = store;
|
||||
this.objectMapper = objectMapper;
|
||||
this.preparation = preparation;
|
||||
this.executor = executor;
|
||||
this.publisher = publisher;
|
||||
this.requestContext = requestContext;
|
||||
this.iamService = iamService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
store.clear();
|
||||
executor.clear(store::clear);
|
||||
}
|
||||
|
||||
// ── ExecuteStatement ────────────────────────────────────────────────────
|
||||
|
||||
public ObjectNode executeStatement(JsonNode request, String region) {
|
||||
PendingStatement pending = prepareStatement(request, region);
|
||||
pending.run().run();
|
||||
return executeResponse(pending.statement());
|
||||
return executeStatement(request, region, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates and resolves the request on the calling thread, so a rejected request throws here,
|
||||
* and returns the SQL run for the caller to schedule. The statement is stored as {@code STARTED}
|
||||
* first, as AWS does, so DescribeStatement can see it while the run is in flight.
|
||||
*/
|
||||
public Runnable submitStatement(JsonNode request, String region) {
|
||||
PendingStatement pending = prepareStatement(request, region);
|
||||
store.put(pending.statement());
|
||||
return pending.run();
|
||||
public ObjectNode executeStatement(JsonNode request, String region, String principal) {
|
||||
int waitSeconds = waitSeconds(request);
|
||||
return submit(prepareStatement(request, region), waitSeconds, principal);
|
||||
}
|
||||
|
||||
private ObjectNode submit(PendingStatement pending, int waitSeconds, String principal) {
|
||||
RedshiftDataStatementStore.StoredStatement stored = pending.statement();
|
||||
if (principal != null) {
|
||||
stored.principal = principal;
|
||||
}
|
||||
ObjectNode response = executeResponse(stored.snapshot());
|
||||
RedshiftDataExecution handle;
|
||||
try {
|
||||
handle = executor.submit(stored.accountId, stored.region, stored.id,
|
||||
() -> store.putForAccount(stored.accountId, stored),
|
||||
execution -> {
|
||||
try {
|
||||
execution.checkCancellation();
|
||||
stored.status = RedshiftDataStatementStore.Status.STARTED;
|
||||
executor.publish(execution, () -> store.putForAccount(stored.accountId, stored));
|
||||
pending.run().accept(execution);
|
||||
} catch (Exception failure) {
|
||||
stored.status = RedshiftDataStatementStore.Status.FAILED;
|
||||
stored.error = failure.getMessage();
|
||||
}
|
||||
complete(stored, execution);
|
||||
},
|
||||
(execution, failure) -> recoverStatement(stored, execution, failure));
|
||||
} catch (AwsException failure) {
|
||||
store.deleteForAccount(stored.accountId, stored.id);
|
||||
throw failure;
|
||||
}
|
||||
if (waitSeconds > 0) {
|
||||
handle.await(Duration.ofSeconds(waitSeconds));
|
||||
RedshiftDataStatementStore.StoredStatement current = store.getForAccount(stored.accountId, stored.id);
|
||||
if (current != null) {
|
||||
return executeResponse(current);
|
||||
}
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
private void complete(RedshiftDataStatementStore.StoredStatement stored, RedshiftDataExecution execution) {
|
||||
execution.terminal();
|
||||
if (execution.isCancellationRequested()) {
|
||||
stored.status = RedshiftDataStatementStore.Status.ABORTED;
|
||||
stored.error = "Statement cancelled";
|
||||
}
|
||||
if (stored.status != RedshiftDataStatementStore.Status.FINISHED) {
|
||||
stored.hasResultSet = false;
|
||||
stored.rows = null;
|
||||
stored.resultRows = 0;
|
||||
stored.resultSize = 0;
|
||||
}
|
||||
stored.updatedAt = Instant.now();
|
||||
executor.publish(execution, () -> {
|
||||
store.putForAccount(stored.accountId, stored);
|
||||
if (stored.withEvent && publisher != null) {
|
||||
RedshiftDataStatementStore.StoredStatement terminal = stored.snapshot();
|
||||
executor.deliver(execution, stored.accountId, stored.region, stored.id,
|
||||
() -> publisher.publish(terminal));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Last resort for a worker that died outside the statement handler: never leave a statement active. */
|
||||
private void recoverStatement(RedshiftDataStatementStore.StoredStatement stored,
|
||||
RedshiftDataExecution execution, RuntimeException failure) {
|
||||
RedshiftDataStatementStore.StoredStatement persisted = store.getForAccount(stored.accountId, stored.id);
|
||||
if (persisted != null && persisted.status != null && persisted.status.isTerminal()) {
|
||||
return;
|
||||
}
|
||||
stored.status = RedshiftDataStatementStore.Status.FAILED;
|
||||
stored.error = "Internal error: " + failure.getMessage();
|
||||
complete(stored, execution);
|
||||
}
|
||||
|
||||
private static int waitSeconds(JsonNode request) {
|
||||
if (!request.has("WaitTimeSeconds")) {
|
||||
return 0;
|
||||
}
|
||||
JsonNode wait = request.get("WaitTimeSeconds");
|
||||
if (!wait.isIntegralNumber() || !wait.canConvertToInt() || wait.asInt() < 1 || wait.asInt() > 30) {
|
||||
throw new AwsException("ValidationException", "WaitTimeSeconds must be an integer between 1 and 30", 400);
|
||||
}
|
||||
return wait.asInt();
|
||||
}
|
||||
|
||||
private void capture(RedshiftDataStatementStore.StoredStatement stored,
|
||||
RedshiftDataResourceResolver.DatabaseTarget target, String region, JsonNode request) {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(target.arn());
|
||||
stored.accountId = arn.accountId();
|
||||
stored.region = region;
|
||||
stored.resourceArn = target.arn();
|
||||
stored.withEvent = request.path("WithEvent").asBoolean(false);
|
||||
stored.expiresAt = store.expiresAt(stored.createdAt);
|
||||
if (stored.withEvent && requestContext != null && requestContext.getAccessKeyId() != null) {
|
||||
stored.principal = iamService.resolveCallerArn(requestContext.getAccessKeyId()).orElse(null);
|
||||
}
|
||||
}
|
||||
|
||||
private PendingStatement prepareStatement(JsonNode request, String region) {
|
||||
@@ -98,20 +204,40 @@ public class RedshiftDataService implements Resettable {
|
||||
stored.dbUser = target.user();
|
||||
stored.database = target.database();
|
||||
stored.resultFormat = request.path("ResultFormat").asText("JSON");
|
||||
capture(stored, target, region, request);
|
||||
|
||||
return new PendingStatement(stored, () -> {
|
||||
runStatement(stored, target, sql, parameters);
|
||||
store.put(stored);
|
||||
});
|
||||
return new PendingStatement(stored, execution -> runStatement(stored, target, sql, parameters, execution));
|
||||
}
|
||||
|
||||
private record PendingStatement(RedshiftDataStatementStore.StoredStatement statement, Runnable run) { }
|
||||
private record PendingStatement(RedshiftDataStatementStore.StoredStatement statement,
|
||||
Consumer<RedshiftDataExecution> run) { }
|
||||
|
||||
private void runStatement(RedshiftDataStatementStore.StoredStatement stored,
|
||||
RedshiftDataResourceResolver.DatabaseTarget target,
|
||||
String sql, Map<String, String> parameters) {
|
||||
String sql, Map<String, String> parameters, RedshiftDataExecution execution) {
|
||||
try (Connection connection = connectionFactory.open(target)) {
|
||||
runOnConnection(stored, connection, sql, parameters, target.spectrum());
|
||||
execution.track(connection);
|
||||
try {
|
||||
boolean autoCommit = AUTO_COMMIT_SQL.matcher(sql).find()
|
||||
|| preparation != null && target.spectrum() != null
|
||||
&& preparation.handlesDdl(sql, target.spectrum());
|
||||
if (autoCommit) {
|
||||
execution.commit(() -> runOnConnection(stored, connection, sql, parameters,
|
||||
target.spectrum(), execution, true));
|
||||
} else {
|
||||
runOnConnection(stored, connection, sql, parameters, target.spectrum(), execution, false);
|
||||
execution.commit(() -> {
|
||||
if (!connection.getAutoCommit()) {
|
||||
connection.commit();
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (SQLException failure) {
|
||||
if (!connection.getAutoCommit()) {
|
||||
connection.rollback();
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
stored.status = RedshiftDataStatementStore.Status.FAILED;
|
||||
stored.error = e.getMessage();
|
||||
@@ -138,13 +264,14 @@ public class RedshiftDataService implements Resettable {
|
||||
}
|
||||
|
||||
private void runOnConnection(RedshiftDataStatementStore.StoredStatement stored,
|
||||
Connection connection, String sql, Map<String, String> parameters, SpectrumSession context)
|
||||
Connection connection, String sql, Map<String, String> parameters, SpectrumSession context,
|
||||
RedshiftDataExecution execution, boolean autoCommit)
|
||||
throws SQLException {
|
||||
if (preparation != null && context != null) {
|
||||
SpectrumSession session = new SpectrumSession(context.accountId(), context.clusterKey(), context.databaseName(),
|
||||
context.iamRoleArns(), !connection.getAutoCommit());
|
||||
try {
|
||||
if (preparation.prepare(sql, session, new RedshiftDataBackendSql(connection))) {
|
||||
if (preparation.prepare(sql, session, new RedshiftDataBackendSql(connection, execution))) {
|
||||
stored.status = RedshiftDataStatementStore.Status.FINISHED;
|
||||
return;
|
||||
}
|
||||
@@ -158,22 +285,32 @@ public class RedshiftDataService implements Resettable {
|
||||
}
|
||||
}
|
||||
ParsedSql parsed = RedshiftDataSqlParameters.parse(sql);
|
||||
execution.checkCancellation();
|
||||
if (!autoCommit) {
|
||||
connection.setAutoCommit(false);
|
||||
}
|
||||
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()) {
|
||||
rejectResultTypesRedshiftLacks(rs.getMetaData());
|
||||
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);
|
||||
execution.track(statement);
|
||||
try {
|
||||
RedshiftDataSqlParameters.bind(statement, parsed.parameterOrder(), parameters);
|
||||
execution.checkCancellation();
|
||||
boolean hasResultSet = statement.execute();
|
||||
if (hasResultSet) {
|
||||
try (ResultSet rs = statement.getResultSet()) {
|
||||
rejectResultTypesRedshiftLacks(rs.getMetaData());
|
||||
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);
|
||||
}
|
||||
} else {
|
||||
stored.hasResultSet = false;
|
||||
stored.resultRows = Math.max(statement.getUpdateCount(), 0);
|
||||
} finally {
|
||||
execution.untrack(statement);
|
||||
}
|
||||
}
|
||||
stored.durationNanos = System.nanoTime() - t0;
|
||||
@@ -336,16 +473,12 @@ public class RedshiftDataService implements Resettable {
|
||||
// ── BatchExecuteStatement ──────────────────────────────────────────────
|
||||
|
||||
public ObjectNode batchExecuteStatement(JsonNode request, String region) {
|
||||
PendingStatement pending = prepareBatch(request, region);
|
||||
pending.run().run();
|
||||
return executeResponse(pending.statement());
|
||||
return batchExecuteStatement(request, region, null);
|
||||
}
|
||||
|
||||
/** Batch counterpart of {@link #submitStatement}. */
|
||||
public Runnable submitBatch(JsonNode request, String region) {
|
||||
PendingStatement pending = prepareBatch(request, region);
|
||||
store.put(pending.statement());
|
||||
return pending.run();
|
||||
public ObjectNode batchExecuteStatement(JsonNode request, String region, String principal) {
|
||||
int waitSeconds = waitSeconds(request);
|
||||
return submit(prepareBatch(request, region), waitSeconds, principal);
|
||||
}
|
||||
|
||||
private PendingStatement prepareBatch(JsonNode request, String region) {
|
||||
@@ -370,15 +503,17 @@ public class RedshiftDataService implements Resettable {
|
||||
parent.database = target.database();
|
||||
parent.resultFormat = request.path("ResultFormat").asText("JSON");
|
||||
parent.subStatements = new ArrayList<>();
|
||||
capture(parent, target, region, request);
|
||||
|
||||
return new PendingStatement(parent, () -> runBatch(parent, sqls, target));
|
||||
return new PendingStatement(parent, execution -> runBatch(parent, sqls, target, execution));
|
||||
}
|
||||
|
||||
private void runBatch(RedshiftDataStatementStore.StoredStatement parent, List<String> sqls,
|
||||
RedshiftDataResourceResolver.DatabaseTarget target) {
|
||||
RedshiftDataResourceResolver.DatabaseTarget target, RedshiftDataExecution execution) {
|
||||
long totalDuration = 0;
|
||||
try (Connection connection = connectionFactory.open(target)) {
|
||||
BackendSql batchBackend = new RedshiftDataBackendSql(connection);
|
||||
execution.track(connection);
|
||||
BackendSql batchBackend = new RedshiftDataBackendSql(connection, execution);
|
||||
boolean committed = false;
|
||||
try {
|
||||
connection.setAutoCommit(false);
|
||||
@@ -397,13 +532,14 @@ public class RedshiftDataService implements Resettable {
|
||||
sub.createdAt = now;
|
||||
sub.updatedAt = now;
|
||||
try {
|
||||
runOnConnection(sub, connection, sqls.get(n), Map.of(), target.spectrum());
|
||||
execution.checkCancellation();
|
||||
runOnConnection(sub, connection, sqls.get(n), Map.of(), target.spectrum(), execution, false);
|
||||
} catch (SQLException e) {
|
||||
sub.status = RedshiftDataStatementStore.Status.FAILED;
|
||||
sub.error = e.getMessage();
|
||||
sub.updatedAt = Instant.now();
|
||||
parent.subStatements.add(sub);
|
||||
store.put(sub);
|
||||
executor.publish(execution, () -> store.putForAccount(parent.accountId, sub));
|
||||
totalDuration += sub.durationNanos;
|
||||
parent.status = RedshiftDataStatementStore.Status.FAILED;
|
||||
parent.error = e.getMessage();
|
||||
@@ -413,11 +549,14 @@ public class RedshiftDataService implements Resettable {
|
||||
}
|
||||
sub.updatedAt = Instant.now();
|
||||
parent.subStatements.add(sub);
|
||||
store.put(sub);
|
||||
executor.publish(execution, () -> {
|
||||
store.putForAccount(parent.accountId, sub);
|
||||
store.putForAccount(parent.accountId, parent);
|
||||
});
|
||||
totalDuration += sub.durationNanos;
|
||||
}
|
||||
if (!failed) {
|
||||
connection.commit();
|
||||
execution.commit(connection::commit);
|
||||
committed = true;
|
||||
parent.status = RedshiftDataStatementStore.Status.FINISHED;
|
||||
}
|
||||
@@ -448,7 +587,6 @@ public class RedshiftDataService implements Resettable {
|
||||
}
|
||||
parent.durationNanos = totalDuration;
|
||||
parent.updatedAt = Instant.now();
|
||||
store.put(parent);
|
||||
}
|
||||
|
||||
// ── ListStatements ─────────────────────────────────────────────────────
|
||||
@@ -506,13 +644,13 @@ public class RedshiftDataService implements Resettable {
|
||||
|
||||
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();
|
||||
if (stored.status.isTerminal()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Could not cancel a query that is already in " + stored.status.name() + " state with ID: " + stored.id,
|
||||
400);
|
||||
}
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("Status", true);
|
||||
response.put("Status", executor.cancel(stored.accountId, stored.id));
|
||||
return response;
|
||||
}
|
||||
|
||||
@@ -700,7 +838,7 @@ public class RedshiftDataService implements Resettable {
|
||||
Instant now = Instant.now();
|
||||
stored.createdAt = now;
|
||||
stored.updatedAt = now;
|
||||
stored.status = RedshiftDataStatementStore.Status.STARTED;
|
||||
stored.status = RedshiftDataStatementStore.Status.SUBMITTED;
|
||||
return stored;
|
||||
}
|
||||
|
||||
@@ -715,7 +853,14 @@ public class RedshiftDataService implements Resettable {
|
||||
|
||||
private RedshiftDataStatementStore.StoredStatement resultBearing(JsonNode request) {
|
||||
RedshiftDataStatementStore.StoredStatement stored = require(request);
|
||||
if (!stored.hasResultSet || stored.rows == null) {
|
||||
int childSuffix = stored.id.indexOf(':');
|
||||
if (childSuffix >= 0) {
|
||||
RedshiftDataStatementStore.StoredStatement parent = store.get(stored.id.substring(0, childSuffix));
|
||||
if (parent == null || parent.status != RedshiftDataStatementStore.Status.FINISHED) {
|
||||
throw new AwsException("ValidationException", "Statement has no result set", 400);
|
||||
}
|
||||
}
|
||||
if (stored.status != RedshiftDataStatementStore.Status.FINISHED || !stored.hasResultSet || stored.rows == null) {
|
||||
throw new AwsException("ValidationException", "Statement has no result set", 400);
|
||||
}
|
||||
return stored;
|
||||
|
||||
+91
-5
@@ -28,7 +28,13 @@ class RedshiftDataStatementStore {
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftDataStatementStore.class);
|
||||
|
||||
@RegisterForReflection
|
||||
enum Status { PICKED, STARTED, FINISHED, FAILED, ABORTED }
|
||||
enum Status {
|
||||
SUBMITTED, PICKED, STARTED, FINISHED, FAILED, ABORTED;
|
||||
|
||||
boolean isTerminal() {
|
||||
return this == FINISHED || this == FAILED || this == 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
|
||||
@@ -56,6 +62,16 @@ class RedshiftDataStatementStore {
|
||||
|
||||
@PostConstruct
|
||||
void start() {
|
||||
for (AccountAwareStorageBackend.AccountEntry<StoredStatement> entry
|
||||
: statements.scanAllAccountEntries(k -> true)) {
|
||||
StoredStatement interrupted = entry.value().snapshot();
|
||||
if (interrupted.status != null && !interrupted.status.isTerminal()) {
|
||||
interrupted.status = Status.FAILED;
|
||||
interrupted.error = "Execution interrupted by emulator restart";
|
||||
interrupted.updatedAt = Instant.now(clock);
|
||||
statements.putForAccount(entry.accountId(), entry.key(), interrupted);
|
||||
}
|
||||
}
|
||||
sweeper = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "redshift-data-statement-sweep");
|
||||
t.setDaemon(true);
|
||||
@@ -72,15 +88,31 @@ class RedshiftDataStatementStore {
|
||||
}
|
||||
|
||||
void put(StoredStatement statement) {
|
||||
statements.put(statement.id, statement);
|
||||
statements.put(statement.id, statement.snapshot());
|
||||
}
|
||||
|
||||
void putForAccount(String accountId, StoredStatement statement) {
|
||||
statements.putForAccount(accountId, statement.id, statement.snapshot());
|
||||
}
|
||||
|
||||
void deleteForAccount(String accountId, String id) {
|
||||
statements.deleteForAccount(accountId, id);
|
||||
}
|
||||
|
||||
Instant expiresAt(Instant createdAt) {
|
||||
return createdAt.plus(ttl);
|
||||
}
|
||||
|
||||
StoredStatement get(String id) {
|
||||
return statements.get(id).orElse(null);
|
||||
return statements.get(id).map(StoredStatement::snapshot).orElse(null);
|
||||
}
|
||||
|
||||
StoredStatement getForAccount(String accountId, String id) {
|
||||
return statements.getForAccount(accountId, id).map(StoredStatement::snapshot).orElse(null);
|
||||
}
|
||||
|
||||
List<StoredStatement> values() {
|
||||
return statements.scan(k -> true);
|
||||
return statements.scan(k -> true).stream().map(StoredStatement::summary).toList();
|
||||
}
|
||||
|
||||
void clear() {
|
||||
@@ -93,7 +125,8 @@ class RedshiftDataStatementStore {
|
||||
// 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)) {
|
||||
if (entry.value().status != null && entry.value().status.isTerminal()
|
||||
&& entry.value().createdAt.isBefore(cutoff)) {
|
||||
statements.deleteForAccount(entry.accountId(), entry.key());
|
||||
}
|
||||
}
|
||||
@@ -132,5 +165,58 @@ class RedshiftDataStatementStore {
|
||||
ArrayNode columnMetadata;
|
||||
List<ArrayNode> rows;
|
||||
List<StoredStatement> subStatements;
|
||||
String accountId;
|
||||
String region;
|
||||
String resourceArn;
|
||||
String principal;
|
||||
boolean withEvent;
|
||||
Instant expiresAt;
|
||||
|
||||
/**
|
||||
* Independent copy for storage and reads. Result data is written once when the statement
|
||||
* completes, so the row nodes and column metadata are shared instead of deep-copied.
|
||||
*/
|
||||
StoredStatement snapshot() {
|
||||
return copy(true);
|
||||
}
|
||||
|
||||
/** Copy without result data or sub-statements, for listings that only need statement metadata. */
|
||||
StoredStatement summary() {
|
||||
return copy(false);
|
||||
}
|
||||
|
||||
private StoredStatement copy(boolean withResults) {
|
||||
StoredStatement copy = new StoredStatement();
|
||||
copy.id = id;
|
||||
copy.sql = sql;
|
||||
copy.sqls = sqls == null ? null : List.copyOf(sqls);
|
||||
copy.batch = batch;
|
||||
copy.statementName = statementName;
|
||||
copy.clusterIdentifier = clusterIdentifier;
|
||||
copy.workgroupName = workgroupName;
|
||||
copy.database = database;
|
||||
copy.dbUser = dbUser;
|
||||
copy.resultFormat = resultFormat;
|
||||
copy.status = status;
|
||||
copy.error = error;
|
||||
copy.createdAt = createdAt;
|
||||
copy.updatedAt = updatedAt;
|
||||
copy.durationNanos = durationNanos;
|
||||
copy.hasResultSet = hasResultSet;
|
||||
copy.resultRows = resultRows;
|
||||
copy.resultSize = resultSize;
|
||||
if (withResults) {
|
||||
copy.columnMetadata = columnMetadata;
|
||||
copy.rows = rows == null ? null : List.copyOf(rows);
|
||||
copy.subStatements = subStatements == null ? null : subStatements.stream().map(StoredStatement::snapshot).toList();
|
||||
}
|
||||
copy.accountId = accountId;
|
||||
copy.region = region;
|
||||
copy.resourceArn = resourceArn;
|
||||
copy.principal = principal;
|
||||
copy.withEvent = withEvent;
|
||||
copy.expiresAt = expiresAt;
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.scheduler;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
@@ -23,7 +24,6 @@ import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsService;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -36,10 +36,6 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Delivers an EventBridge Scheduler target invocation to the underlying service.
|
||||
@@ -71,7 +67,6 @@ public class ScheduleInvoker {
|
||||
private final String baseUrl;
|
||||
private final String defaultRegion;
|
||||
private final ServiceRegistry serviceRegistry;
|
||||
private final Executor redshiftDataExecutor;
|
||||
|
||||
@Inject
|
||||
public ScheduleInvoker(SqsService sqsService,
|
||||
@@ -84,21 +79,6 @@ public class ScheduleInvoker {
|
||||
ObjectMapper objectMapper,
|
||||
EmulatorConfig config,
|
||||
ServiceRegistry serviceRegistry) {
|
||||
this(sqsService, lambdaService, snsService, eventBridgeService, ecsService, stepFunctionsService,
|
||||
redshiftDataService, objectMapper, config, serviceRegistry, newRedshiftDataExecutor());
|
||||
}
|
||||
|
||||
ScheduleInvoker(SqsService sqsService,
|
||||
LambdaService lambdaService,
|
||||
SnsService snsService,
|
||||
EventBridgeService eventBridgeService,
|
||||
EcsService ecsService,
|
||||
StepFunctionsService stepFunctionsService,
|
||||
RedshiftDataService redshiftDataService,
|
||||
ObjectMapper objectMapper,
|
||||
EmulatorConfig config,
|
||||
ServiceRegistry serviceRegistry,
|
||||
Executor redshiftDataExecutor) {
|
||||
this.sqsService = sqsService;
|
||||
this.lambdaService = lambdaService;
|
||||
this.snsService = snsService;
|
||||
@@ -110,22 +90,6 @@ public class ScheduleInvoker {
|
||||
this.baseUrl = config.baseUrl();
|
||||
this.defaultRegion = config.defaultRegion();
|
||||
this.serviceRegistry = serviceRegistry;
|
||||
this.redshiftDataExecutor = redshiftDataExecutor;
|
||||
}
|
||||
|
||||
private static ExecutorService newRedshiftDataExecutor() {
|
||||
return Executors.newCachedThreadPool(r -> {
|
||||
Thread t = new Thread(r, "scheduler-redshift-data");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
if (redshiftDataExecutor instanceof ExecutorService service) {
|
||||
service.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -152,7 +116,7 @@ public class ScheduleInvoker {
|
||||
String input = contextualInput(schedule, scheduledAt, executionId, attemptNumber);
|
||||
if (isUniversalTarget(arn)) {
|
||||
invokeUniversalTarget(arn.substring(arn.indexOf(":aws-sdk:") + ":aws-sdk:".length()),
|
||||
input, region, schedule.getAccountId());
|
||||
input, region, schedule.getAccountId(), target.getRoleArn());
|
||||
return universalTargetRequest(input);
|
||||
}
|
||||
|
||||
@@ -450,7 +414,7 @@ public class ScheduleInvoker {
|
||||
* statement storage is account-aware and the dispatcher thread carries no request account.
|
||||
*/
|
||||
private void invokeUniversalTarget(String serviceAction, String input, String region,
|
||||
String scheduleAccountId) {
|
||||
String scheduleAccountId, String principal) {
|
||||
JsonNode params;
|
||||
try {
|
||||
params = objectMapper.readTree(input == null || input.isBlank() ? "{}" : input);
|
||||
@@ -485,12 +449,16 @@ public class ScheduleInvoker {
|
||||
}
|
||||
case "redshiftdata:executeStatement" -> {
|
||||
requireRedshiftData();
|
||||
submitRedshiftData(scheduleAccountId, region, () -> redshiftDataService.submitStatement(params, region));
|
||||
JsonNode executeParams = withoutWait(params);
|
||||
RequestScopes.callAs(scheduleAccountId, region,
|
||||
() -> redshiftDataService.executeStatement(executeParams, region, principal));
|
||||
LOG.debugv("Scheduler submitted to the Redshift Data API (universal target): {0}", serviceAction);
|
||||
}
|
||||
case "redshiftdata:batchExecuteStatement" -> {
|
||||
requireRedshiftData();
|
||||
submitRedshiftData(scheduleAccountId, region, () -> redshiftDataService.submitBatch(params, region));
|
||||
JsonNode batchParams = withoutWait(params);
|
||||
RequestScopes.callAs(scheduleAccountId, region,
|
||||
() -> redshiftDataService.batchExecuteStatement(batchParams, region, principal));
|
||||
LOG.debugv("Scheduler submitted to the Redshift Data API (universal target): {0}", serviceAction);
|
||||
}
|
||||
default -> throw new UnsupportedOperationException(
|
||||
@@ -498,29 +466,22 @@ public class ScheduleInvoker {
|
||||
}
|
||||
}
|
||||
|
||||
// The shared dispatcher thread must never wait for a statement to finish.
|
||||
private static JsonNode withoutWait(JsonNode params) {
|
||||
if (params instanceof ObjectNode object && object.has("WaitTimeSeconds")) {
|
||||
ObjectNode copy = object.deepCopy();
|
||||
copy.remove("WaitTimeSeconds");
|
||||
return copy;
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
private void requireRedshiftData() {
|
||||
if (!serviceRegistry.isServiceEnabled("redshift-data")) {
|
||||
throw new AwsException("ServiceNotAvailableException", "Service redshift-data is not enabled.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The Data API is asynchronous: AWS returns once the statement is submitted. The request check
|
||||
* runs here, so a rejected request still fails the occurrence and is retried, while the SQL runs
|
||||
* on its own thread so a slow statement cannot hold up the single dispatcher thread. Both halves
|
||||
* run as the schedule's account, which neither thread carries.
|
||||
*/
|
||||
private void submitRedshiftData(String scheduleAccountId, String region, Supplier<Runnable> submit) {
|
||||
Runnable statement = RequestScopes.callAs(scheduleAccountId, region, submit);
|
||||
redshiftDataExecutor.execute(() -> {
|
||||
try {
|
||||
RequestScopes.runAs(scheduleAccountId, region, statement);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Scheduled Redshift Data statement failed: {0}", e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static Map<String, MessageAttributeValue> parseUniversalSqsMessageAttributes(JsonNode attrsNode) {
|
||||
Map<String, MessageAttributeValue> attributes = new HashMap<>();
|
||||
if (attrsNode == null || !attrsNode.isObject()) {
|
||||
|
||||
Reference in new issue
Block a user