Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(stepfunctions): add aws-sdk CloudFormation/EC2 and S3 PutObject integrations (#1556)

Alex Banna677dfd6a1612
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 40da0727a4..5175ee2461 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
@@ -3,8 +3,12 @@ package io.github.hectorvent.floci.services.stepfunctions;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
+import io.github.hectorvent.floci.services.ec2.Ec2Service;
+import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;
import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
@@ -22,9 +26,13 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
+import jakarta.ws.rs.core.MultivaluedHashMap;
+import jakarta.ws.rs.core.MultivaluedMap;
import org.jboss.logging.Logger;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -51,6 +59,9 @@ public class AslExecutor {
private final DynamoDbService dynamoDbService;
private final DynamoDbJsonHandler dynamoDbJsonHandler;
private final SqsJsonHandler sqsJsonHandler;
+ private final CloudFormationQueryHandler cloudFormationHandler;
+ private final Ec2Service ec2Service;
+ private final S3Service s3Service;
private final ObjectMapper objectMapper;
private final JsonataEvaluator jsonataEvaluator;
private final Instance<StepFunctionsService> sfnService;
@@ -63,7 +74,8 @@ public class AslExecutor {
@Inject
public AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore,
DynamoDbService dynamoDbService, DynamoDbJsonHandler dynamoDbJsonHandler,
- SqsJsonHandler sqsJsonHandler,
+ SqsJsonHandler sqsJsonHandler, CloudFormationQueryHandler cloudFormationHandler,
+ Ec2Service ec2Service, S3Service s3Service,
ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,
Instance<StepFunctionsService> sfnService) {
this.lambdaExecutor = lambdaExecutor;
@@ -71,6 +83,9 @@ public class AslExecutor {
this.dynamoDbService = dynamoDbService;
this.dynamoDbJsonHandler = dynamoDbJsonHandler;
this.sqsJsonHandler = sqsJsonHandler;
+ this.cloudFormationHandler = cloudFormationHandler;
+ this.ec2Service = ec2Service;
+ this.s3Service = s3Service;
this.objectMapper = objectMapper;
this.jsonataEvaluator = jsonataEvaluator;
this.sfnService = sfnService;
@@ -359,6 +374,24 @@ public class AslExecutor {
return invokeAwsSdkSqsSendMessage(input, region);
}
+ // AWS SDK service integration: CloudFormation (query protocol → JSON)
+ if (resource.startsWith("arn:aws:states:::aws-sdk:cloudformation:")) {
+ String action = resource.substring("arn:aws:states:::aws-sdk:cloudformation:".length());
+ String region = extractRegionFromArn(sm.getStateMachineArn());
+ return invokeAwsSdkCloudFormation(action, input, region);
+ }
+
+ // AWS SDK service integration: EC2 DescribeRegions
+ if (resource.equals("arn:aws:states:::aws-sdk:ec2:describeRegions")) {
+ return invokeAwsSdkEc2DescribeRegions();
+ }
+
+ // S3 PutObject — optimized and aws-sdk integrations
+ if (resource.equals("arn:aws:states:::s3:putObject")
+ || resource.equals("arn:aws:states:::aws-sdk:s3:putObject")) {
+ return invokeS3PutObject(input);
+ }
+
// Nested state machine integration
if (resource.startsWith("arn:aws:states:::states:startExecution")) {
String mode = resource.substring("arn:aws:states:::states:startExecution".length());
@@ -381,6 +414,108 @@ public class AslExecutor {
"Unsupported resource: " + resource);
}
+ /**
+ * AWS SDK integration for CloudFormation (a Query-protocol service): flattens the task input to
+ * Query parameters, dispatches to the CloudFormation handler, and converts the XML response back
+ * to the JSON shape the {@code aws-sdk:*} integration returns.
+ */
+ private JsonNode invokeAwsSdkCloudFormation(String camelAction, JsonNode input, String region) {
+ String pascalAction = capitalizeFirst(camelAction);
+ MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
+ flattenQueryParams(input, "", params);
+
+ jakarta.ws.rs.core.Response response;
+ try {
+ response = cloudFormationHandler.handle(pascalAction, params, region);
+ } catch (AwsException e) {
+ throw new FailStateException("CloudFormation." + e.getErrorCode(), e.getMessage());
+ } catch (Exception e) {
+ throw new FailStateException("CloudFormation.InternalFailure",
+ e.getMessage() != null ? e.getMessage() : "CloudFormation error");
+ }
+
+ String xml = response.getEntity() == null ? "" : response.getEntity().toString();
+ if (response.getStatus() >= 400) {
+ String code = XmlParser.extractFirst(xml, "Code", "ServiceException");
+ String message = XmlParser.extractFirst(xml, "Message", "CloudFormation request failed");
+ throw new FailStateException("CloudFormation." + code, message);
+ }
+ try {
+ return QueryXmlToJson.convert(xml, pascalAction + "Result", objectMapper);
+ } catch (Exception e) {
+ throw new FailStateException("CloudFormation.InternalFailure",
+ "Failed to parse CloudFormation response: " + e.getMessage());
+ }
+ }
+
+ private JsonNode invokeAwsSdkEc2DescribeRegions() {
+ ObjectNode result = objectMapper.createObjectNode();
+ ArrayNode regions = objectMapper.createArrayNode();
+ for (String name : ec2Service.describeRegions()) {
+ ObjectNode region = objectMapper.createObjectNode();
+ region.put("RegionName", name);
+ region.put("Endpoint", "ec2." + name + ".amazonaws.com");
+ region.put("OptInStatus", "opt-in-not-required");
+ regions.add(region);
+ }
+ result.set("Regions", regions);
+ return result;
+ }
+
+ private JsonNode invokeS3PutObject(JsonNode input) {
+ String bucket = input.path("Bucket").asText(null);
+ String key = input.path("Key").asText(null);
+ if (bucket == null || key == null) {
+ throw new FailStateException("S3.InvalidRequest", "Bucket and Key are required");
+ }
+ JsonNode body = input.path("Body");
+ byte[] data;
+ if (body.isMissingNode() || body.isNull()) {
+ data = new byte[0];
+ } else if (body.isValueNode()) {
+ data = body.asText().getBytes(StandardCharsets.UTF_8);
+ } else {
+ data = body.toString().getBytes(StandardCharsets.UTF_8);
+ }
+ try {
+ var stored = s3Service.putObject(bucket, key, data, "application/octet-stream", new HashMap<>());
+ ObjectNode result = objectMapper.createObjectNode();
+ if (stored != null && stored.getETag() != null) {
+ result.put("ETag", stored.getETag());
+ }
+ return result;
+ } catch (AwsException e) {
+ throw new FailStateException("S3." + e.getErrorCode(), e.getMessage());
+ }
+ }
+
+ /** Flattens a JSON object into AWS Query parameters (lists → {@code key.member.N}). */
+ private void flattenQueryParams(JsonNode node, String prefix, MultivaluedMap<String, String> out) {
+ if (node == null || node.isNull() || node.isMissingNode()) {
+ return;
+ }
+ if (node.isObject()) {
+ Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
+ while (fields.hasNext()) {
+ Map.Entry<String, JsonNode> entry = fields.next();
+ String key = prefix.isEmpty() ? entry.getKey() : prefix + "." + entry.getKey();
+ flattenQueryParams(entry.getValue(), key, out);
+ }
+ } else if (node.isArray()) {
+ int i = 1;
+ for (JsonNode item : node) {
+ flattenQueryParams(item, prefix + ".member." + i, out);
+ i++;
+ }
+ } else {
+ out.add(prefix, node.asText());
+ }
+ }
+
+ private static String capitalizeFirst(String s) {
+ return s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1);
+ }
+
private JsonNode invokeNestedStateMachine(String mode, JsonNode input, String region) throws Exception {
String smArn = input.path("StateMachineArn").asText(null);
if (smArn == null || smArn.isBlank()) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/QueryXmlToJson.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/QueryXmlToJson.java
new file mode 100644
index 0000000000..57c83e34e6
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/QueryXmlToJson.java
@@ -0,0 +1,125 @@
+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 com.fasterxml.jackson.databind.node.ObjectNode;
+import com.fasterxml.jackson.databind.node.TextNode;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Converts an AWS Query-protocol XML response into the JSON shape that the Step Functions
+ * {@code aws-sdk:*} service integration returns: the contents of the {@code <ActionResult>} element
+ * as a JSON object, with {@code <member>} lists unwrapped into arrays and repeated elements
+ * collapsed to arrays. When no {@code <ActionResult>} wrapper is present the document element's
+ * children are converted (skipping {@code ResponseMetadata}/{@code requestId}).
+ *
+ * <p>A general DOM walk is used deliberately: the response shape varies per action (scalar,
+ * nested object, member list), so element-by-element extraction is not sufficient.
+ */
+final class QueryXmlToJson {
+
+ private QueryXmlToJson() {
+ }
+
+ static JsonNode convert(String xml, String resultElementName, ObjectMapper mapper) throws Exception {
+ Document doc = parse(xml);
+ Element wrapper = firstByLocalName(doc.getDocumentElement(), resultElementName);
+ Element scope = wrapper != null ? wrapper : doc.getDocumentElement();
+ ObjectNode obj = mapper.createObjectNode();
+ for (Element child : childElements(scope)) {
+ String name = localName(child);
+ if (wrapper == null && (name.equals("ResponseMetadata") || name.equalsIgnoreCase("requestId"))) {
+ continue;
+ }
+ merge(obj, name, toJson(child, mapper), mapper);
+ }
+ return obj;
+ }
+
+ private static JsonNode toJson(Element el, ObjectMapper mapper) {
+ List<Element> kids = childElements(el);
+ if (kids.isEmpty()) {
+ return TextNode.valueOf(el.getTextContent());
+ }
+ boolean allMembers = kids.stream().allMatch(k -> "member".equals(localName(k)));
+ if (allMembers) {
+ ArrayNode arr = mapper.createArrayNode();
+ for (Element k : kids) {
+ arr.add(toJson(k, mapper));
+ }
+ return arr;
+ }
+ ObjectNode obj = mapper.createObjectNode();
+ for (Element k : kids) {
+ merge(obj, localName(k), toJson(k, mapper), mapper);
+ }
+ return obj;
+ }
+
+ private static void merge(ObjectNode obj, String name, JsonNode value, ObjectMapper mapper) {
+ JsonNode existing = obj.get(name);
+ if (existing == null) {
+ obj.set(name, value);
+ return;
+ }
+ if (existing.isArray()) {
+ ((ArrayNode) existing).add(value);
+ return;
+ }
+ ArrayNode arr = mapper.createArrayNode();
+ arr.add(existing);
+ arr.add(value);
+ obj.set(name, arr);
+ }
+
+ private static Element firstByLocalName(Element root, String name) {
+ if (localName(root).equals(name)) {
+ return root;
+ }
+ NodeList nl = root.getElementsByTagName("*");
+ for (int i = 0; i < nl.getLength(); i++) {
+ if (nl.item(i) instanceof Element e && localName(e).equals(name)) {
+ return e;
+ }
+ }
+ return null;
+ }
+
+ private static List<Element> childElements(Element el) {
+ List<Element> out = new ArrayList<>();
+ NodeList nl = el.getChildNodes();
+ for (int i = 0; i < nl.getLength(); i++) {
+ Node n = nl.item(i);
+ if (n instanceof Element e) {
+ out.add(e);
+ }
+ }
+ return out;
+ }
+
+ private static String localName(Element e) {
+ return e.getLocalName() != null ? e.getLocalName() : e.getTagName();
+ }
+
+ private static Document parse(String xml) throws Exception {
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+ factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
+ factory.setExpandEntityReferences(false);
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ return builder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java
index 6bfc305128..d8792ab37b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java
@@ -74,6 +74,9 @@ class AslExecutorCatchTest {
mock(DynamoDbService.class),
mock(DynamoDbJsonHandler.class),
mock(SqsJsonHandler.class),
+ mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class),
+ mock(io.github.hectorvent.floci.services.ec2.Ec2Service.class),
+ mock(io.github.hectorvent.floci.services.s3.S3Service.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class));
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/QueryXmlToJsonTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/QueryXmlToJsonTest.java
new file mode 100644
index 0000000000..3c909b50a4
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/QueryXmlToJsonTest.java
@@ -0,0 +1,63 @@
+package io.github.hectorvent.floci.services.stepfunctions;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class QueryXmlToJsonTest {
+
+ private static final String NS = "http://cloudformation.amazonaws.com/doc/2010-05-15/";
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @Test
+ void scalarResultField() throws Exception {
+ String xml = "<CreateStackSetResponse xmlns=\"" + NS + "\">"
+ + "<CreateStackSetResult><StackSetId>my-set:abc-123</StackSetId></CreateStackSetResult>"
+ + "<ResponseMetadata><RequestId>r1</RequestId></ResponseMetadata></CreateStackSetResponse>";
+ JsonNode json = QueryXmlToJson.convert(xml, "CreateStackSetResult", mapper);
+ assertEquals("my-set:abc-123", json.path("StackSetId").asText());
+ }
+
+ @Test
+ void nestedObjectWithMemberLists() throws Exception {
+ String xml = "<DescribeStackSetResponse xmlns=\"" + NS + "\"><DescribeStackSetResult><StackSet>"
+ + "<StackSetName>s</StackSetName><Status>ACTIVE</Status>"
+ + "<Capabilities><member>CAPABILITY_IAM</member><member>CAPABILITY_NAMED_IAM</member></Capabilities>"
+ + "<Parameters><member><ParameterKey>K</ParameterKey><ParameterValue>V</ParameterValue></member></Parameters>"
+ + "</StackSet></DescribeStackSetResult></DescribeStackSetResponse>";
+ JsonNode json = QueryXmlToJson.convert(xml, "DescribeStackSetResult", mapper);
+ JsonNode ss = json.path("StackSet");
+ assertEquals("ACTIVE", ss.path("Status").asText());
+ assertTrue(ss.path("Capabilities").isArray());
+ assertEquals(2, ss.path("Capabilities").size());
+ assertEquals("CAPABILITY_IAM", ss.path("Capabilities").get(0).asText());
+ assertTrue(ss.path("Parameters").isArray());
+ assertEquals("K", ss.path("Parameters").get(0).path("ParameterKey").asText());
+ assertEquals("V", ss.path("Parameters").get(0).path("ParameterValue").asText());
+ }
+
+ @Test
+ void summariesMemberListBecomesArray() throws Exception {
+ String xml = "<ListStackInstancesResponse xmlns=\"" + NS + "\"><ListStackInstancesResult><Summaries>"
+ + "<member><Account>111111111111</Account><Region>us-east-1</Region></member>"
+ + "<member><Account>222222222222</Account><Region>us-east-1</Region></member>"
+ + "</Summaries></ListStackInstancesResult></ListStackInstancesResponse>";
+ JsonNode json = QueryXmlToJson.convert(xml, "ListStackInstancesResult", mapper);
+ assertTrue(json.path("Summaries").isArray());
+ assertEquals(2, json.path("Summaries").size());
+ assertEquals("111111111111", json.path("Summaries").get(0).path("Account").asText());
+ assertEquals("us-east-1", json.path("Summaries").get(1).path("Region").asText());
+ }
+
+ @Test
+ void emptyResultWhenWrapperAbsent() throws Exception {
+ String xml = "<DeleteStackSetResponse xmlns=\"" + NS + "\">"
+ + "<ResponseMetadata><RequestId>r</RequestId></ResponseMetadata></DeleteStackSetResponse>";
+ JsonNode json = QueryXmlToJson.convert(xml, "DeleteStackSetResult", mapper);
+ assertTrue(json.isObject());
+ assertTrue(json.isEmpty());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsAwsSdkQueryIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsAwsSdkQueryIntegrationTest.java
new file mode 100644
index 0000000000..a019236032
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsAwsSdkQueryIntegrationTest.java
@@ -0,0 +1,136 @@
+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 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;
+
+/**
+ * Exercises the Step Functions {@code aws-sdk:*} / optimized service integrations added for query and
+ * REST services: CloudFormation (query protocol bridged to JSON), EC2 DescribeRegions, and S3
+ * PutObject. These are the integrations DPS-style provisioning state machines rely on.
+ */
+@QuarkusTest
+class StepFunctionsAwsSdkQueryIntegrationTest {
+
+ 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 ec2DescribeRegions_returnsRegionsArray() throws Exception {
+ String output = execute("ec2-regions", "arn:aws:states:::aws-sdk:ec2:describeRegions", "{}");
+ JsonNode result = mapper.readTree(output);
+ assertTrue(result.path("Regions").isArray(), "Regions should be an array");
+ assertFalse(result.path("Regions").isEmpty(), "Regions should be non-empty");
+ assertFalse(result.path("Regions").get(0).path("RegionName").asText().isBlank());
+ }
+
+ @Test
+ void cloudFormation_validateTemplate_dispatchesAndParses() throws Exception {
+ String params = """
+ {"TemplateBody": "{\\"Resources\\":{\\"Q\\":{\\"Type\\":\\"AWS::SQS::Queue\\"}}}"}
+ """;
+ // A successful execution proves the query-protocol bridge dispatched to CloudFormation and
+ // converted the XML response without error.
+ String output = execute("cfn-validate", "arn:aws:states:::aws-sdk:cloudformation:validateTemplate", params);
+ assertTrue(mapper.readTree(output).isObject());
+ }
+
+ @Test
+ void s3PutObject_storesObject() throws Exception {
+ String bucket = "sfn-s3-put-" + System.currentTimeMillis();
+ given().when().put("/" + bucket).then().statusCode(200);
+
+ String params = """
+ {"Bucket": "%s", "Key": "from-sfn.txt", "Body": "hello from step functions"}
+ """.formatted(bucket);
+ String output = execute("s3-put", "arn:aws:states:::s3:putObject", params);
+ assertTrue(mapper.readTree(output).has("ETag"), "PutObject result should carry an ETag");
+
+ // Confirm the object is actually retrievable.
+ given().when().get("/" + bucket + "/from-sfn.txt")
+ .then().statusCode(200).body(org.hamcrest.Matchers.containsString("hello from step functions"));
+ }
+
+ // ── helpers ─────────────────────────────────────────────────────────────
+
+ private String execute(String nameSuffix, String resource, String parameters) throws Exception {
+ String definition = """
+ {"StartAt":"Action","States":{"Action":{"Type":"Task","Resource":"%s","Parameters":%s,"End":true}}}
+ """.formatted(resource, parameters.strip());
+ String smArn = createStateMachine(nameSuffix + "-" + System.currentTimeMillis(), definition);
+ String execArn = startExecution(smArn);
+ return waitForExecution(execArn);
+ }
+
+ private String createStateMachine(String name, String definition) {
+ Response resp = given()
+ .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
+ .contentType(SFN_CONTENT_TYPE)
+ .body("""
+ {"name": "%s", "definition": %s, "roleArn": "%s"}
+ """.formatted(name, quote(definition), ROLE_ARN))
+ .when().post("/");
+ resp.then().statusCode(200);
+ return resp.jsonPath().getString("stateMachineArn");
+ }
+
+ private String startExecution(String smArn) {
+ Response resp = given()
+ .header("X-Amz-Target", "AWSStepFunctions.StartExecution")
+ .contentType(SFN_CONTENT_TYPE)
+ .body("""
+ {"stateMachineArn": "%s", "input": "{}"}
+ """.formatted(smArn))
+ .when().post("/");
+ resp.then().statusCode(200);
+ return resp.jsonPath().getString("executionArn");
+ }
+
+ private String waitForExecution(String execArn) throws InterruptedException {
+ for (int i = 0; i < 50; i++) {
+ Response resp = given()
+ .header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
+ .contentType(SFN_CONTENT_TYPE)
+ .body("""
+ {"executionArn": "%s"}
+ """.formatted(execArn))
+ .when().post("/");
+ String status = resp.jsonPath().getString("status");
+ if ("SUCCEEDED".equals(status)) {
+ return resp.jsonPath().getString("output");
+ }
+ if ("FAILED".equals(status) || "ABORTED".equals(status) || "TIMED_OUT".equals(status)) {
+ fail("Execution " + status + ": " + resp.body().asString());
+ }
+ Thread.sleep(100);
+ }
+ fail("Execution did not complete within timeout");
+ return null;
+ }
+
+ private static String quote(String raw) {
+ return "\"" + raw
+ .replace("\\", "\\\\")
+ .replace("\"", "\\\"")
+ .replace("\n", "\\n")
+ .replace("\r", "\\r")
+ .replace("\t", "\\t")
+ + "\"";
+ }
+}