mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift-data): support session reuse (#6396)
* feat(redshift-data): support session reuse * fix(redshift-data): address session lifecycle review findings * fix(test): assert Redshift cancellation monitor directly
This commit is contained in:
1 parent
eb84c9d65a
commit
348874766f
11 files changed
+1806
-41
No files matched your search
+41
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
import io.restassured.response.Response;
|
||||
@@ -12,7 +13,14 @@ import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.redshiftdata.RedshiftDataClient;
|
||||
import software.amazon.awssdk.services.redshiftdata.model.ExecuteStatementResponse;
|
||||
import software.amazon.awssdk.services.redshiftdata.model.ResourceNotFoundException;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
@@ -20,6 +28,8 @@ import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@@ -31,6 +41,9 @@ class RedshiftDataApiIntegrationTest {
|
||||
@Inject
|
||||
RedshiftService redshift;
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
private String clusterId;
|
||||
|
||||
@BeforeAll
|
||||
@@ -87,6 +100,34 @@ class RedshiftDataApiIntegrationTest {
|
||||
return ((Number) value).intValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdkSessionPreservesPostgresTemporaryTablesAcrossExecuteAndBatch() {
|
||||
try (RedshiftDataClient data = RedshiftDataClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))).build()) {
|
||||
ExecuteStatementResponse created = data.executeStatement(request -> request.clusterIdentifier(clusterId)
|
||||
.dbUser("admin").database("dev").sessionKeepAliveSeconds(60)
|
||||
.sql("CREATE TEMP TABLE session_rows(id integer)"));
|
||||
assertNotNull(created.sessionId());
|
||||
awaitFinished(created.id());
|
||||
String session = created.sessionId();
|
||||
awaitFinished(data.batchExecuteStatement(request -> request.sessionId(session)
|
||||
.sqls("INSERT INTO session_rows VALUES (41)", "INSERT INTO session_rows VALUES (42)")).id());
|
||||
awaitFinished(data.executeStatement(request -> request.sessionId(session).sql("VACUUM")).id());
|
||||
awaitFinished(data.executeStatement(request -> request.sessionId(session).sql("BEGIN")).id());
|
||||
awaitFinished(data.executeStatement(request -> request.sessionId(session).sql("INSERT INTO session_rows VALUES (99)")).id());
|
||||
awaitFinished(data.executeStatement(request -> request.sessionId(session).sql("ROLLBACK")).id());
|
||||
String query = data.executeStatement(request -> request.sessionId(session).sql("SELECT id FROM session_rows ORDER BY id")).id();
|
||||
awaitFinished(query);
|
||||
assertEquals(session, data.describeStatement(request -> request.id(query)).sessionId());
|
||||
assertEquals(2L, data.getStatementResult(request -> request.id(query)).totalNumRows());
|
||||
assertEquals(41L, data.getStatementResult(request -> request.id(query)).records().getFirst().getFirst().longValue());
|
||||
String last = data.executeStatement(request -> request.sessionId(session).sessionKeepAliveSeconds(0).sql("SELECT 1")).id();
|
||||
awaitFinished(last);
|
||||
assertThrows(ResourceNotFoundException.class,
|
||||
() -> data.executeStatement(request -> request.sessionId(session).sql("SELECT 1")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void vacuumPreservesAutoCommitExecution() {
|
||||
executeAndWait("VACUUM");
|
||||
|
||||
+18
@@ -42,6 +42,24 @@ class RedshiftDataExecutionTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancellationSignalHoldsExecutionMonitor() throws Exception {
|
||||
RedshiftDataExecution execution = new RedshiftDataExecution(0);
|
||||
Statement statement = mock(Statement.class);
|
||||
execution.track(statement);
|
||||
assertTrue(execution.requestCancellation());
|
||||
doAnswer(invocation -> {
|
||||
assertTrue(Thread.holdsLock(execution));
|
||||
return null;
|
||||
}).when(statement).cancel();
|
||||
|
||||
execution.signalCancellation();
|
||||
execution.terminal();
|
||||
execution.signalCancellation();
|
||||
verify(statement).cancel();
|
||||
execution.completed();
|
||||
}
|
||||
|
||||
@Test
|
||||
void successfulCommitWinsOverCancellation() throws Exception {
|
||||
try (RedshiftDataExecutor executor = new RedshiftDataExecutor(1, 1, 1)) {
|
||||
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.h2.Driver;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
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.ResourceNotFoundException;
|
||||
import software.amazon.awssdk.services.redshiftdata.model.StatusString;
|
||||
import software.amazon.awssdk.services.redshiftdata.model.ValidationException;
|
||||
|
||||
import java.net.URI;
|
||||
import java.sql.DriverManager;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@QuarkusTest
|
||||
class RedshiftDataSessionIntegrationTest {
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
@InjectMock
|
||||
RedshiftDataResourceResolver resolver;
|
||||
@InjectMock
|
||||
RedshiftDataConnectionFactory factory;
|
||||
@Inject
|
||||
RedshiftDataService service;
|
||||
@Inject
|
||||
RegionResolver regions;
|
||||
|
||||
private RedshiftDataClient data;
|
||||
|
||||
@BeforeEach
|
||||
void setup() throws Exception {
|
||||
Driver.load();
|
||||
String url = "jdbc:h2:mem:" + UUID.randomUUID();
|
||||
when(factory.open(any())).thenAnswer(invocation -> DriverManager.getConnection(url));
|
||||
when(resolver.resolve(any(), any())).thenAnswer(invocation -> {
|
||||
JsonNode request = invocation.getArgument(0);
|
||||
String region = invocation.getArgument(1);
|
||||
boolean serverless = request.has("WorkgroupName");
|
||||
String arn = AwsArnUtils.Arn.of(serverless ? "redshift-serverless" : "redshift", region,
|
||||
regions.getAccountId(), serverless ? "workgroup/12345678-1234-1234-1234-123456789012" : "cluster:warehouse").toString();
|
||||
return new RedshiftDataResourceResolver.DatabaseTarget(arn, "localhost", 5439, "dev", "admin", "password");
|
||||
});
|
||||
data = client("test", Region.US_EAST_1);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() {
|
||||
service.clear();
|
||||
if (data != null) {
|
||||
data.close();
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void sdkReusesSessionForSingleAndBatchStatements(boolean serverless) throws Exception {
|
||||
ExecuteStatementRequest.Builder request = ExecuteStatementRequest.builder().waitTimeSeconds(30).database("dev")
|
||||
.sessionKeepAliveSeconds(60).sql("CREATE LOCAL TEMPORARY TABLE staging(id integer)");
|
||||
if (serverless) {
|
||||
request.workgroupName("analytics");
|
||||
} else {
|
||||
request.clusterIdentifier("warehouse").dbUser("admin");
|
||||
}
|
||||
ExecuteStatementResponse created = data.executeStatement(request.build());
|
||||
assertNotNull(created.sessionId());
|
||||
finished(created.id());
|
||||
String batch = data.batchExecuteStatement(r -> r.waitTimeSeconds(30).sessionId(created.sessionId())
|
||||
.sqls("INSERT INTO staging VALUES (41)", "INSERT INTO staging VALUES (42)")).id();
|
||||
finished(batch);
|
||||
ExecuteStatementResponse query = data.executeStatement(r -> r.waitTimeSeconds(30).sessionId(created.sessionId()).sql("SELECT id FROM staging ORDER BY id"));
|
||||
DescribeStatementResponse described = finished(query.id());
|
||||
|
||||
assertEquals(created.sessionId(), described.sessionId());
|
||||
assertEquals(created.sessionId(), query.sessionId());
|
||||
assertEquals(41L, data.getStatementResult(r -> r.id(query.id())).records().getFirst().getFirst().longValue());
|
||||
assertEquals(2L, data.getStatementResult(r -> r.id(query.id())).totalNumRows());
|
||||
assertTrue(data.listStatements(r -> r.maxResults(100)).statements().stream()
|
||||
.anyMatch(statement -> created.sessionId().equals(statement.sessionId())));
|
||||
verify(factory).open(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdkSessionIsIsolatedByCallerAccountAndRegion() {
|
||||
ExecuteStatementResponse created = data.executeStatement(r -> r.waitTimeSeconds(30).clusterIdentifier("warehouse").dbUser("admin")
|
||||
.database("dev").sessionKeepAliveSeconds(60).sql("SELECT 1"));
|
||||
finished(created.id());
|
||||
for (String key : new String[]{"another-caller", "111111111111"}) {
|
||||
try (RedshiftDataClient other = client(key, Region.US_EAST_1)) {
|
||||
assertThrows(ResourceNotFoundException.class, () -> other.executeStatement(r -> r.waitTimeSeconds(30).sessionId(created.sessionId()).sql("SELECT 2")));
|
||||
}
|
||||
}
|
||||
try (RedshiftDataClient otherRegion = client("test", Region.US_WEST_2)) {
|
||||
assertThrows(ResourceNotFoundException.class, () -> otherRegion.executeStatement(r -> r.waitTimeSeconds(30).sessionId(created.sessionId()).sql("SELECT 2")));
|
||||
}
|
||||
finished(data.executeStatement(r -> r.waitTimeSeconds(30).sessionId(created.sessionId()).sql("SELECT 3")).id());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdkValidatesKeepAliveAndReplaysAClosedSessionReceipt() {
|
||||
assertThrows(ValidationException.class, () -> data.executeStatement(r -> r.waitTimeSeconds(30).clusterIdentifier("warehouse")
|
||||
.dbUser("admin").database("dev").sessionKeepAliveSeconds(86401).sql("SELECT 1")));
|
||||
ExecuteStatementResponse created = data.executeStatement(r -> r.waitTimeSeconds(30).clusterIdentifier("warehouse").dbUser("admin")
|
||||
.database("dev").sessionKeepAliveSeconds(60).sql("SELECT 1"));
|
||||
finished(created.id());
|
||||
ExecuteStatementRequest last = ExecuteStatementRequest.builder().waitTimeSeconds(30).sessionId(created.sessionId()).sessionKeepAliveSeconds(0)
|
||||
.clientToken(UUID.randomUUID().toString()).sql("SELECT 2").build();
|
||||
ExecuteStatementResponse closed = data.executeStatement(last);
|
||||
finished(closed.id());
|
||||
assertEquals(closed.id(), data.executeStatement(last).id());
|
||||
assertEquals(closed.sessionId(), data.executeStatement(last).sessionId());
|
||||
try (RedshiftDataClient other = client("another-caller", Region.US_EAST_1)) {
|
||||
assertThrows(ResourceNotFoundException.class, () -> other.executeStatement(last));
|
||||
}
|
||||
assertThrows(ResourceNotFoundException.class, () -> data.executeStatement(r -> r.waitTimeSeconds(30).sessionId(created.sessionId()).sql("SELECT 3")));
|
||||
}
|
||||
|
||||
private RedshiftDataClient client(String key, Region region) {
|
||||
return RedshiftDataClient.builder().endpointOverride(endpoint).region(region)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(key, "test"))).build();
|
||||
}
|
||||
|
||||
private DescribeStatementResponse finished(String id) {
|
||||
DescribeStatementResponse statement = data.describeStatement(r -> r.id(id));
|
||||
assertEquals(StatusString.FINISHED, statement.status(), statement.error());
|
||||
return statement;
|
||||
}
|
||||
}
|
||||
+537
@@ -0,0 +1,537 @@
|
||||
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.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 org.h2.Driver;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class RedshiftDataSessionServiceTest {
|
||||
|
||||
@Test
|
||||
void sessionOnlyRequestsShareTemporaryTablesAndReportSessionMetadata() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
ObjectNode created = fixture.service.executeStatement(fixture.request(
|
||||
"CREATE LOCAL TEMPORARY TABLE staging(id integer)").put("SessionKeepAliveSeconds", 60), "us-east-1");
|
||||
assertTrue(created.path("SessionId").isTextual(), "A retained session must have an id");
|
||||
String session = created.path("SessionId").asText();
|
||||
fixture.service.executeStatement(fixture.reuse(session, "INSERT INTO staging VALUES (42)"), "us-east-1");
|
||||
ObjectNode query = fixture.service.executeStatement(fixture.reuse(session, "SELECT id FROM staging"), "us-east-1");
|
||||
ObjectNode described = fixture.service.describeStatement(fixture.mapper.createObjectNode().put("Id", query.path("Id").asText()));
|
||||
|
||||
assertEquals("FINISHED", described.path("Status").asText(), described.toString());
|
||||
assertEquals(session, described.path("SessionId").asText());
|
||||
ObjectNode result = fixture.service.getStatementResult(fixture.mapper.createObjectNode().put("Id", query.path("Id").asText()));
|
||||
assertEquals(42, result.path("Records").get(0).get(0).path("longValue").asInt());
|
||||
assertEquals(session, fixture.service.listStatements(fixture.mapper.createObjectNode())
|
||||
.path("Statements").get(0).path("SessionId").asText());
|
||||
verify(fixture.factory).open(any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchAndSingleStatementCanShareOneSession() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
ObjectNode request = fixture.request("unused").put("SessionKeepAliveSeconds", 60);
|
||||
request.remove("Sql");
|
||||
request.putArray("Sqls").add("CREATE LOCAL TEMPORARY TABLE staging(id integer)")
|
||||
.add("INSERT INTO staging VALUES (7)");
|
||||
ObjectNode batch = fixture.service.batchExecuteStatement(request, "us-east-1");
|
||||
String session = batch.path("SessionId").asText();
|
||||
ObjectNode query = fixture.service.executeStatement(fixture.reuse(session, "SELECT id FROM staging"), "us-east-1");
|
||||
ObjectNode result = fixture.service.getStatementResult(fixture.mapper.createObjectNode().put("Id", query.path("Id").asText()));
|
||||
|
||||
assertEquals(7, result.path("Records").get(0).get(0).path("longValue").asInt());
|
||||
verify(fixture.factory).open(any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void clientTokenRetryKeepsTheOriginalSessionAndExecutesOnce() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
ObjectNode request = fixture.request("CREATE LOCAL TEMPORARY TABLE staging(id integer)")
|
||||
.put("SessionKeepAliveSeconds", 60).put("ClientToken", "retained-session");
|
||||
ObjectNode first = fixture.service.executeStatement(request, "us-east-1");
|
||||
ObjectNode retry = fixture.service.executeStatement(request, "us-east-1");
|
||||
|
||||
assertTrue(first.path("SessionId").isTextual());
|
||||
assertEquals(first.path("SessionId"), retry.path("SessionId"));
|
||||
assertEquals(first.path("Id"), retry.path("Id"));
|
||||
verify(fixture.factory).open(any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitTransactionCanBeRolledBackAcrossCalls() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
String session = fixture.service.executeStatement(fixture.request("CREATE TABLE changes(id integer)")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
fixture.service.executeStatement(fixture.reuse(session, "BEGIN"), "us-east-1");
|
||||
fixture.service.executeStatement(fixture.reuse(session, "INSERT INTO changes VALUES (1)"), "us-east-1");
|
||||
assertEquals(0, fixture.count("changes"));
|
||||
fixture.service.executeStatement(fixture.reuse(session, "ROLLBACK"), "us-east-1");
|
||||
assertEquals(0, fixture.count("changes"));
|
||||
fixture.service.executeStatement(fixture.reuse(session, "BEGIN TRANSACTION"), "us-east-1");
|
||||
fixture.service.executeStatement(fixture.reuse(session, "INSERT INTO changes VALUES (2)"), "us-east-1");
|
||||
fixture.service.executeStatement(fixture.reuse(session, "COMMIT"), "us-east-1");
|
||||
assertEquals(1, fixture.count("changes"));
|
||||
fixture.service.executeStatement(fixture.reuse(session, "BEGIN"), "us-east-1");
|
||||
fixture.service.executeStatement(fixture.reuse(session, "INSERT INTO changes VALUES (3)"), "us-east-1");
|
||||
ObjectNode batch = fixture.reuse(session, "unused");
|
||||
batch.remove("Sql");
|
||||
batch.putArray("Sqls").add("INSERT INTO changes VALUES (4)");
|
||||
fixture.service.batchExecuteStatement(batch, "us-east-1");
|
||||
assertEquals(3, fixture.count("changes"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedExplicitTransactionCannotAccidentallyCommitLaterStatements() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
String session = fixture.service.executeStatement(fixture.request("CREATE TABLE changes(id integer)")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
fixture.service.executeStatement(fixture.reuse(session, "BEGIN -- keep this transaction open"), "us-east-1");
|
||||
fixture.service.executeStatement(fixture.reuse(session, "INSERT INTO changes VALUES (1)"), "us-east-1");
|
||||
assertEquals(0, fixture.count("changes"));
|
||||
fixture.service.executeStatement(fixture.reuse(session, "INSERT INTO missing_table VALUES (2)"), "us-east-1");
|
||||
ObjectNode later = fixture.service.executeStatement(fixture.reuse(session, "INSERT INTO changes VALUES (3)"), "us-east-1");
|
||||
assertEquals("FAILED", fixture.service.describeStatement(fixture.mapper.createObjectNode()
|
||||
.put("Id", later.path("Id").asText())).path("Status").asText());
|
||||
ObjectNode batch = fixture.reuse(session, "unused");
|
||||
batch.remove("Sql");
|
||||
batch.putArray("Sqls").add("INSERT INTO changes VALUES (9)");
|
||||
String batchId = fixture.service.batchExecuteStatement(batch, "us-east-1").path("Id").asText();
|
||||
assertEquals("FAILED", fixture.service.describeStatement(fixture.mapper.createObjectNode()
|
||||
.put("Id", batchId)).path("Status").asText());
|
||||
fixture.service.executeStatement(fixture.reuse(session, "ROLLBACK"), "us-east-1");
|
||||
assertEquals(0, fixture.count("changes"));
|
||||
fixture.service.executeStatement(fixture.reuse(session, "INSERT INTO changes VALUES (4)"), "us-east-1");
|
||||
assertEquals(1, fixture.count("changes"));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void connectionFailureRetiresTheSessionWithoutReportingCancellation(boolean batch) throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
Connection connection = spy(DriverManager.getConnection(fixture.url));
|
||||
doThrow(new SQLException("broken connection", "08006")).when(connection).prepareStatement("SELECT broken");
|
||||
when(fixture.factory.open(any())).thenReturn(connection);
|
||||
String session = fixture.service.executeStatement(fixture.request("SELECT 1")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
ObjectNode request = fixture.reuse(session, "SELECT broken");
|
||||
if (batch) {
|
||||
request.remove("Sql");
|
||||
request.putArray("Sqls").add("SELECT broken");
|
||||
}
|
||||
String failed = (batch ? fixture.service.batchExecuteStatement(request, "us-east-1")
|
||||
: fixture.service.executeStatement(request, "us-east-1")).path("Id").asText();
|
||||
ObjectNode described = fixture.service.describeStatement(fixture.mapper.createObjectNode().put("Id", failed));
|
||||
assertEquals("FAILED", described.path("Status").asText());
|
||||
assertTrue(connection.isClosed());
|
||||
assertThrows(AwsException.class, () -> fixture.service.executeStatement(fixture.reuse(session, "SELECT 2"), "us-east-1"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedTransactionModesFailInsteadOfSilentlyCommitting() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
String session = fixture.service.executeStatement(fixture.request("SELECT 1")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
for (String sql : new String[]{"BEGIN ISOLATION LEVEL SERIALIZABLE", "START TRANSACTION READ ONLY", "COMMIT AND CHAIN"}) {
|
||||
ObjectNode response = fixture.service.executeStatement(fixture.reuse(session, sql), "us-east-1");
|
||||
ObjectNode described = fixture.service.describeStatement(fixture.mapper.createObjectNode().put("Id", response.path("Id").asText()));
|
||||
assertEquals("FAILED", described.path("Status").asText());
|
||||
assertTrue(described.path("Error").asText().contains("not supported"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedBatchRollsBackWithoutClosingTheReusableConnection() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
String session = fixture.service.executeStatement(fixture.request("CREATE LOCAL TEMPORARY TABLE staging(id integer)")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
ObjectNode batch = fixture.reuse(session, "unused");
|
||||
batch.remove("Sql");
|
||||
batch.putArray("Sqls").add("INSERT INTO staging VALUES (42)").add("INSERT INTO missing_table VALUES (1)");
|
||||
String id = fixture.service.batchExecuteStatement(batch, "us-east-1").path("Id").asText();
|
||||
assertEquals("FAILED", fixture.service.describeStatement(fixture.mapper.createObjectNode().put("Id", id))
|
||||
.path("Status").asText());
|
||||
ObjectNode query = fixture.service.executeStatement(fixture.reuse(session, "SELECT COUNT(*) FROM staging"), "us-east-1");
|
||||
ObjectNode result = fixture.service.getStatementResult(fixture.mapper.createObjectNode().put("Id", query.path("Id").asText()));
|
||||
assertEquals(0, result.path("Records").get(0).get(0).path("longValue").asInt());
|
||||
verify(fixture.factory).open(any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitSessionTerminationStillAllowsIdempotentReplay() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
String session = fixture.service.executeStatement(fixture.request("SELECT 1")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
ObjectNode request = fixture.reuse(session, "SELECT 2").put("SessionKeepAliveSeconds", 0).put("ClientToken", "last");
|
||||
ObjectNode first = fixture.service.executeStatement(request, "us-east-1");
|
||||
ObjectNode retry = fixture.service.executeStatement(request, "us-east-1");
|
||||
assertEquals(first.path("Id"), retry.path("Id"));
|
||||
AwsException gone = assertThrows(AwsException.class, () -> fixture.service.executeStatement(
|
||||
fixture.reuse(session, "SELECT 3"), "us-east-1"));
|
||||
assertEquals("ResourceNotFoundException", gone.getErrorCode());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void busySessionRejectsNewQueriesButAllowsClientTokenRetriesAndQueuedCancellation() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
String session = fixture.service.executeStatement(fixture.request("SELECT 1")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
CountDownLatch started = new CountDownLatch(2);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
for (int n = 0; n < 2; n++) {
|
||||
fixture.executor.submit("000000000000", "us-east-1", "block-" + n, execution -> {
|
||||
started.countDown();
|
||||
try {
|
||||
release.await(5, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException expected) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
});
|
||||
}
|
||||
try {
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
ObjectNode request = fixture.reuse(session, "SELECT 2").put("ClientToken", "queued");
|
||||
request.remove("WaitTimeSeconds");
|
||||
ObjectNode queued = fixture.service.executeStatement(request, "us-east-1");
|
||||
assertEquals(queued.path("Id"), fixture.service.executeStatement(request, "us-east-1").path("Id"));
|
||||
AwsException busy = assertThrows(AwsException.class, () -> fixture.service.executeStatement(
|
||||
fixture.reuse(session, "SELECT 3"), "us-east-1"));
|
||||
assertEquals("ValidationException", busy.getErrorCode());
|
||||
assertTrue(fixture.service.cancelStatement(fixture.mapper.createObjectNode()
|
||||
.put("Id", queued.path("Id").asText())).path("Status").asBoolean());
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
ObjectNode query = fixture.service.executeStatement(fixture.reuse(session, "SELECT 4"), "us-east-1");
|
||||
assertEquals("FINISHED", fixture.service.describeStatement(fixture.mapper.createObjectNode()
|
||||
.put("Id", query.path("Id").asText())).path("Status").asText());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void mismatchedTargetsAndResetSessionsAreRejected() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
String session = fixture.service.executeStatement(fixture.request("SELECT 1")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
for (String field : new String[]{"Database", "DbUser", "ClusterIdentifier", "WorkgroupName", "SecretArn"}) {
|
||||
assertThrows(AwsException.class, () -> fixture.service.executeStatement(
|
||||
fixture.reuse(session, "SELECT 2").put(field, "different"), "us-east-1"));
|
||||
}
|
||||
fixture.service.clear();
|
||||
assertThrows(AwsException.class, () -> fixture.service.executeStatement(fixture.reuse(session, "SELECT 2"), "us-east-1"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void fullExecutorQueueDoesNotLeaveTheSessionBusy() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
String session = fixture.service.executeStatement(fixture.request("SELECT 1")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
CountDownLatch started = new CountDownLatch(2);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
List<RedshiftDataExecution> executions = new ArrayList<>();
|
||||
for (int n = 0; n < 2; n++) {
|
||||
executions.add(fixture.executor.submit("000000000000", "us-east-1", "block-" + n, execution -> {
|
||||
started.countDown();
|
||||
try {
|
||||
release.await(5, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException expected) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}));
|
||||
}
|
||||
try {
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
for (int n = 0; n < 8; n++) {
|
||||
executions.add(fixture.executor.submit("000000000000", "us-east-1", "queued-" + n, execution -> { }));
|
||||
}
|
||||
AwsException full = assertThrows(AwsException.class, () -> fixture.service.executeStatement(
|
||||
fixture.reuse(session, "SELECT 2"), "us-east-1"));
|
||||
assertEquals("ActiveStatementsExceededException", full.getErrorCode());
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
for (RedshiftDataExecution execution : executions) {
|
||||
execution.await(Duration.ofSeconds(5));
|
||||
assertTrue(execution.isDone());
|
||||
}
|
||||
String query = fixture.service.executeStatement(fixture.reuse(session, "SELECT 3"), "us-east-1").path("Id").asText();
|
||||
assertEquals("FINISHED", fixture.service.describeStatement(fixture.mapper.createObjectNode().put("Id", query)).path("Status").asText());
|
||||
verify(fixture.factory).open(any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectedAdmissionReleasesAnExistingSessionWithoutOpeningAnotherConnection() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
String session = fixture.service.executeStatement(fixture.request("SELECT 1")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
doThrow(new IllegalStateException("statement storage unavailable")).when(fixture.statements)
|
||||
.putForAccount(any(), any());
|
||||
assertThrows(IllegalStateException.class, () -> fixture.service.executeStatement(
|
||||
fixture.reuse(session, "SELECT 2"), "us-east-1"));
|
||||
doCallRealMethod().when(fixture.statements).putForAccount(any(), any());
|
||||
doThrow(new IllegalStateException("receipt storage unavailable")).when(fixture.receipts).put(any(), any(), any());
|
||||
assertThrows(IllegalStateException.class, () -> fixture.service.executeStatement(
|
||||
fixture.reuse(session, "SELECT 2").put("ClientToken", "rejected"), "us-east-1"));
|
||||
doCallRealMethod().when(fixture.receipts).put(any(), any(), any());
|
||||
ObjectNode retried = fixture.service.executeStatement(fixture.reuse(session, "SELECT 2")
|
||||
.put("ClientToken", "rejected"), "us-east-1");
|
||||
assertEquals("FINISHED", fixture.service.describeStatement(fixture.mapper.createObjectNode()
|
||||
.put("Id", retried.path("Id").asText())).path("Status").asText());
|
||||
verify(fixture.factory).open(any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void receiptReplaysAfterLosingLiveSessionsAndEvictingStatementResults() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
String session = fixture.service.executeStatement(fixture.request("SELECT 1")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
ObjectNode request = fixture.reuse(session, "SELECT 2").put("ClientToken", "restart-replay");
|
||||
ObjectNode first = fixture.service.executeStatement(request, "us-east-1");
|
||||
fixture.statements.deleteForAccount("000000000000", first.path("Id").asText());
|
||||
RedshiftDataService restarted = new RedshiftDataService(fixture.resolver, fixture.factory, fixture.statements,
|
||||
fixture.mapper, null, fixture.executor, null, null, null, fixture.receipts);
|
||||
|
||||
ObjectNode replay = restarted.executeStatement(request, "us-east-1");
|
||||
assertEquals(first.path("Id"), replay.path("Id"));
|
||||
assertEquals(first.path("SessionId"), replay.path("SessionId"));
|
||||
verify(fixture.factory).open(any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void uncheckedFailureAfterSqlExecutionAbortsTheExplicitTransaction() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
Connection connection = spy(DriverManager.getConnection(fixture.url));
|
||||
when(fixture.factory.open(any())).thenReturn(connection);
|
||||
String session = fixture.service.executeStatement(fixture.request("CREATE TABLE changes(id integer)")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
PreparedStatement insert = spy(connection.prepareStatement("INSERT INTO changes VALUES (1)"));
|
||||
doAnswer(invocation -> {
|
||||
invocation.callRealMethod();
|
||||
throw new IllegalStateException("result conversion failed");
|
||||
}).when(insert).execute();
|
||||
doReturn(insert).when(connection).prepareStatement("INSERT INTO changes VALUES (1)");
|
||||
fixture.service.executeStatement(fixture.reuse(session, "BEGIN"), "us-east-1");
|
||||
String failed = fixture.service.executeStatement(fixture.reuse(session, "INSERT INTO changes VALUES (1)"), "us-east-1")
|
||||
.path("Id").asText();
|
||||
ObjectNode described = fixture.service.describeStatement(fixture.mapper.createObjectNode().put("Id", failed));
|
||||
assertEquals("FAILED", described.path("Status").asText());
|
||||
assertTrue(described.path("Error").asText().contains("result conversion failed"), described.toString());
|
||||
String committed = fixture.service.executeStatement(fixture.reuse(session, "COMMIT"), "us-east-1").path("Id").asText();
|
||||
assertEquals("FINISHED", fixture.service.describeStatement(fixture.mapper.createObjectNode().put("Id", committed))
|
||||
.path("Status").asText());
|
||||
assertEquals(0, fixture.count("changes"));
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void malformedSessionIdentifiersFailBeforeTargetLookup(boolean batch) throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
for (String raw : new String[]{"\"malformed\"", "7", "true", "null", "[]", "{}"}) {
|
||||
ObjectNode request = fixture.request("SELECT 1");
|
||||
JsonNode invalid = fixture.mapper.readTree(raw);
|
||||
request.set("SessionId", invalid);
|
||||
if (batch) {
|
||||
request.remove("Sql");
|
||||
request.putArray("Sqls").add("SELECT 1");
|
||||
}
|
||||
AwsException error = assertThrows(AwsException.class, () -> {
|
||||
if (batch) {
|
||||
fixture.service.batchExecuteStatement(request, "us-east-1");
|
||||
} else {
|
||||
fixture.service.executeStatement(request, "us-east-1");
|
||||
}
|
||||
});
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
}
|
||||
verifyNoInteractions(fixture.factory, fixture.resolver);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void ordinaryRequestsDoNotResolveSessionCaller(boolean batch) throws Exception {
|
||||
RequestContext context = new RequestContext();
|
||||
context.setAccessKeyId("caller-key");
|
||||
IamService iam = mock(IamService.class);
|
||||
when(iam.resolveCallerArn("caller-key")).thenReturn(Optional.of("caller-arn"));
|
||||
try (Fixture fixture = new Fixture(context, iam)) {
|
||||
for (boolean token : new boolean[]{false, true}) {
|
||||
ObjectNode request = fixture.request("SELECT 1").put("SessionKeepAliveSeconds", 0);
|
||||
if (token) {
|
||||
request.put("ClientToken", "ordinary");
|
||||
}
|
||||
if (batch) {
|
||||
request.remove("Sql");
|
||||
request.putArray("Sqls").add("SELECT 1");
|
||||
fixture.service.batchExecuteStatement(request, "us-east-1");
|
||||
} else {
|
||||
fixture.service.executeStatement(request, "us-east-1");
|
||||
}
|
||||
}
|
||||
verifyNoInteractions(iam);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void cleanupFailureIsReportedWithoutSkippingResetOfStatementAndReceiptState() throws Exception {
|
||||
try (Fixture fixture = new Fixture(); Connection connection = spy(DriverManager.getConnection(fixture.url))) {
|
||||
when(fixture.factory.open(any())).thenReturn(connection);
|
||||
ObjectNode request = fixture.request("SELECT 1").put("ClientToken", "cleanup-reset").put("SessionKeepAliveSeconds", 60);
|
||||
String id = fixture.service.executeStatement(request, "us-east-1").path("Id").asText();
|
||||
doThrow(new IllegalStateException("unexpected close failure")).doCallRealMethod().when(connection).close();
|
||||
|
||||
assertThrows(IllegalStateException.class, fixture.service::clear);
|
||||
|
||||
assertNull(fixture.statements.getForAccount("000000000000", id));
|
||||
assertNull(fixture.receipts.find(new RedshiftDataIdempotencyStore.Scope("000000000000", "us-east-1",
|
||||
"ExecuteStatement", "cleanup-reset")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void terminatingSessionReportsUnexpectedConnectionCleanupFailure() throws Exception {
|
||||
try (Fixture fixture = new Fixture(); Connection connection = spy(DriverManager.getConnection(fixture.url))) {
|
||||
when(fixture.factory.open(any())).thenReturn(connection);
|
||||
String session = fixture.service.executeStatement(fixture.request("SELECT 1")
|
||||
.put("SessionKeepAliveSeconds", 60), "us-east-1").path("SessionId").asText();
|
||||
doThrow(new IllegalStateException("unexpected close failure")).doCallRealMethod().when(connection).close();
|
||||
String id = fixture.service.executeStatement(fixture.reuse(session, "SELECT 2")
|
||||
.put("SessionKeepAliveSeconds", 0), "us-east-1").path("Id").asText();
|
||||
ObjectNode described = fixture.service.describeStatement(fixture.mapper.createObjectNode().put("Id", id));
|
||||
assertEquals("FAILED", described.path("Status").asText());
|
||||
assertTrue(described.path("Error").asText().contains("unexpected close failure"), described.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void replayWithoutSessionFieldsStillChecksRetainedReceiptOwnership() throws Exception {
|
||||
RequestContext context = new RequestContext();
|
||||
context.setAccessKeyId("owner");
|
||||
IamService iam = mock(IamService.class);
|
||||
when(iam.resolveCallerArn("owner")).thenReturn(Optional.of("owner-principal"));
|
||||
when(iam.resolveCallerArn("other")).thenReturn(Optional.of("other-principal"));
|
||||
try (Fixture fixture = new Fixture(context, iam)) {
|
||||
ObjectNode request = fixture.request("SELECT 1").put("ClientToken", "retained-replay")
|
||||
.put("SessionKeepAliveSeconds", 60);
|
||||
String id = fixture.service.executeStatement(request, "us-east-1").path("Id").asText();
|
||||
request.remove("SessionKeepAliveSeconds");
|
||||
context.setAccessKeyId("other");
|
||||
AwsException denied = assertThrows(AwsException.class, () -> fixture.service.executeStatement(request, "us-east-1"));
|
||||
assertEquals("ResourceNotFoundException", denied.getErrorCode());
|
||||
context.setAccessKeyId("owner");
|
||||
assertEquals(id, fixture.service.executeStatement(request, "us-east-1").path("Id").asText());
|
||||
verify(fixture.factory).open(any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedKeepAliveValuesAreRejectedBeforeOpeningAConnection() throws Exception {
|
||||
try (Fixture fixture = new Fixture()) {
|
||||
for (int seconds : new int[]{-1, 86401}) {
|
||||
AwsException error = assertThrows(AwsException.class, () -> fixture.service.executeStatement(
|
||||
fixture.request("SELECT 1").put("SessionKeepAliveSeconds", seconds), "us-east-1"));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
}
|
||||
assertThrows(AwsException.class, () -> fixture.service.executeStatement(
|
||||
fixture.request("SELECT 1").put("SessionKeepAliveSeconds", "60"), "us-east-1"));
|
||||
assertThrows(AwsException.class, () -> fixture.service.executeStatement(
|
||||
fixture.request("SELECT 1").put("SessionKeepAliveSeconds", 0.5), "us-east-1"));
|
||||
verifyNoInteractions(fixture.factory);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Fixture implements AutoCloseable {
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final RedshiftDataResourceResolver resolver = mock(RedshiftDataResourceResolver.class);
|
||||
private final RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
private final RedshiftDataExecutor executor = new RedshiftDataExecutor(2, 8, 1);
|
||||
private final RedshiftDataStatementStore statements = spy(new RedshiftDataStatementStore(24, Clock.systemUTC()));
|
||||
private final RedshiftDataIdempotencyStore receipts = spy(new RedshiftDataIdempotencyStore(
|
||||
AccountAwareStorageBackend.inMemory("000000000000"), Clock.systemUTC()));
|
||||
private final RedshiftDataService service;
|
||||
private final String url = "jdbc:h2:mem:" + UUID.randomUUID();
|
||||
|
||||
private Fixture() throws Exception {
|
||||
this(null, null);
|
||||
}
|
||||
|
||||
private Fixture(RequestContext context, IamService iam) throws Exception {
|
||||
Driver.load();
|
||||
when(resolver.resolve(any(), any())).thenAnswer(invocation -> {
|
||||
ObjectNode request = invocation.getArgument(0);
|
||||
if (!request.has("Database")) {
|
||||
throw new AwsException("ValidationException", "Database is required", 400);
|
||||
}
|
||||
return new RedshiftDataResourceResolver.DatabaseTarget(
|
||||
"arn:aws:redshift:us-east-1:000000000000:cluster:warehouse", "localhost", 5439,
|
||||
"dev", "admin", "password");
|
||||
});
|
||||
when(factory.open(any())).thenAnswer(invocation -> DriverManager.getConnection(url));
|
||||
service = new RedshiftDataService(resolver, factory, statements, mapper, null, executor, null,
|
||||
context, iam, receipts);
|
||||
}
|
||||
|
||||
private ObjectNode request(String sql) {
|
||||
return mapper.createObjectNode().put("Sql", sql).put("WaitTimeSeconds", 5)
|
||||
.put("ClusterIdentifier", "warehouse").put("Database", "dev").put("DbUser", "admin");
|
||||
}
|
||||
|
||||
private ObjectNode reuse(String session, String sql) {
|
||||
return mapper.createObjectNode().put("Sql", sql).put("SessionId", session).put("WaitTimeSeconds", 5);
|
||||
}
|
||||
|
||||
private int count(String table) throws Exception {
|
||||
try (Connection connection = DriverManager.getConnection(url);
|
||||
Statement statement = connection.createStatement();
|
||||
ResultSet rows = statement.executeQuery("SELECT COUNT(*) FROM " + table)) {
|
||||
assertTrue(rows.next());
|
||||
return rows.getInt(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
service.clear();
|
||||
executor.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
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 static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class RedshiftDataSessionsTest {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final RedshiftDataSessions.Scope OWNER = new RedshiftDataSessions.Scope("000000000000", "us-east-1", "caller");
|
||||
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 failedConnectionOpeningCannotAdmitAReplacementReservation() throws Exception {
|
||||
try (RedshiftDataSessions sessions = new RedshiftDataSessions(Clock.systemUTC());
|
||||
ExecutorService workers = Executors.newFixedThreadPool(2)) {
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
when(factory.open(any())).thenThrow(new SQLException("connection refused", "08001"));
|
||||
for (int attempt = 0; attempt < 2000; attempt++) {
|
||||
RedshiftDataSessions.Reservation first = sessions.reserve(OWNER,
|
||||
request().put("SessionKeepAliveSeconds", 60), TARGET);
|
||||
first.admitted();
|
||||
assertThrows(SQLException.class, () -> first.connection(factory));
|
||||
ObjectNode reuse = MAPPER.createObjectNode().put("SessionId", first.id());
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
Future<?> finishing = workers.submit(() -> {
|
||||
assertTrue(start.await(5, TimeUnit.SECONDS));
|
||||
first.finish();
|
||||
return null;
|
||||
});
|
||||
Future<Boolean> admitted = workers.submit(() -> {
|
||||
assertTrue(start.await(5, TimeUnit.SECONDS));
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
try {
|
||||
sessions.reserve(OWNER, reuse, TARGET);
|
||||
return true;
|
||||
} catch (AwsException expected) {
|
||||
if ("ResourceNotFoundException".equals(expected.getErrorCode())) {
|
||||
return false;
|
||||
}
|
||||
assertEquals("ValidationException", expected.getErrorCode());
|
||||
Thread.onSpinWait();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
start.countDown();
|
||||
try {
|
||||
assertFalse(admitted.get(5, TimeUnit.SECONDS), "A failed session admitted a new query at attempt " + attempt);
|
||||
finishing.get(5, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
admitted.cancel(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void clearSurfacesUnexpectedCleanupFailuresAndStillClosesOtherConnections(boolean unchecked) throws Exception {
|
||||
try (RedshiftDataSessions sessions = new RedshiftDataSessions(Clock.systemUTC())) {
|
||||
Connection broken = mock(Connection.class);
|
||||
Connection healthy = mock(Connection.class);
|
||||
Throwable failure = unchecked ? new IllegalStateException("close failed") : new SQLException("close failed", "08006");
|
||||
doThrow(failure).when(broken).close();
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
when(factory.open(any())).thenReturn(broken, healthy);
|
||||
for (int n = 0; n < 2; n++) {
|
||||
RedshiftDataSessions.Reservation reservation = sessions.reserve(OWNER,
|
||||
request().put("SessionKeepAliveSeconds", 60), TARGET);
|
||||
reservation.admitted();
|
||||
reservation.connection(factory);
|
||||
reservation.finish();
|
||||
}
|
||||
RuntimeException observed = assertThrows(RuntimeException.class, sessions::clear);
|
||||
assertSame(failure, observed.getCause());
|
||||
verify(healthy).close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void alreadyClosedConnectionIsABenignCleanupOutcome() throws Exception {
|
||||
try (RedshiftDataSessions sessions = new RedshiftDataSessions(Clock.systemUTC())) {
|
||||
Connection connection = mock(Connection.class);
|
||||
doThrow(new SQLException("connection already closed", "08003")).when(connection).close();
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
when(factory.open(any())).thenReturn(connection);
|
||||
RedshiftDataSessions.Reservation reservation = sessions.reserve(OWNER,
|
||||
request().put("SessionKeepAliveSeconds", 60), TARGET);
|
||||
reservation.admitted();
|
||||
reservation.connection(factory);
|
||||
reservation.finish();
|
||||
assertDoesNotThrow(sessions::clear);
|
||||
verify(connection).close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearClosesAConnectionThatFinishesOpeningAfterReset() throws Exception {
|
||||
try (RedshiftDataSessions sessions = new RedshiftDataSessions(Clock.systemUTC());
|
||||
ExecutorService worker = Executors.newSingleThreadExecutor()) {
|
||||
Connection connection = mock(Connection.class);
|
||||
CountDownLatch opening = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
when(factory.open(any())).thenAnswer(invocation -> {
|
||||
opening.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS));
|
||||
return connection;
|
||||
});
|
||||
RedshiftDataSessions.Reservation reservation = sessions.reserve(OWNER, request().put("SessionKeepAliveSeconds", 10), TARGET);
|
||||
reservation.admitted();
|
||||
Future<Connection> late = worker.submit(() -> reservation.connection(factory));
|
||||
try {
|
||||
assertTrue(opening.await(5, TimeUnit.SECONDS));
|
||||
sessions.clear();
|
||||
release.countDown();
|
||||
assertThrows(ExecutionException.class, () -> late.get(5, TimeUnit.SECONDS));
|
||||
verify(connection).close();
|
||||
assertThrows(AwsException.class, () -> sessions.find(OWNER, reservation.id()));
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void idleDeadlineStartsAfterCompletionAndUnspecifiedTimeoutIsRetained() throws Exception {
|
||||
MutableClock clock = new MutableClock();
|
||||
try (RedshiftDataSessions sessions = new RedshiftDataSessions(clock)) {
|
||||
Connection connection = mock(Connection.class);
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
when(factory.open(any())).thenReturn(connection);
|
||||
RedshiftDataSessions.Reservation first = sessions.reserve(OWNER, request().put("SessionKeepAliveSeconds", 10), TARGET);
|
||||
first.admitted();
|
||||
first.connection(factory);
|
||||
clock.advance(Duration.ofSeconds(20));
|
||||
sessions.sweep();
|
||||
verify(connection, never()).close();
|
||||
first.finish();
|
||||
clock.advance(Duration.ofSeconds(9));
|
||||
ObjectNode reuse = MAPPER.createObjectNode().put("SessionId", first.id());
|
||||
RedshiftDataSessions.Reservation next = sessions.reserve(OWNER, reuse, TARGET);
|
||||
next.admitted();
|
||||
assertSame(connection, next.connection(factory));
|
||||
next.finish();
|
||||
clock.advance(Duration.ofSeconds(9));
|
||||
assertNotNull(sessions.find(OWNER, first.id()));
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
sessions.sweep();
|
||||
verify(connection).close();
|
||||
assertThrows(AwsException.class, () -> sessions.find(OWNER, first.id()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void busySessionsRejectNewWorkAndFailedAdmissionDoesNotExtendIdleTime() throws Exception {
|
||||
MutableClock clock = new MutableClock();
|
||||
try (RedshiftDataSessions sessions = new RedshiftDataSessions(clock)) {
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
when(factory.open(any())).thenReturn(mock(Connection.class));
|
||||
RedshiftDataSessions.Reservation first = sessions.reserve(OWNER, request().put("SessionKeepAliveSeconds", 10), TARGET);
|
||||
first.admitted();
|
||||
first.connection(factory);
|
||||
ObjectNode reuse = MAPPER.createObjectNode().put("SessionId", first.id());
|
||||
assertThrows(AwsException.class, () -> sessions.reserve(OWNER, reuse, TARGET));
|
||||
first.finish();
|
||||
clock.advance(Duration.ofSeconds(9));
|
||||
RedshiftDataSessions.Reservation rejected = sessions.reserve(OWNER, reuse.put("SessionKeepAliveSeconds", 100), TARGET);
|
||||
rejected.abort();
|
||||
clock.advance(Duration.ofSeconds(1));
|
||||
assertThrows(AwsException.class, () -> sessions.find(OWNER, first.id()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sessionsAreScopedToAccountRegionAndCaller() throws Exception {
|
||||
try (RedshiftDataSessions sessions = new RedshiftDataSessions(Clock.systemUTC())) {
|
||||
RedshiftDataSessions.Reservation first = sessions.reserve(OWNER, request().put("SessionKeepAliveSeconds", 10), TARGET);
|
||||
for (RedshiftDataSessions.Scope foreign : new RedshiftDataSessions.Scope[]{
|
||||
new RedshiftDataSessions.Scope("111111111111", "us-east-1", "caller"),
|
||||
new RedshiftDataSessions.Scope("000000000000", "us-west-2", "caller"),
|
||||
new RedshiftDataSessions.Scope("000000000000", "us-east-1", "another-caller")}) {
|
||||
assertThrows(AwsException.class, () -> sessions.find(foreign, first.id()));
|
||||
}
|
||||
assertNotNull(sessions.find(OWNER, first.id()));
|
||||
first.abort();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroTimeoutClosesTheSessionAfterItsLastQuery() throws Exception {
|
||||
try (RedshiftDataSessions sessions = new RedshiftDataSessions(Clock.systemUTC())) {
|
||||
Connection connection = mock(Connection.class);
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
when(factory.open(any())).thenReturn(connection);
|
||||
RedshiftDataSessions.Reservation first = sessions.reserve(OWNER, request().put("SessionKeepAliveSeconds", 10), 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();
|
||||
last.connection(factory);
|
||||
last.finish();
|
||||
verify(connection).close();
|
||||
assertThrows(AwsException.class, () -> sessions.find(OWNER, first.id()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void absoluteDeadlineClosesAnActiveConnectionAndCannotBeExtended() throws Exception {
|
||||
MutableClock clock = new MutableClock();
|
||||
try (RedshiftDataSessions sessions = new RedshiftDataSessions(clock)) {
|
||||
Connection connection = mock(Connection.class);
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
when(factory.open(any())).thenReturn(connection);
|
||||
RedshiftDataSessions.Reservation first = sessions.reserve(OWNER, request().put("SessionKeepAliveSeconds", 86400), TARGET);
|
||||
first.admitted();
|
||||
RedshiftDataExecution execution = new RedshiftDataExecution(0);
|
||||
first.bind(execution);
|
||||
first.connection(factory);
|
||||
clock.advance(Duration.ofHours(24));
|
||||
sessions.sweep();
|
||||
await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> verify(connection).close());
|
||||
execution.completed();
|
||||
assertThrows(AwsException.class, () -> sessions.find(OWNER, first.id()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sessionLimitIsSharedAcrossCallersAndAbortedReservationsReleaseCapacity() {
|
||||
try (RedshiftDataSessions sessions = new RedshiftDataSessions(Clock.systemUTC())) {
|
||||
RedshiftDataSessions.Reservation first = sessions.reserve(OWNER, request().put("SessionKeepAliveSeconds", 10), TARGET);
|
||||
for (int n = 1; n < 500; n++) {
|
||||
sessions.reserve(new RedshiftDataSessions.Scope("000000000000", "us-east-1", "caller-" + n),
|
||||
request().put("SessionKeepAliveSeconds", 10), TARGET);
|
||||
}
|
||||
AwsException full = assertThrows(AwsException.class, () -> sessions.reserve(OWNER,
|
||||
request().put("SessionKeepAliveSeconds", 10), TARGET));
|
||||
assertEquals("ActiveSessionsExceededException", full.getErrorCode());
|
||||
first.abort();
|
||||
assertNotNull(sessions.reserve(OWNER, request().put("SessionKeepAliveSeconds", 10), TARGET));
|
||||
}
|
||||
}
|
||||
|
||||
private static ObjectNode request() {
|
||||
return MAPPER.createObjectNode().put("ClusterIdentifier", "warehouse").put("Database", "dev").put("DbUser", "admin");
|
||||
}
|
||||
|
||||
private static final class MutableClock extends Clock {
|
||||
private Instant now = Instant.parse("2026-10-24T00:00:00Z");
|
||||
|
||||
void advance(Duration duration) {
|
||||
now = now.plus(duration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ZoneId getZone() {
|
||||
return ZoneOffset.UTC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Clock withZone(ZoneId zone) {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant instant() {
|
||||
return now;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user