Light, fluffy, and always free - The AWS Local Emulator alternative
feat(stepfunctions): emit execution status change events to EventBridge (#5567)
andrei-fabricdatafc5e1aea0aae
diff --git a/docs/services/step-functions.md b/docs/services/step-functions.mdindex 021825dbaf..03a4aeddcc 100644--- a/docs/services/step-functions.md+++ b/docs/services/step-functions.md@@ -740,6 +740,41 @@ history is retained, and a previously running execution is marked `ABORTED` with`ExecutionAborted` event appended. After a further restart, the execution is already terminal, sono additional event is written.+## Execution status change events++Floci publishes AWS-shaped `Step Functions Execution Status Change` events to the **default**+EventBridge bus (`source: aws.states`, `resources: [executionArn]`) for every status a STANDARD+execution enters. Rules that match `aws.states`, for example on `detail.stateMachineArn` or+`detail.status`, fire as they do on AWS. EXPRESS executions emit no events, as on AWS.++| `detail.status` | When |+|---|---|+| `RUNNING` | `StartExecution` creates the execution, including a nested `states:startExecution` |+| `SUCCEEDED` | the execution reaches a terminal state without failing |+| `FAILED` | a `Fail` state, an unhandled error, or a runtime error ends the execution |+| `TIMED_OUT` | the state machine's `TimeoutSeconds` elapses |+| `ABORTED` | `StopExecution` stops the execution |++The `detail` carries every key of AWS's documented event, null when it does not apply:+`executionArn`, `stateMachineArn`, `name`, `status`, `startDate` and `stopDate` (epoch+milliseconds, `stopDate` null while `RUNNING`), `input`, `inputDetails`, `output` and+`outputDetails` (set only on `SUCCEEDED`), `stateMachineVersionArn` and `stateMachineAliasArn`+(null unless the execution was started through one), `error`, `cause`, and the redrive fields.++- A `TIMED_OUT` event names `States.Timeout` as its `error`.+- `FAILED` and `TIMED_OUT` report `redriveStatus` `REDRIVABLE` with the reason+ `Execution is <status> and is redrivable`. Every other status reports `NOT_REDRIVABLE` with+ `Execution is <status> and cannot be redriven`.+- As on AWS, when the escaped `input` and escaped `output` together exceed 248 KiB, `input` is+ left out and `inputDetails.included` is `false`. When the escaped `output` alone exceeds+ 248 KiB, `output` is left out and `outputDetails.included` is `false`.+ `DescribeExecution` still returns both in full.++Known differences from AWS:++- Executions aborted by the startup sweep described above emit no `ABORTED` event.+- Floci does not implement redrive, so `redriveCount` is always `0` and `redriveDate` is null.+## PartitionsService integration resources carry the partition of the state machine's regiondiff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsEventPublisher.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsEventPublisher.javanew file mode 100644index 0000000000..413645cb86--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsEventPublisher.java@@ -0,0 +1,168 @@+package io.github.hectorvent.floci.services.stepfunctions;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ArrayNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;+import io.github.hectorvent.floci.services.stepfunctions.model.Execution;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.util.HashMap;+import java.util.List;+import java.util.Map;++/**+ * Publishes AWS-shaped {@code aws.states} "Step Functions Execution Status Change" events to the+ * default EventBridge bus. AWS emits them for STANDARD workflows only, one per status the+ * execution enters: RUNNING, SUCCEEDED, FAILED, TIMED_OUT and ABORTED.+ *+ * <p>The event's account is left to the caller's request context, which is the execution's own+ * account on every path that emits: the StartExecution and StopExecution requests, and the worker+ * thread that runs under the execution's account. The region is taken from the execution ARN.+ */+@ApplicationScoped+public class StepFunctionsEventPublisher {++ private static final Logger LOG = Logger.getLogger(StepFunctionsEventPublisher.class);+ static final String SOURCE = "aws.states";+ static final String DETAIL_TYPE = "Step Functions Execution Status Change";+ // AWS's documented EventBridge quota rule: when the escaped input and escaped output together+ // exceed 248 KiB the input is left out, and when the escaped output alone exceeds it the output+ // is left out too. inputDetails/outputDetails.included report which ones were.+ static final long MAX_PAYLOAD_BYTES = 248L * 1024;++ private final EventBridgeService eventBridgeService;+ private final RegionResolver regionResolver;+ private final ObjectMapper objectMapper;++ @Inject+ public StepFunctionsEventPublisher(EventBridgeService eventBridgeService,+ RegionResolver regionResolver,+ ObjectMapper objectMapper) {+ this.eventBridgeService = eventBridgeService;+ this.regionResolver = regionResolver;+ this.objectMapper = objectMapper;+ }++ /**+ * Emits one status change event carrying the execution's current fields. Never throws: a+ * failure to publish is logged and the execution carries on.+ */+ public void emitStatusChange(Execution exec) {+ String executionArn = exec.getExecutionArn();+ try {+ ObjectNode detail = buildDetail(exec);+ ArrayNode resources = objectMapper.createArrayNode();+ if (executionArn != null) {+ resources.add(executionArn);+ }+ Map<String, Object> entry = new HashMap<>();+ entry.put("Source", SOURCE);+ entry.put("DetailType", DETAIL_TYPE);+ entry.put("Detail", objectMapper.writeValueAsString(detail));+ entry.put("Resources", resources);+ EventBridgeService.PutEventsResult result = eventBridgeService.putEvents(List.of(entry),+ AwsArnUtils.regionOrDefault(executionArn, regionResolver.getDefaultRegion()));+ if (result != null && result.failedCount() > 0) {+ LOG.warnv("EventBridge rejected Step Functions Execution Status Change for {0}: {1}",+ executionArn, result.entries());+ }+ } catch (Exception e) {+ LOG.warnv("Failed to emit Step Functions Execution Status Change for {0}: {1}",+ executionArn, e.getMessage());+ }+ }++ /**+ * AWS emits status change events for STANDARD executions only. An EXPRESS execution's ARN is+ * minted under the {@code express:} resource namespace, a STANDARD one under {@code execution:}.+ */+ static boolean isStandard(Execution exec) {+ String arn = exec.getExecutionArn();+ if (arn == null || !AwsArnUtils.isArn(arn)) {+ return false;+ }+ return AwsArnUtils.parse(arn).resource().startsWith("execution:");+ }++ // The fields are read under the Execution's monitor, the one the worker and StopExecution take+ // for their terminal writes, so the event never pairs one status with another's stopDate.+ // Every key of the documented event is always present, null when it does not apply.+ private ObjectNode buildDetail(Execution exec) throws JsonProcessingException {+ ObjectNode detail = objectMapper.createObjectNode();+ synchronized (exec) {+ String status = exec.getStatus();+ boolean succeeded = "SUCCEEDED".equals(status);+ detail.put("executionArn", exec.getExecutionArn());+ detail.put("stateMachineArn", exec.getStateMachineArn());+ detail.put("name", exec.getName());+ detail.put("status", status);+ detail.put("startDate", toEpochMillis(exec.getStartDate()));+ if (exec.getStopDate() != null && !"RUNNING".equals(status)) {+ detail.put("stopDate", toEpochMillis(exec.getStopDate()));+ } else {+ detail.putNull("stopDate");+ }++ String output = succeeded ? exec.getOutput() : null;+ long outputSize = escapedSize(output);+ boolean outputIncluded = outputSize <= MAX_PAYLOAD_BYTES;+ boolean inputIncluded = escapedSize(exec.getInput()) + outputSize <= MAX_PAYLOAD_BYTES;+ detail.put("input", inputIncluded ? exec.getInput() : null);+ detail.putObject("inputDetails").put("included", inputIncluded);+ detail.put("output", outputIncluded ? output : null);+ if (succeeded) {+ detail.putObject("outputDetails").put("included", outputIncluded);+ } else {+ detail.putNull("outputDetails");+ }++ detail.put("stateMachineVersionArn", exec.getStateMachineVersionArn());+ detail.put("stateMachineAliasArn", exec.getStateMachineAliasArn());+ detail.put("redriveCount", 0);+ detail.putNull("redriveDate");+ detail.put("redriveStatus", redriveStatus(status));+ detail.put("redriveStatusReason", redriveStatusReason(status));+ detail.put("error", "TIMED_OUT".equals(status) && exec.getError() == null+ ? "States.Timeout" : exec.getError());+ detail.put("cause", exec.getCause());+ }+ return detail;+ }++ /**+ * The size of {@code value} once escaped as a JSON string, the measure AWS applies its 248 KiB+ * rule to. A null value takes no room.+ */+ private long escapedSize(String value) throws JsonProcessingException {+ if (value == null) {+ return 0;+ }+ // writeValueAsBytes quotes the string; the quotes are not part of the payload.+ return objectMapper.writeValueAsBytes(value).length - 2L;+ }++ // Floci does not implement RedriveExecution, so these carry what AWS's documented events report+ // for an execution that was never redriven: FAILED and TIMED_OUT are redrivable, the rest are not.+ private static String redriveStatus(String status) {+ return "FAILED".equals(status) || "TIMED_OUT".equals(status) ? "REDRIVABLE" : "NOT_REDRIVABLE";+ }++ private static String redriveStatusReason(String status) {+ if (status == null) {+ return null;+ }+ return "FAILED".equals(status) || "TIMED_OUT".equals(status)+ ? "Execution is " + status + " and is redrivable"+ : "Execution is " + status + " and cannot be redriven";+ }++ private static long toEpochMillis(double epochSeconds) {+ return Math.round(epochSeconds * 1000.0);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.javaindex 8afddf188f..6fd1395a80 100644--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java@@ -71,6 +71,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider {private final AslExecutor aslExecutor;private final ObjectMapper objectMapper;private final SfnMockLoader mockLoader;+ private final StepFunctionsEventPublisher eventPublisher;// Fields that are valid only in JSONPath mode. Validated against real AWS:// creating a JSONata state machine with any of these fields returns SCHEMA_VALIDATION_FAILED.@@ -123,7 +124,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider {@Injectpublic StepFunctionsService(StorageFactory storageFactory, RegionResolver regionResolver,AslExecutor aslExecutor, ObjectMapper objectMapper,- SfnMockLoader mockLoader) {+ SfnMockLoader mockLoader, StepFunctionsEventPublisher eventPublisher) {this.stateMachineStore = storageFactory.create("stepfunctions", "sfn-state-machines.json",new TypeReference<Map<String, StateMachine>>() {});this.executionStore = storageFactory.create("stepfunctions", "sfn-executions.json",@@ -141,6 +142,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider {this.aslExecutor = aslExecutor;this.objectMapper = objectMapper;this.mockLoader = mockLoader;+ this.eventPublisher = eventPublisher;}public void clear() {@@ -781,12 +783,19 @@ public class StepFunctionsService implements Resettable, ResourceProvider {}LOG.infov("Started execution: {0}", arn);+ if (!express) {+ eventPublisher.emitStatusChange(exec);+ }// The executor appends to this same history, so the cache entry put above is already the- // finished history by the time this runs.+ // finished history by the time this runs. The worker also lands here after StopExecution+ // aborted it; that ABORTED event is StopExecution's to emit, so it is not emitted twice.aslExecutor.executeAsync(sm, exec, history, mockedTestCase, (updatedExec, updatedHistory) -> {executionStore.put(updatedExec.getExecutionArn(), updatedExec);LOG.infov("Execution {0} completed with status {1}", updatedExec.getExecutionArn(), updatedExec.getStatus());+ if (!express && !"ABORTED".equals(updatedExec.getStatus())) {+ eventPublisher.emitStatusChange(updatedExec);+ }});return exec;@@ -962,6 +971,9 @@ public class StepFunctionsService implements Resettable, ResourceProvider {return;}executionStore.put(arn, exec);+ if (StepFunctionsEventPublisher.isStandard(exec)) {+ eventPublisher.emitStatusChange(exec);+ }}/**diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsEventPublisherTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsEventPublisherTest.javanew file mode 100644index 0000000000..70e090e268--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsEventPublisherTest.java@@ -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));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsExecutionStatusEventsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsExecutionStatusEventsIntegrationTest.javanew file mode 100644index 0000000000..94415967e3--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsExecutionStatusEventsIntegrationTest.java@@ -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")+ + "\"";+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsListPartitionTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsListPartitionTest.javaindex 9e6bd12330..d57147a607 100644--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsListPartitionTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsListPartitionTest.java@@ -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 =diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceExecutionEventsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceExecutionEventsTest.javanew file mode 100644index 0000000000..57aa73446b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceExecutionEventsTest.java@@ -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);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServicePersistenceTest.javaindex 1975c51bb1..3086ab91c5 100644--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServicePersistenceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServicePersistenceTest.java@@ -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) {diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionExpressTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionExpressTest.javaindex 2489e2a648..0c75ecceb7 100644--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionExpressTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionExpressTest.java@@ -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);diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionIdempotencyTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionIdempotencyTest.javaindex bb62b0e948..9ddd819bd3 100644--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionIdempotencyTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionIdempotencyTest.java@@ -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);}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionRaceTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionRaceTest.javaindex b3a9a05b30..45e01c0b83 100644--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionRaceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionRaceTest.java@@ -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);diff --git a/src/test/java/io/github/hectorvent/floci/testing/StepFunctionsExecutions.java b/src/test/java/io/github/hectorvent/floci/testing/StepFunctionsExecutions.javanew file mode 100644index 0000000000..519b263a6d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/testing/StepFunctionsExecutions.java@@ -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")));+ }+}