mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(stepfunctions): emit execution status change events to EventBridge (#5567)
* feat(stepfunctions): emit execution status change events to EventBridge STANDARD executions now publish "Step Functions Execution Status Change" events (source aws.states) to the default EventBridge bus on RUNNING, SUCCEEDED, FAILED, TIMED_OUT and ABORTED, so rules matching aws.states fire as they do on AWS. EXPRESS executions emit nothing, as on AWS. StepFunctionsEventPublisher follows the EcsEventPublisher pattern. RUNNING is published when StartExecution creates the execution, terminal statuses from the worker's completion callback, and ABORTED from StopExecution only, so a stopped execution emits exactly one ABORTED. An idempotent StartExecution and the startup sweep of executions abandoned by a restart emit nothing. * fix(stepfunctions): match the documented execution status change event Address review feedback on the aws.states events: - Always send stateMachineVersionArn and stateMachineAliasArn, null when unused, as AWS's documented events do. - Report redrive status as the documented examples do: FAILED and TIMED_OUT are REDRIVABLE with "Execution is <status> and is redrivable"; RUNNING, SUCCEEDED and ABORTED are NOT_REDRIVABLE with "Execution is <status> and cannot be redriven". - Name States.Timeout as the error of a TIMED_OUT event. - Apply the 248 KiB rule: input is left out when the escaped input and output together exceed it, output when the escaped output alone does, and inputDetails/outputDetails.included report it. * test(stepfunctions): check event absences without waiting on empty queues The integration test long-polled SQS for 2 s after each case to show nothing more arrived, so the class waited about 10 s by design. It now asserts only the events that should arrive. The absences that matter are checked in StepFunctionsServiceExecutionEventsTest: it captures the completion callback from a mocked AslExecutor and verifies that an EXPRESS execution publishes nothing and that the worker's callback after StopExecution adds no second ABORTED. Add StepFunctionsExecutions.waitForTerminalState to the shared testing package and use it here; moving the other Step Functions integration tests onto it is left for a separate PR.
This commit is contained in:
1 parent
ad1b225591
commit
fc5e1aea0a
12 files changed
+916
-7
No files matched your search
+257
@@ -0,0 +1,257 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class StepFunctionsEventPublisherTest {
|
||||
|
||||
private static final String SM_ARN = "arn:aws:states:eu-west-1:111122223333:stateMachine:jobs";
|
||||
private static final String EXEC_ARN = "arn:aws:states:eu-west-1:111122223333:execution:jobs:run-1";
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
private final EventBridgeService eventBridge = mock(EventBridgeService.class);
|
||||
private final StepFunctionsEventPublisher publisher = new StepFunctionsEventPublisher(
|
||||
eventBridge, new RegionResolver("us-east-1", "000000000000"), objectMapper);
|
||||
|
||||
private static Execution execution(String status) {
|
||||
Execution exec = new Execution();
|
||||
exec.setExecutionArn(EXEC_ARN);
|
||||
exec.setStateMachineArn(SM_ARN);
|
||||
exec.setName("run-1");
|
||||
exec.setInput("{\"job\":1}");
|
||||
exec.setStartDate(1_700_000_000.5);
|
||||
exec.setStatus(status);
|
||||
return exec;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> captureEntry() {
|
||||
ArgumentCaptor<List<Map<String, Object>>> cap = ArgumentCaptor.forClass(List.class);
|
||||
verify(eventBridge).putEvents(cap.capture(), eq("eu-west-1"));
|
||||
return cap.getValue().getFirst();
|
||||
}
|
||||
|
||||
private JsonNode detailOf(Map<String, Object> entry) throws Exception {
|
||||
return objectMapper.readTree((String) entry.get("Detail"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void runningEventCarriesAwsEnvelopeAndExecutionFields() throws Exception {
|
||||
publisher.emitStatusChange(execution("RUNNING"));
|
||||
|
||||
Map<String, Object> entry = captureEntry();
|
||||
assertEquals("aws.states", entry.get("Source"));
|
||||
assertEquals("Step Functions Execution Status Change", entry.get("DetailType"));
|
||||
ArrayNode resources = (ArrayNode) entry.get("Resources");
|
||||
assertEquals(1, resources.size());
|
||||
assertEquals(EXEC_ARN, resources.get(0).asText());
|
||||
|
||||
JsonNode detail = detailOf(entry);
|
||||
assertEquals(EXEC_ARN, detail.path("executionArn").asText());
|
||||
assertEquals(SM_ARN, detail.path("stateMachineArn").asText());
|
||||
assertEquals("run-1", detail.path("name").asText());
|
||||
assertEquals("RUNNING", detail.path("status").asText());
|
||||
assertEquals(1_700_000_000_500L, detail.path("startDate").asLong());
|
||||
assertTrue(detail.path("stopDate").isNull());
|
||||
assertEquals("{\"job\":1}", detail.path("input").asText());
|
||||
assertTrue(detail.path("inputDetails").path("included").asBoolean());
|
||||
assertTrue(detail.path("output").isNull());
|
||||
assertTrue(detail.path("outputDetails").isNull());
|
||||
assertTrue(detail.path("error").isNull());
|
||||
assertTrue(detail.path("cause").isNull());
|
||||
// Present and null when unused, as in AWS's documented events, not left out.
|
||||
assertTrue(detail.has("stateMachineVersionArn"));
|
||||
assertTrue(detail.path("stateMachineVersionArn").isNull());
|
||||
assertTrue(detail.has("stateMachineAliasArn"));
|
||||
assertTrue(detail.path("stateMachineAliasArn").isNull());
|
||||
assertTrue(detail.has("redriveDate"));
|
||||
assertEquals(0, detail.path("redriveCount").asInt());
|
||||
assertEquals("NOT_REDRIVABLE", detail.path("redriveStatus").asText());
|
||||
assertEquals("Execution is RUNNING and cannot be redriven", detail.path("redriveStatusReason").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void succeededEventCarriesOutputAndStopDateInMillis() throws Exception {
|
||||
Execution exec = execution("SUCCEEDED");
|
||||
exec.setOutput("{\"done\":true}");
|
||||
exec.setStopDate(1_700_000_002.25);
|
||||
|
||||
publisher.emitStatusChange(exec);
|
||||
|
||||
JsonNode detail = detailOf(captureEntry());
|
||||
assertEquals("SUCCEEDED", detail.path("status").asText());
|
||||
assertEquals(1_700_000_002_250L, detail.path("stopDate").asLong());
|
||||
assertEquals("{\"done\":true}", detail.path("output").asText());
|
||||
assertTrue(detail.path("outputDetails").path("included").asBoolean());
|
||||
assertEquals("NOT_REDRIVABLE", detail.path("redriveStatus").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedEventCarriesErrorAndCause() throws Exception {
|
||||
Execution exec = execution("FAILED");
|
||||
exec.setError("Job.Broken");
|
||||
exec.setCause("boom");
|
||||
exec.setStopDate(1_700_000_003.0);
|
||||
|
||||
publisher.emitStatusChange(exec);
|
||||
|
||||
JsonNode detail = detailOf(captureEntry());
|
||||
assertEquals("FAILED", detail.path("status").asText());
|
||||
assertEquals("Job.Broken", detail.path("error").asText());
|
||||
assertEquals("boom", detail.path("cause").asText());
|
||||
assertTrue(detail.path("output").isNull());
|
||||
assertEquals("REDRIVABLE", detail.path("redriveStatus").asText());
|
||||
assertEquals("Execution is FAILED and is redrivable", detail.path("redriveStatusReason").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void timedOutEventNamesStatesTimeoutAndIsRedrivable() throws Exception {
|
||||
Execution exec = execution("TIMED_OUT");
|
||||
exec.setStopDate(1_700_000_004.0);
|
||||
|
||||
publisher.emitStatusChange(exec);
|
||||
|
||||
JsonNode detail = detailOf(captureEntry());
|
||||
assertEquals("TIMED_OUT", detail.path("status").asText());
|
||||
assertEquals("States.Timeout", detail.path("error").asText());
|
||||
assertEquals("REDRIVABLE", detail.path("redriveStatus").asText());
|
||||
assertEquals("Execution is TIMED_OUT and is redrivable", detail.path("redriveStatusReason").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void abortedEventIsNotRedrivable() throws Exception {
|
||||
Execution exec = execution("ABORTED");
|
||||
exec.setStopDate(1_700_000_005.0);
|
||||
|
||||
publisher.emitStatusChange(exec);
|
||||
|
||||
JsonNode detail = detailOf(captureEntry());
|
||||
assertEquals("ABORTED", detail.path("status").asText());
|
||||
assertEquals("NOT_REDRIVABLE", detail.path("redriveStatus").asText());
|
||||
assertEquals("Execution is ABORTED and cannot be redriven", detail.path("redriveStatusReason").asText());
|
||||
assertTrue(detail.path("outputDetails").isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void inputOverTheLimitIsExcluded() throws Exception {
|
||||
Execution exec = execution("RUNNING");
|
||||
exec.setInput(payloadOfSize(StepFunctionsEventPublisher.MAX_PAYLOAD_BYTES + 1));
|
||||
|
||||
publisher.emitStatusChange(exec);
|
||||
|
||||
JsonNode detail = detailOf(captureEntry());
|
||||
assertTrue(detail.path("input").isNull());
|
||||
assertFalse(detail.path("inputDetails").path("included").asBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
void inputAtTheLimitIsIncluded() throws Exception {
|
||||
Execution exec = execution("RUNNING");
|
||||
String input = payloadOfSize(StepFunctionsEventPublisher.MAX_PAYLOAD_BYTES);
|
||||
exec.setInput(input);
|
||||
|
||||
publisher.emitStatusChange(exec);
|
||||
|
||||
JsonNode detail = detailOf(captureEntry());
|
||||
assertEquals(input, detail.path("input").asText());
|
||||
assertTrue(detail.path("inputDetails").path("included").asBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
void inputIsExcludedWhenInputAndOutputTogetherExceedTheLimit() throws Exception {
|
||||
Execution exec = execution("SUCCEEDED");
|
||||
exec.setStopDate(1_700_000_002.0);
|
||||
long half = StepFunctionsEventPublisher.MAX_PAYLOAD_BYTES / 2;
|
||||
exec.setInput(payloadOfSize(half + 1));
|
||||
String output = payloadOfSize(half);
|
||||
exec.setOutput(output);
|
||||
|
||||
publisher.emitStatusChange(exec);
|
||||
|
||||
JsonNode detail = detailOf(captureEntry());
|
||||
assertTrue(detail.path("input").isNull());
|
||||
assertFalse(detail.path("inputDetails").path("included").asBoolean());
|
||||
assertEquals(output, detail.path("output").asText());
|
||||
assertTrue(detail.path("outputDetails").path("included").asBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
void outputOverTheLimitIsExcluded() throws Exception {
|
||||
Execution exec = execution("SUCCEEDED");
|
||||
exec.setStopDate(1_700_000_002.0);
|
||||
exec.setOutput(payloadOfSize(StepFunctionsEventPublisher.MAX_PAYLOAD_BYTES + 1));
|
||||
|
||||
publisher.emitStatusChange(exec);
|
||||
|
||||
JsonNode detail = detailOf(captureEntry());
|
||||
assertTrue(detail.path("output").isNull());
|
||||
assertFalse(detail.path("outputDetails").path("included").asBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sizeIsMeasuredOnTheEscapedPayload() throws Exception {
|
||||
Execution exec = execution("RUNNING");
|
||||
// Each quote escapes to two characters, so this fits raw but not escaped.
|
||||
long quotes = StepFunctionsEventPublisher.MAX_PAYLOAD_BYTES / 2 + 1;
|
||||
exec.setInput("\"".repeat((int) quotes));
|
||||
|
||||
publisher.emitStatusChange(exec);
|
||||
|
||||
JsonNode detail = detailOf(captureEntry());
|
||||
assertFalse(detail.path("inputDetails").path("included").asBoolean());
|
||||
}
|
||||
|
||||
// A payload whose escaped form is exactly {@code size} bytes: ASCII letters escape to themselves.
|
||||
private static String payloadOfSize(long size) {
|
||||
return "a".repeat((int) size);
|
||||
}
|
||||
|
||||
@Test
|
||||
void versionAndAliasArnsAreIncludedWhenTheExecutionHasThem() throws Exception {
|
||||
Execution exec = execution("RUNNING");
|
||||
exec.setStateMachineVersionArn(SM_ARN + ":3");
|
||||
exec.setStateMachineAliasArn(SM_ARN + ":prod");
|
||||
|
||||
publisher.emitStatusChange(exec);
|
||||
|
||||
JsonNode detail = detailOf(captureEntry());
|
||||
assertEquals(SM_ARN + ":3", detail.path("stateMachineVersionArn").asText());
|
||||
assertEquals(SM_ARN + ":prod", detail.path("stateMachineAliasArn").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void putEventsFailureIsSwallowed() {
|
||||
when(eventBridge.putEvents(any(), anyString())).thenThrow(new RuntimeException("bus down"));
|
||||
|
||||
publisher.emitStatusChange(execution("RUNNING"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyStandardExecutionArnsAreStandard() {
|
||||
assertTrue(StepFunctionsEventPublisher.isStandard(execution("RUNNING")));
|
||||
|
||||
Execution express = execution("RUNNING");
|
||||
express.setExecutionArn("arn:aws:states:eu-west-1:111122223333:express:jobs:run-1:"
|
||||
+ "8f2b0c1e-5c4a-4b8e-9a51-3d6f1e2a7b90");
|
||||
assertFalse(StepFunctionsEventPublisher.isStandard(express));
|
||||
}
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.github.hectorvent.floci.testing.StepFunctionsExecutions;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* "Step Functions Execution Status Change" events reach an EventBridge rule's SQS target for every
|
||||
* status a STANDARD execution enters. Each test routes its own state machine's events to its own
|
||||
* queue, so executions started by other test classes sharing this Quarkus app do not leak in.
|
||||
*
|
||||
* <p>Only events that should arrive are asserted here. The absences, nothing for an EXPRESS
|
||||
* execution and no second ABORTED from the worker after StopExecution, are verified without
|
||||
* waiting on an empty queue in {@code StepFunctionsServiceExecutionEventsTest}.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class StepFunctionsExecutionStatusEventsIntegrationTest {
|
||||
|
||||
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
|
||||
private static final String SQS_CONTENT_TYPE = "application/x-amz-json-1.0";
|
||||
private static final String EVENTS_CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";
|
||||
private static final String DETAIL_TYPE = "Step Functions Execution Status Change";
|
||||
private static final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void succeededExecutionEmitsRunningThenSucceeded() throws Exception {
|
||||
String smArn = createStateMachine("status-events-pass", "STANDARD", """
|
||||
{"StartAt": "P", "States": {"P": {"Type": "Pass", "Result": {"done": true}, "End": true}}}
|
||||
""");
|
||||
String queueUrl = routeEventsTo("status-events-pass", smArn);
|
||||
|
||||
String execArn = startExecution(smArn, "{\\\"job\\\":1}");
|
||||
StepFunctionsExecutions.waitForTerminalState(execArn);
|
||||
|
||||
List<JsonNode> events = receiveEvents(queueUrl, 2);
|
||||
assertEquals(List.of("RUNNING", "SUCCEEDED"), statuses(events));
|
||||
|
||||
JsonNode running = events.get(0);
|
||||
assertEquals("aws.states", running.path("source").asText());
|
||||
assertEquals(DETAIL_TYPE, running.path("detail-type").asText());
|
||||
assertEquals("000000000000", running.path("account").asText());
|
||||
assertEquals("us-east-1", running.path("region").asText());
|
||||
assertEquals(execArn, running.path("resources").get(0).asText());
|
||||
assertEquals(execArn, running.path("detail").path("executionArn").asText());
|
||||
assertEquals(smArn, running.path("detail").path("stateMachineArn").asText());
|
||||
assertEquals("{\"job\":1}", running.path("detail").path("input").asText());
|
||||
assertTrue(running.path("detail").path("stopDate").isNull());
|
||||
assertTrue(running.path("detail").path("output").isNull());
|
||||
|
||||
JsonNode succeeded = events.get(1).path("detail");
|
||||
assertEquals("{\"done\":true}", succeeded.path("output").asText());
|
||||
assertTrue(succeeded.path("outputDetails").path("included").asBoolean());
|
||||
assertTrue(succeeded.path("stopDate").asLong() >= succeeded.path("startDate").asLong());
|
||||
// Epoch milliseconds, as AWS sends, not DescribeExecution's epoch seconds.
|
||||
assertTrue(succeeded.path("startDate").asLong() > 1_000_000_000_000L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedExecutionCarriesErrorAndCause() throws Exception {
|
||||
String smArn = createStateMachine("status-events-fail", "STANDARD", """
|
||||
{"StartAt": "F", "States": {"F": {"Type": "Fail", "Error": "Job.Broken", "Cause": "boom"}}}
|
||||
""");
|
||||
String queueUrl = routeEventsTo("status-events-fail", smArn);
|
||||
|
||||
StepFunctionsExecutions.waitForTerminalState(startExecution(smArn, "{}"));
|
||||
|
||||
List<JsonNode> events = receiveEvents(queueUrl, 2);
|
||||
assertEquals(List.of("RUNNING", "FAILED"), statuses(events));
|
||||
JsonNode failed = events.get(1).path("detail");
|
||||
assertEquals("Job.Broken", failed.path("error").asText());
|
||||
assertEquals("boom", failed.path("cause").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void timedOutExecutionNamesStatesTimeout() throws Exception {
|
||||
String smArn = createStateMachine("status-events-timeout", "STANDARD", """
|
||||
{"TimeoutSeconds": 1, "StartAt": "W", "States": {"W": {"Type": "Wait", "Seconds": 5, "End": true}}}
|
||||
""");
|
||||
String queueUrl = routeEventsTo("status-events-timeout", smArn);
|
||||
|
||||
StepFunctionsExecutions.waitForTerminalState(startExecution(smArn, "{}"));
|
||||
|
||||
List<JsonNode> events = receiveEvents(queueUrl, 2);
|
||||
assertEquals(List.of("RUNNING", "TIMED_OUT"), statuses(events));
|
||||
JsonNode timedOut = events.get(1).path("detail");
|
||||
assertEquals("States.Timeout", timedOut.path("error").asText());
|
||||
assertEquals("REDRIVABLE", timedOut.path("redriveStatus").asText());
|
||||
assertEquals("Execution is TIMED_OUT and is redrivable", timedOut.path("redriveStatusReason").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stoppedExecutionEmitsAbortedExactlyOnce() throws Exception {
|
||||
String smArn = createStateMachine("status-events-stop", "STANDARD", """
|
||||
{"StartAt": "W", "States": {"W": {"Type": "Wait", "Seconds": 30, "End": true}}}
|
||||
""");
|
||||
String queueUrl = routeEventsTo("status-events-stop", smArn);
|
||||
|
||||
String execArn = startExecution(smArn, "{}");
|
||||
given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.StopExecution")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"executionArn": "%s", "error": "Halted", "cause": "by test"}
|
||||
""".formatted(execArn))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
List<JsonNode> events = receiveEvents(queueUrl, 2);
|
||||
assertEquals(List.of("RUNNING", "ABORTED"), statuses(events));
|
||||
assertEquals("Halted", events.get(1).path("detail").path("error").asText());
|
||||
}
|
||||
|
||||
private static List<String> statuses(List<JsonNode> events) {
|
||||
List<String> statuses = new ArrayList<>();
|
||||
for (JsonNode event : events) {
|
||||
statuses.add(event.path("detail").path("status").asText());
|
||||
}
|
||||
return statuses;
|
||||
}
|
||||
|
||||
private static String routeEventsTo(String name, String smArn) {
|
||||
String queueUrl = createQueue(name);
|
||||
String pattern = """
|
||||
{"source":["aws.states"],"detail-type":["%s"],"detail":{"stateMachineArn":["%s"]}}
|
||||
""".formatted(DETAIL_TYPE, smArn).strip();
|
||||
given()
|
||||
.header("X-Amz-Target", "AWSEvents.PutRule")
|
||||
.contentType(EVENTS_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"Name":"%s","EventPattern":%s,"State":"ENABLED"}
|
||||
""".formatted(name, quote(pattern)))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
given()
|
||||
.header("X-Amz-Target", "AWSEvents.PutTargets")
|
||||
.contentType(EVENTS_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"Rule":"%s","Targets":[{"Id":"1","Arn":"%s"}]}
|
||||
""".formatted(name, queueArn(queueUrl)))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
return queueUrl;
|
||||
}
|
||||
|
||||
private static String createQueue(String name) {
|
||||
Response resp = given()
|
||||
.header("X-Amz-Target", "AmazonSQS.CreateQueue")
|
||||
.contentType(SQS_CONTENT_TYPE)
|
||||
.body("{\"QueueName\":\"%s\"}".formatted(name))
|
||||
.when().post("/");
|
||||
resp.then().statusCode(200);
|
||||
return resp.jsonPath().getString("QueueUrl");
|
||||
}
|
||||
|
||||
private static String queueArn(String queueUrl) {
|
||||
Response resp = given()
|
||||
.header("X-Amz-Target", "AmazonSQS.GetQueueAttributes")
|
||||
.contentType(SQS_CONTENT_TYPE)
|
||||
.body("{\"QueueUrl\":\"%s\",\"AttributeNames\":[\"QueueArn\"]}".formatted(queueUrl))
|
||||
.when().post("/");
|
||||
resp.then().statusCode(200);
|
||||
return resp.jsonPath().getString("Attributes.QueueArn");
|
||||
}
|
||||
|
||||
private static List<JsonNode> receiveEvents(String queueUrl, int expected) throws Exception {
|
||||
List<JsonNode> events = new ArrayList<>();
|
||||
for (int i = 0; i < 20 && events.size() < expected; i++) {
|
||||
events.addAll(receive(queueUrl, 1));
|
||||
}
|
||||
if (events.size() < expected) {
|
||||
fail("Expected " + expected + " events on " + queueUrl + " but received " + events);
|
||||
}
|
||||
// A standard SQS queue does not promise order, so order by the status lifecycle.
|
||||
events.sort((a, b) -> Boolean.compare(
|
||||
!"RUNNING".equals(a.path("detail").path("status").asText()),
|
||||
!"RUNNING".equals(b.path("detail").path("status").asText())));
|
||||
return events;
|
||||
}
|
||||
|
||||
private static List<JsonNode> receive(String queueUrl, int waitSeconds) throws Exception {
|
||||
Response resp = given()
|
||||
.header("X-Amz-Target", "AmazonSQS.ReceiveMessage")
|
||||
.contentType(SQS_CONTENT_TYPE)
|
||||
.body("{\"QueueUrl\":\"%s\",\"MaxNumberOfMessages\":10,\"WaitTimeSeconds\":%d}"
|
||||
.formatted(queueUrl, waitSeconds))
|
||||
.when().post("/");
|
||||
resp.then().statusCode(200);
|
||||
List<JsonNode> events = new ArrayList<>();
|
||||
for (JsonNode message : mapper.readTree(resp.body().asString()).path("Messages")) {
|
||||
events.add(mapper.readTree(message.path("Body").asText()));
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
private static String createStateMachine(String name, String type, String definition) {
|
||||
Response resp = given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"name": "%s", "type": "%s", "roleArn": "%s", "definition": %s}
|
||||
""".formatted(name, type, ROLE_ARN, quote(definition.strip())))
|
||||
.when().post("/");
|
||||
resp.then().statusCode(200);
|
||||
return resp.jsonPath().getString("stateMachineArn");
|
||||
}
|
||||
|
||||
private static String startExecution(String smArn, String escapedInput) {
|
||||
Response resp = given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.StartExecution")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"stateMachineArn": "%s", "input": "%s"}
|
||||
""".formatted(smArn, escapedInput))
|
||||
.when().post("/");
|
||||
resp.then().statusCode(200);
|
||||
return resp.jsonPath().getString("executionArn");
|
||||
}
|
||||
|
||||
private static String quote(String raw) {
|
||||
return "\"" + raw
|
||||
.replace("\\", "\\\\")
|
||||
.replace("\"", "\\\"")
|
||||
.replace("\n", "\\n")
|
||||
.replace("\r", "\\r")
|
||||
.replace("\t", "\\t")
|
||||
+ "\"";
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -44,7 +44,8 @@ class StepFunctionsListPartitionTest {
|
||||
// aslExecutor stays null: neither CreateStateMachine nor CreateActivity reaches it, and
|
||||
// AslExecutor cannot be class-loaded in this sandbox because it needs Vert.x.
|
||||
return new StepFunctionsService(factory, new RegionResolver("us-east-1", ACCOUNT), null,
|
||||
new ObjectMapper(), mock(SfnMockLoader.class));
|
||||
new ObjectMapper(), mock(SfnMockLoader.class),
|
||||
mock(StepFunctionsEventPublisher.class));
|
||||
}
|
||||
|
||||
private static final String DEFINITION =
|
||||
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.Activity;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Which status changes {@link StepFunctionsService} hands to the {@link StepFunctionsEventPublisher},
|
||||
* over a real service with in-memory stores, a mocked {@link AslExecutor} and a mocked publisher.
|
||||
* The executor's completion callback is captured and invoked by the test, standing in for the worker
|
||||
* thread, so the cases where no event may be published are checked directly instead of by waiting
|
||||
* on an empty queue.
|
||||
*/
|
||||
class StepFunctionsServiceExecutionEventsTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String STANDARD_SM_ARN = "arn:aws:states:us-east-1:000000000000:stateMachine:standard-sm";
|
||||
private static final String EXPRESS_SM_ARN = "arn:aws:states:us-east-1:000000000000:stateMachine:express-sm";
|
||||
|
||||
private AslExecutor executor;
|
||||
private StepFunctionsEventPublisher publisher;
|
||||
// The status at the moment of each publish: the service hands over the live Execution, which
|
||||
// later transitions keep mutating.
|
||||
private final List<String> publishedStatuses = new ArrayList<>();
|
||||
|
||||
private StepFunctionsService buildService() {
|
||||
AccountAwareStorageBackend<StateMachine> smStore = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
AccountAwareStorageBackend<Execution> execStore = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
AccountAwareStorageBackend<Activity> actStore = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
|
||||
StorageFactory factory = mock(StorageFactory.class);
|
||||
doReturn(smStore).doReturn(execStore).doReturn(actStore)
|
||||
.when(factory).create(anyString(), anyString(), any());
|
||||
|
||||
RegionResolver region = mock(RegionResolver.class);
|
||||
when(region.buildArn(eq("states"), any(), anyString()))
|
||||
.thenAnswer(i -> "arn:aws:states:us-east-1:000000000000:" + i.getArgument(2));
|
||||
|
||||
executor = mock(AslExecutor.class);
|
||||
publisher = mock(StepFunctionsEventPublisher.class);
|
||||
doAnswer(i -> publishedStatuses.add(i.<Execution>getArgument(0).getStatus()))
|
||||
.when(publisher).emitStatusChange(any());
|
||||
StepFunctionsService service = new StepFunctionsService(factory, region, executor, new ObjectMapper(),
|
||||
mock(SfnMockLoader.class), publisher);
|
||||
|
||||
smStore.put(STANDARD_SM_ARN, stateMachine(STANDARD_SM_ARN, "standard-sm", "STANDARD"));
|
||||
smStore.put(EXPRESS_SM_ARN, stateMachine(EXPRESS_SM_ARN, "express-sm", "EXPRESS"));
|
||||
return service;
|
||||
}
|
||||
|
||||
private static StateMachine stateMachine(String arn, String name, String type) {
|
||||
StateMachine sm = new StateMachine();
|
||||
sm.setStateMachineArn(arn);
|
||||
sm.setName(name);
|
||||
sm.setRoleArn("arn:aws:iam::000000000000:role/r");
|
||||
sm.setType(type);
|
||||
sm.setDefinition("{\"StartAt\":\"P\",\"States\":{\"P\":{\"Type\":\"Pass\",\"End\":true}}}");
|
||||
return sm;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private BiConsumer<Execution, List<HistoryEvent>> completionCallback() {
|
||||
ArgumentCaptor<BiConsumer<Execution, List<HistoryEvent>>> callback = ArgumentCaptor.forClass(BiConsumer.class);
|
||||
verify(executor).executeAsync(any(), any(), any(), any(), callback.capture());
|
||||
return callback.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void standardExecutionPublishesRunningThenItsTerminalStatus() {
|
||||
StepFunctionsService service = buildService();
|
||||
Execution exec = service.startExecution(STANDARD_SM_ARN, "run-1", "{}", REGION);
|
||||
BiConsumer<Execution, List<HistoryEvent>> callback = completionCallback();
|
||||
|
||||
exec.setStatus("SUCCEEDED");
|
||||
exec.setStopDate(exec.getStartDate() + 1);
|
||||
callback.accept(exec, List.of());
|
||||
|
||||
assertEquals(List.of("RUNNING", "SUCCEEDED"), publishedStatuses);
|
||||
}
|
||||
|
||||
@Test
|
||||
void expressExecutionPublishesNothing() {
|
||||
StepFunctionsService service = buildService();
|
||||
Execution exec = service.startExecution(EXPRESS_SM_ARN, "run-1", "{}", REGION);
|
||||
BiConsumer<Execution, List<HistoryEvent>> callback = completionCallback();
|
||||
|
||||
exec.setStatus("SUCCEEDED");
|
||||
exec.setStopDate(exec.getStartDate() + 1);
|
||||
callback.accept(exec, List.of());
|
||||
|
||||
verifyNoInteractions(publisher);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stoppedExecutionPublishesAbortedOnceAndTheWorkerAddsNothing() {
|
||||
StepFunctionsService service = buildService();
|
||||
Execution exec = service.startExecution(STANDARD_SM_ARN, "run-1", "{}", REGION);
|
||||
BiConsumer<Execution, List<HistoryEvent>> callback = completionCallback();
|
||||
|
||||
service.stopExecution(exec.getExecutionArn(), "by test", "Halted");
|
||||
// The worker notices the abort and reports through the same callback as any other ending.
|
||||
callback.accept(exec, List.of());
|
||||
|
||||
assertEquals(List.of("RUNNING", "ABORTED"), publishedStatuses);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stoppingAnAlreadyStoppedExecutionPublishesNothingMore() {
|
||||
StepFunctionsService service = buildService();
|
||||
Execution exec = service.startExecution(STANDARD_SM_ARN, "run-1", "{}", REGION);
|
||||
|
||||
service.stopExecution(exec.getExecutionArn(), null, null);
|
||||
service.stopExecution(exec.getExecutionArn(), null, null);
|
||||
|
||||
assertEquals(List.of("RUNNING", "ABORTED"), publishedStatuses);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -431,7 +431,7 @@ class StepFunctionsServicePersistenceTest {
|
||||
|
||||
private StepFunctionsService serviceWithStorage(StorageFactory storage, AslExecutor executor) {
|
||||
return new StepFunctionsService(storage, regionResolver, executor,
|
||||
new ObjectMapper(), mockLoader);
|
||||
new ObjectMapper(), mockLoader, Mockito.mock(StepFunctionsEventPublisher.class));
|
||||
}
|
||||
|
||||
private static AccountAwareStorageBackend<Execution> executionStore(StorageFactory storage) {
|
||||
|
||||
+2
-1
@@ -73,7 +73,8 @@ class StepFunctionsServiceStartExecutionExpressTest {
|
||||
// invokes it explicitly (mirroring what AslExecutor would do on the worker thread).
|
||||
executor = mock(AslExecutor.class);
|
||||
StepFunctionsService svc =
|
||||
new StepFunctionsService(factory, region, executor, new ObjectMapper(), mock(SfnMockLoader.class));
|
||||
new StepFunctionsService(factory, region, executor, new ObjectMapper(), mock(SfnMockLoader.class),
|
||||
mock(StepFunctionsEventPublisher.class));
|
||||
|
||||
StateMachine sm = new StateMachine();
|
||||
sm.setStateMachineArn(SM_ARN);
|
||||
|
||||
+7
-1
@@ -17,6 +17,7 @@ import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
@@ -34,6 +35,7 @@ class StepFunctionsServiceStartExecutionIdempotencyTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
private AccountAwareStorageBackend<Execution> execStore;
|
||||
private StepFunctionsEventPublisher eventPublisher;
|
||||
|
||||
private StepFunctionsService buildService(String smType) {
|
||||
AccountAwareStorageBackend<StateMachine> smStore = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
@@ -50,8 +52,10 @@ class StepFunctionsServiceStartExecutionIdempotencyTest {
|
||||
|
||||
// aslExecutor is null: the return-existing / conflict branches never reach executeAsync, and a
|
||||
// null field is never dereferenced (AslExecutor cannot be class-loaded here: it needs Vert.x).
|
||||
eventPublisher = mock(StepFunctionsEventPublisher.class);
|
||||
StepFunctionsService svc =
|
||||
new StepFunctionsService(factory, region, null, new ObjectMapper(), mock(SfnMockLoader.class));
|
||||
new StepFunctionsService(factory, region, null, new ObjectMapper(), mock(SfnMockLoader.class),
|
||||
eventPublisher);
|
||||
|
||||
StateMachine sm = new StateMachine();
|
||||
sm.setStateMachineArn(SM_ARN);
|
||||
@@ -83,6 +87,8 @@ class StepFunctionsServiceStartExecutionIdempotencyTest {
|
||||
assertEquals("RUNNING", result.getStatus());
|
||||
// Must be the ORIGINAL execution (with its original startDate), not a freshly built one.
|
||||
assertEquals(1234567.0, result.getStartDate());
|
||||
// Nothing changed status, so no second RUNNING event is published.
|
||||
verifyNoInteractions(eventPublisher);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
-1
@@ -135,7 +135,8 @@ class StepFunctionsServiceStartExecutionRaceTest {
|
||||
|
||||
AslExecutor executor = mock(AslExecutor.class);
|
||||
StepFunctionsService service =
|
||||
new StepFunctionsService(factory, region, executor, new ObjectMapper(), mock(SfnMockLoader.class));
|
||||
new StepFunctionsService(factory, region, executor, new ObjectMapper(), mock(SfnMockLoader.class),
|
||||
mock(StepFunctionsEventPublisher.class));
|
||||
|
||||
StateMachine sm = new StateMachine();
|
||||
sm.setStateMachineArn(SM_ARN);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package io.github.hectorvent.floci.testing;
|
||||
|
||||
import io.restassured.response.Response;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
|
||||
/** Step Functions execution calls shared by the integration tests. */
|
||||
public final class StepFunctionsExecutions {
|
||||
|
||||
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
|
||||
private static final Duration TERMINAL_STATE_TIMEOUT = Duration.ofSeconds(10);
|
||||
private static final Duration POLL_INTERVAL = Duration.ofMillis(100);
|
||||
|
||||
private StepFunctionsExecutions() {}
|
||||
|
||||
public static Response describeExecution(String executionArn) {
|
||||
Response response = given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"executionArn": "%s"}
|
||||
""".formatted(executionArn))
|
||||
.when().post("/");
|
||||
response.then().statusCode(200);
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls DescribeExecution until the execution leaves RUNNING and returns that response, whatever
|
||||
* the terminal status: asserting which one is the caller's business.
|
||||
*/
|
||||
public static Response waitForTerminalState(String executionArn) {
|
||||
return await("execution " + executionArn + " to leave RUNNING")
|
||||
.atMost(TERMINAL_STATE_TIMEOUT)
|
||||
.pollInterval(POLL_INTERVAL)
|
||||
.until(() -> describeExecution(executionArn),
|
||||
response -> !"RUNNING".equals(response.jsonPath().getString("status")));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user