diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index 186ca06eb4..cccfd7e92f 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -432,6 +432,17 @@ integrations, and only the casing of the result tells them apart. SDK call itself succeeded, so the task result carries `Status`, `Error` and `Cause` and the parent decides what to do next. +The two `.sync` modes fail the calling task with `States.TaskFailed` however the child ended +(`FAILED`, `TIMED_OUT` or `ABORTED`) and whatever its own error was, `States.Timeout` included, so +a `Catch` on the child's own error name never takes it. The cause is the child's `DescribeExecution` +response as JSON, PascalCase with its keys in alphabetical order: `Cause` and `Error` when the +child has them, then `ExecutionArn`, `Input`, `InputDetails`, `Name`, `RedriveCount`, +`RedriveStatus`, `StartDate`, `StateMachineArn`, `Status` and `StopDate`, with dates in epoch +milliseconds and no `Output`. A child started through an alias also carries `StateMachineAliasArn` +and `StateMachineVersionArn`, and one started through a version carries `StateMachineVersionArn`, +each in its alphabetical place. A parent that needs the child's error reads it from there, for +example with `States.StringToJson($.Cause)` after a `Catch`. + A `Name` a Standard child already used fails the calling task with the child's collision error, named for the integration that raised it: `StepFunctions.ExecutionAlreadyExistsException` through `states:startExecution` in any of its modes, and `Sfn.ExecutionAlreadyExistsException` through diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java index 7c4133eb95..124f4f23c9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java @@ -1736,7 +1736,13 @@ public class AslExecutor { } io.github.hectorvent.floci.services.stepfunctions.model.Execution current = sfnService.get().describeExecution(execArn); - String status = current.getStatus(); + String status; + // The child's worker and StopExecution write its terminal fields under this monitor, + // status last. Reading the status under it makes everything written before it visible, + // so a terminal status is never seen without the error, cause and stop date behind it. + synchronized (current) { + status = current.getStatus(); + } if ("RUNNING".equals(status)) { continue; } @@ -1763,13 +1769,50 @@ public class AslExecutor { } return envelope; } - throw new FailStateException( - current.getError() != null ? current.getError() : "States.TaskFailed", - current.getCause() != null ? current.getCause() - : "Nested execution ended with status: " + status); + // However the child ended, FAILED, TIMED_OUT or ABORTED, and whatever its own error, the + // parent sees States.TaskFailed (measured), so a Catch on the child's error never fires. + throw new FailStateException("States.TaskFailed", nestedExecutionFailureCause(current)); } } + /** + * The cause of a {@code .sync} Task whose child ended other than SUCCEEDED, as measured on AWS + * for {@code .sync} and {@code .sync:2} alike: the child's DescribeExecution response in + * PascalCase with its keys in alphabetical order, {@code Cause} and {@code Error} only when the + * child has them, {@code StateMachineAliasArn} and {@code StateMachineVersionArn} only when it + * was started through an alias or a version (an alias carries both), dates in epoch + * milliseconds, and no {@code Output}. Floci does not implement + * redrive, so the two redrive fields carry what AWS reports for a child never redriven. + */ + private String nestedExecutionFailureCause(Execution child) { + ObjectNode cause = objectMapper.createObjectNode(); + if (child.getCause() != null) { + cause.put("Cause", child.getCause()); + } + if (child.getError() != null) { + cause.put("Error", child.getError()); + } + cause.put("ExecutionArn", child.getExecutionArn()); + cause.put("Input", child.getInput() != null ? child.getInput() : "{}"); + cause.putObject("InputDetails").put("Included", true); + cause.put("Name", child.getName()); + cause.put("RedriveCount", 0); + cause.put("RedriveStatus", "REDRIVABLE"); + cause.put("StartDate", Math.round(child.getStartDate() * 1000)); + if (child.getStateMachineAliasArn() != null) { + cause.put("StateMachineAliasArn", child.getStateMachineAliasArn()); + } + cause.put("StateMachineArn", child.getStateMachineArn()); + if (child.getStateMachineVersionArn() != null) { + cause.put("StateMachineVersionArn", child.getStateMachineVersionArn()); + } + cause.put("Status", child.getStatus()); + if (child.getStopDate() != null) { + cause.put("StopDate", Math.round(child.getStopDate() * 1000)); + } + return cause.toString(); + } + /** * Optimized ECS RunTask integration. Step Functions passes PascalCase parameters * ({@code Cluster}, {@code TaskDefinition}, {@code Overrides.ContainerOverrides}, …) diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedSyncFailureTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedSyncFailureTest.java new file mode 100644 index 0000000000..3b5b3b3e40 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedSyncFailureTest.java @@ -0,0 +1,293 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ecs.EcsJsonHandler; +import io.github.hectorvent.floci.services.ecs.EcsService; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler; +import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; +import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.scheduler.SchedulerController; +import io.github.hectorvent.floci.services.scheduler.SchedulerService; +import io.github.hectorvent.floci.services.sns.SnsJsonHandler; +import io.github.hectorvent.floci.services.sqs.SqsJsonHandler; +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 jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.time.Clock; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * A {@code states:startExecution.sync} or {@code .sync:2} Task whose child ends other than + * SUCCEEDED fails with {@code States.TaskFailed}, whatever the child's own error, and carries the + * child's DescribeExecution response as its cause. Measured on AWS (ap-northeast-1, 2026-09-29) for + * six endings under both modes: FAILED with a custom error with and without a cause, FAILED with + * {@code States.Timeout} from a Task's own TimeoutSeconds, FAILED with {@code States.TaskFailed}, + * TIMED_OUT, and ABORTED by a StopExecution carrying an error and a cause. + */ +class AslExecutorNestedSyncFailureTest { + + private static final String REGION = "us-east-2"; + private static final String ACCOUNT = "000000000000"; + private static final String CHILD_SM_ARN = + "arn:aws:states:%s:%s:stateMachine:child".formatted(REGION, ACCOUNT); + private static final String CHILD_ARN = + "arn:aws:states:%s:%s:execution:child:run-1".formatted(REGION, ACCOUNT); + private static final String PARENT_ARN = + "arn:aws:states:%s:%s:execution:parent:parent-run".formatted(REGION, ACCOUNT); + private static final String CHILD_TAIL = """ + "ExecutionArn":"%s","Input":"{\\"k\\":1}","InputDetails":{"Included":true},"Name":"run-1",\ + "RedriveCount":0,"RedriveStatus":"REDRIVABLE","StartDate":1790676767025,\ + "StateMachineArn":"%s",""".formatted(CHILD_ARN, CHILD_SM_ARN); + + private final ObjectMapper objectMapper = new ObjectMapper(); + private StepFunctionsService sfnService; + private List history; + + @BeforeEach + void setUp() { + sfnService = mock(StepFunctionsService.class); + when(sfnService.startExecution(any(), any(), any(), any())).thenReturn(child("RUNNING", null, null)); + Execution parent = new Execution(); + parent.setExecutionArn(PARENT_ARN); + parent.setStatus("RUNNING"); + when(sfnService.describeExecution(PARENT_ARN)).thenReturn(parent); + } + + static Stream childEndings() { + List endings = List.of( + Arguments.of("FAILED", "Boom", "custom cause", + "{\"Cause\":\"custom cause\",\"Error\":\"Boom\"," + CHILD_TAIL + + "\"Status\":\"FAILED\",\"StopDate\":1790676767071}"), + Arguments.of("FAILED", "Boom", null, + "{\"Error\":\"Boom\"," + CHILD_TAIL + "\"Status\":\"FAILED\",\"StopDate\":1790676767071}"), + Arguments.of("FAILED", "States.Timeout", null, + "{\"Error\":\"States.Timeout\"," + CHILD_TAIL + + "\"Status\":\"FAILED\",\"StopDate\":1790676767071}"), + Arguments.of("FAILED", "States.TaskFailed", "child says TaskFailed", + "{\"Cause\":\"child says TaskFailed\",\"Error\":\"States.TaskFailed\"," + CHILD_TAIL + + "\"Status\":\"FAILED\",\"StopDate\":1790676767071}"), + Arguments.of("TIMED_OUT", null, null, + "{" + CHILD_TAIL + "\"Status\":\"TIMED_OUT\",\"StopDate\":1790676767071}"), + Arguments.of("ABORTED", "ManualStop", "stopped by test", + "{\"Cause\":\"stopped by test\",\"Error\":\"ManualStop\"," + CHILD_TAIL + + "\"Status\":\"ABORTED\",\"StopDate\":1790676767071}")); + return Stream.of(".sync", ".sync:2").flatMap(mode -> endings.stream().map(ending -> { + Object[] values = ending.get(); + return Arguments.of(mode, values[0], values[1], values[2], values[3]); + })); + } + + @ParameterizedTest(name = "{0} child {1} {2}") + @MethodSource("childEndings") + void aChildThatDoesNotSucceedFailsTheTaskWithStatesTaskFailedAndItsDescription( + String mode, String status, String error, String cause, String expectedCause) { + when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child(status, error, cause)); + + Execution execution = run(mode, ""); + + assertEquals("FAILED", execution.getStatus()); + assertEquals("States.TaskFailed", execution.getError()); + assertEquals(expectedCause, execution.getCause()); + HistoryEvent taskFailed = history.stream().filter(event -> "TaskFailed".equals(event.getType())) + .findFirst().orElseThrow(() -> new AssertionError("no TaskFailed in " + history)); + assertEquals("States.TaskFailed", taskFailed.getDetails().get("error")); + assertEquals(expectedCause, taskFailed.getDetails().get("cause")); + } + + @Test + void aChildStartedThroughAnAliasCarriesTheAliasAndVersionInTheirAlphabeticalPlaces() { + Execution failed = child("FAILED", "Boom", null); + failed.setStateMachineAliasArn(CHILD_SM_ARN + ":live"); + failed.setStateMachineVersionArn(CHILD_SM_ARN + ":1"); + when(sfnService.describeExecution(CHILD_ARN)).thenReturn(failed); + + Execution execution = run(".sync:2", ""); + + // Measured on AWS: an alias carries both ARNs, between StartDate and Status. + assertEquals("{\"Error\":\"Boom\"," + CHILD_TAIL.replace( + "\"StateMachineArn\":", "\"StateMachineAliasArn\":\"" + CHILD_SM_ARN + ":live\",\"StateMachineArn\":") + + "\"StateMachineVersionArn\":\"" + CHILD_SM_ARN + ":1\"," + + "\"Status\":\"FAILED\",\"StopDate\":1790676767071}", + execution.getCause()); + } + + @Test + void aChildStartedThroughAVersionCarriesTheVersionOnly() { + Execution failed = child("FAILED", "Boom", null); + failed.setStateMachineVersionArn(CHILD_SM_ARN + ":1"); + when(sfnService.describeExecution(CHILD_ARN)).thenReturn(failed); + + Execution execution = run(".sync", ""); + + assertEquals("{\"Error\":\"Boom\"," + CHILD_TAIL + + "\"StateMachineVersionArn\":\"" + CHILD_SM_ARN + ":1\"," + + "\"Status\":\"FAILED\",\"StopDate\":1790676767071}", + execution.getCause()); + } + + @Test + void aTerminalStatusIsReadTogetherWithTheFieldsWrittenBeforeItsMonitorIsReleased() throws Exception { + // The child's worker writes its terminal fields under the execution's monitor. This writer + // publishes the status first and holds the monitor for 200 ms before writing the rest, and + // the parent's first read of the child lands inside that window, so a reader that skipped + // the monitor would build the cause from a half-written child. + Execution live = child("RUNNING", null, null); + CountDownLatch statusWritten = new CountDownLatch(1); + Thread writer = new Thread(() -> { + synchronized (live) { + live.setStatus("FAILED"); + statusWritten.countDown(); + try { + Thread.sleep(200); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + live.setError("Boom"); + live.setCause("custom cause"); + live.setStopDate(1790676767.071); + } + }); + when(sfnService.describeExecution(CHILD_ARN)).thenAnswer(invocation -> { + if (writer.getState() == Thread.State.NEW) { + writer.start(); + statusWritten.await(); + } + return live; + }); + + Execution execution = run(".sync", ""); + writer.join(); + + assertEquals("{\"Cause\":\"custom cause\",\"Error\":\"Boom\"," + CHILD_TAIL + + "\"Status\":\"FAILED\",\"StopDate\":1790676767071}", execution.getCause()); + } + + @Test + void aCatchOnTheChildsOwnErrorDoesNotFireButOneOnStatesTaskFailedDoes() throws Exception { + when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child("FAILED", "Boom", "custom cause")); + + Execution execution = run(".sync:2", """ + "Catch": [ + {"ErrorEquals": ["Boom"], "Next": "CaughtByName"}, + {"ErrorEquals": ["States.TaskFailed"], "Next": "CaughtAsTaskFailed"} + ],"""); + + assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause()); + assertEquals("CaughtAsTaskFailed", objectMapper.readTree(execution.getOutput()).path("caughtBy").asText()); + } + + @Test + void aChildThatTimedOutIsNotCaughtUnderStatesTimeout() throws Exception { + when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child("FAILED", "States.Timeout", null)); + + Execution execution = run(".sync", """ + "Catch": [ + {"ErrorEquals": ["States.Timeout"], "Next": "CaughtByName"}, + {"ErrorEquals": ["States.ALL"], "Next": "CaughtAsTaskFailed"} + ],"""); + + assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause()); + assertEquals("CaughtAsTaskFailed", objectMapper.readTree(execution.getOutput()).path("caughtBy").asText()); + } + + private static Execution child(String status, String error, String cause) { + Execution current = new Execution(); + current.setExecutionArn(CHILD_ARN); + current.setStateMachineArn(CHILD_SM_ARN); + current.setName("run-1"); + current.setInput("{\"k\":1}"); + current.setStatus(status); + current.setError(error); + current.setCause(cause); + current.setStartDate(1790676767.025); + if (!"RUNNING".equals(status)) { + current.setStopDate(1790676767.071); + } + return current; + } + + @SuppressWarnings("unchecked") + private AslExecutor newExecutor() { + Instance instance = mock(Instance.class); + when(instance.get()).thenReturn(sfnService); + return new AslExecutor( + mock(LambdaExecutorService.class), + mock(LambdaFunctionStore.class), + mock(DynamoDbFacade.class), + mock(DynamoDbJsonHandler.class), + mock(SqsJsonHandler.class), mock(SnsJsonHandler.class), + mock(CloudFormationQueryHandler.class), + mock(Ec2Service.class), + mock(S3Service.class), + mock(EcsService.class), + mock(EcsJsonHandler.class), + mock(EventBridgeHandler.class), + mock(SchedulerService.class), + mock(SchedulerController.class), + objectMapper, + new JsonataEvaluator(objectMapper), + instance, + mock(EmulatorConfig.class), + null, + null, + Clock.systemUTC(), + nanos -> { }, + null); + } + + private Execution run(String mode, String catcher) { + String definition = """ + { + "StartAt": "Child", + "States": { + "Child": { + "Type": "Task", + "Resource": "arn:aws:states:::states:startExecution%s", + %s + "Parameters": { "StateMachineArn": "%s", "Input": {"k": 1} }, + "End": true + }, + "CaughtByName": { "Type": "Pass", "Result": {"caughtBy": "CaughtByName"}, "End": true }, + "CaughtAsTaskFailed": { "Type": "Pass", "Result": {"caughtBy": "CaughtAsTaskFailed"}, "End": true } + } + } + """.formatted(mode, catcher, CHILD_SM_ARN); + + StateMachine stateMachine = new StateMachine(); + stateMachine.setName("parent"); + stateMachine.setStateMachineArn("arn:aws:states:%s:%s:stateMachine:parent".formatted(REGION, ACCOUNT)); + stateMachine.setRoleArn("arn:aws:iam::%s:role/test-role".formatted(ACCOUNT)); + stateMachine.setDefinition(definition); + + Execution execution = new Execution(); + execution.setName("parent-run"); + execution.setExecutionArn(PARENT_ARN); + execution.setStateMachineArn(stateMachine.getStateMachineArn()); + execution.setInput("{}"); + + history = new ArrayList<>(); + newExecutor().executeSync(stateMachine, execution, history, (updated, events) -> { }); + return execution; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNestedSyncFailureIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNestedSyncFailureIntegrationTest.java new file mode 100644 index 0000000000..69ffc51241 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNestedSyncFailureIntegrationTest.java @@ -0,0 +1,172 @@ +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.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.Iterator; +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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * A {@code states:startExecution.sync} Task whose child does not succeed fails with + * {@code States.TaskFailed} and the child's DescribeExecution response as its cause, whatever the + * child's own error, the way AWS reports it (measured in ap-northeast-1 on 2026-09-29). + */ +@QuarkusTest +class StepFunctionsNestedSyncFailureIntegrationTest { + + private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0"; + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role"; + private static final ObjectMapper mapper = new ObjectMapper(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aFailedChildReachesTheParentAsStatesTaskFailedWithTheChildsDescription() throws Exception { + String childArn = createStateMachine("nested-failure-child", """ + {"StartAt": "F", "States": {"F": {"Type": "Fail", "Error": "Boom", "Cause": "custom cause"}}} + """); + String parentArn = createStateMachine("nested-failure-parent", """ + { + "StartAt": "RunChild", + "States": { + "RunChild": { + "Type": "Task", + "Resource": "arn:aws:states:::states:startExecution.sync:2", + "Parameters": {"StateMachineArn": "%s", "Input": {"k": 1}}, + "End": true + } + } + } + """.formatted(childArn)); + + Response failed = waitForTerminalExecution(startExecution(parentArn, "{}")); + + assertEquals("FAILED", failed.jsonPath().getString("status"), failed.body().asString()); + assertEquals("States.TaskFailed", failed.jsonPath().getString("error")); + JsonNode cause = mapper.readTree(failed.jsonPath().getString("cause")); + assertEquals(List.of("Cause", "Error", "ExecutionArn", "Input", "InputDetails", "Name", "RedriveCount", + "RedriveStatus", "StartDate", "StateMachineArn", "Status", "StopDate"), fieldNames(cause)); + assertEquals("custom cause", cause.path("Cause").asText()); + assertEquals("Boom", cause.path("Error").asText()); + assertEquals("{\"k\":1}", cause.path("Input").asText()); + assertEquals(childArn, cause.path("StateMachineArn").asText()); + assertEquals("FAILED", cause.path("Status").asText()); + assertTrue(cause.path("StartDate").isIntegralNumber(), "epoch milliseconds: " + cause); + Response child = describeExecution(cause.path("ExecutionArn").asText()); + assertEquals("Boom", child.jsonPath().getString("error"), child.body().asString()); + } + + @Test + void aTimedOutChildIsCaughtUnderStatesTaskFailed() throws Exception { + String childArn = createStateMachine("nested-timeout-child", """ + {"StartAt": "W", "TimeoutSeconds": 1, "States": {"W": {"Type": "Wait", "Seconds": 5, "End": true}}} + """); + String parentArn = createStateMachine("nested-timeout-parent", """ + { + "StartAt": "RunChild", + "States": { + "RunChild": { + "Type": "Task", + "Resource": "arn:aws:states:::states:startExecution.sync", + "Parameters": {"StateMachineArn": "%s"}, + "Catch": [{"ErrorEquals": ["States.TaskFailed"], "Next": "Handled"}], + "End": true + }, + "Handled": {"Type": "Pass", "End": true} + } + } + """.formatted(childArn)); + + Response done = waitForTerminalExecution(startExecution(parentArn, "{}")); + + assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.body().asString()); + JsonNode output = mapper.readTree(done.jsonPath().getString("output")); + assertEquals("States.TaskFailed", output.path("Error").asText()); + JsonNode cause = mapper.readTree(output.path("Cause").asText()); + assertEquals("TIMED_OUT", cause.path("Status").asText()); + assertFalse(cause.has("Error"), "a TIMED_OUT child has no error: " + cause); + } + + private static List fieldNames(JsonNode node) { + List names = new ArrayList<>(); + Iterator it = node.fieldNames(); + while (it.hasNext()) { + names.add(it.next()); + } + return names; + } + + private static String createStateMachine(String name, String definition) { + Response resp = given() + .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"name": "%s-%d", "definition": %s, "roleArn": "%s"} + """.formatted(name, System.currentTimeMillis(), quote(definition), ROLE_ARN)) + .when() + .post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("stateMachineArn"); + } + + private static String startExecution(String smArn, String input) { + Response resp = given() + .header("X-Amz-Target", "AWSStepFunctions.StartExecution") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"stateMachineArn": "%s", "input": %s} + """.formatted(smArn, quote(input))) + .when() + .post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("executionArn"); + } + + private static Response describeExecution(String execArn) { + return given() + .header("X-Amz-Target", "AWSStepFunctions.DescribeExecution") + .contentType(SFN_CONTENT_TYPE) + .body(""" + {"executionArn": "%s"} + """.formatted(execArn)) + .when() + .post("/"); + } + + private static Response waitForTerminalExecution(String execArn) throws InterruptedException { + for (int poll = 0; poll < 200; poll++) { + Response resp = describeExecution(execArn); + if (!"RUNNING".equals(resp.jsonPath().getString("status"))) { + return resp; + } + Thread.sleep(100); + } + fail("Execution " + execArn + " was still RUNNING after 20 seconds"); + return null; + } + + private static String quote(String raw) { + return "\"" + raw + .replace("\\", "\\\\") + .replace("\"", "\\\"") + .replace("\n", "\\n") + .replace("\r", "\\r") + .replace("\t", "\\t") + + "\""; + } +}