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 780409afeb..f40a76ff07 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 @@ -22,6 +22,7 @@ import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine; 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.MissingNode; import com.fasterxml.jackson.databind.node.NullNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.quarkus.arc.Arc; @@ -288,11 +289,14 @@ public class AslExecutor { JsonNode effectiveInput = applyInputPath(stateDef, input); - JsonNode result; + // Pass states transform their input through Parameters (with intrinsics), then a static + // Result overrides if present. + JsonNode result = effectiveInput; + if (stateDef.has("Parameters")) { + result = resolveParameters(stateDef.get("Parameters"), effectiveInput, context); + } if (stateDef.has("Result")) { result = stateDef.get("Result"); - } else { - result = effectiveInput; } JsonNode output = mergeResult(stateDef, input, result); @@ -343,6 +347,10 @@ public class AslExecutor { JsonNode output = applyJsonataOutput(stateDef, input, taskResult, context); return new StateResult(output, stateDef.path("Next").asText(null)); } else { + // ResultSelector transforms the raw result before ResultPath merges it into the state input. + if (stateDef.has("ResultSelector")) { + taskResult = resolveParameters(stateDef.get("ResultSelector"), taskResult, context); + } JsonNode output = mergeResult(stateDef, input, taskResult); output = applyOutputPath(stateDef, input, output); return new StateResult(output, stateDef.path("Next").asText(null)); @@ -955,7 +963,10 @@ public class AslExecutor { } if (rule.has("IsPresent")) { boolean expectPresent = rule.get("IsPresent").asBoolean(); - return !value.isMissingNode() == expectPresent; + // A field that exists with an explicit null value still counts as present in AWS, so + // resolve without collapsing missing into null: only a truly absent path is "not present". + boolean present = !resolvePathNode(variable, input).isMissingNode(); + return present == expectPresent; } if (rule.has("IsString")) { return value.isTextual() == rule.get("IsString").asBoolean(); @@ -1065,7 +1076,11 @@ public class AslExecutor { return new StateResult(output, stateDef.path("Next").asText(null)); } - JsonNode output = mergeResult(stateDef, input, results); + // ResultSelector transforms the raw branch results before ResultPath merges them in. + JsonNode selected = stateDef.has("ResultSelector") + ? resolveParameters(stateDef.get("ResultSelector"), results, context) + : results; + JsonNode output = mergeResult(stateDef, input, selected); output = applyOutputPath(stateDef, input, output); return new StateResult(output, stateDef.path("Next").asText(null)); } @@ -1127,7 +1142,11 @@ public class AslExecutor { return new StateResult(output, stateDef.path("Next").asText(null)); } - JsonNode output = mergeResult(stateDef, input, results); + // ResultSelector transforms the raw iteration results before ResultPath merges them in. + JsonNode selected = stateDef.has("ResultSelector") + ? resolveParameters(stateDef.get("ResultSelector"), results, context) + : results; + JsonNode output = mergeResult(stateDef, input, selected); output = applyOutputPath(stateDef, input, output); return new StateResult(output, stateDef.path("Next").asText(null)); } @@ -1280,7 +1299,7 @@ public class AslExecutor { return resolvePath(path, output); } - private JsonNode resolveParameters(JsonNode parameters, JsonNode input, JsonNode context) throws Exception { + JsonNode resolveParameters(JsonNode parameters, JsonNode input, JsonNode context) throws Exception { if (parameters.isObject()) { ObjectNode resolved = objectMapper.createObjectNode(); Iterator> fields = parameters.fields(); @@ -1311,39 +1330,116 @@ public class AslExecutor { } JsonNode resolvePath(String path, JsonNode root) { + JsonNode node = resolvePathNode(path, root); + // Most callers do not distinguish an absent path from an explicit null; collapse both to null. + return node.isMissingNode() ? NullNode.getInstance() : node; + } + + /** + * Resolves a reference path while preserving the distinction between an explicit null value + * (returns a {@link NullNode}) and a missing/absent path (returns a {@link MissingNode}). + * {@link #resolvePath} collapses both to null; only callers that care about presence + * (e.g. {@code IsPresent}) should use this variant. + */ + JsonNode resolvePathNode(String path, JsonNode root) { if (path == null || "$".equals(path)) { return root; } if (path.startsWith("States.")) { return evaluateIntrinsic(path, root); } - if (!path.startsWith("$.")) { - return NullNode.getInstance(); + // Support dotted ($.a.b) and root-bracket ($[*], $[0]) forms; anything else is unsupported. + if (!path.startsWith("$.") && !path.startsWith("$[")) { + return MissingNode.getInstance(); } - String[] parts = path.substring(2).split("\\."); - JsonNode current = root; - for (String part : parts) { - if (current == null || current.isMissingNode()) { - return NullNode.getInstance(); + return walkPath(splitPathSegments(path), 0, root); + } + + /** + * Splits a reference path into segments, normalizing bracket notation into dot segments so the + * AWS bracket forms reduce to the same walk as the dot forms: + * {@code $.Regions[*].RegionName} and {@code $.Regions.*.RegionName} both yield + * {@code [Regions, *, RegionName]}, and {@code $[*][*]} yields {@code [*, *]}. + * + *

Limitation: every literal dot is treated as a segment separator, so a field name that + * itself contains a dot is mis-split. AWS's bracket-quoted escape hatch ({@code $.a['b.c']}) + * is not supported; this matches the prior behavior and is rare in ASL reference paths. + */ + private String[] splitPathSegments(String path) { + String rest = path.substring(1); // drop leading '$' + rest = rest.replaceAll("\\[(\\*|\\d+)]", ".$1"); // [*] -> .*, [0] -> .0 + rest = rest.replaceAll("\\.{2,}", "."); // collapse ".[0]" -> "..0" -> ".0" + if (rest.startsWith(".")) { + rest = rest.substring(1); + } + return rest.isEmpty() ? new String[0] : rest.split("\\."); + } + + /** + * Walks the remaining path segments from {@code idx}. A {@code *} segment projects the rest of + * the path over each element of the current array and collects the results into an array + * (e.g. {@code $.Regions[*].RegionName}). When the projected suffix contains a further wildcard, + * the nested projections are flattened one level so {@code $[*][*]} flattens an array of arrays. + * A purely numeric segment indexes into an array (e.g. {@code $.items[0]}). + */ + private JsonNode walkPath(String[] parts, int idx, JsonNode current) { + for (int i = idx; i < parts.length; i++) { + if (current == null || current.isMissingNode() || current.isNull()) { + return MissingNode.getInstance(); } - // Handle array index notation like field[0] - if (part.contains("[")) { - int bracketOpen = part.indexOf('['); - int bracketClose = part.indexOf(']'); - String fieldName = part.substring(0, bracketOpen); - int index = Integer.parseInt(part.substring(bracketOpen + 1, bracketClose)); - current = current.path(fieldName).path(index); + String part = parts[i]; + if ("*".equals(part)) { + if (!current.isArray()) { + return MissingNode.getInstance(); + } + boolean flattenSub = false; + for (int j = i + 1; j < parts.length; j++) { + if ("*".equals(parts[j])) { + flattenSub = true; + break; + } + } + ArrayNode projected = objectMapper.createArrayNode(); + for (JsonNode element : current) { + JsonNode value = walkPath(parts, i + 1, element); + // Only absent matches are skipped; an explicit null is a real value and is kept, + // so $[*].field over [{"field":null},{"field":"x"}] yields [null,"x"]. + if (value == null || value.isMissingNode()) { + continue; + } + if (flattenSub && value.isArray()) { + value.forEach(projected::add); + } else { + projected.add(value); + } + } + return projected; + } + if (current.isArray() && isArrayIndex(part)) { + current = current.path(Integer.parseInt(part)); } else { current = current.path(part); } } - return current.isMissingNode() ? NullNode.getInstance() : current; + return current; + } + + private static boolean isArrayIndex(String segment) { + if (segment.isEmpty()) { + return false; + } + for (int i = 0; i < segment.length(); i++) { + if (!Character.isDigit(segment.charAt(i))) { + return false; + } + } + return true; } /** * Evaluate a JSONPath-mode intrinsic function (States.*). * Supports: States.StringToJson, States.JsonToString, States.Format, - * States.Array, States.ArrayLength, States.MathAdd, States.UUID. + * States.Array, States.ArrayLength, States.ArrayContains, States.MathAdd, States.UUID. * Throws FailStateException("States.Runtime") for unrecognized functions. */ private JsonNode evaluateIntrinsic(String expr, JsonNode root) { @@ -1419,6 +1515,28 @@ public class AslExecutor { JsonNode b = resolveIntrinsicArg(parts.get(1).trim(), root); yield objectMapper.getNodeFactory().numberNode(a.asLong() + b.asLong()); } + case "States.ArrayContains" -> { + List parts = splitIntrinsicArgs(argsStr); + if (parts.size() != 2) { + throw new FailStateException("States.Runtime", + "States.ArrayContains requires exactly 2 arguments"); + } + JsonNode array = resolveIntrinsicArg(parts.get(0).trim(), root); + JsonNode value = resolveIntrinsicArg(parts.get(1).trim(), root); + if (!array.isArray()) { + // AWS throws rather than silently returning false, matching States.ArrayLength. + throw new FailStateException("States.Runtime", + "States.ArrayContains: first argument must be an array"); + } + boolean contains = false; + for (JsonNode element : array) { + if (element.equals(value)) { + contains = true; + break; + } + } + yield objectMapper.getNodeFactory().booleanNode(contains); + } case "States.UUID" -> { yield objectMapper.getNodeFactory().textNode(java.util.UUID.randomUUID().toString()); } diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorPathIntrinsicsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorPathIntrinsicsTest.java new file mode 100644 index 0000000000..f824f9ff45 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorPathIntrinsicsTest.java @@ -0,0 +1,160 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; +import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; +import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; +import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore; +import io.github.hectorvent.floci.services.sqs.SqsJsonHandler; +import jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +/** + * Unit coverage for the JSONPath/intrinsic features DPS's provisioning state machine relies on: + * the {@code $.X.*.Y} wildcard projection, {@code States.ArrayContains}, and {@code ResultSelector} + * evaluation (which reuses the Parameters resolver). + */ +class AslExecutorPathIntrinsicsTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private AslExecutor executor; + + @BeforeEach + @SuppressWarnings("unchecked") + void setUp() { + executor = new AslExecutor( + mock(LambdaExecutorService.class), + mock(LambdaFunctionStore.class), + 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), + mapper, + new JsonataEvaluator(mapper), + mock(Instance.class)); + } + + @Test + void wildcardProjectionCollectsFieldFromEachArrayElement() throws Exception { + JsonNode root = mapper.readTree( + "{\"Regions\":[{\"RegionName\":\"us-east-1\"},{\"RegionName\":\"eu-west-1\"}]}"); + JsonNode result = executor.resolvePath("$.Regions.*.RegionName", root); + assertTrue(result.isArray()); + assertEquals(2, result.size()); + assertEquals("us-east-1", result.get(0).asText()); + assertEquals("eu-west-1", result.get(1).asText()); + } + + @Test + void wildcardProjectionOnNonArrayIsNull() throws Exception { + JsonNode root = mapper.readTree("{\"Regions\":\"not-an-array\"}"); + assertTrue(executor.resolvePath("$.Regions.*.RegionName", root).isNull()); + } + + @Test + void bracketWildcardProjectionMatchesDotForm() throws Exception { + JsonNode root = mapper.readTree( + "{\"Regions\":[{\"RegionName\":\"us-east-1\"},{\"RegionName\":\"eu-west-1\"}]}"); + // The AWS bracket form must behave exactly like the dot form. + JsonNode result = executor.resolvePath("$.Regions[*].RegionName", root); + assertTrue(result.isArray()); + assertEquals(2, result.size()); + assertEquals("us-east-1", result.get(0).asText()); + assertEquals("eu-west-1", result.get(1).asText()); + } + + @Test + void rootBracketDoubleWildcardFlattensArrayOfArrays() throws Exception { + JsonNode root = mapper.readTree("[[1,2],[3,4]]"); + JsonNode result = executor.resolvePath("$[*][*]", root); + assertTrue(result.isArray()); + assertEquals(4, result.size()); + assertEquals(1, result.get(0).asInt()); + assertEquals(4, result.get(3).asInt()); + } + + @Test + void numericBracketSegmentIndexesIntoArray() throws Exception { + JsonNode root = mapper.readTree("{\"items\":[\"a\",\"b\",\"c\"]}"); + assertEquals("b", executor.resolvePath("$.items[1]", root).asText()); + } + + @Test + void resolvePathNodeDistinguishesExplicitNullFromMissing() throws Exception { + JsonNode root = mapper.readTree("{\"x\":null}"); + // An explicit null exists, so it is present (not a MissingNode)... + assertFalse(executor.resolvePathNode("$.x", root).isMissingNode()); + assertTrue(executor.resolvePathNode("$.x", root).isNull()); + // ...while an absent field resolves to a MissingNode. + assertTrue(executor.resolvePathNode("$.y", root).isMissingNode()); + } + + @Test + void arrayContainsTrueAndFalse() throws Exception { + JsonNode root = mapper.readTree("{\"list\":[\"a\",\"b\",\"c\"],\"hit\":\"b\",\"miss\":\"z\"}"); + assertTrue(executor.resolvePath("States.ArrayContains($.list, $.hit)", root).asBoolean()); + assertFalse(executor.resolvePath("States.ArrayContains($.list, $.miss)", root).asBoolean()); + } + + @Test + void arrayContainsThrowsWhenFirstArgIsNotAnArray() throws Exception { + JsonNode root = mapper.readTree("{\"notList\":\"oops\",\"hit\":\"b\"}"); + // AWS raises States.Runtime instead of silently returning false on a non-array argument. + assertThrows(AslExecutor.FailStateException.class, + () -> executor.resolvePath("States.ArrayContains($.notList, $.hit)", root)); + } + + @Test + void wildcardProjectionKeepsExplicitNullsButOmitsMissing() throws Exception { + JsonNode root = mapper.readTree("[{\"field\":null},{\"field\":\"x\"},{\"other\":1}]"); + JsonNode result = executor.resolvePath("$[*].field", root); + assertTrue(result.isArray()); + // The explicit null is kept; the element missing "field" is omitted. + assertEquals(2, result.size()); + assertTrue(result.get(0).isNull()); + assertEquals("x", result.get(1).asText()); + } + + @Test + void resultSelectorAppliesProjectionAndIntrinsics() throws Exception { + JsonNode result = mapper.readTree( + "{\"Regions\":[{\"RegionName\":\"us-east-1\"},{\"RegionName\":\"us-west-2\"}]}"); + JsonNode selector = mapper.readTree("{\"list.$\":\"$.Regions.*.RegionName\"}"); + JsonNode out = executor.resolveParameters(selector, result, mapper.createObjectNode()); + assertTrue(out.path("list").isArray()); + assertEquals(2, out.path("list").size()); + assertEquals("us-east-1", out.path("list").get(0).asText()); + } + + @Test + void rootArrayIndexDotBracketIsResolved() throws Exception { + // EventBridge Pipes delivers a batch as a JSON array; an SFN unwraps it via InputPath "$.[0]". + JsonNode root = mapper.readTree("[{\"systemId\":\"DFSLOCAL\",\"solutions\":[1,2]}]"); + JsonNode out = executor.resolvePath("$.[0]", root); + assertTrue(out.isObject()); + assertEquals("DFSLOCAL", out.path("systemId").asText()); + assertEquals(2, out.path("solutions").size()); + } + + @Test + void rootArrayIndexNoDotIsResolved() throws Exception { + JsonNode root = mapper.readTree("[{\"k\":\"v0\"},{\"k\":\"v1\"}]"); + assertEquals("v1", executor.resolvePath("$[1]", root).path("k").asText()); + } + + @Test + void rootArrayIndexThenFieldIsResolved() throws Exception { + JsonNode root = mapper.readTree("[{\"systemId\":\"S1\"}]"); + assertEquals("S1", executor.resolvePath("$.[0].systemId", root).asText()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsChoiceIsPresentIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsChoiceIsPresentIntegrationTest.java new file mode 100644 index 0000000000..570c055af9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsChoiceIsPresentIntegrationTest.java @@ -0,0 +1,95 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +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.fail; + +/** + * A Choice rule {@code Not { IsPresent: $.absentField }} must take the "absent" branch when the + * field is missing — previously an absent path resolved to a non-missing null node, so IsPresent + * wrongly reported the field as present. + */ +@QuarkusTest +class StepFunctionsChoiceIsPresentIntegrationTest { + + 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 String DEFINITION = """ + {"StartAt":"Check","States":{ + "Check":{"Type":"Choice", + "Choices":[{"Not":{"Variable":"$.maybe","IsPresent":true},"Next":"Absent"}], + "Default":"Present"}, + "Absent":{"Type":"Pass","Result":"absent","End":true}, + "Present":{"Type":"Pass","Result":"present","End":true}}} + """; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void absentFieldTakesNotIsPresentBranch() throws Exception { + assertEquals("\"absent\"", run("{}")); + } + + @Test + void presentFieldTakesDefaultBranch() throws Exception { + assertEquals("\"present\"", run("{\"maybe\":\"here\"}")); + } + + @Test + void explicitNullCountsAsPresent() throws Exception { + // A field that exists with a null value is present in AWS, so it must NOT take the absent branch. + assertEquals("\"present\"", run("{\"maybe\":null}")); + } + + private String run(String input) throws InterruptedException { + String name = "ispresent-" + System.currentTimeMillis() + "-" + input.length(); + Response create = given() + .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine") + .contentType(SFN_CONTENT_TYPE) + .body("{\"name\":\"" + name + "\",\"definition\":" + quote(DEFINITION) + ",\"roleArn\":\"" + ROLE_ARN + "\"}") + .when().post("/"); + create.then().statusCode(200); + String smArn = create.jsonPath().getString("stateMachineArn"); + + Response start = given() + .header("X-Amz-Target", "AWSStepFunctions.StartExecution") + .contentType(SFN_CONTENT_TYPE) + .body("{\"stateMachineArn\":\"" + smArn + "\",\"input\":" + quote(input) + "}") + .when().post("/"); + start.then().statusCode(200); + String execArn = start.jsonPath().getString("executionArn"); + + for (int i = 0; i < 50; i++) { + Response d = given() + .header("X-Amz-Target", "AWSStepFunctions.DescribeExecution") + .contentType(SFN_CONTENT_TYPE) + .body("{\"executionArn\":\"" + execArn + "\"}") + .when().post("/"); + String status = d.jsonPath().getString("status"); + if ("SUCCEEDED".equals(status)) { + return d.jsonPath().getString("output"); + } + if ("FAILED".equals(status)) { + fail("Execution failed: " + d.body().asString()); + } + Thread.sleep(100); + } + fail("Execution did not complete"); + return null; + } + + 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/StepFunctionsPassParametersIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPassParametersIntegrationTest.java new file mode 100644 index 0000000000..0f94dd8378 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsPassParametersIntegrationTest.java @@ -0,0 +1,98 @@ +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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Verifies a Pass state applies its {@code Parameters} (with intrinsics) — previously they were + * accepted but ignored, so the input flowed through unchanged. + */ +@QuarkusTest +class StepFunctionsPassParametersIntegrationTest { + + 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(); + + private static final String DEFINITION = """ + {"StartAt":"Validate","States":{ + "Validate":{"Type":"Pass", + "Parameters":{"result.$":"States.ArrayContains($.list, $.target)"}, + "ResultPath":"$.validation","End":true}}} + """; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void passStateAppliesParametersWithArrayContains() throws Exception { + JsonNode hit = mapper.readTree(run("{\"list\":[\"a\",\"b\",\"c\"],\"target\":\"b\"}")); + assertTrue(hit.path("validation").path("result").asBoolean()); + + JsonNode miss = mapper.readTree(run("{\"list\":[\"a\",\"b\",\"c\"],\"target\":\"z\"}")); + assertFalse(miss.path("validation").path("result").asBoolean()); + } + + private String run(String input) throws InterruptedException { + String smArn = create("pass-params-" + System.currentTimeMillis()); + String execArn = start(smArn, input); + for (int i = 0; i < 50; i++) { + Response resp = describe(execArn); + String status = resp.jsonPath().getString("status"); + if ("SUCCEEDED".equals(status)) { + return resp.jsonPath().getString("output"); + } + if ("FAILED".equals(status) || "ABORTED".equals(status)) { + fail("Execution " + status + ": " + resp.body().asString()); + } + Thread.sleep(100); + } + fail("Execution did not complete"); + return null; + } + + private String create(String name) { + Response resp = given() + .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine") + .contentType(SFN_CONTENT_TYPE) + .body("{\"name\":\"" + name + "\",\"definition\":" + quote(DEFINITION) + ",\"roleArn\":\"" + ROLE_ARN + "\"}") + .when().post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("stateMachineArn"); + } + + private String start(String smArn, String input) { + Response resp = given() + .header("X-Amz-Target", "AWSStepFunctions.StartExecution") + .contentType(SFN_CONTENT_TYPE) + .body("{\"stateMachineArn\":\"" + smArn + "\",\"input\":" + quote(input) + "}") + .when().post("/"); + resp.then().statusCode(200); + return resp.jsonPath().getString("executionArn"); + } + + private Response describe(String execArn) { + return given() + .header("X-Amz-Target", "AWSStepFunctions.DescribeExecution") + .contentType(SFN_CONTENT_TYPE) + .body("{\"executionArn\":\"" + execArn + "\"}") + .when().post("/"); + } + + 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/StepFunctionsResultSelectorMapParallelIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsResultSelectorMapParallelIntegrationTest.java new file mode 100644 index 0000000000..4da9613e20 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsResultSelectorMapParallelIntegrationTest.java @@ -0,0 +1,99 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +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.fail; + +/** + * ResultSelector is not Task-only in AWS: it also transforms the raw result of Map and Parallel + * states before ResultPath merges it back into the state input. These tests also exercise the + * AWS bracket wildcard form ({@code $[*].field}) inside the selector. + */ +@QuarkusTest +class StepFunctionsResultSelectorMapParallelIntegrationTest { + + 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 String MAP_DEFINITION = """ + {"StartAt":"M","States":{ + "M":{"Type":"Map","ItemsPath":"$.people", + "ItemProcessor":{"StartAt":"P","States":{"P":{"Type":"Pass","End":true}}}, + "ResultSelector":{"names.$":"$[*].name"}, + "End":true}}} + """; + + private static final String PARALLEL_DEFINITION = """ + {"StartAt":"P","States":{ + "P":{"Type":"Parallel", + "Branches":[ + {"StartAt":"A","States":{"A":{"Type":"Pass","Result":{"v":1},"End":true}}}, + {"StartAt":"B","States":{"B":{"Type":"Pass","Result":{"v":2},"End":true}}}], + "ResultSelector":{"values.$":"$[*].v"}, + "End":true}}} + """; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void mapResultSelectorCollectsFieldFromEachIteration() throws Exception { + assertEquals("{\"names\":[\"a\",\"b\"]}", + run(MAP_DEFINITION, "{\"people\":[{\"name\":\"a\"},{\"name\":\"b\"}]}")); + } + + @Test + void parallelResultSelectorCollectsFieldFromEachBranch() throws Exception { + assertEquals("{\"values\":[1,2]}", run(PARALLEL_DEFINITION, "{}")); + } + + private String run(String definition, String input) throws InterruptedException { + String name = "resultselector-" + System.nanoTime(); + Response create = given() + .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine") + .contentType(SFN_CONTENT_TYPE) + .body("{\"name\":\"" + name + "\",\"definition\":" + quote(definition) + ",\"roleArn\":\"" + ROLE_ARN + "\"}") + .when().post("/"); + create.then().statusCode(200); + String smArn = create.jsonPath().getString("stateMachineArn"); + + Response start = given() + .header("X-Amz-Target", "AWSStepFunctions.StartExecution") + .contentType(SFN_CONTENT_TYPE) + .body("{\"stateMachineArn\":\"" + smArn + "\",\"input\":" + quote(input) + "}") + .when().post("/"); + start.then().statusCode(200); + String execArn = start.jsonPath().getString("executionArn"); + + for (int i = 0; i < 50; i++) { + Response d = given() + .header("X-Amz-Target", "AWSStepFunctions.DescribeExecution") + .contentType(SFN_CONTENT_TYPE) + .body("{\"executionArn\":\"" + execArn + "\"}") + .when().post("/"); + String status = d.jsonPath().getString("status"); + if ("SUCCEEDED".equals(status)) { + return d.jsonPath().getString("output"); + } + if ("FAILED".equals(status)) { + fail("Execution failed: " + d.body().asString()); + } + Thread.sleep(100); + } + fail("Execution did not complete"); + return null; + } + + private static String quote(String raw) { + return "\"" + raw.replace("\\", "\\\\").replace("\"", "\\\"") + .replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t") + "\""; + } +}