mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(redshift-data): add async execution and statement status events (#5383)
* feat(redshift-data): add async execution and statement status events
* fix(redshift-data): address review findings on async Data API
- Mark a statement FAILED when its worker dies unexpectedly instead of leaving it active
- Let unexpected publisher errors propagate; the delivery pool logs them at error level
- Run CREATE/DROP INDEX CONCURRENTLY, REINDEX CONCURRENTLY, ALTER SYSTEM and tablespace DDL outside a transaction
- Drop WaitTimeSeconds from Scheduler targets so the shared dispatcher thread never blocks
- Share result rows and column metadata between snapshots; ListStatements no longer copies results
- Replace the global monitor with a ReentrantReadWriteLock for status writes and reset
* fix(redshift-data): reject CancelStatement on terminal statements
- Throw ValidationException ("Could not cancel a query that is already in <STATE> state.") instead of returning Status false, as AWS does
- Use WaitTimeSeconds instead of 30 s polling in the Serverless compatibility test and the Spectrum integration test
* fix(redshift-data): match AWS CancelStatement message and tidy test signature
- Append "with ID: <id>" to the terminal-state ValidationException message
- Drop the unused throws InterruptedException from workgroupLifecycleUsesAwsSdk
This commit is contained in:
1 parent
641bf980d0
commit
ae75a653d6
27 files changed
+1756
-198
No files matched your search
+1
-1
@@ -255,7 +255,7 @@ class RedshiftSpectrumIntegrationTest {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
String queryId = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
|
||||
{"ClusterIdentifier":"%s","DbUser":"admin","Database":"dev",
|
||||
"Sql":"SELECT SUM(amount) AS total FROM lake.events"}
|
||||
"Sql":"SELECT SUM(amount) AS total FROM lake.events","WaitTimeSeconds":30}
|
||||
""".formatted(clusterId)).then().statusCode(200).extract().path("Id");
|
||||
assertEquals("FINISHED", RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
|
||||
"{\"Id\":\"" + queryId + "\"}").then().statusCode(200).extract().path("Status"));
|
||||
|
||||
+50
-3
@@ -18,6 +18,7 @@ import java.util.List;
|
||||
|
||||
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.assertTrue;
|
||||
|
||||
@@ -73,10 +74,11 @@ class RedshiftDataApiIntegrationTest {
|
||||
private void awaitFinished(String id) {
|
||||
Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO)
|
||||
.pollInterval(Duration.ofMillis(250)).until(() -> {
|
||||
String status = RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
|
||||
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract().path("Status");
|
||||
ExtractableResponse<Response> described = RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
|
||||
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract();
|
||||
String status = described.path("Status");
|
||||
assertTrue(!"FAILED".equals(status) && !"ABORTED".equals(status),
|
||||
() -> "statement " + id + " ended " + status);
|
||||
() -> "statement " + id + " ended " + status + ": " + described.path("Error"));
|
||||
return "FINISHED".equals(status);
|
||||
});
|
||||
}
|
||||
@@ -85,6 +87,11 @@ class RedshiftDataApiIntegrationTest {
|
||||
return ((Number) value).intValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void vacuumPreservesAutoCommitExecution() {
|
||||
executeAndWait("VACUUM");
|
||||
}
|
||||
|
||||
@Test
|
||||
void executeDescribeGetResultRoundTrip() {
|
||||
executeAndWait("CREATE TABLE t (id int, name varchar(20))");
|
||||
@@ -190,4 +197,44 @@ class RedshiftDataApiIntegrationTest {
|
||||
"FAILED".equals(RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement",
|
||||
"{\"Id\":\"" + id + "\"}").then().statusCode(200).extract().path("Status")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void slowSqlReturnsEarlyAndCanBeCancelled() {
|
||||
long started = System.nanoTime();
|
||||
String id = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """
|
||||
{"Sql":"SELECT pg_sleep(20)","ClusterIdentifier":"%s","DbUser":"admin","Database":"dev"}
|
||||
""".formatted(clusterId)).then().statusCode(200).extract().path("Id");
|
||||
assertTrue(Duration.ofNanos(System.nanoTime() - started).compareTo(Duration.ofSeconds(10)) < 0);
|
||||
Awaitility.await().atMost(Duration.ofSeconds(10)).until(() -> "STARTED".equals(
|
||||
RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement", "{\"Id\":\"" + id + "\"}")
|
||||
.then().statusCode(200).extract().path("Status")));
|
||||
RestAssuredJsonUtils.awsAction("RedshiftData", "CancelStatement", "{\"Id\":\"" + id + "\"}")
|
||||
.then().statusCode(200).body("Status", is(true));
|
||||
Awaitility.await().atMost(Duration.ofSeconds(10)).until(() -> "ABORTED".equals(
|
||||
RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement", "{\"Id\":\"" + id + "\"}")
|
||||
.then().statusCode(200).extract().path("Status")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancellingBatchRollsBackEarlierWrites() {
|
||||
executeAndWait("CREATE TABLE cancel_batch (id int)");
|
||||
String id = RestAssuredJsonUtils.awsAction("RedshiftData", "BatchExecuteStatement", """
|
||||
{"Sqls":["INSERT INTO cancel_batch VALUES (1)","SELECT pg_sleep(20)",
|
||||
"INSERT INTO cancel_batch VALUES (2)"],"ClusterIdentifier":"%s","DbUser":"admin","Database":"dev"}
|
||||
""".formatted(clusterId)).then().statusCode(200).extract().path("Id");
|
||||
Awaitility.await().atMost(Duration.ofSeconds(10)).until(() -> {
|
||||
List<?> children = RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement", "{\"Id\":\"" + id + "\"}")
|
||||
.then().statusCode(200).extract().path("SubStatements");
|
||||
return children != null && !children.isEmpty();
|
||||
});
|
||||
RestAssuredJsonUtils.awsAction("RedshiftData", "CancelStatement", "{\"Id\":\"" + id + "\"}")
|
||||
.then().statusCode(200).body("Status", is(true));
|
||||
Awaitility.await().atMost(Duration.ofSeconds(10)).until(() -> "ABORTED".equals(
|
||||
RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement", "{\"Id\":\"" + id + "\"}")
|
||||
.then().statusCode(200).extract().path("Status")));
|
||||
String countId = executeAndWait("SELECT count(*) FROM cancel_batch");
|
||||
Object count = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult", "{\"Id\":\"" + countId + "\"}")
|
||||
.then().statusCode(200).extract().path("Records[0][0].longValue");
|
||||
assertEquals(0, asInt(count));
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
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.h2.Driver;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
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 RedshiftDataAsyncServiceTest {
|
||||
|
||||
@Test
|
||||
void cancellationDuringBindingDoesNotStartJdbcQuery() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
RedshiftDataResourceResolver resolver = mock(RedshiftDataResourceResolver.class);
|
||||
when(resolver.resolve(any(), any())).thenReturn(new RedshiftDataResourceResolver.DatabaseTarget(
|
||||
"arn:aws:redshift:us-east-1:000000000000:cluster:wh", "localhost", 5439, "dev", "admin", "password"));
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
Connection connection = mock(Connection.class);
|
||||
PreparedStatement statement = mock(PreparedStatement.class);
|
||||
when(factory.open(any())).thenReturn(connection);
|
||||
when(connection.prepareStatement(anyString())).thenReturn(statement);
|
||||
CountDownLatch binding = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
doAnswer(invocation -> {
|
||||
binding.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS));
|
||||
return null;
|
||||
}).when(statement).setString(eq(1), eq("20"));
|
||||
try (RedshiftDataExecutor executor = new RedshiftDataExecutor(1, 1, 1)) {
|
||||
RedshiftDataService service = new RedshiftDataService(resolver, factory,
|
||||
new RedshiftDataStatementStore(24, Clock.systemUTC()), mapper, null, executor, null);
|
||||
ObjectNode request = mapper.createObjectNode().put("Sql", "SELECT pg_sleep(:seconds)");
|
||||
request.putArray("Parameters").addObject().put("name", "seconds").put("value", "20");
|
||||
String id = service.executeStatement(request, "us-east-1").path("Id").asText();
|
||||
assertTrue(binding.await(5, TimeUnit.SECONDS));
|
||||
try {
|
||||
assertTrue(service.cancelStatement(mapper.createObjectNode().put("Id", id)).path("Status").asBoolean());
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> assertEquals("ABORTED",
|
||||
service.describeStatement(mapper.createObjectNode().put("Id", id)).path("Status").asText()));
|
||||
verify(statement, never()).execute();
|
||||
verify(connection, never()).commit();
|
||||
verify(connection).rollback();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchEmitsOnlyParentEventAndFalseOrOmittedWithEventEmitsNone() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
RedshiftDataResourceResolver resolver = mock(RedshiftDataResourceResolver.class);
|
||||
when(resolver.resolve(any(), any())).thenReturn(new RedshiftDataResourceResolver.DatabaseTarget(
|
||||
"arn:aws:redshift:us-east-1:000000000000:cluster:wh", "localhost", 5439, "dev", "admin", "password"));
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
Driver.load();
|
||||
String jdbcUrl = "jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1";
|
||||
when(factory.open(any())).thenAnswer(invocation -> DriverManager.getConnection(jdbcUrl));
|
||||
RedshiftDataEventPublisher publisher = mock(RedshiftDataEventPublisher.class);
|
||||
try (RedshiftDataExecutor executor = new RedshiftDataExecutor(1, 4, 1)) {
|
||||
RedshiftDataStatementStore store = new RedshiftDataStatementStore(24, Clock.systemUTC());
|
||||
RedshiftDataService service = new RedshiftDataService(resolver, factory, store, mapper, null, executor, publisher);
|
||||
ObjectNode request = mapper.createObjectNode().put("WithEvent", true).put("WaitTimeSeconds", 5);
|
||||
request.putArray("Sqls").add("SELECT 1").add("SELECT 2");
|
||||
String id = service.batchExecuteStatement(request, "us-east-1").path("Id").asText();
|
||||
assertEquals(RedshiftDataStatementStore.Status.FINISHED, store.getForAccount("000000000000", id).status,
|
||||
() -> store.getForAccount("000000000000", id).error);
|
||||
await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> verify(publisher).publish(argThat(statement ->
|
||||
id.equals(statement.id) && statement.status == RedshiftDataStatementStore.Status.FINISHED)));
|
||||
assertEquals(RedshiftDataStatementStore.Status.FINISHED, store.getForAccount("000000000000", id).status);
|
||||
service.executeStatement(mapper.createObjectNode().put("Sql", "SELECT 3").put("WaitTimeSeconds", 5), "us-east-1");
|
||||
service.executeStatement(mapper.createObjectNode().put("Sql", "SELECT 4").put("WaitTimeSeconds", 5)
|
||||
.put("WithEvent", false), "us-east-1");
|
||||
executor.close();
|
||||
verify(publisher, times(1)).publish(any());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void queuedCancellationPublishesOneAbortedEventAfterTerminalStorage() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
RedshiftDataResourceResolver resolver = mock(RedshiftDataResourceResolver.class);
|
||||
when(resolver.resolve(any(), any())).thenReturn(new RedshiftDataResourceResolver.DatabaseTarget(
|
||||
"arn:aws-cn:redshift:cn-north-1:111111111111:cluster:wh", "localhost", 5439, "dev", "admin", "password"));
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
RedshiftDataEventPublisher publisher = mock(RedshiftDataEventPublisher.class);
|
||||
RedshiftDataStatementStore store = new RedshiftDataStatementStore(24, Clock.systemUTC());
|
||||
AtomicReference<RedshiftDataStatementStore.StoredStatement> delivered = new AtomicReference<>();
|
||||
doAnswer(invocation -> {
|
||||
RedshiftDataStatementStore.StoredStatement statement = invocation.getArgument(0);
|
||||
assertEquals(RedshiftDataStatementStore.Status.ABORTED,
|
||||
store.getForAccount(statement.accountId, statement.id).status);
|
||||
delivered.set(statement);
|
||||
return null;
|
||||
}).when(publisher).publish(any());
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
try (RedshiftDataExecutor executor = new RedshiftDataExecutor(1, 2, 1)) {
|
||||
executor.submit("111111111111", "cn-north-1", "blocking", execution -> {
|
||||
started.countDown();
|
||||
try {
|
||||
release.await(5, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException expected) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
});
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
RedshiftDataService service = new RedshiftDataService(resolver, factory, store, mapper, null, executor, publisher);
|
||||
String id = service.executeStatement(mapper.createObjectNode().put("Sql", "SELECT 1")
|
||||
.put("WithEvent", true).put("StatementName", "etl"), "cn-north-1", "role-principal").path("Id").asText();
|
||||
try {
|
||||
assertTrue(executor.cancel("111111111111", id));
|
||||
await().atMost(Duration.ofSeconds(5)).until(() -> delivered.get() != null);
|
||||
assertEquals("111111111111", delivered.get().accountId);
|
||||
assertEquals("cn-north-1", delivered.get().region);
|
||||
assertEquals("role-principal", delivered.get().principal);
|
||||
assertEquals("etl", delivered.get().statementName);
|
||||
assertEquals(RedshiftDataStatementStore.Status.ABORTED, delivered.get().status);
|
||||
verifyNoInteractions(factory);
|
||||
assertFalse(executor.cancel("111111111111", id));
|
||||
verify(publisher, times(1)).publish(any());
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsIdBeforeDatabaseConnectionCompletes() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
RedshiftDataResourceResolver resolver = mock(RedshiftDataResourceResolver.class);
|
||||
when(resolver.resolve(any(), any())).thenReturn(new RedshiftDataResourceResolver.DatabaseTarget(
|
||||
"arn:aws:redshift:us-east-1:000000000000:cluster:wh", "localhost", 5439, "dev", "admin", "password"));
|
||||
RedshiftDataConnectionFactory factory = mock(RedshiftDataConnectionFactory.class);
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
when(factory.open(any())).thenAnswer(invocation -> {
|
||||
started.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS));
|
||||
throw new SQLException("connection refused");
|
||||
});
|
||||
try (RedshiftDataExecutor executor = new RedshiftDataExecutor(1, 1, 1)) {
|
||||
RedshiftDataService service = new RedshiftDataService(resolver, factory,
|
||||
new RedshiftDataStatementStore(24, Clock.systemUTC()), mapper, null, executor, null);
|
||||
ObjectNode request = mapper.createObjectNode().put("Sql", "select 1").put("ClusterIdentifier", "wh");
|
||||
ObjectNode response = service.executeStatement(request, "us-east-1");
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
ObjectNode id = mapper.createObjectNode().put("Id", response.path("Id").asText());
|
||||
assertEquals("STARTED", service.describeStatement(id).path("Status").asText());
|
||||
assertThrows(AwsException.class, () -> service.getStatementResult(id));
|
||||
release.countDown();
|
||||
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
|
||||
assertEquals("FAILED", service.describeStatement(id).path("Status").asText()));
|
||||
AwsException rejected = assertThrows(AwsException.class, () -> service.cancelStatement(id));
|
||||
assertEquals("ValidationException", rejected.getErrorCode());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatesWaitTimeBeforeAcceptingWork() {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
RedshiftDataResourceResolver resolver = mock(RedshiftDataResourceResolver.class);
|
||||
try (RedshiftDataExecutor executor = new RedshiftDataExecutor(1, 1, 1)) {
|
||||
RedshiftDataService service = new RedshiftDataService(resolver, mock(RedshiftDataConnectionFactory.class),
|
||||
new RedshiftDataStatementStore(24, Clock.systemUTC()), mapper, null, executor, null);
|
||||
ObjectNode request = mapper.createObjectNode().put("Sql", "select 1").put("WaitTimeSeconds", 31);
|
||||
assertThrows(AwsException.class, () -> service.executeStatement(request, "us-east-1"));
|
||||
verifyNoInteractions(resolver);
|
||||
}
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
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 io.github.hectorvent.floci.core.common.ServiceRegistry;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class RedshiftDataEventPublisherTest {
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void publishesAwsEnvelopeInResourceAccountAndRegion() throws Exception {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
EventBridgeService events = mock(EventBridgeService.class);
|
||||
ServiceRegistry registry = mock(ServiceRegistry.class);
|
||||
when(registry.isServiceEnabled("eventbridge")).thenReturn(true);
|
||||
when(events.putEvents(anyList(), anyString(), anyString()))
|
||||
.thenReturn(new EventBridgeService.PutEventsResult(0, List.of()));
|
||||
RedshiftDataEventPublisher publisher = new RedshiftDataEventPublisher(events, mapper, registry);
|
||||
RedshiftDataStatementStore.StoredStatement statement = new RedshiftDataStatementStore.StoredStatement();
|
||||
statement.id = "statement-id";
|
||||
statement.accountId = "111111111111";
|
||||
statement.region = "cn-north-1";
|
||||
statement.resourceArn = "arn:aws-cn:redshift-serverless:cn-north-1:111111111111:workgroup/group-id";
|
||||
statement.principal = "arn:aws-cn:iam::111111111111:role/etl";
|
||||
statement.statementName = "etl";
|
||||
statement.status = RedshiftDataStatementStore.Status.FINISHED;
|
||||
statement.resultRows = 3;
|
||||
statement.expiresAt = Instant.parse("2026-10-11T00:00:00Z");
|
||||
publisher.publish(statement);
|
||||
ArgumentCaptor<List<Map<String, Object>>> entries = ArgumentCaptor.forClass(List.class);
|
||||
verify(events).putEvents(entries.capture(), eq("cn-north-1"), eq("111111111111"));
|
||||
Map<String, Object> entry = entries.getValue().getFirst();
|
||||
assertEquals("aws.redshift-data", entry.get("Source"));
|
||||
assertEquals("Redshift Data Statement Status Change", entry.get("DetailType"));
|
||||
assertEquals(statement.resourceArn, mapper.valueToTree(entry.get("Resources")).get(0).asText());
|
||||
ObjectNode detail = (ObjectNode) mapper.readTree((String) entry.get("Detail"));
|
||||
assertEquals("FINISHED", detail.path("state").asText());
|
||||
assertEquals(3, detail.path("rows").asInt());
|
||||
assertEquals(statement.principal, detail.path("principal").asText());
|
||||
assertEquals(statement.expiresAt.getEpochSecond(), detail.path("expireAt").asLong());
|
||||
assertEquals(statement.id.hashCode() & Integer.MAX_VALUE, detail.path("redshiftQueryId").asLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectedEntriesAndRefusalsDoNotFailSqlCompletion() {
|
||||
EventBridgeService events = mock(EventBridgeService.class);
|
||||
ServiceRegistry registry = mock(ServiceRegistry.class);
|
||||
when(registry.isServiceEnabled("eventbridge")).thenReturn(true);
|
||||
RedshiftDataEventPublisher publisher = new RedshiftDataEventPublisher(events, new ObjectMapper(), registry);
|
||||
RedshiftDataStatementStore.StoredStatement statement = new RedshiftDataStatementStore.StoredStatement();
|
||||
statement.id = "id";
|
||||
statement.accountId = "111111111111";
|
||||
statement.region = "us-east-1";
|
||||
statement.status = RedshiftDataStatementStore.Status.FAILED;
|
||||
statement.expiresAt = Instant.now();
|
||||
when(events.putEvents(anyList(), anyString(), anyString()))
|
||||
.thenReturn(new EventBridgeService.PutEventsResult(1, List.of(Map.of("ErrorCode", "InternalFailure"))))
|
||||
.thenThrow(new AwsException("InvalidEventPatternException", "refused", 400))
|
||||
.thenThrow(new IllegalStateException("programming error"));
|
||||
assertDoesNotThrow(() -> publisher.publish(statement));
|
||||
assertDoesNotThrow(() -> publisher.publish(statement));
|
||||
assertThrows(IllegalStateException.class, () -> publisher.publish(statement));
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.sqs.model.Message;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@QuarkusTest
|
||||
class RedshiftDataEventsIntegrationTest {
|
||||
private static final String ACCOUNT = "111122223333";
|
||||
private static final String OTHER_ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Inject
|
||||
RedshiftDataService service;
|
||||
@Inject
|
||||
EventBridgeService events;
|
||||
@Inject
|
||||
SqsService sqs;
|
||||
@Inject
|
||||
ObjectMapper mapper;
|
||||
@InjectMock
|
||||
RedshiftDataResourceResolver resolver;
|
||||
@InjectMock
|
||||
RedshiftDataConnectionFactory factory;
|
||||
|
||||
@Test
|
||||
void statusEventReachesOnlyTheCapturedAccountRule() throws Exception {
|
||||
String name = "rsdata-event-" + UUID.randomUUID();
|
||||
String pattern = mapper.writeValueAsString(Map.of("source", List.of("aws.redshift-data"),
|
||||
"detail", Map.of("statementName", List.of(name))));
|
||||
String queue = createRuleAndQueue(ACCOUNT, name, pattern);
|
||||
String otherQueue = createRuleAndQueue(OTHER_ACCOUNT, name, pattern);
|
||||
when(resolver.resolve(any(), any())).thenReturn(new RedshiftDataResourceResolver.DatabaseTarget(
|
||||
"arn:aws:redshift:us-east-1:" + ACCOUNT + ":cluster:analytics",
|
||||
"localhost", 5439, "dev", "admin", "password"));
|
||||
when(factory.open(any())).thenThrow(new SQLException("connection refused"));
|
||||
try {
|
||||
String id = RequestScopes.callAs(ACCOUNT, REGION, () -> service.executeStatement(
|
||||
mapper.createObjectNode().put("Sql", "SELECT 1").put("WithEvent", true)
|
||||
.put("StatementName", name), REGION, "arn:aws:iam::" + ACCOUNT + ":role/etl"))
|
||||
.path("Id").asText();
|
||||
AtomicReference<JsonNode> delivered = new AtomicReference<>();
|
||||
await().atMost(Duration.ofSeconds(10)).until(() -> {
|
||||
List<Message> messages = RequestScopes.callAs(ACCOUNT, REGION,
|
||||
() -> sqs.receiveMessage(queue, 1, 30, 0, REGION));
|
||||
if (messages.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
delivered.set(mapper.readTree(messages.getFirst().getBody()));
|
||||
return true;
|
||||
});
|
||||
assertEquals(ACCOUNT, delivered.get().path("account").asText());
|
||||
assertEquals(REGION, delivered.get().path("region").asText());
|
||||
assertEquals(id, delivered.get().path("detail").path("statementId").asText());
|
||||
assertEquals("FAILED", delivered.get().path("detail").path("state").asText());
|
||||
assertEquals("arn:aws:iam::" + ACCOUNT + ":role/etl",
|
||||
delivered.get().path("detail").path("principal").asText());
|
||||
assertEquals("FAILED", RequestScopes.callAs(ACCOUNT, REGION, () ->
|
||||
service.describeStatement(mapper.createObjectNode().put("Id", id))).path("Status").asText());
|
||||
assertTrue(RequestScopes.callAs(OTHER_ACCOUNT, REGION,
|
||||
() -> sqs.receiveMessage(otherQueue, 1, 30, 0, REGION)).isEmpty());
|
||||
} finally {
|
||||
deleteRuleAndQueue(ACCOUNT, name, queue);
|
||||
deleteRuleAndQueue(OTHER_ACCOUNT, name, otherQueue);
|
||||
service.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private String createRuleAndQueue(String account, String name, String pattern) {
|
||||
return RequestScopes.callAs(account, REGION, () -> {
|
||||
String queue = sqs.createQueue(name, Map.of(), REGION).getQueueUrl();
|
||||
events.putRule(name, "default", pattern, null, RuleState.ENABLED, null, null, Map.of(), REGION);
|
||||
events.putTargets(name, "default", List.of(new Target("queue",
|
||||
"arn:aws:sqs:" + REGION + ":" + account + ":" + name, null, null)), REGION);
|
||||
return queue;
|
||||
});
|
||||
}
|
||||
|
||||
private void deleteRuleAndQueue(String account, String name, String queue) {
|
||||
RequestScopes.runAs(account, REGION, () -> {
|
||||
events.removeTargets(name, "default", List.of("queue"), REGION);
|
||||
events.deleteRule(name, "default", REGION);
|
||||
sqs.deleteQueue(queue, REGION);
|
||||
});
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class RedshiftDataExecutionTest {
|
||||
|
||||
@Test
|
||||
void runningCancellationCancelsJdbcAndPreventsCommit() throws Exception {
|
||||
try (RedshiftDataExecutor executor = new RedshiftDataExecutor(1, 1, 1)) {
|
||||
AtomicReference<Throwable> workerFailure = new AtomicReference<>();
|
||||
Statement statement = mock(Statement.class);
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
RedshiftDataExecution handle = executor.submit("111111111111", "us-east-1", "query", execution -> {
|
||||
try {
|
||||
execution.track(statement);
|
||||
started.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS));
|
||||
assertThrows(SQLException.class, () -> execution.commit(() -> fail("must not commit")));
|
||||
} catch (Throwable failure) {
|
||||
workerFailure.set(failure);
|
||||
}
|
||||
});
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
assertTrue(executor.cancel("111111111111", "query"));
|
||||
verify(statement).cancel();
|
||||
release.countDown();
|
||||
handle.await(Duration.ofSeconds(5));
|
||||
assertTrue(handle.isDone());
|
||||
assertNull(workerFailure.get());
|
||||
assertFalse(executor.cancel("111111111111", "query"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void successfulCommitWinsOverCancellation() throws Exception {
|
||||
try (RedshiftDataExecutor executor = new RedshiftDataExecutor(1, 1, 1)) {
|
||||
AtomicReference<Throwable> workerFailure = new AtomicReference<>();
|
||||
CountDownLatch committed = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
RedshiftDataExecution handle = executor.submit("111111111111", "us-east-1", "query", execution -> {
|
||||
try {
|
||||
execution.commit(committed::countDown);
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS));
|
||||
} catch (Throwable failure) {
|
||||
workerFailure.set(failure);
|
||||
}
|
||||
});
|
||||
assertTrue(committed.await(5, TimeUnit.SECONDS));
|
||||
assertFalse(executor.cancel("111111111111", "query"));
|
||||
release.countDown();
|
||||
handle.await(Duration.ofSeconds(5));
|
||||
assertTrue(handle.isDone());
|
||||
assertNull(workerFailure.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
package io.github.hectorvent.floci.services.redshiftdata;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class RedshiftDataExecutorTest {
|
||||
|
||||
@Test
|
||||
void admissionReturnsWhileSqlIsRunningAndRejectsOverflow() throws Exception {
|
||||
try (RedshiftDataExecutor executor = new RedshiftDataExecutor(1, 1, 1)) {
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
RedshiftDataExecution first = executor.submit("111111111111", "us-east-1", "first", execution -> {
|
||||
started.countDown();
|
||||
await(release);
|
||||
});
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
assertFalse(first.isDone());
|
||||
executor.submit("111111111111", "us-east-1", "second", execution -> {});
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> executor.submit("111111111111", "us-east-1", "third", execution -> {}));
|
||||
assertEquals("ActiveStatementsExceededException", failure.getErrorCode());
|
||||
release.countDown();
|
||||
first.await(Duration.ofSeconds(5));
|
||||
assertTrue(first.isDone());
|
||||
assertFalse(executor.cancel("222222222222", "second"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void queuedCancellationSkipsSqlAndCompletesImmediately() throws Exception {
|
||||
try (RedshiftDataExecutor executor = new RedshiftDataExecutor(1, 1, 1)) {
|
||||
CountDownLatch started = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
executor.submit("111111111111", "us-east-1", "first", execution -> {
|
||||
started.countDown();
|
||||
await(release);
|
||||
});
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS));
|
||||
AtomicBoolean cancelled = new AtomicBoolean();
|
||||
RedshiftDataExecution second = executor.submit("111111111111", "us-east-1", "second",
|
||||
execution -> cancelled.set(execution.isCancellationRequested()));
|
||||
assertTrue(executor.cancel("111111111111", "second"));
|
||||
second.await(Duration.ofSeconds(5));
|
||||
assertTrue(cancelled.get());
|
||||
assertFalse(executor.cancel("111111111111", "second"));
|
||||
release.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidLimitsAreRejected() {
|
||||
assertThrows(IllegalArgumentException.class, () -> new RedshiftDataExecutor(0, 1, 1));
|
||||
assertThrows(IllegalArgumentException.class, () -> new RedshiftDataExecutor(1, 0, 1));
|
||||
assertThrows(IllegalArgumentException.class, () -> new RedshiftDataExecutor(1, 1, -1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetSuppressesEventsQueuedByAnAlreadyCompletedExecution() throws Exception {
|
||||
try (RedshiftDataExecutor executor = new RedshiftDataExecutor(1, 4, 1)) {
|
||||
RedshiftDataExecution completed = executor.submit("111111111111", "us-east-1", "query", execution -> {});
|
||||
completed.await(Duration.ofSeconds(5));
|
||||
CountDownLatch delivering = new CountDownLatch(2);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
Runnable blockedDelivery = () -> {
|
||||
delivering.countDown();
|
||||
await(release);
|
||||
};
|
||||
executor.deliver(completed, "111111111111", "us-east-1", "query", blockedDelivery);
|
||||
executor.deliver(completed, "111111111111", "us-east-1", "query", blockedDelivery);
|
||||
assertTrue(delivering.await(5, TimeUnit.SECONDS));
|
||||
AtomicBoolean publishedAfterClear = new AtomicBoolean();
|
||||
executor.deliver(completed, "111111111111", "us-east-1", "query", () -> publishedAfterClear.set(true));
|
||||
executor.clear(() -> {});
|
||||
release.countDown();
|
||||
executor.close();
|
||||
assertFalse(publishedAfterClear.get());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownReturnsWithinBudgetWhileCommitIsBlocked() throws Exception {
|
||||
RedshiftDataExecutor executor = new RedshiftDataExecutor(1, 1, 0);
|
||||
CountDownLatch committing = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
CountDownLatch closed = new CountDownLatch(1);
|
||||
executor.submit("111111111111", "us-east-1", "query", execution -> {
|
||||
try {
|
||||
execution.commit(() -> {
|
||||
committing.countDown();
|
||||
boolean waiting = true;
|
||||
while (waiting) {
|
||||
try {
|
||||
release.await();
|
||||
waiting = false;
|
||||
} catch (InterruptedException ignored) {
|
||||
// Model a JDBC commit that does not respond to thread interruption.
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (Exception failure) {
|
||||
throw new AssertionError(failure);
|
||||
}
|
||||
});
|
||||
assertTrue(committing.await(5, TimeUnit.SECONDS));
|
||||
Thread closer = Thread.startVirtualThread(() -> {
|
||||
executor.close();
|
||||
closed.countDown();
|
||||
});
|
||||
try {
|
||||
assertTrue(closed.await(1, TimeUnit.SECONDS), "shutdown must not wait on the JDBC commit monitor");
|
||||
} finally {
|
||||
release.countDown();
|
||||
closer.join(5000);
|
||||
}
|
||||
}
|
||||
|
||||
private static void await(CountDownLatch latch) {
|
||||
try {
|
||||
assertTrue(latch.await(10, TimeUnit.SECONDS));
|
||||
} catch (InterruptedException expected) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError(expected);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unexpectedWorkerFailureReachesTheFailureHandler() throws Exception {
|
||||
try (RedshiftDataExecutor executor = new RedshiftDataExecutor(1, 1, 1)) {
|
||||
AtomicBoolean recovered = new AtomicBoolean();
|
||||
RedshiftDataExecution execution = executor.submit("111111111111", "us-east-1", "broken", () -> { },
|
||||
ignored -> {
|
||||
throw new IllegalStateException("storage unavailable");
|
||||
},
|
||||
(failed, failure) -> recovered.set("storage unavailable".equals(failure.getMessage())));
|
||||
execution.await(Duration.ofSeconds(5));
|
||||
assertTrue(execution.isDone());
|
||||
assertTrue(recovered.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
+77
-10
@@ -8,16 +8,23 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumQueryPreparation;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumReadException;
|
||||
import io.github.hectorvent.floci.services.redshift.spectrum.SpectrumSession;
|
||||
import org.awaitility.Awaitility;
|
||||
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 java.sql.DriverManager;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
@@ -43,6 +50,7 @@ class RedshiftDataServiceTest {
|
||||
private String jdbcUrl;
|
||||
private RedshiftDataService service;
|
||||
private SpectrumQueryPreparation preparation;
|
||||
private RedshiftDataExecutor executor;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
@@ -57,12 +65,18 @@ class RedshiftDataServiceTest {
|
||||
when(factory.open(any())).thenAnswer(inv -> DriverManager.getConnection(jdbcUrl, "sa", ""));
|
||||
|
||||
preparation = mock(SpectrumQueryPreparation.class);
|
||||
executor = new RedshiftDataExecutor(2, 100, 1);
|
||||
service = new RedshiftDataService(resolver, factory,
|
||||
new RedshiftDataStatementStore(24, Clock.systemUTC()), om, preparation);
|
||||
new RedshiftDataStatementStore(24, Clock.systemUTC()), om, preparation, executor, null);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stopExecutor() {
|
||||
executor.close();
|
||||
}
|
||||
|
||||
private ObjectNode req(String sql) {
|
||||
ObjectNode r = om.createObjectNode();
|
||||
ObjectNode r = om.createObjectNode().put("WaitTimeSeconds", 5);
|
||||
r.put("Sql", sql);
|
||||
r.put("ClusterIdentifier", "wh");
|
||||
r.put("DbUser", "admin");
|
||||
@@ -74,6 +88,40 @@ class RedshiftDataServiceTest {
|
||||
return om.createObjectNode().put("Id", id);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rolledBackBatchDoesNotExposeChildResults() {
|
||||
ObjectNode request = req("unused");
|
||||
request.putArray("Sqls").add("SELECT 1").add("SELECT * FROM nonexistent_batch_table");
|
||||
String id = service.batchExecuteStatement(request, REGION).path("Id").asText();
|
||||
assertEquals("FAILED", service.describeStatement(idOf(id)).path("Status").asText());
|
||||
assertThrows(AwsException.class, () -> service.getStatementResult(idOf(id + ":1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void spectrumDdlOwnsCompletionBeforeAutoCommittedWrites() throws Exception {
|
||||
String sql = "CREATE EXTERNAL SCHEMA lake";
|
||||
when(preparation.handlesDdl(eq(sql), any())).thenReturn(true);
|
||||
CountDownLatch writing = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
when(preparation.prepare(eq(sql), any(), any())).thenAnswer(invocation -> {
|
||||
writing.countDown();
|
||||
assertTrue(release.await(5, TimeUnit.SECONDS));
|
||||
return true;
|
||||
});
|
||||
ObjectNode request = req(sql);
|
||||
request.remove("WaitTimeSeconds");
|
||||
String id = service.executeStatement(request, REGION).path("Id").asText();
|
||||
assertTrue(writing.await(5, TimeUnit.SECONDS));
|
||||
try {
|
||||
assertFalse(service.cancelStatement(idOf(id)).path("Status").asBoolean(),
|
||||
"auto-committed external writes must not be reported as aborted");
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
Awaitility.await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
|
||||
assertEquals("FINISHED", service.describeStatement(idOf(id)).path("Status").asText()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void preparationFailureIsStoredAsFailedStatement() {
|
||||
doThrow(new SpectrumReadException("42501", "S3 access denied")).when(preparation)
|
||||
@@ -94,7 +142,7 @@ class RedshiftDataServiceTest {
|
||||
|
||||
@Test
|
||||
void aWorkgroupStatementNamesItsWorkgroupAndOmitsTheClusterIdentifier() {
|
||||
ObjectNode request = om.createObjectNode();
|
||||
ObjectNode request = om.createObjectNode().put("WaitTimeSeconds", 5);
|
||||
request.put("Sql", "select 1");
|
||||
request.put("WorkgroupName", "wg-1");
|
||||
request.put("Database", "dev");
|
||||
@@ -122,7 +170,7 @@ class RedshiftDataServiceTest {
|
||||
|
||||
@Test
|
||||
void aWorkgroupBatchPassesItsWorkgroupToEverySubStatement() {
|
||||
ObjectNode request = om.createObjectNode();
|
||||
ObjectNode request = om.createObjectNode().put("WaitTimeSeconds", 5);
|
||||
request.putArray("Sqls").add("select 1").add("select 2");
|
||||
request.put("WorkgroupName", "wg-1");
|
||||
request.put("Database", "dev");
|
||||
@@ -226,7 +274,7 @@ class RedshiftDataServiceTest {
|
||||
}
|
||||
|
||||
private ObjectNode batchReq(String... sqls) {
|
||||
ObjectNode r = om.createObjectNode();
|
||||
ObjectNode r = om.createObjectNode().put("WaitTimeSeconds", 5);
|
||||
r.put("ClusterIdentifier", "wh");
|
||||
r.put("DbUser", "admin");
|
||||
r.put("Database", "dev");
|
||||
@@ -283,10 +331,12 @@ class RedshiftDataServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancelOnFinishedStatementReturnsTrueWithoutChangingIt() {
|
||||
void cancelOnFinishedStatementIsRejectedWithoutChangingIt() {
|
||||
service.executeStatement(req("create table cf (id int)"), REGION);
|
||||
String id = service.executeStatement(req("select id from cf"), REGION).get("Id").asText();
|
||||
assertTrue(service.cancelStatement(idOf(id)).get("Status").asBoolean());
|
||||
AwsException rejected = assertThrows(AwsException.class, () -> service.cancelStatement(idOf(id)));
|
||||
assertEquals("ValidationException", rejected.getErrorCode());
|
||||
assertEquals("Could not cancel a query that is already in FINISHED state with ID: " + id, rejected.getMessage());
|
||||
assertEquals("FINISHED", service.describeStatement(idOf(id)).get("Status").asText());
|
||||
}
|
||||
|
||||
@@ -297,7 +347,7 @@ class RedshiftDataServiceTest {
|
||||
}
|
||||
|
||||
private ObjectNode targetReq() {
|
||||
ObjectNode r = om.createObjectNode();
|
||||
ObjectNode r = om.createObjectNode().put("WaitTimeSeconds", 5);
|
||||
r.put("ClusterIdentifier", "wh");
|
||||
r.put("DbUser", "admin");
|
||||
r.put("Database", "dev");
|
||||
@@ -375,10 +425,11 @@ class RedshiftDataServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancelOnFailedStatementLeavesItFailed() {
|
||||
void cancelOnFailedStatementIsRejectedAndLeavesItFailed() {
|
||||
String id = service.executeStatement(req("select * from missing_table"), REGION).get("Id").asText();
|
||||
assertEquals("FAILED", service.describeStatement(idOf(id)).get("Status").asText());
|
||||
assertTrue(service.cancelStatement(idOf(id)).get("Status").asBoolean());
|
||||
AwsException rejected = assertThrows(AwsException.class, () -> service.cancelStatement(idOf(id)));
|
||||
assertEquals("Could not cancel a query that is already in FAILED state with ID: " + id, rejected.getMessage());
|
||||
assertEquals("FAILED", service.describeStatement(idOf(id)).get("Status").asText());
|
||||
}
|
||||
|
||||
@@ -409,4 +460,20 @@ class RedshiftDataServiceTest {
|
||||
assertEquals(1, described.get("ColumnList").size());
|
||||
assertEquals("x", described.get("ColumnList").get(0).get("name").asText().toLowerCase());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"VACUUM t", " -- note\n create database d", "CREATE INDEX CONCURRENTLY i ON t (c)",
|
||||
"create unique index concurrently i on t (c)", "DROP INDEX CONCURRENTLY i",
|
||||
"REINDEX TABLE CONCURRENTLY t", "ALTER SYSTEM SET work_mem = '8MB'"})
|
||||
void transactionIncompatibleCommandsRunOutsideATransaction(String sql) {
|
||||
assertTrue(RedshiftDataService.AUTO_COMMIT_SQL.matcher(sql).find(), sql);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"CREATE INDEX i ON t (c)", "REINDEX TABLE t", "select 'vacuum'", "CREATE TABLE concurrently (a int)"})
|
||||
void ordinaryCommandsStayInsideATransaction(String sql) {
|
||||
assertFalse(RedshiftDataService.AUTO_COMMIT_SQL.matcher(sql).find(), sql);
|
||||
}
|
||||
}
|
||||
+40
@@ -21,6 +21,46 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class RedshiftDataStatementStoreTest {
|
||||
|
||||
@Test
|
||||
void recoveryFailsInterruptedWorkWithoutChangingTerminalResults() {
|
||||
RedshiftDataStatementStore store = new RedshiftDataStatementStore(24, Clock.systemUTC());
|
||||
RedshiftDataStatementStore.StoredStatement active = statement("active", Instant.now());
|
||||
active.status = RedshiftDataStatementStore.Status.STARTED;
|
||||
store.put(active);
|
||||
store.put(statement("finished", Instant.now()));
|
||||
store.start();
|
||||
try {
|
||||
assertEquals(RedshiftDataStatementStore.Status.FAILED, store.get("active").status);
|
||||
assertEquals("Execution interrupted by emulator restart", store.get("active").error);
|
||||
assertEquals(RedshiftDataStatementStore.Status.FINISHED, store.get("finished").status);
|
||||
} finally {
|
||||
store.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sweepRetainsActiveStatementsOlderThanTtl() {
|
||||
Instant now = Instant.parse("2026-10-10T00:00:00Z");
|
||||
RedshiftDataStatementStore store = new RedshiftDataStatementStore(24, Clock.fixed(now, ZoneOffset.UTC));
|
||||
RedshiftDataStatementStore.StoredStatement active = statement("active", now.minus(Duration.ofHours(25)));
|
||||
active.status = RedshiftDataStatementStore.Status.SUBMITTED;
|
||||
store.put(active);
|
||||
store.sweep();
|
||||
assertNotNull(store.get("active"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void storedSnapshotDoesNotChangeWhenWorkerMutatesItsRecord() {
|
||||
RedshiftDataStatementStore store = new RedshiftDataStatementStore(24, Clock.systemUTC());
|
||||
RedshiftDataStatementStore.StoredStatement original = statement("snapshot", Instant.now());
|
||||
original.status = RedshiftDataStatementStore.Status.STARTED;
|
||||
store.put(original);
|
||||
original.status = RedshiftDataStatementStore.Status.FINISHED;
|
||||
assertEquals(RedshiftDataStatementStore.Status.STARTED, store.get("snapshot").status);
|
||||
store.get("snapshot").status = RedshiftDataStatementStore.Status.FAILED;
|
||||
assertEquals(RedshiftDataStatementStore.Status.STARTED, store.get("snapshot").status);
|
||||
}
|
||||
|
||||
private static RedshiftDataStatementStore.StoredStatement statement(String id, Instant createdAt) {
|
||||
RedshiftDataStatementStore.StoredStatement s = new RedshiftDataStatementStore.StoredStatement();
|
||||
s.id = id;
|
||||
|
||||
+25
-31
@@ -66,7 +66,6 @@ class ScheduleInvokerTest {
|
||||
private EcsService ecsService;
|
||||
private StepFunctionsService stepFunctionsService;
|
||||
private RedshiftDataService redshiftDataService;
|
||||
private final List<Runnable> submittedStatements = new ArrayList<>();
|
||||
private ScheduleInvoker invoker;
|
||||
|
||||
@BeforeEach
|
||||
@@ -86,10 +85,9 @@ class ScheduleInvokerTest {
|
||||
when(config.baseUrl()).thenReturn("http://localhost:4566");
|
||||
ServiceRegistry serviceRegistry = mock(ServiceRegistry.class);
|
||||
when(serviceRegistry.isServiceEnabled("redshift-data")).thenReturn(redshiftEnabled && redshiftDataEnabled);
|
||||
// Queue instead of run, so a test can see that the invoker returns before the SQL runs.
|
||||
return new ScheduleInvoker(sqsService, lambdaService, snsService,
|
||||
eventBridgeService, ecsService, stepFunctionsService, redshiftDataService,
|
||||
new ObjectMapper(), config, serviceRegistry, submittedStatements::add);
|
||||
new ObjectMapper(), config, serviceRegistry);
|
||||
}
|
||||
|
||||
/** Delivers one occurrence of a schedule in {@code region} whose target is {@code target}. */
|
||||
@@ -385,7 +383,7 @@ class ScheduleInvokerTest {
|
||||
invoke(target, "eu-west-1");
|
||||
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(redshiftDataService).submitStatement(request.capture(), eq("eu-west-1"));
|
||||
verify(redshiftDataService).executeStatement(request.capture(), eq("eu-west-1"), eq("arn:aws:iam::000000000000:role/x"));
|
||||
assertEquals("select 1", request.getValue().path("Sql").asText());
|
||||
assertEquals("analytics", request.getValue().path("ClusterIdentifier").asText());
|
||||
}
|
||||
@@ -400,7 +398,7 @@ class ScheduleInvokerTest {
|
||||
invoke(target, "us-east-1");
|
||||
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(redshiftDataService).submitStatement(request.capture(), eq("us-east-1"));
|
||||
verify(redshiftDataService).executeStatement(request.capture(), eq("us-east-1"), eq("arn:aws:iam::000000000000:role/x"));
|
||||
assertEquals("wg-1", request.getValue().path("WorkgroupName").asText());
|
||||
assertTrue(request.getValue().path("ClusterIdentifier").isMissingNode());
|
||||
}
|
||||
@@ -416,7 +414,7 @@ class ScheduleInvokerTest {
|
||||
invoke(target, "us-east-1");
|
||||
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(redshiftDataService).submitBatch(request.capture(), eq("us-east-1"));
|
||||
verify(redshiftDataService).batchExecuteStatement(request.capture(), eq("us-east-1"), eq("arn:aws:iam::000000000000:role/x"));
|
||||
assertEquals(2, request.getValue().path("Sqls").size());
|
||||
}
|
||||
|
||||
@@ -426,42 +424,21 @@ class ScheduleInvokerTest {
|
||||
target.setArn("arn:aws:scheduler:::aws-sdk:redshiftdata:executeStatement");
|
||||
target.setRoleArn("arn:aws:iam::000000000000:role/x");
|
||||
target.setInput("{\"Sql\":\"select 1\"}");
|
||||
when(redshiftDataService.submitStatement(any(JsonNode.class), anyString()))
|
||||
when(redshiftDataService.executeStatement(any(JsonNode.class), anyString(), anyString()))
|
||||
.thenThrow(new AwsException("ValidationException", "no cluster", 400));
|
||||
|
||||
assertThrows(AwsException.class, () -> invoke(target, "us-east-1"));
|
||||
assertTrue(submittedStatements.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void universalRedshiftDataRunsTheStatementOffTheCallingThread() {
|
||||
void universalRedshiftDataDelegatesToSharedAdmission() {
|
||||
Target target = new Target();
|
||||
target.setArn("arn:aws:scheduler:::aws-sdk:redshiftdata:executeStatement");
|
||||
target.setRoleArn("arn:aws:iam::000000000000:role/x");
|
||||
target.setInput("{\"ClusterIdentifier\":\"analytics\",\"Database\":\"dev\",\"Sql\":\"select 1\"}");
|
||||
Runnable statement = mock(Runnable.class);
|
||||
when(redshiftDataService.submitStatement(any(JsonNode.class), anyString())).thenReturn(statement);
|
||||
|
||||
invoke(target, "us-east-1");
|
||||
|
||||
verifyNoInteractions(statement);
|
||||
assertEquals(1, submittedStatements.size());
|
||||
submittedStatements.get(0).run();
|
||||
verify(statement).run();
|
||||
}
|
||||
|
||||
@Test
|
||||
void universalRedshiftDataFailedStatementDoesNotEscapeTheExecutor() {
|
||||
Target target = new Target();
|
||||
target.setArn("arn:aws:scheduler:::aws-sdk:redshiftdata:executeStatement");
|
||||
target.setRoleArn("arn:aws:iam::000000000000:role/x");
|
||||
target.setInput("{\"ClusterIdentifier\":\"analytics\",\"Database\":\"dev\",\"Sql\":\"select 1\"}");
|
||||
when(redshiftDataService.submitStatement(any(JsonNode.class), anyString()))
|
||||
.thenReturn(() -> { throw new IllegalStateException("boom"); });
|
||||
|
||||
invoke(target, "us-east-1");
|
||||
|
||||
submittedStatements.get(0).run();
|
||||
verify(redshiftDataService).executeStatement(any(JsonNode.class), eq("us-east-1"),
|
||||
eq("arn:aws:iam::000000000000:role/x"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -853,4 +830,21 @@ class ScheduleInvokerTest {
|
||||
verify(sqsService).sendMessage(anyString(), body.capture(), eq(0), isNull(), isNull(), eq("us-east-1"));
|
||||
assertTrue(body.getValue().matches("[0-9a-f]{16}/1"), body.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void universalRedshiftDataDoesNotWaitOnTheSharedDispatcherThread() {
|
||||
Target target = new Target();
|
||||
target.setArn("arn:aws:scheduler:::aws-sdk:redshiftdata:executeStatement");
|
||||
target.setRoleArn("arn:aws:iam::000000000000:role/x");
|
||||
target.setInput("{\"ClusterIdentifier\":\"analytics\",\"Database\":\"dev\",\"Sql\":\"select 1\","
|
||||
+ "\"WaitTimeSeconds\":30}");
|
||||
|
||||
invoke(target, "us-east-1");
|
||||
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(redshiftDataService).executeStatement(request.capture(), eq("us-east-1"),
|
||||
eq("arn:aws:iam::000000000000:role/x"));
|
||||
assertTrue(request.getValue().path("WaitTimeSeconds").isMissingNode());
|
||||
assertEquals("select 1", request.getValue().path("Sql").asText());
|
||||
}
|
||||
}
|
||||
+20
-4
@@ -65,8 +65,16 @@ class StepFunctionsRedshiftDataDockerIntegrationTest {
|
||||
"Type": "Task",
|
||||
"Resource": "arn:aws:states:::aws-sdk:redshiftdata:describeStatement",
|
||||
"Arguments": {"Id": "{% $states.input.Id %}"},
|
||||
"End": true
|
||||
}
|
||||
"Output": "{% $states.result %}",
|
||||
"Next": "Check"
|
||||
},
|
||||
"Check": {
|
||||
"Type": "Choice",
|
||||
"Choices": [{"Condition": "{% $states.input.Status = 'FINISHED' or $states.input.Status = 'FAILED' or $states.input.Status = 'ABORTED' %}", "Next": "Done"}],
|
||||
"Default": "Wait"
|
||||
},
|
||||
"Wait": {"Type": "Wait", "Seconds": 1, "Next": "Describe"},
|
||||
"Done": {"Type": "Succeed"}
|
||||
}
|
||||
}
|
||||
""".replace("CLUSTER", CLUSTER_ID);
|
||||
@@ -95,8 +103,16 @@ class StepFunctionsRedshiftDataDockerIntegrationTest {
|
||||
"Type": "Task",
|
||||
"Resource": "arn:aws:states:::aws-sdk:redshiftdata:describeStatement",
|
||||
"Arguments": {"Id": "{% $states.input.Id %}"},
|
||||
"End": true
|
||||
}
|
||||
"Output": "{% $states.result %}",
|
||||
"Next": "Check"
|
||||
},
|
||||
"Check": {
|
||||
"Type": "Choice",
|
||||
"Choices": [{"Condition": "{% $states.input.Status = 'FINISHED' or $states.input.Status = 'FAILED' or $states.input.Status = 'ABORTED' %}", "Next": "Done"}],
|
||||
"Default": "Wait"
|
||||
},
|
||||
"Wait": {"Type": "Wait", "Seconds": 1, "Next": "Describe"},
|
||||
"Done": {"Type": "Succeed"}
|
||||
}
|
||||
}
|
||||
""".replace("CLUSTER", CLUSTER_ID);
|
||||
|
||||
Reference in new issue
Block a user