mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift-data): implement ListSessions (#6892)
This commit is contained in:
1 parent
5ffe6d1123
commit
da8e22744b
15 files changed
+865
-13
No files matched your search
+302
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+49
@@ -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")
|
||||
|
||||
+62
@@ -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");
|
||||
|
||||
|
||||
+76
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user