feat(redshift-data): support session reuse (#6396)

* feat(redshift-data): support session reuse

* fix(redshift-data): address session lifecycle review findings

* fix(test): assert Redshift cancellation monitor directly
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-24 00:01:55 -04:00
1 parent eb84c9d65a
commit 348874766f
11 files changed
+1806 -41

No files matched your search

@@ -95,13 +95,10 @@ final class RedshiftDataExecution {
return true;
}
void signalCancellation() {
Statement activeStatement;
Connection activeConnection;
synchronized (this) {
activeStatement = statement;
activeConnection = connection;
}
synchronized void signalCancellation() {
// terminal() must wait until the old cancellation reaches JDBC before the connection can be reused.
Statement activeStatement = statement;
Connection activeConnection = connection;
try {
if (activeStatement != null) {
activeStatement.cancel();
@@ -62,10 +62,15 @@ class RedshiftDataIdempotencyStore {
}
void put(Scope scope, ObjectNode response) {
put(scope, response, null);
}
void put(Scope scope, ObjectNode response, String sessionOwner) {
Receipt receipt = new Receipt();
receipt.acceptedAt = clock.instant();
receipt.expiresAt = receipt.acceptedAt.plus(TOKEN_TTL);
receipt.response = response.deepCopy();
receipt.sessionOwner = sessionOwner;
mutations.readLock().lock();
try {
receipts.putAllAtomicallyForAccount(scope.accountId(), Map.of(scope.key(), receipt));
@@ -137,12 +142,14 @@ class RedshiftDataIdempotencyStore {
Instant acceptedAt;
Instant expiresAt;
ObjectNode response;
String sessionOwner;
Receipt snapshot() {
Receipt copy = new Receipt();
copy.acceptedAt = acceptedAt;
copy.expiresAt = expiresAt;
copy.response = response.deepCopy();
copy.sessionOwner = sessionOwner;
return copy;
}
}
@@ -32,11 +32,14 @@ import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.BiConsumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ApplicationScoped
@@ -48,6 +51,10 @@ public class RedshiftDataService implements Resettable {
+ "(?: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 static final Pattern TRANSACTION_CONTROL = Pattern.compile(
"(?is)\\A(BEGIN|START\\s+TRANSACTION|COMMIT|END|ROLLBACK|ABORT)(?:\\s+(?:WORK|TRANSACTION))?\\s*;?\\s*\\z");
private static final Pattern TRANSACTION_PREFIX = Pattern.compile("(?is)\\A(?:BEGIN|START|COMMIT|END|ROLLBACK|ABORT)\\b");
private static final Pattern TRANSACTION_COMMENTS = Pattern.compile("(?s)/\\*.*?\\*/|--[^\\r\\n]*");
private final RedshiftDataResourceResolver resolver;
private final RedshiftDataConnectionFactory connectionFactory;
@@ -59,6 +66,7 @@ public class RedshiftDataService implements Resettable {
private final RequestContext requestContext;
private final IamService iamService;
private final RedshiftDataIdempotencyStore idempotency;
private final RedshiftDataSessions sessions;
private final ConcurrentHashMap<RedshiftDataIdempotencyStore.Scope, AdmissionLock> admissionLocks = new ConcurrentHashMap<>();
RedshiftDataService(RedshiftDataResourceResolver resolver, RedshiftDataConnectionFactory connectionFactory,
@@ -69,11 +77,20 @@ public class RedshiftDataService implements Resettable {
Clock.systemUTC()));
}
RedshiftDataService(RedshiftDataResourceResolver resolver, RedshiftDataConnectionFactory connectionFactory,
RedshiftDataStatementStore store, ObjectMapper objectMapper, SpectrumQueryPreparation preparation,
RedshiftDataExecutor executor, RedshiftDataEventPublisher publisher,
RequestContext requestContext, IamService iamService, RedshiftDataIdempotencyStore idempotency) {
this(resolver, connectionFactory, store, objectMapper, preparation, executor, publisher,
requestContext, iamService, idempotency, new RedshiftDataSessions());
}
@Inject
public RedshiftDataService(RedshiftDataResourceResolver resolver, RedshiftDataConnectionFactory connectionFactory,
RedshiftDataStatementStore store, ObjectMapper objectMapper, SpectrumQueryPreparation preparation,
RedshiftDataExecutor executor, RedshiftDataEventPublisher publisher,
RequestContext requestContext, IamService iamService, RedshiftDataIdempotencyStore idempotency) {
RequestContext requestContext, IamService iamService, RedshiftDataIdempotencyStore idempotency,
RedshiftDataSessions sessions) {
this.resolver = resolver;
this.connectionFactory = connectionFactory;
this.store = store;
@@ -84,23 +101,33 @@ public class RedshiftDataService implements Resettable {
this.requestContext = requestContext;
this.iamService = iamService;
this.idempotency = idempotency;
this.sessions = sessions;
}
@Override
public void clear() {
executor.clear(() -> {
RuntimeException failure = null;
try {
sessions.clear();
} catch (RuntimeException sessionFailure) {
failure = sessionFailure;
}
try {
store.clear();
} catch (RuntimeException storageFailure) {
failure = storageFailure;
if (failure == null) {
failure = storageFailure;
} else if (failure != storageFailure) {
failure.addSuppressed(storageFailure);
}
}
try {
idempotency.clear();
} catch (RuntimeException receiptFailure) {
if (failure == null) {
failure = receiptFailure;
} else {
} else if (failure != receiptFailure) {
failure.addSuppressed(receiptFailure);
}
}
@@ -123,12 +150,31 @@ public class RedshiftDataService implements Resettable {
private ObjectNode execute(JsonNode request, String region, String principal, boolean batch) {
String token = RedshiftDataIdempotencyStore.clientToken(request);
int waitSeconds = waitSeconds(request);
PendingStatement pending = batch ? prepareBatch(request, region) : prepareStatement(request, region);
RedshiftDataSessions.validate(request);
boolean retained = request.has("SessionId") || request.path("SessionKeepAliveSeconds").asInt() > 0;
RedshiftDataSessions.Scope owner = retained ? sessionScope(region, principal)
: new RedshiftDataSessions.Scope(store.accountId(), region, null);
if (token != null && request.has("SessionId")) {
RedshiftDataIdempotencyStore.Scope retryScope = new RedshiftDataIdempotencyStore.Scope(
owner.accountId(), region, batch ? "BatchExecuteStatement" : "ExecuteStatement", token);
Admission replay = executor.admitting(() -> {
RedshiftDataIdempotencyStore.Receipt receipt = idempotency.find(retryScope);
return receipt == null ? null : replay(receipt, retryScope, owner, principal);
});
if (replay != null) {
return awaitAdmission(replay, waitSeconds);
}
}
PendingStatement pending = batch ? prepareBatch(request, region, owner) : prepareStatement(request, region, owner);
RedshiftDataStatementStore.StoredStatement stored = pending.statement();
RedshiftDataIdempotencyStore.Scope scope = token == null ? null : new RedshiftDataIdempotencyStore.Scope(
stored.accountId, region, batch ? "BatchExecuteStatement" : "ExecuteStatement", token);
Admission admission = executor.admitting(() -> scope == null ? submit(pending, principal, null)
: admitScoped(pending, principal, scope));
return awaitAdmission(admission, waitSeconds);
}
private ObjectNode awaitAdmission(Admission admission, int waitSeconds) {
if (waitSeconds > 0 && admission.execution() != null) {
admission.execution().await(Duration.ofSeconds(waitSeconds));
RedshiftDataStatementStore.StoredStatement current = store.getForAccount(admission.accountId(), admission.id());
@@ -139,6 +185,30 @@ public class RedshiftDataService implements Resettable {
return admission.response();
}
private RedshiftDataSessions.Scope sessionScope(String region, String principal) {
String caller = principal;
if (caller == null && requestContext != null && requestContext.getAccessKeyId() != null) {
String accessKey = requestContext.getAccessKeyId();
caller = iamService == null ? "access-key:" + accessKey
: iamService.resolveCallerArn(accessKey).orElse("access-key:" + accessKey);
}
return new RedshiftDataSessions.Scope(store.accountId(), region, caller == null ? "anonymous" : caller);
}
private Admission replay(RedshiftDataIdempotencyStore.Receipt receipt, RedshiftDataIdempotencyStore.Scope scope,
RedshiftDataSessions.Scope owner, String principal) {
if (receipt.sessionOwner != null) {
String caller = owner.caller() == null ? sessionScope(scope.region(), principal).caller() : owner.caller();
if (!Objects.equals(receipt.sessionOwner, caller)) {
throw new AwsException("ResourceNotFoundException", "Session was not found", 400);
}
}
String id = receipt.response.path("Id").asText();
RedshiftDataStatementStore.StoredStatement current = store.getForAccount(scope.accountId(), id);
return new Admission(scope.accountId(), id, current == null ? receipt.response : executeResponse(current),
executor.execution(scope.accountId(), id));
}
private record Admission(String accountId, String id, ObjectNode response, RedshiftDataExecution execution) { }
private static final class AdmissionLock {
@@ -158,10 +228,7 @@ public class RedshiftDataService implements Resettable {
if (receipt == null) {
return submit(pending, principal, scope);
}
String id = receipt.response.path("Id").asText();
RedshiftDataStatementStore.StoredStatement current = store.getForAccount(scope.accountId(), id);
return new Admission(scope.accountId(), id, current == null ? receipt.response : executeResponse(current),
executor.execution(scope.accountId(), id));
return replay(receipt, scope, pending.owner(), principal);
} finally {
scoped.lock.unlock();
admissionLocks.compute(scope, (key, existing) -> --scoped.users == 0 ? null : scoped);
@@ -173,6 +240,10 @@ public class RedshiftDataService implements Resettable {
if (principal != null) {
stored.principal = principal;
}
RedshiftDataSessions.Reservation session = sessions.reserve(pending.owner(), pending.request(), pending.target());
if (session != null) {
stored.sessionId = session.id();
}
ObjectNode response = executeResponse(stored.snapshot());
RedshiftDataExecution handle;
try {
@@ -182,23 +253,41 @@ public class RedshiftDataService implements Resettable {
store.putForAccount(stored.accountId, stored);
} else {
store.admitForAccount(stored.accountId, stored);
idempotency.put(scope, response);
if (session == null) {
idempotency.put(scope, response);
} else {
idempotency.put(scope, response, pending.owner().caller());
}
}
if (session != null) {
session.admitted();
}
},
execution -> {
try {
execution.checkCancellation();
if (session != null) {
session.bind(execution);
}
stored.status = RedshiftDataStatementStore.Status.STARTED;
executor.publish(execution, () -> store.putForAccount(stored.accountId, stored));
pending.run().accept(execution);
pending.run().accept(execution, session);
} catch (Exception failure) {
stored.status = RedshiftDataStatementStore.Status.FAILED;
stored.error = failure.getMessage();
} finally {
execution.terminal();
if (session != null) {
session.finish();
}
}
complete(stored, execution);
},
(execution, failure) -> recoverStatement(stored, execution, failure));
} catch (RuntimeException failure) {
if (session != null) {
session.abort();
}
try {
if (scope != null) {
idempotency.removeIfStatement(scope, stored.id);
@@ -275,54 +364,121 @@ public class RedshiftDataService implements Resettable {
}
}
private PendingStatement prepareStatement(JsonNode request, String region) {
private PendingStatement prepareStatement(JsonNode request, String region, RedshiftDataSessions.Scope owner) {
String sql = requiredText(request, "Sql");
rejectMultiStatement(sql);
Map<String, String> parameters = RedshiftDataSqlParameters.parseParameters(request, "Parameters");
RedshiftDataResourceResolver.DatabaseTarget target = resolver.resolve(request, region);
ResolvedTarget resolved = resolveTarget(request, region, owner);
RedshiftDataResourceResolver.DatabaseTarget target = resolved.target();
RedshiftDataStatementStore.StoredStatement stored = newStatement(request);
stored.sql = sql;
stored.sqls = List.of(sql);
stored.clusterIdentifier = clusterIdentifierOrNull(request);
stored.workgroupName = workgroupNameOrNull(request);
stored.clusterIdentifier = clusterIdentifierOrNull(resolved.parameters());
stored.workgroupName = workgroupNameOrNull(resolved.parameters());
stored.dbUser = target.user();
stored.database = target.database();
stored.resultFormat = request.path("ResultFormat").asText("JSON");
capture(stored, target, region, request);
return new PendingStatement(stored, execution -> runStatement(stored, target, sql, parameters, execution));
return new PendingStatement(stored, (execution, session) -> runStatement(stored, target, sql, parameters, execution, session),
target, request.deepCopy(), owner);
}
private record PendingStatement(RedshiftDataStatementStore.StoredStatement statement,
Consumer<RedshiftDataExecution> run) { }
BiConsumer<RedshiftDataExecution, RedshiftDataSessions.Reservation> run,
RedshiftDataResourceResolver.DatabaseTarget target, JsonNode request,
RedshiftDataSessions.Scope owner) { }
private record ResolvedTarget(RedshiftDataResourceResolver.DatabaseTarget target, JsonNode parameters) { }
private ResolvedTarget resolveTarget(JsonNode request, String region, RedshiftDataSessions.Scope owner) {
if (request.has("SessionId")) {
RedshiftDataSessions.Session session = sessions.find(owner, request.get("SessionId").asText());
return new ResolvedTarget(session.target(request), session.parameters());
}
return new ResolvedTarget(resolver.resolve(request, region), request);
}
private ConnectionUse connection(RedshiftDataResourceResolver.DatabaseTarget target,
RedshiftDataSessions.Reservation session) throws SQLException {
return new ConnectionUse(session == null ? connectionFactory.open(target) : session.connection(connectionFactory), session);
}
private record ConnectionUse(Connection connection, RedshiftDataSessions.Reservation session) implements AutoCloseable {
@Override
public void close() throws SQLException {
if (session == null) {
connection.close();
return;
}
try {
if (connection.isClosed()) {
session.discard();
} else if (!session.inTransaction() && !connection.getAutoCommit()) {
// A failed batch or worker must not leak an open transaction to the next request.
connection.rollback();
connection.setAutoCommit(true);
}
} catch (SQLException | RuntimeException failure) {
try {
session.discard();
} catch (RuntimeException cleanupFailure) {
failure.addSuppressed(cleanupFailure);
}
throw failure;
}
}
}
private void runStatement(RedshiftDataStatementStore.StoredStatement stored,
RedshiftDataResourceResolver.DatabaseTarget target,
String sql, Map<String, String> parameters, RedshiftDataExecution execution) {
try (Connection connection = connectionFactory.open(target)) {
String sql, Map<String, String> parameters, RedshiftDataExecution execution,
RedshiftDataSessions.Reservation session) {
try (ConnectionUse use = connection(target, session)) {
Connection connection = use.connection();
execution.track(connection);
try {
if (session != null && transactionControl(stored, sql, connection, session, execution)) {
return;
}
if (session != null && session.transactionFailed()) {
throw new SQLException("Current transaction is aborted; use COMMIT or ROLLBACK to end it", "25P02");
}
boolean autoCommit = AUTO_COMMIT_SQL.matcher(sql).find()
|| preparation != null && target.spectrum() != null
&& preparation.handlesDdl(sql, target.spectrum());
if (autoCommit) {
if (session != null && session.inTransaction()) {
throw new SQLException("Statement cannot run inside a transaction block", "25001");
}
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()) {
if ((session == null || !session.inTransaction()) && !connection.getAutoCommit()) {
connection.commit();
}
});
}
} catch (SQLException failure) {
if (!connection.getAutoCommit()) {
if (session != null && failure.getSQLState() != null && failure.getSQLState().startsWith("08")) {
session.discard();
throw failure;
}
if (session != null && session.inTransaction()) {
session.failTransaction();
} else if (!connection.getAutoCommit()) {
connection.rollback();
}
throw failure;
} catch (RuntimeException failure) {
if (session != null && session.inTransaction()) {
session.failTransaction();
}
throw failure;
}
} catch (SQLException e) {
stored.status = RedshiftDataStatementStore.Status.FAILED;
@@ -331,6 +487,52 @@ public class RedshiftDataService implements Resettable {
stored.updatedAt = Instant.now();
}
private boolean transactionControl(RedshiftDataStatementStore.StoredStatement stored, String sql,
Connection connection, RedshiftDataSessions.Reservation session,
RedshiftDataExecution execution) throws SQLException {
String normalized = TRANSACTION_COMMENTS.matcher(sql).replaceAll(" ").trim();
Matcher control = TRANSACTION_CONTROL.matcher(normalized);
if (!control.matches()) {
if (TRANSACTION_PREFIX.matcher(normalized).find()) {
throw new SQLException("Transaction control modifiers are not supported", "0A000");
}
return false;
}
String command = control.group(1).toUpperCase(Locale.ROOT).split("\\s+")[0];
execution.commit(() -> {
switch (command) {
case "BEGIN", "START" -> {
if (session.transactionFailed()) {
throw new SQLException("Current transaction is aborted; use COMMIT or ROLLBACK to end it", "25P02");
}
connection.setAutoCommit(false);
session.transaction(true);
}
case "COMMIT", "END" -> {
if (!connection.getAutoCommit()) {
if (session.transactionFailed()) {
connection.rollback();
} else {
connection.commit();
}
}
session.transaction(false);
connection.setAutoCommit(true);
}
default -> {
if (!connection.getAutoCommit()) {
connection.rollback();
}
session.transaction(false);
connection.setAutoCommit(true);
}
}
});
stored.status = RedshiftDataStatementStore.Status.FINISHED;
stored.updatedAt = Instant.now();
return true;
}
/**
* Redshift has no line, json or jsonb type and fails a statement that produces one with
* exactly these messages (checked on a real cluster 2026-09-13).
@@ -419,7 +621,11 @@ public class RedshiftDataService implements Resettable {
response.putArray("DbGroups");
putWorkgroupName(response, stored);
response.put("HasResultSet", stored.hasResultSet);
response.putNull("SessionId");
if (stored.sessionId == null) {
response.putNull("SessionId");
} else {
response.put("SessionId", stored.sessionId);
}
return response;
}
@@ -428,6 +634,9 @@ public class RedshiftDataService implements Resettable {
public ObjectNode describeStatement(JsonNode request) {
RedshiftDataStatementStore.StoredStatement stored = require(request);
ObjectNode response = objectMapper.createObjectNode();
if (stored.sessionId != null) {
response.put("SessionId", stored.sessionId);
}
response.put("Id", stored.id);
response.put("Status", stored.status.name());
response.put("CreatedAt", epochSeconds(stored.createdAt));
@@ -566,7 +775,7 @@ public class RedshiftDataService implements Resettable {
return execute(request, region, principal, true);
}
private PendingStatement prepareBatch(JsonNode request, String region) {
private PendingStatement prepareBatch(JsonNode request, String region, RedshiftDataSessions.Scope owner) {
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);
@@ -576,27 +785,40 @@ public class RedshiftDataService implements Resettable {
sqls.add(n.asText());
}
RedshiftDataResourceResolver.DatabaseTarget target = resolver.resolve(request, region);
ResolvedTarget resolved = resolveTarget(request, region, owner);
RedshiftDataResourceResolver.DatabaseTarget target = resolved.target();
RedshiftDataStatementStore.StoredStatement parent = newStatement(request);
parent.batch = true;
parent.sql = String.join("; ", sqls);
parent.sqls = sqls;
parent.clusterIdentifier = clusterIdentifierOrNull(request);
parent.workgroupName = workgroupNameOrNull(request);
parent.clusterIdentifier = clusterIdentifierOrNull(resolved.parameters());
parent.workgroupName = workgroupNameOrNull(resolved.parameters());
parent.dbUser = target.user();
parent.database = target.database();
parent.resultFormat = request.path("ResultFormat").asText("JSON");
parent.subStatements = new ArrayList<>();
capture(parent, target, region, request);
return new PendingStatement(parent, execution -> runBatch(parent, sqls, target, execution));
return new PendingStatement(parent, (execution, session) -> runBatch(parent, sqls, target, execution, session),
target, request.deepCopy(), owner);
}
private void runBatch(RedshiftDataStatementStore.StoredStatement parent, List<String> sqls,
RedshiftDataResourceResolver.DatabaseTarget target, RedshiftDataExecution execution) {
RedshiftDataResourceResolver.DatabaseTarget target, RedshiftDataExecution execution,
RedshiftDataSessions.Reservation session) {
long totalDuration = 0;
try (Connection connection = connectionFactory.open(target)) {
if (session != null) {
if (session.transactionFailed()) {
parent.status = RedshiftDataStatementStore.Status.FAILED;
parent.error = "Current transaction is aborted; use COMMIT or ROLLBACK to end it";
parent.updatedAt = Instant.now();
return;
}
session.transaction(false);
}
try (ConnectionUse use = connection(target, session)) {
Connection connection = use.connection();
execution.track(connection);
BackendSql batchBackend = new RedshiftDataBackendSql(connection, execution);
boolean committed = false;
@@ -612,6 +834,7 @@ public class RedshiftDataService implements Resettable {
sub.workgroupName = parent.workgroupName;
sub.database = parent.database;
sub.dbUser = parent.dbUser;
sub.sessionId = parent.sessionId;
sub.resultFormat = parent.resultFormat;
Instant now = Instant.now();
sub.createdAt = now;
@@ -628,6 +851,10 @@ public class RedshiftDataService implements Resettable {
totalDuration += sub.durationNanos;
parent.status = RedshiftDataStatementStore.Status.FAILED;
parent.error = e.getMessage();
if (session != null && e.getSQLState() != null && e.getSQLState().startsWith("08")) {
session.discard();
throw e;
}
connection.rollback();
failed = true;
break;
@@ -703,6 +930,9 @@ public class RedshiftDataService implements Resettable {
RedshiftDataStatementStore.StoredStatement s = all.get(i);
ObjectNode node = statements.addObject();
node.put("Id", s.id);
if (s.sessionId != null) {
node.put("SessionId", s.sessionId);
}
node.put("QueryString", s.sql);
ArrayNode queryStrings = node.putArray("QueryStrings");
for (String sql : s.sqls != null ? s.sqls : List.of(s.sql)) {
@@ -0,0 +1,423 @@
package io.github.hectorvent.floci.services.redshiftdata;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import org.jboss.logging.Logger;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
@ApplicationScoped
class RedshiftDataSessions implements AutoCloseable {
private static final Logger LOG = Logger.getLogger(RedshiftDataSessions.class);
private static final Pattern SESSION_ID = Pattern.compile("[a-z0-9]{8}(-[a-z0-9]{4}){3}-[a-z0-9]{12}(:\\d{0,2})?");
private static final Duration MAX_AGE = Duration.ofHours(24);
private static final List<String> TARGET_FIELDS = List.of("ClusterIdentifier", "WorkgroupName", "Database", "DbUser", "SecretArn");
private final ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();
private final Clock clock;
private ScheduledExecutorService sweeper;
private boolean closed;
RedshiftDataSessions() {
this(Clock.systemUTC());
}
RedshiftDataSessions(Clock clock) {
this.clock = clock;
}
@PostConstruct
void start() {
sweeper = Executors.newSingleThreadScheduledExecutor(task -> {
Thread thread = new Thread(task, "redshift-data-session-sweep");
thread.setDaemon(true);
return thread;
});
sweeper.scheduleAtFixedRate(this::sweepSafely, 1, 1, TimeUnit.SECONDS);
}
static void validate(JsonNode request) {
keepAlive(request);
JsonNode id = request.get("SessionId");
if (id != null && (!id.isTextual() || !SESSION_ID.matcher(id.textValue()).matches())) {
throw validation("SessionId must be a valid session identifier");
}
}
private static Integer keepAlive(JsonNode request) {
JsonNode seconds = request.get("SessionKeepAliveSeconds");
if (seconds == null) {
return null;
}
if (!seconds.isIntegralNumber() || !seconds.canConvertToInt() || seconds.intValue() < 0 || seconds.intValue() > 86400) {
throw validation("SessionKeepAliveSeconds must be an integer between 0 and 86400");
}
return seconds.intValue();
}
Session find(Scope owner, String id) {
Session session = sessions.get(id);
if (session == null || !session.owner.equals(owner)) {
throw missing();
}
synchronized (session) {
if (!session.closed && !expired(session)) {
return session;
}
}
retire(session);
throw missing();
}
Reservation reserve(Scope owner, JsonNode request, RedshiftDataResourceResolver.DatabaseTarget target) {
Integer seconds = keepAlive(request);
String id = request.has("SessionId") ? request.get("SessionId").asText() : null;
if (id == null && (seconds == null || seconds == 0)) {
return null;
}
Session session;
boolean created = id == null;
if (created) {
sweepSafely();
synchronized (this) {
if (closed) {
throw validation("Data API sessions are shutting down");
}
long count = sessions.values().stream().filter(existing -> existing.target.arn().equals(target.arn())
&& existing.owner.accountId().equals(owner.accountId()) && existing.owner.region().equals(owner.region())).count();
if (count >= 500) {
throw new AwsException("ActiveSessionsExceededException", "Too many active sessions for this resource", 400);
}
session = new Session(owner, target, request, clock.instant());
sessions.put(session.id, session);
}
} else {
session = find(owner, id);
}
synchronized (session) {
if (session.closed || expired(session)) {
throw missing();
}
if (session.active != null) {
throw validation("Session is busy; wait for its current statement to finish");
}
Reservation reservation = new Reservation(session, created, seconds == null ? session.keepAlive : seconds);
session.active = reservation;
return reservation;
}
}
void sweep() {
RuntimeException failure = null;
for (Session session : sessions.values()) {
boolean expire;
synchronized (session) {
expire = expired(session);
}
if (expire) {
try {
retire(session);
} catch (RuntimeException cleanupFailure) {
failure = accumulate(failure, cleanupFailure);
}
}
}
if (failure != null) {
throw failure;
}
}
private void sweepSafely() {
try {
sweep();
} catch (RuntimeException failure) {
// Maintenance has no request to report to; keep future sweeps running and report the failure.
LOG.errorv(failure, "Failed to clean up expired Redshift Data API sessions");
}
}
private boolean expired(Session session) {
Instant now = clock.instant();
return !now.isBefore(session.createdAt.plus(MAX_AGE))
|| session.active == null && !now.isBefore(session.idleUntil);
}
private void retire(Session session) {
retire(session, true);
}
private void retire(Session session, boolean cancel) {
Retirement retirement;
synchronized (session) {
retirement = retireLocked(session, cancel);
}
cleanUp(retirement);
}
private Retirement retireLocked(Session session, boolean cancel) {
if (session.closed) {
return null;
}
session.closed = true;
sessions.remove(session.id, session);
Retirement retirement = new Retirement(session.id, session.connection, cancel ? session.execution : null);
session.active = null;
session.execution = null;
session.connection = null;
return retirement;
}
private record Retirement(String id, Connection connection, RedshiftDataExecution execution) { }
private static void cleanUp(Retirement retirement) {
if (retirement == null) {
return;
}
Runnable cleanup = () -> {
try {
if (retirement.execution() != null) {
retirement.execution().cancel();
}
} finally {
closeConnection(retirement.connection(), retirement.id());
}
};
if (retirement.execution() == null) {
cleanup.run();
} else {
Thread.startVirtualThread(() -> {
try {
cleanup.run();
} catch (RuntimeException failure) {
// Expiration/reset cancellation finishes asynchronously after the session is unavailable.
LOG.errorv(failure, "Failed to clean up Redshift Data API session {0}", retirement.id());
}
});
}
}
private static void closeConnection(Connection connection, String id) {
if (connection != null) {
try {
connection.close();
} catch (SQLException | RuntimeException failure) {
if (failure instanceof SQLException sql && "08003".equals(sql.getSQLState())) {
LOG.debugv("Redshift Data API session {0} connection was already closed", id);
} else {
throw new IllegalStateException("Unable to close Redshift Data API session " + id + ": " + failure.getMessage(), failure);
}
}
}
}
synchronized void clear() {
RuntimeException failure = null;
for (Session session : sessions.values()) {
try {
retire(session);
} catch (RuntimeException cleanupFailure) {
failure = accumulate(failure, cleanupFailure);
}
}
if (failure != null) {
throw failure;
}
}
private static RuntimeException accumulate(RuntimeException first, RuntimeException next) {
if (first == null) {
return next;
}
if (first != next) {
first.addSuppressed(next);
}
return first;
}
@Override
@PreDestroy
public synchronized void close() {
closed = true;
if (sweeper != null) {
sweeper.shutdownNow();
}
clear();
}
record Scope(String accountId, String region, String caller) { }
static final class Session {
private final String id = UUID.randomUUID().toString();
private final Scope owner;
private final RedshiftDataResourceResolver.DatabaseTarget target;
private final ObjectNode parameters;
private final Instant createdAt;
private Instant idleUntil;
private int keepAlive;
private boolean closed;
private boolean transaction;
private boolean transactionFailed;
private Connection connection;
private RedshiftDataExecution execution;
private Reservation active;
private Session(Scope owner, RedshiftDataResourceResolver.DatabaseTarget target, JsonNode request, Instant createdAt) {
this.owner = owner;
this.target = target;
this.parameters = ((ObjectNode) request).objectNode();
for (String field : TARGET_FIELDS) {
if (request.has(field)) {
parameters.set(field, request.get(field).deepCopy());
}
}
this.createdAt = createdAt;
this.idleUntil = createdAt.plus(MAX_AGE);
}
RedshiftDataResourceResolver.DatabaseTarget target(JsonNode request) {
for (String field : TARGET_FIELDS) {
JsonNode value = request.get(field);
if (value != null && !Objects.equals(value, parameters.get(field))
&& !("WorkgroupName".equals(field) && value.isTextual() && target.arn().equals(value.textValue()))) {
throw validation(field + " does not match the session");
}
}
return target;
}
ObjectNode parameters() {
return parameters.deepCopy();
}
}
final class Reservation {
private final Session session;
private final boolean created;
private final int seconds;
private final AtomicBoolean released = new AtomicBoolean();
private boolean admitted;
private Reservation(Session session, boolean created, int seconds) {
this.session = session;
this.created = created;
this.seconds = seconds;
}
String id() {
return session.id;
}
void admitted() {
admitted = true;
}
void bind(RedshiftDataExecution execution) throws SQLException {
synchronized (session) {
if (session.closed || expired(session)) {
throw new SQLException("Session has expired", "08003");
}
session.execution = execution;
}
}
Connection connection(RedshiftDataConnectionFactory factory) throws SQLException {
synchronized (session) {
if (session.closed) {
throw new SQLException("Session has expired", "08003");
}
if (session.connection != null) {
return session.connection;
}
}
Connection opened = factory.open(session.target);
synchronized (session) {
if (!session.closed && !expired(session)) {
session.connection = opened;
return opened;
}
}
closeConnection(opened, session.id);
throw new SQLException("Session has expired", "08003");
}
boolean inTransaction() {
return session.transaction;
}
void transaction(boolean active) {
session.transaction = active;
if (!active) {
session.transactionFailed = false;
}
}
boolean transactionFailed() {
return session.transactionFailed;
}
void failTransaction() {
session.transactionFailed = true;
}
void abort() {
release(false);
}
void finish() {
release(admitted);
}
void discard() {
retire(session, false);
}
private void release(boolean completed) {
if (!released.compareAndSet(false, true)) {
return;
}
Retirement retirement = null;
synchronized (session) {
if (session.active != this) {
return;
}
boolean remove = !completed && created || completed && (seconds == 0 || session.connection == null);
if (remove) {
retirement = retireLocked(session, false);
} else {
session.active = null;
session.execution = null;
if (completed) {
session.keepAlive = seconds;
session.idleUntil = clock.instant().plusSeconds(seconds);
}
}
}
cleanUp(retirement);
}
}
private static AwsException validation(String message) {
return new AwsException("ValidationException", message, 400);
}
private static AwsException missing() {
return new AwsException("ResourceNotFoundException", "Session was not found or is no longer available", 400);
}
}
@@ -130,6 +130,10 @@ class RedshiftDataStatementStore {
statements.clear();
}
String accountId() {
return statements.accountId();
}
void sweep() {
if (idempotency != null) {
try {
@@ -171,6 +175,7 @@ class RedshiftDataStatementStore {
String workgroupName;
String database;
String dbUser;
String sessionId;
String resultFormat = "JSON";
Status status;
String error;
@@ -214,6 +219,7 @@ class RedshiftDataStatementStore {
copy.workgroupName = workgroupName;
copy.database = database;
copy.dbUser = dbUser;
copy.sessionId = sessionId;
copy.resultFormat = resultFormat;
copy.status = status;
copy.error = error;