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

@@ -22,6 +22,7 @@ import software.amazon.awssdk.services.redshiftdata.model.GetStatementResultRequ
import software.amazon.awssdk.services.redshiftdata.model.GetStatementResultResponse;
import software.amazon.awssdk.services.redshiftdata.model.GetStatementResultV2Response;
import software.amazon.awssdk.services.redshiftdata.model.ResultFormatString;
import software.amazon.awssdk.services.redshiftdata.model.SessionData;
import software.amazon.awssdk.services.redshiftdata.model.SqlParameter;
import software.amazon.awssdk.services.redshiftdata.model.StatusString;
import software.amazon.awssdk.services.redshiftdata.model.SubStatementData;
@@ -86,6 +87,26 @@ class RedshiftDataOperationsTest {
}
}
@Test
@DisplayName("ListSessions exposes retained sessions and their closed history")
void listSessionsLifecycle() throws Exception {
String statement = data.executeStatement(r -> r.clusterIdentifier(clusterId).database(DATABASE)
.dbUser(USERNAME).sessionKeepAliveSeconds(60).sql("SELECT 1")).id();
awaitFinished(statement);
String sessionId = data.describeStatement(r -> r.id(statement)).sessionId();
SessionData session = data.listSessions(r -> r.sessionId(sessionId)).sessions().get(0);
assertThat(session.statusAsString()).isEqualTo("AVAILABLE");
assertThat(session.clusterIdentifier()).isEqualTo(clusterId);
assertThat(session.database()).isEqualTo(DATABASE);
assertThat(session.createdAt()).isNotNull();
assertThat(session.sessionTtl()).isAfter(session.createdAt());
String close = data.executeStatement(r -> r.sessionId(sessionId).sessionKeepAliveSeconds(0).sql("SELECT 2")).id();
awaitFinished(close);
assertThat(data.listSessions(r -> r.sessionId(sessionId)).sessions().get(0).statusAsString()).isEqualTo("CLOSED");
assertThat(data.listSessions(r -> r.clusterIdentifier(clusterId)).sessions())
.noneMatch(candidate -> sessionId.equals(candidate.sessionId()));
}
@Test
@DisplayName("explicit client token retries an INSERT without inserting twice")
void executeStatementClientTokenRetry() throws Exception {
+1 -1
View File
@@ -77,7 +77,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 13 |
| [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 20 |
| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 50 |
| [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 11 |
| [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 12 |
| [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 55 |
| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 40 |
| [EMR Serverless](emr-serverless.md) | `/applications/*`, `/tags/*` | REST JSON | 15 |
+34 -3
View File
@@ -25,6 +25,7 @@ For the upstream API shape, see the AWS documentation:
| `GetStatementResult` | Page through a finished statement's rows as typed `Records` |
| `GetStatementResultV2` | Same rows in the V2 envelope, with `CSVRecords` when the statement used `ResultFormat=CSV` |
| `ListStatements` | List stored statements newest first, filtered by `StatementName` or `Status` |
| `ListSessions` | List caller-owned session metadata, with lifecycle status, target filters and pagination |
| `CancelStatement` | Cancel queued or running SQL; returns whether cancellation was accepted, and rejects terminal statements |
| `ListDatabases` | List databases on the cluster (`pg_database`) |
| `ListSchemas` | List schemas, optionally filtered by `SchemaPattern` |
@@ -91,12 +92,42 @@ Session ids appear in Execute, Batch, DescribeStatement and ListStatements respo
is saved with statement metadata and idempotency receipts, but live connections are runtime-only:
reset and shutdown close them, and restarting Floci never reopens a session. A session request
with an existing receipt can still replay its original response after the connection expires or
after restart, subject to the normal receipt lifetime and caller ownership. `ListSessions` is
not implemented.
after restart, subject to the normal receipt lifetime and caller ownership.
### Listing sessions
`ListSessions` returns session metadata created in the last 24 hours. It defaults to
`AVAILABLE` and `BUSY` sessions; `Status=CLOSED` includes retained metadata for sessions
closed explicitly, expired or retired after a connection failure. `SessionId` retrieves
one visible session regardless of status and cannot be combined with `Status`,
`ClusterIdentifier`, `WorkgroupName` or `Database`. A missing or foreign session id
returns `ResourceNotFoundException`.
Filter by `ClusterIdentifier` or `WorkgroupName` (name or ARN), optionally with
`Database`. Cluster and workgroup filters are mutually exclusive. `MaxResults` accepts
0 through 100; omitted or zero uses 100. Continue with `NextToken` and the same filters
and ownership scope. Results are ordered by creation timestamp and session id; this
ordering and the default page size are Floci choices, not claims about AWS.
Sessions remain isolated by account and Region. `RoleLevel` defaults to true and
lists sessions for the caller's IAM role across assumed-role sessions. False limits
results to the current caller session. Unresolved credentials are isolated by access
key; Floci does not model Identity Center identity-enhanced session restrictions.
`CreatedAt`, `UpdatedAt` and `SessionTtl` are epoch-second timestamps with the same
millisecond precision as statement timestamps.
`CurrentStatementId` appears only while the session is `BUSY`, including admitted
work waiting for a worker. `SessionAliveSeconds` reports the selected keep-alive.
Closed history contains metadata only, does not consume the 500-live-session quota,
and expires 24 hours after session creation. History is runtime-only: reset, shutdown
and restart remove it even when statement persistence is enabled. Failed admissions
do not create session history. The exact queued-state reporting and lifecycle timestamp
choices have not been compared with live AWS.
Unexpected synchronous connection-cleanup failures are reported to the affected operation.
Reset still attempts to close the remaining sessions and clear statement and receipt state before
reporting cleanup errors. Background expiration failures are logged without stopping later sweeps.
reporting cleanup errors. Opportunistic expiration during `ListSessions` logs cleanup failures
without failing the listing. Background expiration failures are logged without stopping later sweeps.
An already-closed connection (`SQLSTATE 08003`) is a benign cleanup outcome.
```python
@@ -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()));
@@ -0,0 +1,302 @@
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.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.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testing.ManualClock;
import org.h2.Driver;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.Duration;
import java.time.Instant;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
class RedshiftDataListSessionsServiceTest {
@Test
void sessionTimestampsUseMillisecondPrecision() throws Exception {
try (Fixture fixture = new Fixture()) {
fixture.clock.advance(Duration.ofNanos(123_456_789));
fixture.create("warehouse");
JsonNode session = fixture.list().path("Sessions").get(0);
assertEquals(1_793_232_000.123, session.path("CreatedAt").asDouble());
assertEquals(1_793_232_000.123, session.path("UpdatedAt").asDouble());
assertEquals(1_793_232_060.123, session.path("SessionTtl").asDouble());
}
}
@Test
void anotherCallersExpiredConnectionCleanupFailureDoesNotFailListing() throws Exception {
try (Fixture fixture = new Fixture(); Connection broken = spy(DriverManager.getConnection(fixture.url))) {
when(fixture.factory.open(any())).thenReturn(broken)
.thenAnswer(invocation -> DriverManager.getConnection(fixture.url));
fixture.context.setAccessKeyId("other");
fixture.create("broken");
doThrow(new SQLException("close failed", "08006")).doCallRealMethod().when(broken).close();
fixture.clock.advance(Duration.ofSeconds(30));
fixture.context.setAccessKeyId("owner");
String healthy = fixture.create("warehouse");
fixture.clock.advance(Duration.ofSeconds(30));
ObjectNode listed = fixture.list();
assertEquals(1, listed.path("Sessions").size());
assertEquals(healthy, listed.path("Sessions").get(0).path("SessionId").asText());
verify(broken).close();
}
}
@Test
void listsAvailableAndClosedSessionsWithLifecycleMetadata() throws Exception {
try (Fixture fixture = new Fixture()) {
String id = fixture.create("warehouse");
JsonNode session = fixture.list().path("Sessions").get(0);
assertEquals(id, session.path("SessionId").asText());
assertEquals("AVAILABLE", session.path("Status").asText());
assertEquals("warehouse", session.path("ClusterIdentifier").asText());
assertEquals("dev", session.path("Database").asText());
assertEquals("admin", session.path("DbUser").asText());
assertEquals(60, session.path("SessionAliveSeconds").asInt());
assertEquals(fixture.clock.instant().getEpochSecond(), session.path("CreatedAt").asLong());
assertEquals(fixture.clock.instant().plusSeconds(60).getEpochSecond(), session.path("SessionTtl").asLong());
assertFalse(session.has("CurrentStatementId"));
assertFalse(session.has("WorkgroupName"));
assertFalse(session.has("SecretArn"));
assertFalse(session.toString().contains("password"));
fixture.clock.advance(Duration.ofSeconds(10));
fixture.service.executeStatement(fixture.json().put("SessionId", id).put("Sql", "SELECT 2")
.put("SessionKeepAliveSeconds", 0).put("WaitTimeSeconds", 5), "us-east-1");
assertTrue(fixture.list().path("Sessions").isEmpty());
JsonNode closed = fixture.list(fixture.json().put("Status", "CLOSED")).path("Sessions").get(0);
assertEquals(id, closed.path("SessionId").asText());
assertEquals("CLOSED", closed.path("Status").asText());
assertEquals(fixture.clock.instant().getEpochSecond(), closed.path("UpdatedAt").asLong());
assertEquals(id, fixture.list(fixture.json().put("SessionId", id))
.path("Sessions").get(0).path("SessionId").asText());
fixture.service.clear();
assertTrue(fixture.list(fixture.json().put("Status", "CLOSED")).path("Sessions").isEmpty());
}
}
@Test
void listsBusySessionsWithTheirCurrentStatement() throws Exception {
try (Fixture fixture = new Fixture()) {
CountDownLatch started = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
when(fixture.factory.open(any())).thenAnswer(invocation -> {
started.countDown();
assertTrue(release.await(10, TimeUnit.SECONDS));
return DriverManager.getConnection(fixture.url);
});
ObjectNode request = fixture.request("warehouse");
request.remove("WaitTimeSeconds");
ObjectNode response = fixture.service.executeStatement(request, "us-east-1");
try {
assertTrue(started.await(5, TimeUnit.SECONDS));
JsonNode busy = fixture.list(fixture.json().put("Status", "BUSY")).path("Sessions").get(0);
assertEquals(response.path("Id").asText(), busy.path("CurrentStatementId").asText());
assertEquals(response.path("SessionId").asText(), busy.path("SessionId").asText());
} finally {
release.countDown();
}
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
assertEquals("AVAILABLE", fixture.list().path("Sessions").get(0).path("Status").asText()));
}
}
@Test
void expiresOnReadAndRetainsClosedHistoryOnlyWithinTheCreationWindow() throws Exception {
try (Fixture fixture = new Fixture()) {
String id = fixture.create("warehouse");
fixture.clock.advance(Duration.ofSeconds(60));
assertTrue(fixture.list().path("Sessions").isEmpty());
assertEquals("CLOSED", fixture.list(fixture.json().put("SessionId", id))
.path("Sessions").get(0).path("Status").asText());
fixture.clock.advance(Duration.ofHours(24));
assertTrue(fixture.list(fixture.json().put("Status", "CLOSED")).path("Sessions").isEmpty());
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
() -> fixture.list(fixture.json().put("SessionId", id))).getErrorCode());
}
}
@Test
void filtersByComputeTargetAndDatabaseBeforePaginating() throws Exception {
try (Fixture fixture = new Fixture()) {
String first = fixture.create("warehouse");
fixture.clock.advance(Duration.ofSeconds(1));
String second = fixture.create("warehouse");
fixture.create("other");
ObjectNode workgroup = fixture.request("unused");
workgroup.remove("ClusterIdentifier");
workgroup.put("WorkgroupName", "analytics");
fixture.service.executeStatement(workgroup, "us-east-1");
ObjectNode filter = fixture.json().put("ClusterIdentifier", "warehouse").put("Database", "dev")
.put("MaxResults", 1);
ObjectNode page = fixture.list(filter);
Set<String> ids = new HashSet<>();
ids.add(page.path("Sessions").get(0).path("SessionId").asText());
assertTrue(page.has("NextToken"));
ObjectNode last = fixture.list(filter.deepCopy().put("NextToken", page.path("NextToken").asText()));
ids.add(last.path("Sessions").get(0).path("SessionId").asText());
assertEquals(Set.of(first, second), ids);
assertFalse(last.has("NextToken"));
assertTrue(fixture.list(fixture.json().put("Database", "missing")).path("Sessions").isEmpty());
JsonNode serverless = fixture.list(fixture.json().put("WorkgroupName", "analytics")).path("Sessions");
assertEquals(1, serverless.size());
assertFalse(serverless.get(0).has("ClusterIdentifier"));
String arn = AwsArnUtils.Arn.of("redshift-serverless", "us-east-1", "000000000000",
"workgroup/12345678-1234-1234-1234-123456789012").toString();
assertEquals(serverless, fixture.list(fixture.json().put("WorkgroupName", arn)).path("Sessions"));
}
}
@Test
void enforcesCallerRegionAndRoleLevelAndBindsTokensToTheQuery() throws Exception {
try (Fixture fixture = new Fixture()) {
when(fixture.iam.resolveCallerArn("owner")).thenReturn(Optional.of("session-one"));
when(fixture.iam.resolvePrincipalArn("owner")).thenReturn(Optional.of("shared-role"));
String id = fixture.create("warehouse");
fixture.create("warehouse");
String token = fixture.list(fixture.json().put("MaxResults", 1)).path("NextToken").asText();
when(fixture.iam.resolveCallerArn("other")).thenReturn(Optional.of("session-two"));
when(fixture.iam.resolvePrincipalArn("other")).thenReturn(Optional.of("shared-role"));
fixture.context.setAccessKeyId("other");
assertEquals(2, fixture.list().path("Sessions").size());
assertTrue(fixture.list(fixture.json().put("RoleLevel", false)).path("Sessions").isEmpty());
when(fixture.iam.resolvePrincipalArn("other")).thenReturn(Optional.of("different-role"));
assertTrue(fixture.list().path("Sessions").isEmpty());
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
() -> fixture.list(fixture.json().put("SessionId", id))).getErrorCode());
assertThrows(AwsException.class, () -> fixture.list(fixture.json().put("NextToken", token)));
fixture.context.setAccessKeyId("owner");
assertThrows(AwsException.class, () -> fixture.list(fixture.json().put("NextToken", token).put("Database", "dev")));
assertTrue(fixture.list(fixture.json(), "eu-west-1").path("Sessions").isEmpty());
assertThrows(AwsException.class, () -> fixture.list(fixture.json().put("NextToken", token), "eu-west-1"));
}
}
@Test
void workgroupArnSessionsCanBeListedByNameAndForeignAccountsStayHidden() throws Exception {
try (Fixture fixture = new Fixture()) {
String arn = AwsArnUtils.Arn.of("redshift-serverless", "us-east-1", "000000000000",
"workgroup/12345678-1234-1234-1234-123456789012").toString();
ObjectNode request = fixture.request("unused");
request.remove("ClusterIdentifier");
request.put("WorkgroupName", arn);
String id = fixture.service.executeStatement(request, "us-east-1").path("SessionId").asText();
assertEquals(id, fixture.list(fixture.json().put("WorkgroupName", "analytics"))
.path("Sessions").get(0).path("SessionId").asText());
RedshiftDataSessions.Reservation foreign = fixture.sessions.reserve(new RedshiftDataSessions.Scope(
"111111111111", "us-east-1", "access-key:owner"), fixture.request("warehouse"),
new RedshiftDataResourceResolver.DatabaseTarget(AwsArnUtils.Arn.of("redshift", "us-east-1",
"111111111111", "cluster:warehouse").toString(), "localhost", 5439, "dev", "admin", "password"));
foreign.admitted();
assertEquals(1, fixture.list().path("Sessions").size());
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
() -> fixture.list(fixture.json().put("SessionId", foreign.id()))).getErrorCode());
}
}
@Test
void rejectsMalformedRequestsWithoutOpeningDatabaseConnections() throws Exception {
try (Fixture fixture = new Fixture()) {
for (ObjectNode request : new ObjectNode[]{fixture.json().put("Status", "FAILED"),
fixture.json().put("RoleLevel", "false"), fixture.json().put("MaxResults", -1),
fixture.json().put("MaxResults", 101), fixture.json().put("MaxResults", 0.5),
fixture.json().put("SessionId", "invalid"), fixture.json().put("ClusterIdentifier", "Uppercase"),
fixture.json().put("WorkgroupName", "x"), fixture.json().put("Database", 5),
fixture.json().put("NextToken", "garbage"),
fixture.json().put("ClusterIdentifier", "warehouse").put("WorkgroupName", "analytics"),
fixture.json().put("SessionId", UUID.randomUUID().toString()).put("Status", "CLOSED")}) {
assertEquals("ValidationException", assertThrows(AwsException.class,
() -> fixture.list(request), request.toString()).getErrorCode());
}
assertTrue(fixture.list(fixture.json().put("MaxResults", 0)).path("Sessions").isEmpty());
verifyNoInteractions(fixture.factory);
}
}
private static final class Fixture implements AutoCloseable {
private final ObjectMapper mapper = new ObjectMapper();
private final ManualClock clock = new ManualClock(Instant.parse("2026-10-29T00:00:00Z"));
private final RequestContext context = new RequestContext();
private final IamService iam = mock(IamService.class);
private final RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
private final RedshiftDataExecutor executor = new RedshiftDataExecutor(2, 8, 1);
private final RedshiftDataSessions sessions = new RedshiftDataSessions(clock);
private final String url = "jdbc:h2:mem:" + UUID.randomUUID();
private final RedshiftDataService service;
private Fixture() throws Exception {
Driver.load();
context.setAccessKeyId("owner");
RedshiftDataResourceResolver resolver = mock(RedshiftDataResourceResolver.class);
when(resolver.resolve(any(), any())).thenAnswer(invocation -> {
JsonNode request = invocation.getArgument(0);
String region = invocation.getArgument(1);
boolean serverless = request.has("WorkgroupName");
String resource = serverless ? "workgroup/12345678-1234-1234-1234-123456789012"
: "cluster:" + request.path("ClusterIdentifier").asText();
return new RedshiftDataResourceResolver.DatabaseTarget(AwsArnUtils.Arn.of(
serverless ? "redshift-serverless" : "redshift", region, "000000000000", resource).toString(),
"localhost", 5439, "dev", "admin", "password", null, null, "admin", serverless ? "analytics" : null);
});
when(factory.open(any())).thenAnswer(invocation -> DriverManager.getConnection(url));
service = new RedshiftDataService(resolver, factory, new RedshiftDataStatementStore(24, clock), mapper,
null, executor, null, context, iam, new RedshiftDataIdempotencyStore(
AccountAwareStorageBackend.inMemory("000000000000"), clock), sessions);
}
private ObjectNode json() {
return mapper.createObjectNode();
}
private ObjectNode request(String cluster) {
return json().put("ClusterIdentifier", cluster).put("Database", "dev").put("DbUser", "admin")
.put("Sql", "SELECT 1").put("SessionKeepAliveSeconds", 60).put("WaitTimeSeconds", 5);
}
private String create(String cluster) {
return service.executeStatement(request(cluster), "us-east-1").path("SessionId").asText();
}
private ObjectNode list() {
return list(json());
}
private ObjectNode list(ObjectNode request) {
return list(request, "us-east-1");
}
private ObjectNode list(ObjectNode request, String region) {
return (ObjectNode) new RedshiftDataJsonHandler(service).handle("ListSessions", request, region).getEntity();
}
@Override
public void close() {
service.clear();
executor.close();
sessions.close();
}
}
}
@@ -20,7 +20,9 @@ import software.amazon.awssdk.services.redshiftdata.RedshiftDataClient;
import software.amazon.awssdk.services.redshiftdata.model.DescribeStatementResponse;
import software.amazon.awssdk.services.redshiftdata.model.ExecuteStatementRequest;
import software.amazon.awssdk.services.redshiftdata.model.ExecuteStatementResponse;
import software.amazon.awssdk.services.redshiftdata.model.ListSessionsResponse;
import software.amazon.awssdk.services.redshiftdata.model.ResourceNotFoundException;
import software.amazon.awssdk.services.redshiftdata.model.SessionData;
import software.amazon.awssdk.services.redshiftdata.model.SqlParameter;
import software.amazon.awssdk.services.redshiftdata.model.StatusString;
import software.amazon.awssdk.services.redshiftdata.model.ValidationException;
@@ -152,6 +154,53 @@ class RedshiftDataSessionIntegrationTest {
verifyNoInteractions(factory);
}
@Test
void sdkListsSessionsWithFiltersPaginationAndClosedHistory() {
ExecuteStatementResponse first = data.executeStatement(r -> r.waitTimeSeconds(30).clusterIdentifier("warehouse")
.dbUser("admin").database("dev").sessionKeepAliveSeconds(60).sql("SELECT 1"));
finished(first.id());
ExecuteStatementResponse second = data.executeStatement(r -> r.waitTimeSeconds(30).workgroupName("analytics")
.database("dev").sessionKeepAliveSeconds(60).sql("SELECT 2"));
finished(second.id());
ListSessionsResponse page = data.listSessions(r -> r.maxResults(1));
assertEquals(1, page.sessions().size());
assertNotNull(page.nextToken());
ListSessionsResponse last = data.listSessions(r -> r.maxResults(1).nextToken(page.nextToken()));
assertEquals(1, last.sessions().size());
assertNotEquals(page.sessions().getFirst().sessionId(), last.sessions().getFirst().sessionId());
assertNull(last.nextToken());
SessionData cluster = data.listSessions(r -> r.clusterIdentifier("warehouse").database("dev")).sessions().getFirst();
assertEquals(first.sessionId(), cluster.sessionId());
assertEquals("AVAILABLE", cluster.statusAsString());
assertEquals("admin", cluster.dbUser());
assertEquals(60, cluster.sessionAliveSeconds());
assertNotNull(cluster.createdAt());
assertNotNull(cluster.updatedAt());
assertTrue(cluster.sessionTtl().isAfter(cluster.createdAt()));
assertNull(cluster.currentStatementId());
assertNull(cluster.workgroupName());
SessionData workgroup = data.listSessions(r -> r.workgroupName("analytics")).sessions().getFirst();
assertEquals(second.sessionId(), workgroup.sessionId());
assertNull(workgroup.clusterIdentifier());
try (RedshiftDataClient other = client("another-caller", Region.US_EAST_1);
RedshiftDataClient otherRegion = client("test", Region.EU_WEST_1)) {
assertTrue(other.listSessions(r -> r.maxResults(100)).sessions().isEmpty());
assertTrue(otherRegion.listSessions(r -> r.maxResults(100)).sessions().isEmpty());
assertThrows(ResourceNotFoundException.class, () -> other.listSessions(r -> r.sessionId(first.sessionId())));
}
String closed = data.executeStatement(r -> r.waitTimeSeconds(30).sessionId(first.sessionId())
.sessionKeepAliveSeconds(0).sql("SELECT 3")).id();
finished(closed);
assertTrue(data.listSessions(r -> r.clusterIdentifier("warehouse")).sessions().isEmpty());
assertEquals(first.sessionId(), data.listSessions(r -> r.status("CLOSED")).sessions().getFirst().sessionId());
assertEquals("CLOSED", data.listSessions(r -> r.sessionId(first.sessionId())).sessions().getFirst().statusAsString());
assertThrows(ValidationException.class, () -> data.listSessions(r -> r.sessionId(first.sessionId()).status("CLOSED")));
assertThrows(ValidationException.class, () -> data.listSessions(r -> r.maxResults(101)));
}
@Test
void sdkValidatesKeepAliveAndReplaysAClosedSessionReceipt() {
assertThrows(ValidationException.class, () -> data.executeStatement(r -> r.waitTimeSeconds(30).clusterIdentifier("warehouse")
@@ -14,12 +14,15 @@ import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.*;
@@ -32,6 +35,44 @@ class RedshiftDataSessionsTest {
private static final RedshiftDataResourceResolver.DatabaseTarget TARGET = new RedshiftDataResourceResolver.DatabaseTarget(
"arn:aws:redshift:us-east-1:000000000000:cluster:warehouse", "localhost", 5439, "dev", "admin", "password");
@Test
void snapshotsKeepSessionsRetiredDuringTheLiveScan() throws Exception {
Clock clock = mock(Clock.class);
Instant now = Instant.parse("2026-10-29T00:00:00Z");
when(clock.instant()).thenReturn(now);
try (RedshiftDataSessions sessions = new RedshiftDataSessions(clock)) {
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
when(factory.open(any())).thenAnswer(invocation -> mock(Connection.class));
List<RedshiftDataSessions.Reservation> closing = new ArrayList<>();
for (int n = 0; n < 64; n++) {
RedshiftDataSessions.Reservation first = sessions.reserve(OWNER,
request().put("SessionKeepAliveSeconds", 60), TARGET);
first.admitted();
first.connection(factory);
first.finish();
RedshiftDataSessions.Reservation last = sessions.reserve(OWNER,
MAPPER.createObjectNode().put("SessionId", first.id()).put("SessionKeepAliveSeconds", 0), TARGET);
last.admitted();
closing.add(last);
}
AtomicInteger reads = new AtomicInteger();
when(clock.instant()).thenAnswer(invocation -> {
// The sweep reads each live session's deadline. Close them at the first live metadata read,
// after the original implementation copied history but before it finishes scanning live sessions.
if (reads.incrementAndGet() == closing.size() + 1) {
closing.forEach(RedshiftDataSessions.Reservation::finish);
}
return now;
});
List<RedshiftDataSessions.SessionInfo> snapshot = sessions.snapshots();
assertEquals(closing.size(), snapshot.size(), "Retirement must not hide a session from both maps");
assertTrue(snapshot.stream().allMatch(info -> "CLOSED".equals(info.status())));
assertEquals(closing.size(), sessions.snapshots().size());
}
}
@Test
void failedConnectionOpeningCannotAdmitAReplacementReservation() throws Exception {
try (RedshiftDataSessions sessions = new RedshiftDataSessions(Clock.systemUTC());
@@ -270,6 +311,27 @@ class RedshiftDataSessionsTest {
return MAPPER.createObjectNode().put("ClusterIdentifier", "warehouse").put("Database", "dev").put("DbUser", "admin");
}
@Test
void failedAdmissionCreatesNoHistoryAndClosedHistoryDoesNotConsumeCapacity() {
try (RedshiftDataSessions sessions = new RedshiftDataSessions(Clock.systemUTC())) {
RedshiftDataSessions.Reservation rejected = sessions.reserve(OWNER, request().put("SessionKeepAliveSeconds", 60), TARGET);
rejected.abort();
assertTrue(sessions.snapshots().isEmpty());
for (int n = 0; n < 501; n++) {
RedshiftDataSessions.Reservation reservation = sessions.reserve(OWNER,
request().put("SessionKeepAliveSeconds", 60), TARGET);
reservation.admitted();
reservation.finish();
}
assertEquals(501, sessions.snapshots().size());
assertTrue(sessions.snapshots().stream().allMatch(info -> "CLOSED".equals(info.status())));
RedshiftDataSessions.Reservation next = sessions.reserve(OWNER, request().put("SessionKeepAliveSeconds", 60), TARGET);
next.abort();
sessions.clear();
assertTrue(sessions.snapshots().isEmpty());
}
}
private static final class MutableClock extends Clock {
private Instant now = Instant.parse("2026-10-24T00:00:00Z");
@@ -0,0 +1,76 @@
package io.github.hectorvent.floci.services.stepfunctions;
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.ServiceRegistry;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataJsonHandler;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataService;
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class AslExecutorRedshiftDataSessionsTest {
@Test
void listSessionsRendersEveryLifecycleTimestampWithoutChangingTheWireResponse() throws Exception {
ObjectMapper mapper = new ObjectMapper();
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
ServiceRegistry registry = mock(ServiceRegistry.class);
when(registry.isServiceEnabled("redshift-data")).thenReturn(true);
RedshiftDataService service = mock(RedshiftDataService.class);
ObjectNode response = mapper.createObjectNode();
ObjectNode session = response.putArray("Sessions").addObject();
session.put("SessionId", "session-id");
session.put("Status", "AVAILABLE");
session.put("CreatedAt", 1_700_000_000.5);
session.put("UpdatedAt", 1_700_000_001.0);
session.put("SessionTtl", 1_700_000_060.25);
session.put("SessionAliveSeconds", 60);
when(service.listSessions(any(), eq("us-east-1"))).thenReturn(response);
AslExecutor executor = AslExecutorFixture.builder()
.objectMapper(mapper)
.config(config)
.customResourceLiveness(null)
.redshiftDataHandler(new RedshiftDataJsonHandler(service))
.serviceRegistry(registry)
.build();
StateMachine machine = new StateMachine();
machine.setStateMachineArn("arn:aws:states:us-east-1:000000000000:stateMachine:list-sessions");
machine.setDefinition("""
{"StartAt":"List","States":{"List":{"Type":"Task",
"Resource":"arn:aws:states:::aws-sdk:redshiftdata:listSessions","End":true}}}
""");
Execution execution = new Execution();
execution.setExecutionArn("arn:aws:states:us-east-1:000000000000:execution:list-sessions:run");
execution.setStateMachineArn(machine.getStateMachineArn());
execution.setInput("{}");
try {
executor.executeSync(machine, execution, new ArrayList<>(), (updated, events) -> { });
assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause());
JsonNode rendered = mapper.readTree(execution.getOutput()).path("Sessions").get(0);
assertEquals("2023-11-14T22:13:20.500Z", rendered.path("CreatedAt").asText());
assertEquals("2023-11-14T22:13:21.000Z", rendered.path("UpdatedAt").asText());
assertEquals("2023-11-14T22:14:20.250Z", rendered.path("SessionTtl").asText());
assertEquals(60, rendered.path("SessionAliveSeconds").asInt());
assertTrue(session.path("CreatedAt").isNumber());
assertTrue(session.path("UpdatedAt").isNumber());
assertTrue(session.path("SessionTtl").isNumber());
verify(service).listSessions(any(), eq("us-east-1"));
} finally {
executor.stop();
}
}
}
@@ -0,0 +1,43 @@
package io.github.hectorvent.floci.testing;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
/** A thread-safe clock that moves only when advanced; zoned views share the same timeline. */
public final class ManualClock extends Clock {
private final AtomicReference<Instant> current;
private final ZoneId zone;
public ManualClock(Instant initial) {
this(new AtomicReference<>(Objects.requireNonNull(initial)), ZoneOffset.UTC);
}
private ManualClock(AtomicReference<Instant> current, ZoneId zone) {
this.current = current;
this.zone = Objects.requireNonNull(zone);
}
@Override
public ZoneId getZone() {
return zone;
}
@Override
public Clock withZone(ZoneId zone) {
return new ManualClock(current, zone);
}
@Override
public Instant instant() {
return current.get();
}
public void advance(Duration duration) {
current.updateAndGet(now -> now.plus(duration));
}
}
@@ -0,0 +1,38 @@
package io.github.hectorvent.floci.testing;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ManualClockTest {
@Test
void readsStayFrozenUntilExplicitlyAdvanced() {
Instant start = Instant.parse("2026-10-29T00:00:00.123456789Z");
ManualClock clock = new ManualClock(start);
assertEquals(start, clock.instant());
assertEquals(start, clock.instant());
clock.advance(Duration.ofNanos(1));
assertEquals(start.plusNanos(1), clock.instant());
assertEquals(start.plusNanos(1), clock.instant());
}
@Test
void zonedViewsShareTheManuallyAdvancedInstant() {
Instant start = Instant.parse("2026-10-29T00:00:00Z");
ManualClock clock = new ManualClock(start);
Clock zoned = clock.withZone(ZoneOffset.ofHours(7));
assertEquals(ZoneOffset.UTC, clock.getZone());
assertEquals(ZoneOffset.ofHours(7), zoned.getZone());
assertEquals(start, zoned.instant());
clock.advance(Duration.ofSeconds(60));
assertEquals(clock.instant(), zoned.instant());
assertEquals(start.plusSeconds(60), zoned.instant());
}
}