feat(redshift-data): implement ListSessions (#6892)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-28 23:49:07 -04:00
1 parent 5ffe6d1123
commit da8e22744b
15 files changed
+865 -13

No files matched your search

@@ -24,6 +24,7 @@ public class RedshiftDataJsonHandler {
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 "ListSessions" -> Response.ok(service.listSessions(request, region)).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();
@@ -79,7 +79,8 @@ class RedshiftDataResourceResolver {
}
if (!hasText(request, "SecretArn")) {
return new DatabaseTarget(workgroup.arn(), workgroup.host(), workgroup.port(), database,
workgroup.masterUsername(), workgroup.masterPassword(), spectrum);
workgroup.masterUsername(), workgroup.masterPassword(), spectrum, null,
workgroup.masterUsername(), workgroup.workgroupName());
}
String secretArn = request.get("SecretArn").asText();
DatabaseSecretCredentials creds = secretCredentials(secretArn, region);
@@ -88,7 +89,7 @@ class RedshiftDataResourceResolver {
user = workgroup.masterUsername();
}
return new DatabaseTarget(workgroup.arn(), workgroup.host(), workgroup.port(), database,
user, creds.password(), spectrum);
user, creds.password(), spectrum, null, user, workgroup.workgroupName());
}
private boolean isManagedAdminSecret(String secretArn, String managedSecretArn, String region) {
@@ -203,7 +204,12 @@ class RedshiftDataResourceResolver {
}
record DatabaseTarget(String arn, String host, int port, String database, String user, String password,
SpectrumSession spectrum, Cluster cluster, String auditUser) {
SpectrumSession spectrum, Cluster cluster, String auditUser, String workgroupName) {
DatabaseTarget(String arn, String host, int port, String database, String user, String password,
SpectrumSession spectrum, Cluster cluster, String auditUser) {
this(arn, host, port, database, user, password, spectrum, cluster, auditUser, null);
}
DatabaseTarget(String arn, String host, int port, String database, String user, String password,
SpectrumSession spectrum, Cluster cluster) {
this(arn, host, port, database, user, password, spectrum, cluster, user);
@@ -209,7 +209,14 @@ public class RedshiftDataService implements Resettable {
caller = iamService == null ? "access-key:" + accessKey
: iamService.resolveCallerArn(accessKey).orElse("access-key:" + accessKey);
}
return new RedshiftDataSessions.Scope(store.accountId(), region, caller == null ? "anonymous" : caller);
String identity = caller == null ? "anonymous" : caller;
String role = principal == null && requestContext != null && iamService != null
? iamService.resolvePrincipalArn(requestContext.getAccessKeyId()).orElse(identity) : identity;
return new RedshiftDataSessions.Scope(store.accountId(), region, identity, role);
}
public ObjectNode listSessions(JsonNode request, String region) {
return new RedshiftDataSessionListing(objectMapper, sessions).list(request, sessionScope(region, null));
}
private Admission replay(RedshiftDataIdempotencyStore.Receipt receipt, RedshiftDataIdempotencyStore.Scope scope,
@@ -277,7 +284,7 @@ public class RedshiftDataService implements Resettable {
}
}
if (session != null) {
session.admitted();
session.admitted(stored.id);
}
},
execution -> {
@@ -1336,7 +1343,7 @@ public class RedshiftDataService implements Resettable {
return offset;
}
private static double epochSeconds(Instant instant) {
static double epochSeconds(Instant instant) {
return instant.toEpochMilli() / 1000.0;
}
@@ -0,0 +1,150 @@
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.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataSessions.Scope;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataSessions.SessionInfo;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
import static io.github.hectorvent.floci.services.redshiftdata.RedshiftDataService.epochSeconds;
final class RedshiftDataSessionListing {
private static final Pattern CLUSTER = Pattern.compile("[a-z][a-z0-9]*(-[a-z0-9]+)*");
private static final Pattern WORKGROUP = Pattern.compile("[a-z0-9-]{3,63}");
private static final Pattern WORKGROUP_RESOURCE = Pattern.compile(
"workgroup/(?:[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}|[a-z0-9-]{1,63}/[a-z0-9-]{1,63})");
private static final Set<String> STATUSES = Set.of("AVAILABLE", "BUSY", "CLOSED");
private final ObjectMapper mapper;
private final RedshiftDataSessions sessions;
RedshiftDataSessionListing(ObjectMapper mapper, RedshiftDataSessions sessions) {
this.mapper = mapper;
this.sessions = sessions;
}
ObjectNode list(JsonNode request, Scope owner) {
RedshiftDataSessions.validate(request);
String id = text(request, "SessionId");
String cluster = text(request, "ClusterIdentifier");
String workgroup = text(request, "WorkgroupName");
String database = text(request, "Database");
String status = text(request, "Status");
if (id != null && (cluster != null || workgroup != null || database != null || status != null)) {
throw validation("SessionId cannot be combined with Status, ClusterIdentifier, WorkgroupName or Database.");
}
if (cluster != null && workgroup != null) {
throw validation("ClusterIdentifier and WorkgroupName cannot both be specified.");
}
if (cluster != null && (cluster.length() > 63 || !CLUSTER.matcher(cluster).matches())) {
throw validation("ClusterIdentifier is not valid.");
}
if (workgroup != null && !validWorkgroup(workgroup)) {
throw validation("WorkgroupName is not valid.");
}
if (status != null && !STATUSES.contains(status)) {
throw validation("Status must be AVAILABLE, BUSY or CLOSED.");
}
JsonNode roleValue = request.get("RoleLevel");
if (roleValue != null && !roleValue.isBoolean()) {
throw validation("RoleLevel must be a boolean.");
}
boolean roleLevel = roleValue == null || roleValue.booleanValue();
Integer maximum = Pagination.parseMaxResults(request, "MaxResults", "ValidationException");
if (maximum != null && (maximum < 0 || maximum > 100)) {
throw validation("MaxResults must be between 0 and 100.");
}
int limit = maximum == null || maximum == 0 ? 100 : maximum;
String token = text(request, "NextToken");
if (token != null && (token.isBlank() || token.length() > 8192)) {
throw validation("NextToken is not valid.");
}
List<SessionInfo> matches = sessions.snapshots().stream()
.filter(info -> visible(info.owner(), owner, roleLevel))
.filter(info -> id == null || id.equals(info.id()))
.filter(info -> id != null || (status == null ? !"CLOSED".equals(info.status()) : status.equals(info.status())))
.filter(info -> cluster == null || cluster.equals(info.cluster()))
.filter(info -> workgroup == null || workgroup.equals(info.workgroup()) || workgroup.equals(info.targetArn()))
.filter(info -> database == null || database.equals(info.database()))
.toList();
if (id != null && matches.isEmpty()) {
throw new AwsException("ResourceNotFoundException", "Session was not found.", 400);
}
ArrayNode scope = mapper.createArrayNode().add(owner.accountId()).add(owner.region())
.add(roleLevel ? owner.principal() : owner.caller()).add(roleLevel)
.add(id).add(cluster).add(workgroup).add(database).add(status);
String namespace = "redshift-data-sessions-" + Digests.sha256Hex(scope.toString());
PaginatedResult<SessionInfo> page = Pagination.paginate(matches,
info -> info.createdAt().toString() + "/" + info.id(), limit, token, namespace,
invalid -> validation("NextToken is not valid."));
ObjectNode response = mapper.createObjectNode();
ArrayNode result = response.putArray("Sessions");
for (SessionInfo info : page.items()) {
ObjectNode node = result.addObject();
node.put("SessionId", info.id());
node.put("Status", info.status());
node.put("CreatedAt", epochSeconds(info.createdAt()));
node.put("UpdatedAt", epochSeconds(info.updatedAt()));
node.put("SessionTtl", epochSeconds(info.ttl()));
node.put("SessionAliveSeconds", info.keepAlive());
node.put("Database", info.database());
node.put("DbUser", info.user());
if (info.cluster() != null) {
node.put("ClusterIdentifier", info.cluster());
} else {
node.put("WorkgroupName", info.workgroup());
}
if (info.statementId() != null) {
node.put("CurrentStatementId", info.statementId());
}
}
if (page.nextToken() != null) {
response.put("NextToken", page.nextToken());
}
return response;
}
private static boolean visible(Scope actual, Scope requested, boolean roleLevel) {
return actual.accountId().equals(requested.accountId()) && actual.region().equals(requested.region())
&& Objects.equals(roleLevel ? actual.principal() : actual.caller(),
roleLevel ? requested.principal() : requested.caller());
}
private static boolean validWorkgroup(String value) {
if (WORKGROUP.matcher(value).matches()) {
return true;
}
if (value.length() > 128 || !AwsArnUtils.isArn(value)) {
return false;
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(value);
return "redshift-serverless".equals(arn.service()) && !arn.region().isBlank()
&& arn.accountId().matches("[0-9]{12}") && WORKGROUP_RESOURCE.matcher(arn.resource()).matches();
}
private static String text(JsonNode request, String field) {
JsonNode value = request.get(field);
if (value == null) {
return null;
}
if (!value.isTextual()) {
throw validation(field + " must be a string.");
}
return value.textValue();
}
private static AwsException validation(String message) {
return new AwsException("ValidationException", message, 400);
}
}
@@ -2,6 +2,7 @@ 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.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.UserChange;
import io.github.hectorvent.floci.services.redshift.RedshiftAuditSql.UserChanges;
@@ -15,6 +16,7 @@ import java.sql.SQLException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
@@ -33,6 +35,7 @@ class RedshiftDataSessions implements AutoCloseable {
private static final List<String> TARGET_FIELDS = List.of("ClusterIdentifier", "WorkgroupName", "Database", "DbUser", "SecretArn");
private final ConcurrentHashMap<String, Session> sessions = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, SessionInfo> history = new ConcurrentHashMap<>();
private final Clock clock;
private ScheduledExecutorService sweeper;
private boolean closed;
@@ -127,6 +130,7 @@ class RedshiftDataSessions implements AutoCloseable {
}
void sweep() {
history.values().removeIf(info -> !clock.instant().isBefore(info.createdAt().plus(MAX_AGE)));
RuntimeException failure = null;
for (Session session : sessions.values()) {
boolean expire;
@@ -178,6 +182,10 @@ class RedshiftDataSessions implements AutoCloseable {
return null;
}
session.closed = true;
session.updatedAt = expired(session) ? session.deadline() : clock.instant();
if (session.admitted && clock.instant().isBefore(session.createdAt.plus(MAX_AGE))) {
history.put(session.id, session.info());
}
sessions.remove(session.id, session);
Retirement retirement = new Retirement(session.id, session.connection, cancel ? session.execution : null,
session.connectionClosed);
@@ -246,6 +254,7 @@ class RedshiftDataSessions implements AutoCloseable {
failure = accumulate(failure, cleanupFailure);
}
}
history.clear();
if (failure != null) {
throw failure;
}
@@ -271,7 +280,29 @@ class RedshiftDataSessions implements AutoCloseable {
clear();
}
record Scope(String accountId, String region, String caller) { }
List<SessionInfo> snapshots() {
sweepSafely();
ConcurrentHashMap<String, SessionInfo> result = new ConcurrentHashMap<>();
for (Session session : sessions.values()) {
synchronized (session) {
if (session.admitted && clock.instant().isBefore(session.createdAt.plus(MAX_AGE))) {
result.put(session.id, session.info());
}
}
}
result.putAll(history);
return new ArrayList<>(result.values());
}
record Scope(String accountId, String region, String caller, String principal) {
Scope(String accountId, String region, String caller) {
this(accountId, region, caller, caller);
}
}
record SessionInfo(String id, Scope owner, String targetArn, String cluster, String workgroup,
String database, String user, Instant createdAt, Instant updatedAt,
Instant ttl, int keepAlive, String status, String statementId) { }
static final class Session {
private final String id = UUID.randomUUID().toString();
@@ -279,6 +310,8 @@ class RedshiftDataSessions implements AutoCloseable {
private final RedshiftDataResourceResolver.DatabaseTarget target;
private final ObjectNode parameters;
private final Instant createdAt;
private Instant updatedAt;
private boolean admitted;
private Instant idleUntil;
private int keepAlive;
private boolean closed;
@@ -300,9 +333,28 @@ class RedshiftDataSessions implements AutoCloseable {
}
}
this.createdAt = createdAt;
this.updatedAt = createdAt;
this.idleUntil = createdAt.plus(MAX_AGE);
}
private Instant deadline() {
Instant maximum = createdAt.plus(MAX_AGE);
return active != null || maximum.isBefore(idleUntil) ? maximum : idleUntil;
}
private SessionInfo info() {
boolean busy = !closed && active != null;
AwsArnUtils.Arn arn = AwsArnUtils.parse(target.arn());
boolean serverless = "redshift-serverless".equals(arn.service());
String cluster = serverless ? null : arn.resource().substring("cluster:".length());
String workgroup = serverless ? target.workgroupName() != null ? target.workgroupName()
: parameters.path("WorkgroupName").asText(target.arn()) : null;
String user = parameters.path("DbUser").asText(target.auditUser());
return new SessionInfo(id, owner, target.arn(), cluster, workgroup, target.database(), user,
createdAt, updatedAt, closed ? updatedAt : deadline(), busy ? active.seconds : keepAlive,
closed ? "CLOSED" : busy ? "BUSY" : "AVAILABLE", busy ? active.statementId : null);
}
RedshiftDataResourceResolver.DatabaseTarget target(JsonNode request) {
for (String field : TARGET_FIELDS) {
JsonNode value = request.get(field);
@@ -325,6 +377,7 @@ class RedshiftDataSessions implements AutoCloseable {
private final int seconds;
private final AtomicBoolean released = new AtomicBoolean();
private boolean admitted;
private String statementId;
private Reservation(Session session, boolean created, int seconds) {
this.session = session;
@@ -337,7 +390,16 @@ class RedshiftDataSessions implements AutoCloseable {
}
void admitted() {
admitted = true;
admitted(null);
}
void admitted(String id) {
synchronized (session) {
admitted = true;
statementId = id;
session.admitted = true;
session.updatedAt = clock.instant();
}
}
void bind(RedshiftDataExecution execution) throws SQLException {
@@ -442,6 +504,10 @@ class RedshiftDataSessions implements AutoCloseable {
return;
}
boolean remove = !completed && created || completed && (seconds == 0 || session.connection == null);
if (completed) {
session.keepAlive = seconds;
session.updatedAt = clock.instant();
}
if (remove) {
retirement = retireLocked(session, false);
} else {
@@ -2654,7 +2654,7 @@ public class AslExecutor {
private static void renderRedshiftDataTimestamps(JsonNode node) {
if (node instanceof ObjectNode object) {
for (String field : List.of("CreatedAt", "UpdatedAt")) {
for (String field : List.of("CreatedAt", "UpdatedAt", "SessionTtl")) {
JsonNode value = object.get(field);
if (value != null && value.isNumber()) {
object.put(field, sdkTimestamp(value.asDouble()));