Light, fluffy, and always free - The AWS Local Emulator alternative
feat(asl): add support for States.ArrayPartition, States.ArrayRange, States.ArrayUnique, and States.MathRandom intrinsics with comprehensive tests (#3224)
Matheus Andrécf8466b58c5f
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.javaindex f0ffc9dec1..ca39b604e0 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@@ -65,6 +65,7 @@ import jakarta.ws.rs.core.MultivaluedHashMap;import jakarta.ws.rs.core.MultivaluedMap;import org.jboss.logging.Logger;+import java.math.BigInteger;import java.net.URI;import java.nio.charset.StandardCharsets;import java.security.MessageDigest;@@ -82,6 +83,7 @@ import java.util.LinkedHashMap;import java.util.List;import java.util.Locale;import java.util.Map;+import java.util.Random;import java.util.Set;import java.util.UUID;import java.util.concurrent.Callable;@@ -140,6 +142,8 @@ public class AslExecutor {// AWS caps the string input of States.Base64Encode/Base64Decode/Hash at 10,000 characters// (measured here in Unicode code points).private static final int INTRINSIC_MAX_INPUT_LENGTH = 10_000;+ // AWS refuses a States.ArrayRange result of more than 1,000 elements.+ private static final int ARRAY_RANGE_MAX_ELEMENTS = 1_000;// Must mirror the identical private set in JsonataEvaluator ($hash): both query languages// expose exactly these five algorithms, case-sensitively.private static final Set<String> HASH_ALGORITHMS =@@ -3551,7 +3555,8 @@ public class AslExecutor {* Supports: States.StringToJson, States.JsonToString, States.Format,* States.Array, States.ArrayLength, States.ArrayContains, States.MathAdd, States.UUID,* States.JsonMerge, States.Base64Encode, States.Base64Decode, States.StringSplit,- * States.ArrayGetItem, States.Hash.+ * States.ArrayGetItem, States.Hash, States.ArrayPartition, States.ArrayRange,+ * States.ArrayUnique, States.MathRandom.* Throws FailStateException("States.Runtime") for unrecognized functions.** <p>An argument that matches nothing fails the execution, and the cause names the whole@@ -3864,11 +3869,210 @@ public class AslExecutor {"States.Hash algorithm '" + algorithm + "' is not available");}}+ case "States.ArrayPartition" -> {+ List<String> parts = splitIntrinsicArgs(argsStr);+ if (parts.size() != 2 || argsStr.stripTrailing().endsWith(",")) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.ArrayPartition requires exactly 2 arguments");+ }+ JsonNode array = resolveIntrinsicArg(parts.get(0).trim(), root, context);+ if (!array.isArray()) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.ArrayPartition first argument must be an array");+ }+ // AWS rounds a non-integer chunk size to the nearest integer, then requires it to+ // be positive.+ long chunkSize = intrinsicInteger(+ resolveIntrinsicArg(parts.get(1).trim(), root, context),+ "States.ArrayPartition", "chunk size");+ if (chunkSize <= 0) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.ArrayPartition chunk size must be a positive integer");+ }+ ArrayNode chunks = objectMapper.createArrayNode();+ int size = (int) Math.min(chunkSize, Math.max(array.size(), 1));+ for (int i = 0; i < array.size(); i += size) {+ ArrayNode chunk = chunks.addArray();+ for (int j = i; j < Math.min(i + size, array.size()); j++) {+ chunk.add(array.get(j));+ }+ }+ yield chunks;+ }+ case "States.ArrayRange" -> {+ List<String> parts = splitIntrinsicArgs(argsStr);+ if (parts.size() != 3 || argsStr.stripTrailing().endsWith(",")) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.ArrayRange requires exactly 3 arguments");+ }+ // AWS rounds non-integer arguments to the nearest integer; the step must be+ // non-zero, and the end is included when the step lands on it exactly.+ long start = intrinsicInteger(+ resolveIntrinsicArg(parts.get(0).trim(), root, context), "States.ArrayRange", "start");+ long end = intrinsicInteger(+ resolveIntrinsicArg(parts.get(1).trim(), root, context), "States.ArrayRange", "end");+ long step = intrinsicInteger(+ resolveIntrinsicArg(parts.get(2).trim(), root, context), "States.ArrayRange", "step");+ if (step == 0) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.ArrayRange step must be a non-zero integer");+ }+ ArrayNode range = objectMapper.createArrayNode();+ if ((step > 0 && start > end) || (step < 0 && start < end)) {+ // A step pointing away from the end yields nothing.+ yield range;+ }+ // Counted in BigInteger, then iterated a fixed number of times, so a step near+ // Long.MAX_VALUE can neither overflow the count nor wrap a `v <= end` walk forever.+ BigInteger elements = BigInteger.valueOf(end)+ .subtract(BigInteger.valueOf(start))+ .divide(BigInteger.valueOf(step))+ .add(BigInteger.ONE);+ if (elements.compareTo(BigInteger.valueOf(ARRAY_RANGE_MAX_ELEMENTS)) > 0) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.ArrayRange result cannot contain more than " + ARRAY_RANGE_MAX_ELEMENTS+ + " elements, size: " + elements);+ }+ long value = start;+ for (int i = 0, n = elements.intValue(); i < n; i++) {+ // Values that fit in an int are added as IntNode, the node Jackson parses+ // such a number from JSON into, so the result compares equal to parsed input.+ if (value >= Integer.MIN_VALUE && value <= Integer.MAX_VALUE) {+ range.add((int) value);+ } else {+ range.add(value);+ }+ value += step;+ }+ yield range;+ }+ case "States.ArrayUnique" -> {+ List<String> parts = splitIntrinsicArgs(argsStr);+ if (parts.size() != 1 || argsStr.stripTrailing().endsWith(",")) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.ArrayUnique requires exactly 1 argument");+ }+ JsonNode array = resolveIntrinsicArg(parts.get(0).trim(), root, context);+ if (!array.isArray()) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.ArrayUnique requires an array");+ }+ // First occurrence wins and input order is kept. Equality is structural, with+ // numbers compared by value so a literal 1 (a LongNode) and a path-resolved 1 (an+ // IntNode) count as the same element.+ ArrayNode unique = objectMapper.createArrayNode();+ for (JsonNode element : array) {+ boolean seen = false;+ for (JsonNode kept : unique) {+ if (intrinsicNodesEqual(kept, element)) {+ seen = true;+ break;+ }+ }+ if (!seen) {+ unique.add(element);+ }+ }+ yield unique;+ }+ case "States.MathRandom" -> {+ List<String> parts = splitIntrinsicArgs(argsStr);+ if (parts.size() < 2 || parts.size() > 3 || argsStr.stripTrailing().endsWith(",")) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.MathRandom requires 2 or 3 arguments");+ }+ // AWS rounds non-integer bounds to the nearest integer and draws an integer from+ // the half-open range [start, end): the start is inclusive, the end exclusive, so+ // the range must be non-empty. An optional integer seed makes the draw+ // reproducible: AWS draws from java.util.Random, so the same seed yields the same+ // number here.+ long start = intrinsicInteger(+ resolveIntrinsicArg(parts.get(0).trim(), root, context), "States.MathRandom", "start");+ long end = intrinsicInteger(+ resolveIntrinsicArg(parts.get(1).trim(), root, context), "States.MathRandom", "end");+ if (start >= end) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.MathRandom start must be less than end");+ }+ long drawn;+ if (parts.size() == 3) {+ long seed = intrinsicInteger(+ resolveIntrinsicArg(parts.get(2).trim(), root, context), "States.MathRandom", "seed");+ drawn = new Random(seed).nextLong(start, end);+ } else {+ drawn = ThreadLocalRandom.current().nextLong(start, end);+ }+ yield objectMapper.getNodeFactory().numberNode(drawn);+ }default -> throw new FailStateException("States.Runtime","Unsupported intrinsic function: " + fnName);};}+ /**+ * Coerces a numeric intrinsic argument to an integer the way AWS does for+ * {@code States.ArrayPartition}, {@code States.ArrayRange} and {@code States.MathRandom}: an+ * integral value is taken as is and a fractional one is rounded to the nearest integer. A+ * non-number, or an integer outside the long range, is a {@code States.IntrinsicFailure}.+ */+ private static long intrinsicInteger(JsonNode node, String fnName, String argName) {+ if (!node.isNumber()) {+ throw new FailStateException("States.IntrinsicFailure",+ fnName + " " + argName + " must be a number");+ }+ if (node.isIntegralNumber()) {+ if (!node.canConvertToLong()) {+ throw new FailStateException("States.IntrinsicFailure",+ fnName + " " + argName + " is out of range");+ }+ return node.asLong();+ }+ double value = node.doubleValue();+ if (Double.isNaN(value) || Double.isInfinite(value)) {+ throw new FailStateException("States.IntrinsicFailure",+ fnName + " " + argName + " must be a finite number");+ }+ return Math.round(value);+ }++ /**+ * Structural equality for intrinsic array elements. Jackson's own {@code equals} tells an+ * {@code IntNode} from a {@code LongNode} holding the same value, and a number literal in an+ * intrinsic expression is parsed as a long while a number read from the state input is parsed+ * as an int, so numbers are compared by value here, recursively through arrays and objects.+ */+ private static boolean intrinsicNodesEqual(JsonNode a, JsonNode b) {+ if (a.isNumber() && b.isNumber()) {+ return a.decimalValue().compareTo(b.decimalValue()) == 0;+ }+ if (a.isArray() && b.isArray()) {+ if (a.size() != b.size()) {+ return false;+ }+ for (int i = 0; i < a.size(); i++) {+ if (!intrinsicNodesEqual(a.get(i), b.get(i))) {+ return false;+ }+ }+ return true;+ }+ if (a.isObject() && b.isObject()) {+ if (a.size() != b.size()) {+ return false;+ }+ Iterator<Map.Entry<String, JsonNode>> fields = a.fields();+ while (fields.hasNext()) {+ Map.Entry<String, JsonNode> field = fields.next();+ JsonNode other = b.get(field.getKey());+ if (other == null || !intrinsicNodesEqual(field.getValue(), other)) {+ return false;+ }+ }+ return true;+ }+ return a.equals(b);+ }+/*** Resolve a single intrinsic argument: a $.path reference, a nested {@code States.*} call, a* quoted string literal, or a numeric literal.diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorArrayAndMathIntrinsicsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorArrayAndMathIntrinsicsTest.javanew file mode 100644index 0000000000..db7a8c2305--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorArrayAndMathIntrinsicsTest.java@@ -0,0 +1,497 @@+package io.github.hectorvent.floci.services.stepfunctions;++import com.fasterxml.jackson.databind.JsonNode;+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.DynamoDbJsonHandler;+import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;+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.lambda.LambdaExecutorService;+import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;+import io.github.hectorvent.floci.services.s3.S3Service;+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 java.util.ArrayList;+import java.util.List;+import java.util.Random;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.Mockito.mock;++/**+ * Functionality + regression coverage for the last four JSONPath-mode intrinsic functions:+ * {@code States.ArrayPartition}, {@code States.ArrayRange}, {@code States.ArrayUnique} and+ * {@code States.MathRandom}. Before this change each aborted the execution with+ * "Unsupported intrinsic function: States.<Name>" ({@code States.Runtime}).+ *+ * <p>AWS-documented examples are used as fixtures where they exist (the ArrayPartition,+ * ArrayRange and ArrayUnique doc examples). Every failure case asserts the exact+ * {@code States.IntrinsicFailure} error name (catchable), never a bare RuntimeException: a+ * reverted implementation throws the uncatchable {@code States.Runtime} instead.+ */+class AslExecutorArrayAndMathIntrinsicsTest {++ 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(CloudFormationQueryHandler.class),+ mock(Ec2Service.class),+ mock(S3Service.class),+ mock(EcsService.class),+ mock(EcsJsonHandler.class),+ mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),+ mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),+ mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),+ mapper,+ new JsonataEvaluator(mapper),+ mock(Instance.class),+ mock(EmulatorConfig.class),+ null, null);+ }++ private void assertIntrinsicFailure(JsonNode root, String expr) {+ AslExecutor.FailStateException ex = assertThrows(AslExecutor.FailStateException.class,+ () -> executor.resolvePath(expr, root));+ assertEquals("States.IntrinsicFailure", ex.error,+ "expected catchable States.IntrinsicFailure for: " + expr);+ }++ private JsonNode obj() {+ return mapper.createObjectNode();+ }++ private JsonNode json(String text) throws Exception {+ return mapper.readTree(text);+ }++ private void assertJson(String expected, JsonNode actual) throws Exception {+ assertEquals(mapper.writeValueAsString(json(expected)), mapper.writeValueAsString(actual));+ }++ // ---------- A. States.ArrayPartition ----------++ @Test+ void arrayPartitionMatchesAwsDocExample() throws Exception {+ JsonNode root = json("{\"inputArray\":[1,2,3,4,5,6,7,8,9]}");+ assertJson("[[1,2,3,4],[5,6,7,8],[9]]",+ executor.resolvePath("States.ArrayPartition($.inputArray, 4)", root));+ }++ @Test+ void arrayPartitionChunkSizeFromPath() throws Exception {+ JsonNode root = json("{\"arr\":[\"a\",\"b\",\"c\"],\"n\":2}");+ assertJson("[[\"a\",\"b\"],[\"c\"]]", executor.resolvePath("States.ArrayPartition($.arr, $.n)", root));+ }++ @Test+ void arrayPartitionChunkLargerThanArrayIsSingleChunk() throws Exception {+ JsonNode root = json("{\"arr\":[1,2]}");+ assertJson("[[1,2]]", executor.resolvePath("States.ArrayPartition($.arr, 10)", root));+ }++ @Test+ void arrayPartitionOfEmptyArrayIsEmpty() throws Exception {+ JsonNode root = json("{\"arr\":[]}");+ assertJson("[]", executor.resolvePath("States.ArrayPartition($.arr, 3)", root));+ }++ @Test+ void arrayPartitionRoundsNonIntegerChunkSize() throws Exception {+ JsonNode root = json("{\"arr\":[1,2,3,4,5],\"n\":2.6}");+ assertJson("[[1,2,3],[4,5]]", executor.resolvePath("States.ArrayPartition($.arr, $.n)", root));+ }++ @Test+ void arrayPartitionKeepsNestedElementsIntact() throws Exception {+ JsonNode root = json("{\"arr\":[{\"a\":1},[2],\"s\",null]}");+ assertJson("[[{\"a\":1},[2]],[\"s\",null]]",+ executor.resolvePath("States.ArrayPartition($.arr, 2)", root));+ }++ @Test+ void arrayPartitionNonArrayIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(json("{\"arr\":\"abc\"}"), "States.ArrayPartition($.arr, 2)");+ }++ @Test+ void arrayPartitionNonPositiveChunkSizeIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(json("{\"arr\":[1,2]}"), "States.ArrayPartition($.arr, 0)");+ assertIntrinsicFailure(json("{\"arr\":[1,2]}"), "States.ArrayPartition($.arr, -1)");+ assertIntrinsicFailure(json("{\"arr\":[1,2],\"n\":0.4}"), "States.ArrayPartition($.arr, $.n)");+ }++ @Test+ void arrayPartitionNonNumericChunkSizeIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(json("{\"arr\":[1,2]}"), "States.ArrayPartition($.arr, '2')");+ assertIntrinsicFailure(json("{\"arr\":[1,2]}"), "States.ArrayPartition($.arr, true)");+ }++ @Test+ void arrayPartitionWrongArityIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(json("{\"arr\":[1,2]}"), "States.ArrayPartition($.arr)");+ assertIntrinsicFailure(json("{\"arr\":[1,2]}"), "States.ArrayPartition($.arr, 1, 2)");+ assertIntrinsicFailure(json("{\"arr\":[1,2]}"), "States.ArrayPartition($.arr, 1,)");+ }++ // ---------- B. States.ArrayRange ----------++ @Test+ void arrayRangeMatchesAwsDocExample() throws Exception {+ assertJson("[1,3,5,7,9]", executor.resolvePath("States.ArrayRange(1, 9, 2)", obj()));+ }++ @Test+ void arrayRangeStopsBeforeEndWhenStepDoesNotLand() throws Exception {+ assertJson("[1,3,5,7]", executor.resolvePath("States.ArrayRange(1, 8, 2)", obj()));+ }++ @Test+ void arrayRangeSupportsNegativeStep() throws Exception {+ assertJson("[9,7,5,3,1]", executor.resolvePath("States.ArrayRange(9, 1, -2)", obj()));+ }++ @Test+ void arrayRangeWithEqualBoundsIsSingleElement() throws Exception {+ assertJson("[5]", executor.resolvePath("States.ArrayRange(5, 5, 1)", obj()));+ assertJson("[5]", executor.resolvePath("States.ArrayRange(5, 5, -3)", obj()));+ }++ @Test+ void arrayRangeWithStepPointingAwayFromEndIsEmpty() throws Exception {+ assertJson("[]", executor.resolvePath("States.ArrayRange(9, 1, 2)", obj()));+ assertJson("[]", executor.resolvePath("States.ArrayRange(1, 9, -2)", obj()));+ }++ @Test+ void arrayRangeArgumentsFromPathsAndRounding() throws Exception {+ JsonNode root = json("{\"s\":0.6,\"e\":4.4,\"st\":1.5}");+ // 0.6 -> 1, 4.4 -> 4, 1.5 -> 2+ assertJson("[1,3]", executor.resolvePath("States.ArrayRange($.s, $.e, $.st)", root));+ }++ @Test+ void arrayRangeAtExactly1000ElementsSucceeds() throws Exception {+ JsonNode out = executor.resolvePath("States.ArrayRange(1, 1000, 1)", obj());+ assertEquals(1000, out.size());+ assertEquals(1, out.get(0).asInt());+ assertEquals(1000, out.get(999).asInt());+ }++ @Test+ void arrayRangeOver1000ElementsIsIntrinsicFailure() {+ assertIntrinsicFailure(obj(), "States.ArrayRange(1, 1001, 1)");+ assertIntrinsicFailure(obj(), "States.ArrayRange(0, 9223372036854775807, 1)");+ }++ @Test+ void arrayRangeNearLongBoundsDoesNotOverflow() throws Exception {+ assertJson("[9223372036854775806,9223372036854775807]",+ executor.resolvePath("States.ArrayRange(9223372036854775806, 9223372036854775807, 1)", obj()));+ // (MAX - MIN) / MAX = 2 whole steps, so three elements; a naive `v <= end` walk would+ // wrap past MAX and never terminate.+ assertJson("[-9223372036854775808,-1,9223372036854775806]",+ executor.resolvePath(+ "States.ArrayRange(-9223372036854775808, 9223372036854775807, 9223372036854775807)",+ obj()));+ }++ @Test+ void arrayRangeZeroStepIsIntrinsicFailure() {+ assertIntrinsicFailure(obj(), "States.ArrayRange(1, 9, 0)");+ }++ @Test+ void arrayRangeNonNumericArgumentIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(obj(), "States.ArrayRange('1', 9, 2)");+ assertIntrinsicFailure(json("{\"e\":null}"), "States.ArrayRange(1, $.e, 2)");+ assertIntrinsicFailure(json("{\"st\":[2]}"), "States.ArrayRange(1, 9, $.st)");+ }++ @Test+ void arrayRangeWrongArityIsIntrinsicFailure() {+ assertIntrinsicFailure(obj(), "States.ArrayRange(1, 9)");+ assertIntrinsicFailure(obj(), "States.ArrayRange(1, 9, 2, 3)");+ assertIntrinsicFailure(obj(), "States.ArrayRange(1, 9, 2,)");+ }++ // ---------- C. States.ArrayUnique ----------++ @Test+ void arrayUniqueMatchesAwsDocExample() throws Exception {+ JsonNode root = json("{\"inputArray\":[1,2,3,3,3,3,3,3,4]}");+ assertJson("[1,2,3,4]", executor.resolvePath("States.ArrayUnique($.inputArray)", root));+ }++ @Test+ void arrayUniqueKeepsFirstOccurrenceOrder() throws Exception {+ JsonNode root = json("{\"arr\":[\"b\",\"a\",\"b\",\"c\",\"a\"]}");+ assertJson("[\"b\",\"a\",\"c\"]", executor.resolvePath("States.ArrayUnique($.arr)", root));+ }++ @Test+ void arrayUniqueComparesStructurally() throws Exception {+ JsonNode root = json(+ "{\"arr\":[{\"a\":1,\"b\":[1,2]},{\"b\":[1,2],\"a\":1},{\"a\":1,\"b\":[2,1]},[1,2],[1,2],null,null]}");+ assertJson("[{\"a\":1,\"b\":[1,2]},{\"a\":1,\"b\":[2,1]},[1,2],null]",+ executor.resolvePath("States.ArrayUnique($.arr)", root));+ }++ @Test+ void arrayUniqueDistinguishesTypes() throws Exception {+ JsonNode root = json("{\"arr\":[1,\"1\",true,\"true\",null,\"null\"]}");+ assertEquals(6, executor.resolvePath("States.ArrayUnique($.arr)", root).size());+ }++ @Test+ void arrayUniqueTreatsLiteralAndPathNumbersAsEqual() throws Exception {+ // A literal 1 is parsed as a LongNode and a path-resolved 1 as an IntNode; Jackson's+ // equals tells them apart, AWS does not.+ JsonNode root = json("{\"n\":1,\"d\":1.0}");+ assertEquals(1, executor.resolvePath("States.ArrayUnique(States.Array(1, $.n, $.d))", root).size());+ }++ @Test+ void arrayUniqueOfEmptyArrayIsEmpty() throws Exception {+ assertJson("[]", executor.resolvePath("States.ArrayUnique($.arr)", json("{\"arr\":[]}")));+ }++ @Test+ void arrayUniqueNonArrayIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(json("{\"arr\":\"abc\"}"), "States.ArrayUnique($.arr)");+ assertIntrinsicFailure(json("{\"arr\":{\"a\":1}}"), "States.ArrayUnique($.arr)");+ }++ @Test+ void arrayUniqueWrongArityIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(json("{\"arr\":[1]}"), "States.ArrayUnique($.arr, $.arr)");+ assertIntrinsicFailure(json("{\"arr\":[1]}"), "States.ArrayUnique($.arr,)");+ }++ // ---------- D. States.MathRandom ----------++ @Test+ void mathRandomStaysWithinHalfOpenRange() throws Exception {+ // AWS documents the start as inclusive and the end as exclusive.+ JsonNode root = json("{\"start\":1,\"end\":999}");+ for (int i = 0; i < 200; i++) {+ JsonNode out = executor.resolvePath("States.MathRandom($.start, $.end)", root);+ assertTrue(out.isIntegralNumber(), "MathRandom must yield an integer");+ long v = out.asLong();+ assertTrue(v >= 1 && v < 999, "out of range: " + v);+ }+ }++ @Test+ void mathRandomNeverReturnsTheExclusiveEnd() {+ // A range of width one has exactly one admissible value; returning the end would be a+ // closed-range draw, which AWS never makes.+ for (int i = 0; i < 500; i++) {+ assertEquals(3, executor.resolvePath("States.MathRandom(3, 4)", obj()).asLong());+ }+ }++ @Test+ void mathRandomCoversBothAdmissibleValuesOfATinyRange() {+ boolean sawLow = false;+ boolean sawHigh = false;+ for (int i = 0; i < 500 && !(sawLow && sawHigh); i++) {+ long v = executor.resolvePath("States.MathRandom(3, 5)", obj()).asLong();+ assertTrue(v == 3 || v == 4, "out of range: " + v);+ sawLow |= v == 3;+ sawHigh |= v == 4;+ }+ assertTrue(sawLow && sawHigh, "both values of the half-open range [3, 5) must be reachable");+ }++ @Test+ void mathRandomIsReproducibleWithSeed() {+ long first = executor.resolvePath("States.MathRandom(1, 1000000, 42)", obj()).asLong();+ long second = executor.resolvePath("States.MathRandom(1, 1000000, 42)", obj()).asLong();+ assertEquals(first, second);+ // AWS draws from java.util.Random, so the draw must be the one that generator produces.+ assertEquals(new Random(42).nextLong(1, 1_000_000), first);+ long other = executor.resolvePath("States.MathRandom(1, 1000000, 43)", obj()).asLong();+ assertNotEquals(first, other);+ }++ @Test+ void mathRandomRoundsNonIntegerBounds() throws Exception {+ JsonNode root = json("{\"s\":2.4,\"e\":3.6}");+ // 2.4 -> 2, 3.6 -> 4, so the draw is from [2, 4)+ for (int i = 0; i < 50; i++) {+ long v = executor.resolvePath("States.MathRandom($.s, $.e)", root).asLong();+ assertTrue(v == 2 || v == 3, "out of range: " + v);+ }+ }++ @Test+ void mathRandomEmptyRangeIsIntrinsicFailure() {+ // The end is exclusive, so equal bounds define no value at all, and neither does a start+ // above the end.+ assertIntrinsicFailure(obj(), "States.MathRandom(7, 7)");+ assertIntrinsicFailure(obj(), "States.MathRandom(10, 1)");+ }++ @Test+ void mathRandomNonNumericArgumentIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(obj(), "States.MathRandom('1', 9)");+ assertIntrinsicFailure(json("{\"e\":\"9\"}"), "States.MathRandom(1, $.e)");+ assertIntrinsicFailure(obj(), "States.MathRandom(1, 9, 'seed')");+ }++ @Test+ void mathRandomWrongArityIsIntrinsicFailure() {+ assertIntrinsicFailure(obj(), "States.MathRandom(1)");+ assertIntrinsicFailure(obj(), "States.MathRandom(1, 9, 2, 3)");+ assertIntrinsicFailure(obj(), "States.MathRandom(1, 9,)");+ }++ // ---------- E. Missing-path arguments still fail with States.Runtime ----------++ @Test+ void missingPathArgumentIsStatesRuntime() throws Exception {+ JsonNode root = json("{\"arr\":[1]}");+ for (String expr : List.of("States.ArrayPartition($.nope, 2)", "States.ArrayRange($.nope, 9, 1)",+ "States.ArrayUnique($.nope)", "States.MathRandom(1, $.nope)")) {+ AslExecutor.FailStateException ex = assertThrows(AslExecutor.FailStateException.class,+ () -> executor.resolvePath(expr, root), expr);+ assertEquals("States.Runtime", ex.error, expr);+ }+ }++ // ---------- F. Parameters-path wiring and nesting ----------++ @Test+ void intrinsicsResolveInsidePassStateParameters() throws Exception {+ JsonNode params = json("{\"chunks.$\":\"States.ArrayPartition($.arr, 2)\","+ + "\"range.$\":\"States.ArrayRange(1, 3, 1)\","+ + "\"unique.$\":\"States.ArrayUnique($.arr)\","+ + "\"rand.$\":\"States.MathRandom(5, 6)\"}");+ JsonNode input = json("{\"arr\":[1,1,2]}");+ JsonNode out = executor.resolveParameters(params, input, null);+ assertJson("[[1,1],[2]]", out.path("chunks"));+ assertJson("[1,2,3]", out.path("range"));+ assertJson("[1,2]", out.path("unique"));+ assertEquals(5, out.path("rand").asLong());+ }++ @Test+ void intrinsicsComposeWithEachOther() throws Exception {+ assertJson("[[1,2],[3,4],[5]]",+ executor.resolvePath("States.ArrayPartition(States.ArrayRange(1, 5, 1), 2)", obj()));+ assertEquals(3, executor.resolvePath("States.ArrayLength(States.ArrayUnique(States.Array(1, 1, 2, 3)))",+ obj()).asInt());+ assertEquals(1, executor.resolvePath("States.ArrayGetItem(States.ArrayRange(0, 4, 1), 1)", obj()).asInt());+ }++ // ---------- G. Execution-level behaviour (full doExecute loop via executeSync) ----------++ @Test+ void issueReproductionSucceedsEndToEnd() throws Exception {+ Execution exec = run("""+ {+ "StartAt": "Calc",+ "States": {+ "Calc": {+ "Type": "Pass",+ "Parameters": {+ "first.$": "States.ArrayGetItem($.items, 0)",+ "chunks.$": "States.ArrayPartition($.items, 2)",+ "range.$": "States.ArrayRange(1, 3, 1)",+ "unique.$": "States.ArrayUnique($.dupes)",+ "rand.$": "States.MathRandom(1, 4, 7)"+ },+ "End": true+ }+ }+ }+ """, "{\"items\": [1, 2, 3], \"dupes\": [1, 1, 2]}");+ assertEquals("SUCCEEDED", exec.getStatus());+ JsonNode out = json(exec.getOutput());+ assertEquals(1, out.path("first").asInt());+ assertJson("[[1,2],[3]]", out.path("chunks"));+ assertJson("[1,2,3]", out.path("range"));+ assertJson("[1,2]", out.path("unique"));+ long rand = out.path("rand").asLong();+ assertTrue(rand >= 1 && rand < 4, "out of range: " + rand);+ }++ @Test+ void intrinsicFailureIsCatchableEndToEnd() {+ Execution exec = run("""+ {+ "StartAt": "Try",+ "States": {+ "Try": {+ "Type": "Pass",+ "Parameters": {"range.$": "States.ArrayRange(1, 9, 0)"},+ "Next": "Unexpected",+ "Catch": [{"ErrorEquals": ["States.IntrinsicFailure"], "Next": "Recover"}]+ },+ "Unexpected": {"Type": "Fail", "Cause": "intrinsic unexpectedly succeeded"},+ "Recover": {"Type": "Pass", "End": true}+ }+ }+ """, "{}");+ assertEquals("SUCCEEDED", exec.getStatus());+ }++ @Test+ void intrinsicFailureWithoutCatchFailsExecutionWithIntrinsicFailure() {+ Execution exec = run("""+ {+ "StartAt": "Try",+ "States": {+ "Try": {+ "Type": "Pass",+ "Parameters": {"u.$": "States.ArrayUnique($.notAnArray)"},+ "End": true+ }+ }+ }+ """, "{\"notAnArray\":\"x\"}");+ assertEquals("FAILED", exec.getStatus());+ assertEquals("States.IntrinsicFailure", exec.getError());+ }++ private Execution run(String definition, String input) {+ StateMachine sm = new StateMachine();+ sm.setName("intrinsic-test");+ sm.setStateMachineArn("arn:aws:states:us-east-1:000000000000:stateMachine:intrinsic-test");+ sm.setRoleArn("arn:aws:iam::000000000000:role/test-role");+ sm.setDefinition(definition);++ Execution exec = new Execution();+ exec.setName("intrinsic-test-execution");+ exec.setExecutionArn(+ "arn:aws:states:us-east-1:000000000000:execution:intrinsic-test:intrinsic-test-execution");+ exec.setStateMachineArn(sm.getStateMachineArn());+ exec.setInput(input);++ List<HistoryEvent> history = new ArrayList<>();+ executor.executeSync(sm, exec, history, (updated, events) -> {+ });+ return exec;+ }+}