Light, fluffy, and always free - The AWS Local Emulator alternative
feat(stepfunctions): close ASL gaps in intrinsics, Choice, StartExecution and ResultPath (#3002)
Guilherme Scaranse352d89ff2d2a
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 38e6a447a0..4dd7aa231f 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@@ -67,12 +67,16 @@ import org.jboss.logging.Logger;import java.net.URI;import java.nio.charset.StandardCharsets;+import java.security.MessageDigest;+import java.security.NoSuchAlgorithmException;import java.time.Instant;import java.time.ZoneOffset;import java.time.format.DateTimeFormatter;import java.util.ArrayList;+import java.util.Base64;import java.util.HashMap;import java.util.HashSet;+import java.util.HexFormat;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.List;@@ -128,6 +132,14 @@ public class AslExecutor {private static final int ECS_SYNC_POLL_ATTEMPTS = 600;private static final long ECS_SYNC_POLL_INTERVAL_MS = 100;+ // 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;+ // 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 =+ Set.of("MD5", "SHA-1", "SHA-256", "SHA-384", "SHA-512");+private static final String QUERY_LANGUAGE_JSONATA = "JSONata";private static final String AWS_SDK_SFN_PREFIX = "arn:aws:states:::aws-sdk:sfn:";private static final String AWS_SDK_SCHEDULER_PREFIX = "arn:aws:states:::aws-sdk:scheduler:";@@ -666,7 +678,8 @@ public class AslExecutor {try {taskResult = mockedSteps != null? mockedTaskResult(mockedSteps, stateName, attempt)- : invokeResource(effectiveResource, effectiveInput, sm, taskToken, executionDeadlineNanos);+ : invokeResource(effectiveResource, effectiveInput, sm, taskToken,+ executionDeadlineNanos, jsonata ? null : stateDef.path("Parameters"));if (tokenFuture != null) {taskResult = awaitToken(tokenFuture, stateDef, taskToken, executionDeadlineNanos);}@@ -847,7 +860,7 @@ public class AslExecutor {}private JsonNode invokeResource(String resource, JsonNode input, StateMachine sm, String taskToken,- long executionDeadlineNanos) throws Exception {+ long executionDeadlineNanos, JsonNode rawParameters) throws Exception {// Support Lambda resources: direct ARN or optimized integrationString functionName = null;JsonNode lambdaPayload = input;@@ -998,7 +1011,7 @@ public class AslExecutor {if (resource.startsWith("arn:aws:states:::states:startExecution")) {String mode = resource.substring("arn:aws:states:::states:startExecution".length());String region = extractRegionFromArn(sm.getStateMachineArn());- return invokeNestedStateMachine(mode, input, region, executionDeadlineNanos);+ return invokeNestedStateMachine(mode, input, region, executionDeadlineNanos, rawParameters);}// Activity resource: arn:aws:states:{region}:{account}:activity:{name}@@ -1332,17 +1345,35 @@ public class AslExecutor {}private JsonNode invokeNestedStateMachine(String mode, JsonNode input, String region,- long executionDeadlineNanos) throws Exception {+ long executionDeadlineNanos, JsonNode rawParameters) throws Exception {String smArn = input.path("StateMachineArn").asText(null);if (smArn == null || smArn.isBlank()) {throw new FailStateException("States.TaskFailed","StateMachineArn is required for nested state machine execution");}- JsonNode inputNode = input.path("Input");- String childInput = inputNode.isMissingNode() ? "{}" : objectMapper.writeValueAsString(inputNode);+ // Preserve provenance: an Input produced by States.JsonToString is JSON text whose content is the+ // child's wire input (so the child parses it back to an object); any other value is serialized as+ // a JSON value. Also honor Name/Name.$ instead of always generating a random execution name.+ boolean fromJsonToString = NestedExecutionInput.isJsonToStringInput(rawParameters);+ String childInput = NestedExecutionInput.childInput(input.path("Input"), fromJsonToString, objectMapper);++ // Honor Name/Name.$ without coercion: use it only when it resolves to a non-empty string. A Name+ // that was SUPPLIED (Name or Name.$ in the raw Parameters) but did not resolve to such a string is+ // a runtime error, not a silent fall-through to a generated name; a truly omitted Name generates one.+ JsonNode nameNode = input.path("Name");+ String childName;+ if (nameNode.isTextual() && !nameNode.asText().isBlank()) {+ childName = nameNode.asText();+ } else if (rawParameters != null && rawParameters.isObject()+ && (rawParameters.has("Name") || rawParameters.has("Name.$"))) {+ throw new FailStateException("States.Runtime",+ "Nested StartExecution 'Name' must resolve to a non-empty string");+ } else {+ childName = null;+ }io.github.hectorvent.floci.services.stepfunctions.model.Execution exec =- sfnService.get().startExecution(smArn, null, childInput, region);+ sfnService.get().startExecution(smArn, childName, childInput, region);String execArn = exec.getExecutionArn();if ("".equals(mode)) {@@ -1867,87 +1898,15 @@ public class AslExecutor {}private boolean evaluateCondition(JsonNode rule, JsonNode input) throws Exception {- // Logical operators- if (rule.has("And")) {- for (JsonNode sub : rule.get("And")) {- if (!evaluateCondition(sub, input)) return false;- }- return true;- }- if (rule.has("Or")) {- for (JsonNode sub : rule.get("Or")) {- if (evaluateCondition(sub, input)) return true;- }- return false;- }- if (rule.has("Not")) {- return !evaluateCondition(rule.get("Not"), input);- }-- String variable = rule.path("Variable").asText();- JsonNode value = resolvePath(variable, input);-- if (rule.has("StringEquals")) {- return value.asText().equals(rule.get("StringEquals").asText());- }- if (rule.has("StringEqualsPath")) {- return value.asText().equals(resolvePath(rule.get("StringEqualsPath").asText(), input).asText());- }- if (rule.has("StringMatches")) {- return value.asText().matches(globToRegex(rule.get("StringMatches").asText()));- }- if (rule.has("NumericEquals")) {- return value.asDouble() == rule.get("NumericEquals").asDouble();- }- if (rule.has("NumericEqualsPath")) {- return value.asDouble() == resolvePath(rule.get("NumericEqualsPath").asText(), input).asDouble();- }- if (rule.has("NumericLessThan")) {- return value.asDouble() < rule.get("NumericLessThan").asDouble();- }- if (rule.has("NumericLessThanPath")) {- return value.asDouble() < resolvePath(rule.get("NumericLessThanPath").asText(), input).asDouble();- }- if (rule.has("NumericGreaterThan")) {- return value.asDouble() > rule.get("NumericGreaterThan").asDouble();- }- if (rule.has("NumericGreaterThanPath")) {- return value.asDouble() > resolvePath(rule.get("NumericGreaterThanPath").asText(), input).asDouble();- }- if (rule.has("NumericLessThanEquals")) {- return value.asDouble() <= rule.get("NumericLessThanEquals").asDouble();- }- if (rule.has("NumericGreaterThanEquals")) {- return value.asDouble() >= rule.get("NumericGreaterThanEquals").asDouble();- }- if (rule.has("BooleanEquals")) {- return value.asBoolean() == rule.get("BooleanEquals").asBoolean();- }- if (rule.has("BooleanEqualsPath")) {- return value.asBoolean() == resolvePath(rule.get("BooleanEqualsPath").asText(), input).asBoolean();- }- if (rule.has("IsNull")) {- boolean expectNull = rule.get("IsNull").asBoolean();- return value.isNull() == expectNull;- }- if (rule.has("IsPresent")) {- boolean expectPresent = rule.get("IsPresent").asBoolean();- // 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();- }- if (rule.has("IsNumeric")) {- return value.isNumber() == rule.get("IsNumeric").asBoolean();- }- if (rule.has("IsBoolean")) {- return value.isBoolean() == rule.get("IsBoolean").asBoolean();+ // Comparator inventory, type-strict evaluation, and the missing-path/unknown-operator rules+ // live in ChoiceOperators so the runtime and the CreateStateMachine validator share one source+ // of truth. An undefined reference path or an unsupported comparator is a runtime error on AWS,+ // not a silently-false fallthrough to the Default branch.+ try {+ return ChoiceOperators.evaluate(rule, path -> resolvePathNode(path, input));+ } catch (ChoiceOperators.ChoiceEvaluationException e) {+ throw new FailStateException("States.Runtime", e.getMessage());}-- return false;}private StateResult executeWaitState(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context,@@ -2857,19 +2816,13 @@ public class AslExecutor {return result;}String resultPath = stateDef.get("ResultPath").asText();- if (resultPath == null || resultPath.equals("null")) {- return input;- }- if ("$".equals(resultPath)) {- return result;- }- // Merge result into input at the given path- if (!input.isObject()) {- return result;+ try {+ return ResultPathMerge.merge(input, resultPath, result, objectMapper);+ } catch (ResultPathMerge.ResultPathMatchException e) {+ // AWS fails a non-applicable ResultPath with States.ResultPathMatchFailure rather than+ // silently discarding the state input.+ throw new FailStateException("States.ResultPathMatchFailure", e.getMessage());}- ObjectNode merged = input.deepCopy();- setPath(merged, resultPath, result);- return merged;}private JsonNode applyOutputPath(JsonNode stateDef, JsonNode input, JsonNode output) {@@ -3379,7 +3332,9 @@ public class AslExecutor {/*** Evaluate a JSONPath-mode intrinsic function (States.*).* Supports: States.StringToJson, States.JsonToString, States.Format,- * States.Array, States.ArrayLength, States.ArrayContains, States.MathAdd, States.UUID.+ * States.Array, States.ArrayLength, States.ArrayContains, States.MathAdd, States.UUID,+ * States.JsonMerge, States.Base64Encode, States.Base64Decode, States.StringSplit,+ * States.ArrayGetItem, States.Hash.* Throws FailStateException("States.Runtime") for unrecognized functions.** <p>An argument that matches nothing fails the execution, and the cause names the whole@@ -3403,7 +3358,7 @@ public class AslExecutor {if (parenOpen < 0 || parenClose < 0) {throw new FailStateException("States.Runtime", "Malformed intrinsic function: " + expr);}- String fnName = expr.substring(0, parenOpen).trim();+ String fnName = NestedExecutionInput.intrinsicFunctionName(expr);String argsStr = expr.substring(parenOpen + 1, parenClose).trim();return switch (fnName) {@@ -3528,6 +3483,165 @@ public class AslExecutor {b.fields().forEachRemaining(e -> merged.set(e.getKey(), e.getValue()));yield merged;}+ case "States.Base64Encode" -> {+ List<String> parts = splitIntrinsicArgs(argsStr);+ if (parts.size() != 1 || argsStr.stripTrailing().endsWith(",")) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.Base64Encode requires exactly 1 argument");+ }+ JsonNode dataArg = resolveIntrinsicArg(parts.get(0).trim(), root, context);+ if (!dataArg.isTextual()) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.Base64Encode requires a string argument");+ }+ String data = dataArg.asText();+ if (data.codePointCount(0, data.length()) > INTRINSIC_MAX_INPUT_LENGTH) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.Base64Encode input exceeds " + INTRINSIC_MAX_INPUT_LENGTH + " characters");+ }+ // Basic (RFC 4648) encoder: AWS documents "MIME" but its real output is unwrapped;+ // Java's MIME encoder would insert CRLF line breaks every 76 characters.+ yield objectMapper.getNodeFactory().textNode(+ Base64.getEncoder().encodeToString(data.getBytes(StandardCharsets.UTF_8)));+ }+ case "States.Base64Decode" -> {+ List<String> parts = splitIntrinsicArgs(argsStr);+ if (parts.size() != 1 || argsStr.stripTrailing().endsWith(",")) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.Base64Decode requires exactly 1 argument");+ }+ JsonNode encodedArg = resolveIntrinsicArg(parts.get(0).trim(), root, context);+ if (!encodedArg.isTextual()) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.Base64Decode requires a string argument");+ }+ String encoded = encodedArg.asText();+ if (encoded.codePointCount(0, encoded.length()) > INTRINSIC_MAX_INPUT_LENGTH) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.Base64Decode input exceeds " + INTRINSIC_MAX_INPUT_LENGTH + " characters");+ }+ byte[] decoded;+ try {+ // Basic decoder, deliberately not MIME: the MIME decoder silently ignores+ // non-alphabet characters, which would turn invalid input into garbage output+ // instead of the required States.IntrinsicFailure.+ decoded = Base64.getDecoder().decode(encoded);+ } catch (IllegalArgumentException e) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.Base64Decode input is not valid base64");+ }+ // Bytes that are not valid UTF-8 become U+FFFD replacement characters.+ yield objectMapper.getNodeFactory().textNode(new String(decoded, StandardCharsets.UTF_8));+ }+ case "States.StringSplit" -> {+ List<String> parts = splitIntrinsicArgs(argsStr);+ if (parts.size() != 2 || argsStr.stripTrailing().endsWith(",")) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.StringSplit requires exactly 2 arguments");+ }+ JsonNode valueArg = resolveIntrinsicArg(parts.get(0).trim(), root, context);+ JsonNode delimitersArg = resolveIntrinsicArg(parts.get(1).trim(), root, context);+ if (!valueArg.isTextual() || !delimitersArg.isTextual()) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.StringSplit requires two string arguments");+ }+ String delimiters = delimitersArg.asText();+ if (delimiters.isEmpty()) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.StringSplit delimiter must not be empty");+ }+ // The second argument is a set of splitting characters. Membership is tested by+ // Unicode code point so a supplementary delimiter (e.g. an emoji) never matches the+ // lone surrogate halves of a different supplementary character in the input.+ Set<Integer> delimiterCodePoints = delimiters.codePoints().boxed().collect(Collectors.toSet());+ String value = valueArg.asText();+ ArrayNode result = objectMapper.createArrayNode();+ StringBuilder current = new StringBuilder();+ for (int i = 0; i < value.length(); ) {+ int codePoint = value.codePointAt(i);+ if (delimiterCodePoints.contains(codePoint)) {+ if (!current.isEmpty()) {+ // Empty segments (consecutive/leading/trailing delimiters) are omitted.+ result.add(objectMapper.getNodeFactory().textNode(current.toString()));+ current.setLength(0);+ }+ } else {+ current.appendCodePoint(codePoint);+ }+ i += Character.charCount(codePoint);+ }+ if (!current.isEmpty()) {+ result.add(objectMapper.getNodeFactory().textNode(current.toString()));+ }+ yield result;+ }+ case "States.ArrayGetItem" -> {+ List<String> parts = splitIntrinsicArgs(argsStr);+ if (parts.size() != 2 || argsStr.stripTrailing().endsWith(",")) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.ArrayGetItem requires exactly 2 arguments");+ }+ JsonNode array = resolveIntrinsicArg(parts.get(0).trim(), root, context);+ JsonNode indexNode = resolveIntrinsicArg(parts.get(1).trim(), root, context);+ if (!array.isArray()) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.ArrayGetItem first argument must be an array");+ }+ // isIntegralNumber rejects non-numbers and floating point; canConvertToInt rejects+ // integral values outside int range (a path-supplied BigInteger whose asInt() would+ // otherwise silently wrap and return the wrong element).+ if (!indexNode.isIntegralNumber() || !indexNode.canConvertToInt()) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.ArrayGetItem index must be a non-negative integer");+ }+ int index = indexNode.asInt();+ if (index < 0 || index >= array.size()) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.ArrayGetItem index " + index + " is out of bounds for length " + array.size());+ }+ yield array.get(index);+ }+ case "States.Hash" -> {+ List<String> parts = splitIntrinsicArgs(argsStr);+ if (parts.size() != 2 || argsStr.stripTrailing().endsWith(",")) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.Hash requires exactly 2 arguments");+ }+ JsonNode dataArg = resolveIntrinsicArg(parts.get(0).trim(), root, context);+ if (!dataArg.isTextual()) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.Hash first argument must be a string");+ }+ JsonNode algorithmArg = resolveIntrinsicArg(parts.get(1).trim(), root, context);+ if (!algorithmArg.isTextual()) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.Hash second argument must be a string");+ }+ String data = dataArg.asText();+ if (data.codePointCount(0, data.length()) > INTRINSIC_MAX_INPUT_LENGTH) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.Hash input exceeds " + INTRINSIC_MAX_INPUT_LENGTH + " characters");+ }+ String algorithm = algorithmArg.asText();+ // Explicit allow-list checked before getInstance: never a silent default, and the+ // caller's string is never passed to MessageDigest for an algorithm AWS rejects.+ if (!HASH_ALGORITHMS.contains(algorithm)) {+ throw new FailStateException("States.IntrinsicFailure",+ "States.Hash algorithm '" + algorithm+ + "' must be one of MD5, SHA-1, SHA-256, SHA-384, SHA-512");+ }+ try {+ MessageDigest digest = MessageDigest.getInstance(algorithm);+ // HexFormat: lowercase, fixed-width (preserves leading zeros, unlike BigInteger).+ yield objectMapper.getNodeFactory().textNode(+ HexFormat.of().formatHex(digest.digest(data.getBytes(StandardCharsets.UTF_8))));+ } catch (NoSuchAlgorithmException e) {+ // Unreachable after the allow-list check; defensive so a JDK regression could+ // never escape as an uncatchable States.Runtime.+ throw new FailStateException("States.IntrinsicFailure",+ "States.Hash algorithm '" + algorithm + "' is not available");+ }+ }default -> throw new FailStateException("States.Runtime","Unsupported intrinsic function: " + fnName);};@@ -3652,32 +3766,6 @@ public class AslExecutor {return s;}- private void setPath(ObjectNode root, String path, JsonNode value) {- if (!path.startsWith("$.") && !"$".equals(path)) {- return;- }- if ("$".equals(path)) {- return;- }- String[] parts = path.substring(2).split("\\.");- ObjectNode current = root;- for (int i = 0; i < parts.length - 1; i++) {- JsonNode next = current.path(parts[i]);- if (!next.isObject()) {- ObjectNode newNode = objectMapper.createObjectNode();- current.set(parts[i], newNode);- current = newNode;- } else {- current = (ObjectNode) next;- }- }- current.set(parts[parts.length - 1], value);- }-- private String globToRegex(String glob) {- return "\\Q" + glob.replace("*", "\\E.*\\Q") + "\\E";- }-// ──────────────────────────── History helpers ────────────────────────────/**diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/ChoiceOperators.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/ChoiceOperators.javanew file mode 100644index 0000000000..725210575f--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/ChoiceOperators.java@@ -0,0 +1,498 @@+package io.github.hectorvent.floci.services.stepfunctions;++import com.fasterxml.jackson.databind.JsonNode;++import java.math.BigDecimal;+import java.time.Instant;+import java.time.OffsetDateTime;+import java.time.format.DateTimeParseException;+import java.util.LinkedHashSet;+import java.util.List;+import java.util.Set;+import java.util.regex.Pattern;++/**+ * Choice-state comparison operators: the single source of truth for the ASL data-test+ * operator set, their <em>type-strict</em> evaluation, and the structural validation of+ * {@code Choice} rules.+ *+ * <p>Extracted from {@link AslExecutor} so the exact same operator inventory and semantics+ * are shared between the runtime evaluator and the {@code CreateStateMachine}/+ * {@code UpdateStateMachine} validator (they can no longer drift), and so the logic is+ * unit-testable without constructing the full Quarkus/Vert.x runtime that {@code AslExecutor}+ * requires.+ *+ * <p>Type strictness matches AWS: a comparator only matches when the resolved value and the+ * operand share the expected JSON type; a mismatched type yields {@code false} rather than a+ * coerced comparison. A {@code Variable} (or {@code *Path} operand) that resolves to a missing+ * path raises {@link ChoiceEvaluationException} for every operator except {@code IsPresent}+ * (which exists precisely to test presence); the caller maps that to a {@code States.Runtime}+ * failure. An unsupported field or a rule that does not carry exactly one operator is likewise a+ * runtime error, not a silently-false fallthrough to the {@code Default} branch.+ *+ * @see <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-choice-state.html">ASL Choice state</a>+ */+public final class ChoiceOperators {++ private ChoiceOperators() {+ }++ public static final Set<String> TYPE_TEST_OPERATORS = Set.of(+ "IsNull", "IsPresent", "IsNumeric", "IsString", "IsBoolean", "IsTimestamp");++ public static final Set<String> STRING_OPERATORS = Set.of(+ "StringEquals", "StringEqualsPath",+ "StringLessThan", "StringLessThanPath",+ "StringGreaterThan", "StringGreaterThanPath",+ "StringLessThanEquals", "StringLessThanEqualsPath",+ "StringGreaterThanEquals", "StringGreaterThanEqualsPath",+ "StringMatches");++ public static final Set<String> NUMERIC_OPERATORS = Set.of(+ "NumericEquals", "NumericEqualsPath",+ "NumericLessThan", "NumericLessThanPath",+ "NumericGreaterThan", "NumericGreaterThanPath",+ "NumericLessThanEquals", "NumericLessThanEqualsPath",+ "NumericGreaterThanEquals", "NumericGreaterThanEqualsPath");++ public static final Set<String> BOOLEAN_OPERATORS = Set.of(+ "BooleanEquals", "BooleanEqualsPath");++ public static final Set<String> TIMESTAMP_OPERATORS = Set.of(+ "TimestampEquals", "TimestampEqualsPath",+ "TimestampLessThan", "TimestampLessThanPath",+ "TimestampGreaterThan", "TimestampGreaterThanPath",+ "TimestampLessThanEquals", "TimestampLessThanEqualsPath",+ "TimestampGreaterThanEquals", "TimestampGreaterThanEqualsPath");++ /** The 39 documented data-test comparison operators (excludes the And/Or/Not logical operators). */+ public static final Set<String> DATA_TEST_OPERATORS = buildDataTestOperators();++ public static final Set<String> LOGICAL_OPERATORS = Set.of("And", "Or", "Not");++ /** Non-operator fields an individual Choice rule may carry. */+ public static final Set<String> RULE_STRUCTURAL_FIELDS = Set.of("Variable", "Comment", "Next", "Assign");++ private static Set<String> buildDataTestOperators() {+ Set<String> all = new LinkedHashSet<>();+ all.addAll(STRING_OPERATORS);+ all.addAll(NUMERIC_OPERATORS);+ all.addAll(BOOLEAN_OPERATORS);+ all.addAll(TIMESTAMP_OPERATORS);+ all.addAll(TYPE_TEST_OPERATORS);+ return Set.copyOf(all);+ }++ // RFC3339 profile AWS accepts: uppercase 'T'; seconds required; optional fraction of 1-9 digits+ // (java.time's nanosecond ceiling); 'Z' or a colonized numeric offset. Leap seconds (:60) and+ // fractions beyond 9 digits are not supported and are treated as invalid, a stated limitation.+ private static final Pattern RFC3339 = Pattern.compile(+ "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,9})?(Z|[+-]\\d{2}:\\d{2})$");++ /** Resolves an ASL reference path against the current input, preserving the missing/null distinction. */+ @FunctionalInterface+ public interface PathResolver {+ JsonNode resolve(String path) throws Exception;+ }++ /**+ * Raised for an undefined reference path, an unsupported/absent comparator, a malformed rule, or an+ * invalid {@code StringMatches} pattern. The runtime caller ({@link AslExecutor}) maps this to a+ * {@code States.Runtime} failure; the validator surfaces the same class of problem at Create/Update time.+ */+ public static final class ChoiceEvaluationException extends RuntimeException {+ public ChoiceEvaluationException(String message) {+ super(message);+ }+ }++ // ──────────────────────────── Evaluation ────────────────────────────++ /**+ * Evaluates a single Choice rule (including {@code And}/{@code Or}/{@code Not} nesting) against the+ * input reachable through {@code resolver}. Returns whether the rule matches.+ *+ * @throws ChoiceEvaluationException if the rule is malformed (unsupported field, or not exactly one+ * operator), a referenced path is undefined (non-{@code IsPresent}),+ * or a {@code StringMatches} pattern is invalid.+ */+ public static boolean evaluate(JsonNode rule, PathResolver resolver) throws Exception {+ // Runtime backstop: a malformed rule is a runtime error, not a silent one-branch pick. This also+ // catches state machines persisted before Create/Update validation rejected such rules.+ assertRuntimeWellFormed(rule);++ if (rule.has("And")) {+ for (JsonNode sub : rule.get("And")) {+ if (!evaluate(sub, resolver)) {+ return false;+ }+ }+ return true;+ }+ if (rule.has("Or")) {+ for (JsonNode sub : rule.get("Or")) {+ if (evaluate(sub, resolver)) {+ return true;+ }+ }+ return false;+ }+ if (rule.has("Not")) {+ return !evaluate(rule.get("Not"), resolver);+ }++ String operator = dataTestOperatorOf(rule);+ String variable = rule.path("Variable").asText(null);+ if (variable == null || variable.isEmpty()) {+ throw new ChoiceEvaluationException(+ "Choice rule with operator '" + operator + "' is missing the required 'Variable' field");+ }+ JsonNode value = resolver.resolve(variable);+ if (!"IsPresent".equals(operator) && (value == null || value.isMissingNode())) {+ throw new ChoiceEvaluationException(+ "Invalid path '" + variable + "': the Choice rule references an undefined value");+ }+ return evaluateLeaf(operator, value, rule.get(operator), resolver);+ }++ /** Rejects rules with an unsupported field or without exactly one comparison/logical operator. */+ private static void assertRuntimeWellFormed(JsonNode rule) {+ int logical = 0;+ int dataTest = 0;+ var it = rule.fieldNames();+ while (it.hasNext()) {+ String field = it.next();+ if (LOGICAL_OPERATORS.contains(field)) {+ logical++;+ } else if (DATA_TEST_OPERATORS.contains(field)) {+ dataTest++;+ } else if (!RULE_STRUCTURAL_FIELDS.contains(field)) {+ throw new ChoiceEvaluationException("Unsupported field '" + field + "' in Choice rule");+ }+ }+ if (logical + dataTest != 1) {+ throw new ChoiceEvaluationException(+ "Choice rule must contain exactly one comparison operator or one of And/Or/Not");+ }+ }++ private static boolean evaluateLeaf(String op, JsonNode value, JsonNode operand, PathResolver resolver)+ throws Exception {+ // Presence / type predicates (operand is the expected boolean).+ switch (op) {+ case "IsPresent":+ return (value != null && !value.isMissingNode()) == operand.asBoolean();+ case "IsNull":+ return value.isNull() == operand.asBoolean();+ case "IsString":+ return value.isTextual() == operand.asBoolean();+ case "IsNumeric":+ return value.isNumber() == operand.asBoolean();+ case "IsBoolean":+ return value.isBoolean() == operand.asBoolean();+ case "IsTimestamp":+ return (value.isTextual() && isRfc3339(value.asText())) == operand.asBoolean();+ case "StringMatches":+ return value.isTextual() && Pattern.matches(stringMatchesToRegex(operand.asText()), value.asText());+ default:+ break;+ }++ boolean isPath = op.endsWith("Path");+ String core = isPath ? op.substring(0, op.length() - "Path".length()) : op;+ JsonNode rhs = isPath ? resolveRequired(resolver, operand.asText()) : operand;++ if (core.startsWith("String")) {+ if (!value.isTextual() || !rhs.isTextual()) {+ return false;+ }+ return applyComparison(value.asText().compareTo(rhs.asText()), core.substring("String".length()));+ }+ if (core.startsWith("Numeric")) {+ if (!value.isNumber() || !rhs.isNumber()) {+ return false;+ }+ BigDecimal a = value.decimalValue();+ BigDecimal b = rhs.decimalValue();+ return applyComparison(a.compareTo(b), core.substring("Numeric".length()));+ }+ if (core.startsWith("Boolean")) {+ // Only BooleanEquals[Path] exists.+ if (!value.isBoolean() || !rhs.isBoolean()) {+ return false;+ }+ return value.asBoolean() == rhs.asBoolean();+ }+ if (core.startsWith("Timestamp")) {+ if (!value.isTextual() || !rhs.isTextual()) {+ return false;+ }+ Instant a = parseRfc3339(value.asText());+ Instant b = parseRfc3339(rhs.asText());+ if (a == null || b == null) {+ return false;+ }+ return applyComparison(a.compareTo(b), core.substring("Timestamp".length()));+ }+ // Unreachable given assertRuntimeWellFormed + dataTestOperatorOf, but fail loud rather than silent.+ throw new ChoiceEvaluationException("Unsupported comparison operator: " + op);+ }++ private static boolean applyComparison(int cmp, String kind) {+ switch (kind) {+ case "Equals":+ return cmp == 0;+ case "LessThan":+ return cmp < 0;+ case "GreaterThan":+ return cmp > 0;+ case "LessThanEquals":+ return cmp <= 0;+ case "GreaterThanEquals":+ return cmp >= 0;+ default:+ throw new ChoiceEvaluationException("Unsupported comparison kind: " + kind);+ }+ }++ private static JsonNode resolveRequired(PathResolver resolver, String path) throws Exception {+ JsonNode node = resolver.resolve(path);+ if (node == null || node.isMissingNode()) {+ throw new ChoiceEvaluationException(+ "Invalid path '" + path + "': the Choice rule references an undefined value");+ }+ return node;+ }++ private static String dataTestOperatorOf(JsonNode rule) {+ var it = rule.fieldNames();+ while (it.hasNext()) {+ String field = it.next();+ if (DATA_TEST_OPERATORS.contains(field)) {+ return field;+ }+ }+ return null;+ }++ static boolean isRfc3339(String text) {+ return parseRfc3339(text) != null;+ }++ private static Instant parseRfc3339(String text) {+ if (text == null || !RFC3339.matcher(text).matches()) {+ return null;+ }+ try {+ return OffsetDateTime.parse(text).toInstant();+ } catch (DateTimeParseException e) {+ return null;+ }+ }++ /**+ * Compiles an ASL {@code StringMatches} pattern to an anchored regex. The only wildcard is {@code *};+ * {@code \\*} is a literal asterisk, {@code \\\\} a literal backslash, and a backslash followed by+ * anything else (or a dangling backslash) is an error, per the ASL specification.+ */+ static String stringMatchesToRegex(String glob) {+ StringBuilder regex = new StringBuilder();+ StringBuilder literal = new StringBuilder();+ for (int i = 0; i < glob.length(); i++) {+ char c = glob.charAt(i);+ if (c == '\\') {+ if (i + 1 >= glob.length()) {+ throw new ChoiceEvaluationException(+ "Invalid StringMatches pattern (dangling escape): '" + glob + "'");+ }+ char next = glob.charAt(++i);+ if (next != '*' && next != '\\') {+ throw new ChoiceEvaluationException(+ "Invalid StringMatches pattern (illegal escape '\\" + next + "'): '" + glob + "'");+ }+ literal.append(next);+ } else if (c == '*') {+ if (literal.length() > 0) {+ regex.append(Pattern.quote(literal.toString()));+ literal.setLength(0);+ }+ regex.append(".*");+ } else {+ literal.append(c);+ }+ }+ if (literal.length() > 0) {+ regex.append(Pattern.quote(literal.toString()));+ }+ return regex.toString();+ }++ // ──────────────────────────── Validation ────────────────────────────++ /**+ * Structurally validates a single Choice rule (recursing through {@code And}/{@code Or}/{@code Not}),+ * appending human-readable messages to {@code errors}. Enforces the field allowlist, exactly one+ * comparison-or-logical operator per rule, reference-path syntax for {@code Variable}/{@code *Path}+ * operands, per-family operand JSON types, valid {@code StringMatches} patterns, {@code Assign} being an+ * object, logical operand shapes, and {@code Next} placement (required at the top level of a Choices+ * entry, forbidden on nested operands).+ */+ public static void validateChoiceRule(String path, JsonNode rule, boolean topLevel, List<String> errors) {+ if (rule == null || !rule.isObject()) {+ errors.add("Choice rule must be a JSON object at " + path);+ return;+ }++ int logicalCount = 0;+ int dataTestCount = 0;+ var names = rule.fieldNames();+ while (names.hasNext()) {+ String field = names.next();+ if (LOGICAL_OPERATORS.contains(field)) {+ logicalCount++;+ } else if (DATA_TEST_OPERATORS.contains(field)) {+ dataTestCount++;+ } else if (!RULE_STRUCTURAL_FIELDS.contains(field)) {+ errors.add("Choice rule has unsupported field '" + field + "' at " + path);+ }+ }++ if (logicalCount + dataTestCount != 1) {+ errors.add("Choice rule must contain exactly one comparison operator or one of And/Or/Not at " + path);+ }++ if (rule.has("Assign") && !rule.get("Assign").isObject()) {+ errors.add("'Assign' must be a JSON object at " + path);+ }++ // Next placement: required at the top level of a Choices entry, forbidden on nested operands.+ boolean hasNext = rule.path("Next").isTextual();+ if (topLevel && !hasNext) {+ errors.add("Choice rule must declare a string 'Next' at " + path);+ } else if (!topLevel && rule.has("Next")) {+ errors.add("Nested Choice rule (inside And/Or/Not) must not declare 'Next' at " + path);+ }++ if (logicalCount == 1) {+ if (rule.has("Variable")) {+ errors.add("Logical Choice rule (And/Or/Not) must not declare 'Variable' at " + path);+ }+ if (rule.has("And") || rule.has("Or")) {+ String key = rule.has("And") ? "And" : "Or";+ JsonNode arr = rule.get(key);+ if (!arr.isArray() || arr.isEmpty()) {+ errors.add("'" + key + "' must be a non-empty array at " + path);+ } else {+ for (int i = 0; i < arr.size(); i++) {+ validateChoiceRule(path + "/" + key + "/" + i, arr.get(i), false, errors);+ }+ }+ } else { // Not+ JsonNode not = rule.get("Not");+ if (!not.isObject()) {+ errors.add("'Not' must be a single object at " + path);+ } else {+ validateChoiceRule(path + "/Not", not, false, errors);+ }+ }+ return;+ }++ if (dataTestCount == 1) {+ JsonNode variable = rule.path("Variable");+ if (!variable.isTextual() || !isReferencePath(variable.asText())) {+ errors.add("Choice comparison rule must declare a valid reference-path 'Variable' at " + path);+ }+ String op = dataTestOperatorOf(rule);+ if (op != null) {+ validateOperandType(path, op, rule.get(op), errors);+ }+ }+ }++ private static void validateOperandType(String path, String op, JsonNode operand, List<String> errors) {+ if (TYPE_TEST_OPERATORS.contains(op)) {+ if (!operand.isBoolean()) {+ errors.add("Operator '" + op + "' requires a boolean operand at " + path);+ }+ return;+ }+ if (op.endsWith("Path")) {+ if (!operand.isTextual() || !isReferencePath(operand.asText())) {+ errors.add("Operator '" + op + "' requires a reference-path string operand at " + path);+ }+ return;+ }+ if ("StringMatches".equals(op)) {+ if (!operand.isTextual()) {+ errors.add("Operator 'StringMatches' requires a string operand at " + path);+ } else {+ try {+ stringMatchesToRegex(operand.asText());+ } catch (ChoiceEvaluationException e) {+ errors.add(e.getMessage() + " at " + path);+ }+ }+ return;+ }+ if (STRING_OPERATORS.contains(op)) {+ if (!operand.isTextual()) {+ errors.add("Operator '" + op + "' requires a string operand at " + path);+ }+ } else if (TIMESTAMP_OPERATORS.contains(op)) {+ if (!operand.isTextual()) {+ errors.add("Operator '" + op + "' requires a string operand at " + path);+ } else if (!isRfc3339(operand.asText())) {+ errors.add("Operator '" + op + "' requires an RFC3339 timestamp operand at " + path);+ }+ } else if (NUMERIC_OPERATORS.contains(op)) {+ if (!operand.isNumber()) {+ errors.add("Operator '" + op + "' requires a numeric operand at " + path);+ }+ } else if (BOOLEAN_OPERATORS.contains(op)) {+ if (!operand.isBoolean()) {+ errors.add("Operator '" + op + "' requires a boolean operand at " + path);+ }+ }+ }++ /**+ * Pragmatic ASL reference-path syntax check: must start with {@code $}; {@code $} alone is valid; a+ * longer path must be a sequence of non-empty {@code .segment} steps and balanced non-empty+ * {@code [..]} steps. Rejects the common malformations ({@code not-a-path}, {@code $.}, {@code $[}).+ */+ static boolean isReferencePath(String p) {+ if (p == null || p.isEmpty() || p.charAt(0) != '$') {+ return false;+ }+ if (p.equals("$")) {+ return true;+ }+ if (!p.startsWith("$.") && !p.startsWith("$[")) {+ return false;+ }+ int i = 1;+ while (i < p.length()) {+ char c = p.charAt(i);+ if (c == '.') {+ int j = i + 1;+ while (j < p.length() && p.charAt(j) != '.' && p.charAt(j) != '[') {+ j++;+ }+ if (j == i + 1) {+ return false; // empty segment: "$." or "$.."+ }+ i = j;+ } else if (c == '[') {+ int close = p.indexOf(']', i);+ if (close < 0 || close == i + 1) {+ return false; // unclosed or empty "[]"+ }+ i = close + 1;+ } else {+ return false;+ }+ }+ return true;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/NestedExecutionInput.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/NestedExecutionInput.javanew file mode 100644index 0000000000..47a4078d05--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/NestedExecutionInput.java@@ -0,0 +1,94 @@+package io.github.hectorvent.floci.services.stepfunctions;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;++/**+ * Encodes the child execution input for a nested {@code states:startExecution} Task, preserving the+ * provenance needed to distinguish a value produced by {@code States.JsonToString} (JSON <em>text</em>+ * that must become the child's object {@code $}) from an ordinary string value that merely looks like+ * JSON.+ *+ * <p>Extracted from {@link AslExecutor} for two reasons: (1) the intrinsic function-name parse is the+ * SAME one {@code evaluateIntrinsic} uses (see {@link #intrinsicFunctionName}), so the provenance check+ * and the evaluator cannot drift apart as parser tolerance changes; and (2) the encoding rules are then+ * unit-testable without constructing the Vert.x-bound {@code AslExecutor}.+ *+ * <p>AWS semantics: {@code StartExecution}'s wire input is a string that the child parses as JSON.+ * {@code States.JsonToString(x)} returns a string whose content is JSON text, so that content is used+ * verbatim as the wire input (the child gets {@code x} back as an object). Any other resolved value is+ * serialized as a JSON value: an object stays an object, a plain string stays a JSON string literal.+ */+public final class NestedExecutionInput {++ private NestedExecutionInput() {+ }++ /**+ * The function name of an intrinsic-call expression (e.g. {@code "States.JsonToString"}), or+ * {@code null} if {@code expr} is not a call. This is the exact parse {@code AslExecutor.evaluateIntrinsic}+ * performs, shared so provenance detection and evaluation stay in lockstep (tolerating the same+ * whitespace, e.g. {@code States.JsonToString ($.x)}).+ */+ public static String intrinsicFunctionName(String expr) {+ if (expr == null) {+ return null;+ }+ int paren = expr.indexOf('(');+ if (paren < 0) {+ return null;+ }+ return expr.substring(0, paren).trim();+ }++ /**+ * Whether the resolved {@code Input} came from a top-level {@code "Input.$": "States.JsonToString(...)"}+ * template. Provenance is intentionally top-level and syntactic: {@code States.JsonToString} nested+ * inside another intrinsic (e.g. {@code States.Format(...)}) follows the plain-value rule, which is+ * the safe direction. JSONata Tasks use {@code Arguments} (not {@code Parameters}) and are out of scope.+ */+ public static boolean isJsonToStringInput(JsonNode rawParameters) {+ if (rawParameters == null || !rawParameters.isObject()) {+ return false;+ }+ JsonNode inputDollar = rawParameters.get("Input.$");+ return inputDollar != null && inputDollar.isTextual()+ && "States.JsonToString".equals(intrinsicFunctionName(inputDollar.asText()));+ }++ /**+ * The wire input string passed to the child execution.+ *+ * <ul>+ * <li>missing {@code Input} → {@code "{}"}</li>+ * <li>{@code fromJsonToString} and textual → the value's content verbatim (it is already JSON text,+ * so the child parses it back to an object)</li>+ * <li>otherwise → the value serialized as a JSON value (object stays object; plain/JSON-looking+ * string stays a JSON string literal)</li>+ * </ul>+ */+ public static String childInput(JsonNode inputNode, boolean fromJsonToString, ObjectMapper mapper)+ throws JsonProcessingException {+ if (inputNode == null || inputNode.isMissingNode()) {+ return "{}";+ }+ // Use the value verbatim only when it is genuinely JSON text (a States.JsonToString result always+ // is). This guards a malformed template with colliding Input / Input.$ keys, where the winning+ // resolved value may not be JSON despite the Input.$ provenance. Such a value is quoted instead+ // of sent verbatim (avoiding parseInput's {} fallback).+ if (fromJsonToString && inputNode.isTextual() && isJsonText(inputNode.asText(), mapper)) {+ return inputNode.asText();+ }+ return mapper.writeValueAsString(inputNode);+ }++ private static boolean isJsonText(String text, ObjectMapper mapper) {+ try {+ mapper.readTree(text);+ return true;+ } catch (JsonProcessingException e) {+ return false;+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/ResultPathMerge.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/ResultPathMerge.javanew file mode 100644index 0000000000..ded0095a87--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/ResultPathMerge.java@@ -0,0 +1,87 @@+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.ObjectNode;++/**+ * Applies a state's JSONPath {@code ResultPath}, merging the state result into the effective input.+ * Extracted from {@link AslExecutor} so the merge rules (including the AWS+ * {@code States.ResultPathMatchFailure} case) are unit-testable without the Vert.x-bound executor.+ *+ * <p>AWS: {@code ResultPath} names where the result is inserted into the state's raw input. When the+ * input is not a JSON object but {@code ResultPath} addresses an object member (a {@code $.field} path),+ * the path cannot apply and the interpreter fails with {@code States.ResultPathMatchFailure}. It does+ * NOT silently discard the input.+ *+ * @see <a href="https://states-language.net/spec.html#filters">ASL ResultPath</a>+ */+public final class ResultPathMerge {++ private ResultPathMerge() {+ }++ /** Raised when a {@code ResultPath} cannot be applied to the given input; the caller maps it to {@code States.ResultPathMatchFailure}. */+ public static final class ResultPathMatchException extends RuntimeException {+ public ResultPathMatchException(String message) {+ super(message);+ }+ }++ /**+ * Merge {@code result} into {@code input} at {@code resultPath}.+ *+ * <ul>+ * <li>{@code null} / literal {@code "null"} ResultPath → keep {@code input} (result discarded, per AWS)</li>+ * <li>{@code "$"} → replace with {@code result}</li>+ * <li>a {@code $.field} path into a non-object input → {@link ResultPathMatchException} (was silently+ * discarding the input)</li>+ * <li>object input → a deep copy with {@code result} set at the path</li>+ * </ul>+ *+ * <p>Known residuals (unchanged, pre-existing {@link #setPath} limitations): a {@code $[...]}-style+ * ResultPath is not applied (returns the result for a non-object input, and is a no-op merge for an+ * object input), and a {@code $.a.b} path whose {@code $.a} is a scalar is silently overwritten rather+ * than raising {@code States.ResultPathMatchFailure}.+ */+ public static JsonNode merge(JsonNode input, String resultPath, JsonNode result, ObjectMapper mapper) {+ if (resultPath == null || resultPath.equals("null")) {+ return input;+ }+ if ("$".equals(resultPath)) {+ return result;+ }+ if (!input.isObject()) {+ if (resultPath.startsWith("$.")) {+ throw new ResultPathMatchException(+ "Failed to apply ResultPath '" + resultPath + "': the state input is not a JSON object");+ }+ return result; // non-$. paths ($[...]) are a documented residual: unchanged behavior+ }+ ObjectNode merged = input.deepCopy();+ setPath(merged, resultPath, result, mapper);+ return merged;+ }++ private static void setPath(ObjectNode root, String path, JsonNode value, ObjectMapper mapper) {+ if (!path.startsWith("$.") && !"$".equals(path)) {+ return;+ }+ if ("$".equals(path)) {+ return;+ }+ String[] parts = path.substring(2).split("\\.");+ ObjectNode current = root;+ for (int i = 0; i < parts.length - 1; i++) {+ JsonNode next = current.path(parts[i]);+ if (!next.isObject()) {+ ObjectNode newNode = mapper.createObjectNode();+ current.set(parts[i], newNode);+ current = newNode;+ } else {+ current = (ObjectNode) next;+ }+ }+ current.set(parts[parts.length - 1], value);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.javaindex 6a61a22546..2c6f20b69a 100644--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java@@ -52,6 +52,9 @@ public class StepFunctionsService implements Resettable, ResourceProvider {// When each pending token last showed progress, so a Task's HeartbeatSeconds can bound the gap// between heartbeats instead of the whole wait.private final Map<String, Long> taskHeartbeatNanos = new ConcurrentHashMap<>();+ // Serializes the StartExecution check-and-create so two concurrent calls with the same name cannot+ // both create and launch an execution; also enables AWS idempotent-success for STANDARD workflows.+ private final Object executionStartLock = new Object();private final RegionResolver regionResolver;private final AslExecutor aslExecutor;private final ObjectMapper objectMapper;@@ -527,29 +530,42 @@ public class StepFunctionsService implements Resettable, ResourceProvider {var execName = (name != null && !name.isBlank()) ? name : UUID.randomUUID().toString();var arn = regionResolver.buildArn("states", region, "execution:" + sm.getName() + ":" + execName);- if (executionStore.get(arn).isPresent()) {- throw new AwsException("ExecutionAlreadyExists", "Execution already exists: " + arn, 400);- }-- var exec = new Execution();- exec.setExecutionArn(arn);- exec.setStateMachineArn(selection.stateMachineArn());- exec.setName(execName);- exec.setInput(input);- exec.setStatus("RUNNING");-- executionStore.put(arn, exec);+ Execution exec;+ ExecutionHistory history;+ synchronized (executionStartLock) {+ Optional<Execution> existing = executionStore.get(arn);+ if (existing.isPresent()) {+ Execution prior = existing.get();+ // AWS idempotency (STANDARD only): the same name + same input while the original is still+ // RUNNING returns the original execution as a success; a different input, or a closed+ // execution with that name, is a conflict. EXPRESS workflows get no idempotency guarantee.+ if ("STANDARD".equals(sm.getType())+ && "RUNNING".equals(prior.getStatus())+ && Objects.equals(prior.getInput(), input)) {+ return prior;+ }+ throw new AwsException("ExecutionAlreadyExists", "Execution already exists: " + arn, 400);+ }- var history = new ExecutionHistory();- var startEvent = new HistoryEvent();- startEvent.setId(1L);- startEvent.setPreviousEventId(0L);- startEvent.setType("ExecutionStarted");- startEvent.setDetails(Map.of("input", input != null ? input : "{}",- "roleArn", sm.getRoleArn() != null ? sm.getRoleArn() : "",- "inputDetails", Map.of("truncated", false)));- history.add(startEvent);- historyCache.put(arn, history);+ exec = new Execution();+ exec.setExecutionArn(arn);+ exec.setStateMachineArn(selection.stateMachineArn());+ exec.setName(execName);+ exec.setInput(input);+ exec.setStatus("RUNNING");+ executionStore.put(arn, exec);++ history = new ExecutionHistory();+ var startEvent = new HistoryEvent();+ startEvent.setId(1L);+ startEvent.setPreviousEventId(0L);+ startEvent.setType("ExecutionStarted");+ startEvent.setDetails(Map.of("input", input != null ? input : "{}",+ "roleArn", sm.getRoleArn() != null ? sm.getRoleArn() : "",+ "inputDetails", Map.of("truncated", false)));+ history.add(startEvent);+ historyCache.put(arn, history);+ }LOG.infov("Started execution: {0}", arn);@@ -1769,6 +1785,16 @@ public class StepFunctionsService implements Resettable, ResourceProvider {collectTopLevelReferences(statePath, stateDef, errors);}+ // Structurally validate JSONPath Choice rules (comparator allowlist, exactly-one operator,+ // per-family operand types, And/Or/Not shapes, Next placement). JSONata Choice uses a+ // Condition string and is validated elsewhere.+ if (choiceType && !stateIsJsonata && stateDef.path("Choices").isArray()) {+ JsonNode choices = stateDef.path("Choices");+ for (int i = 0; i < choices.size(); i++) {+ ChoiceOperators.validateChoiceRule(statePath + "/Choices/" + i, choices.get(i), true, errors);+ }+ }+if ("Map".equals(stateType)) {validateMapConcurrency(statePath, stateDef, stateIsJsonata, errors);if (stateDef.has("ItemReader")) {diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorChoiceRuntimeTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorChoiceRuntimeTest.javanew file mode 100644index 0000000000..db5a096774--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorChoiceRuntimeTest.java@@ -0,0 +1,154 @@+package io.github.hectorvent.floci.services.stepfunctions;++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 com.fasterxml.jackson.databind.ObjectMapper;+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 static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.Mockito.mock;++/**+ * End-to-end Choice-state routing through the full {@code executeSync} loop, covering the+ * {@link AslExecutor} delegation to {@link ChoiceOperators} and the mapping of a+ * {@code ChoiceEvaluationException} to a {@code States.Runtime} execution failure. Complements the+ * unit-level {@link ChoiceOperatorsTest} by exercising the actual wiring the comparator fix depends on.+ *+ * <p>Plain JUnit5 (mirrors {@code AslExecutorIntrinsicFunctionsTest}'s harness), executed by CI only:+ * it cannot run in the offline sandbox because a full {@code AslExecutor} compile pulls in Vert.x.+ */+class AslExecutorChoiceRuntimeTest {++ 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 static final String GTE_MACHINE = """+ {+ "StartAt": "Pick",+ "States": {+ "Pick": {+ "Type": "Choice",+ "Choices": [{"Variable": "$.a", "NumericGreaterThanEqualsPath": "$.b", "Next": "TAKEN"}],+ "Default": "FELL"+ },+ "TAKEN": {"Type": "Pass", "End": true},+ "FELL": {"Type": "Fail", "Error": "FELL", "Cause": "took the Default branch"}+ }+ }+ """;++ @Test+ void numericGreaterThanEqualsPath_routesToTakenWhenTrue() {+ // 5 >= 3: previously the unsupported comparator was silently false and the machine took Default (FELL, a Fail).+ assertEquals("SUCCEEDED", run(GTE_MACHINE, "{\"a\":5,\"b\":3}").getStatus());+ assertEquals("SUCCEEDED", run(GTE_MACHINE, "{\"a\":3,\"b\":3}").getStatus());+ }++ @Test+ void numericGreaterThanEqualsPath_routesToDefaultWhenFalse() {+ Execution exec = run(GTE_MACHINE, "{\"a\":2,\"b\":3}"); // 2 >= 3 is false -> Default -> FELL (Fail)+ assertEquals("FAILED", exec.getStatus());+ }++ @Test+ void unknownComparatorFailsExecutionWithStatesRuntime() {+ // executeSync bypasses create-time validation, so the runtime backstop must fire loudly.+ Execution exec = run("""+ {+ "StartAt": "Pick",+ "States": {+ "Pick": {+ "Type": "Choice",+ "Choices": [{"Variable": "$.a", "NumericSpicyThan": 1, "Next": "TAKEN"}],+ "Default": "FELL"+ },+ "TAKEN": {"Type": "Pass", "End": true},+ "FELL": {"Type": "Pass", "End": true}+ }+ }+ """, "{\"a\":5}");+ assertEquals("FAILED", exec.getStatus());+ assertEquals("States.Runtime", exec.getError());+ }++ @Test+ void missingPathFailsExecutionWithStatesRuntime() {+ Execution exec = run("""+ {+ "StartAt": "Pick",+ "States": {+ "Pick": {+ "Type": "Choice",+ "Choices": [{"Variable": "$.missing", "NumericGreaterThan": 1, "Next": "TAKEN"}],+ "Default": "FELL"+ },+ "TAKEN": {"Type": "Pass", "End": true},+ "FELL": {"Type": "Pass", "End": true}+ }+ }+ """, "{\"a\":5}");+ assertEquals("FAILED", exec.getStatus());+ assertEquals("States.Runtime", exec.getError());+ }++ private Execution run(String definition, String input) {+ StateMachine sm = new StateMachine();+ sm.setName("choice-test");+ sm.setStateMachineArn("arn:aws:states:us-east-1:000000000000:stateMachine:choice-test");+ sm.setRoleArn("arn:aws:iam::000000000000:role/test-role");+ sm.setDefinition(definition);++ Execution exec = new Execution();+ exec.setName("choice-test-execution");+ exec.setExecutionArn(+ "arn:aws:states:us-east-1:000000000000:execution:choice-test:choice-test-execution");+ exec.setStateMachineArn(sm.getStateMachineArn());+ exec.setInput(input);++ List<HistoryEvent> history = new ArrayList<>();+ executor.executeSync(sm, exec, history, (updated, events) -> {+ });+ return exec;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicFunctionsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicFunctionsTest.javanew file mode 100644index 0000000000..46bb9c3e56--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorIntrinsicFunctionsTest.java@@ -0,0 +1,542 @@+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.ObjectNode;+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 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;++/**+ * Functionality + regression coverage for the five JSONPath-mode intrinsic functions added+ * alongside the existing nine: {@code States.Base64Encode}, {@code States.Base64Decode},+ * {@code States.StringSplit}, {@code States.ArrayGetItem}, and {@code States.Hash}. Before this+ * change each aborted execution with "Unsupported intrinsic function: States.<Name>"+ * ({@code States.Runtime}).+ *+ * <p>AWS-documented examples are used as fixtures where they exist (StringSplit and ArrayGetItem+ * doc examples; a computed SHA-256/SHA-1/MD5 of "input data"). AWS's published SHA-1 example digest+ * is a 39-character typo, so the true 40-character digest is asserted instead. Every failure case+ * asserts the exact {@code States.IntrinsicFailure} error name (catchable), never a bare+ * RuntimeException. A reverted implementation would instead throw the uncatchable+ * {@code States.Runtime}, so a bare-throw assertion would silently pass against broken code.+ */+class AslExecutorIntrinsicFunctionsTest {++ 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();+ }++ // ---------- A. States.Base64Encode ----------++ @Test+ void base64EncodeMatchesAwsDocExample() throws Exception {+ JsonNode root = mapper.readTree("{\"data\":\"Data to encode\"}");+ assertEquals("RGF0YSB0byBlbmNvZGU=",+ executor.resolvePath("States.Base64Encode($.data)", root).asText());+ }++ @Test+ void base64EncodeUsesBasicAlphabetNotUrlSafe() {+ assertEquals("Pj4+", executor.resolvePath("States.Base64Encode('>>>')", obj()).asText());+ assertEquals("Pz8/", executor.resolvePath("States.Base64Encode('???')", obj()).asText());+ }++ @Test+ void base64EncodeDoesNotMimeWrapLongOutput() {+ ObjectNode root = mapper.createObjectNode();+ root.put("s", "a".repeat(100));+ String out = executor.resolvePath("States.Base64Encode($.s)", root).asText();+ assertEquals(136, out.length());+ assertFalse(out.contains("\n"), "Basic encoder must not insert line breaks");+ assertFalse(out.contains("\r"), "Basic encoder must not insert carriage returns");+ }++ @Test+ void base64EncodeOfEmptyStringIsEmptyString() {+ assertEquals("", executor.resolvePath("States.Base64Encode('')", obj()).asText());+ }++ @Test+ void base64EncodeAtExactly10000CharsSucceeds() {+ ObjectNode root = mapper.createObjectNode();+ root.put("s", "a".repeat(10_000));+ assertEquals(13_336, executor.resolvePath("States.Base64Encode($.s)", root).asText().length());+ }++ @Test+ void base64EncodeOver10000CharsIsIntrinsicFailure() {+ ObjectNode root = mapper.createObjectNode();+ root.put("s", "a".repeat(10_001));+ assertIntrinsicFailure(root, "States.Base64Encode($.s)");+ }++ @Test+ void base64EncodeCapCountsCodePointsNotUtf16Units() {+ // 5,001 astral characters = 5,001 code points but 10,002 UTF-16 units. A String.length()+ // based cap would wrongly reject this; the code-point cap accepts it.+ ObjectNode root = mapper.createObjectNode();+ root.put("s", "😀".repeat(5_001));+ assertFalse(executor.resolvePath("States.Base64Encode($.s)", root).asText().isEmpty());+ }++ @Test+ void base64EncodeNonStringArgumentIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"n\":5}"), "States.Base64Encode($.n)");+ }++ @Test+ void base64EncodeWrongArgumentCountIsIntrinsicFailure() throws Exception {+ JsonNode root = mapper.readTree("{\"a\":\"x\",\"b\":\"y\"}");+ assertIntrinsicFailure(root, "States.Base64Encode($.a, $.b)");+ }++ // ---------- B. States.Base64Decode ----------++ @Test+ void base64DecodeMatchesAwsDocExample() {+ assertEquals("Data to encode",+ executor.resolvePath("States.Base64Decode('RGF0YSB0byBlbmNvZGU=')", obj()).asText());+ }++ @Test+ void base64RoundTripsThroughNestedIntrinsics() throws Exception {+ JsonNode root = mapper.readTree("{\"s\":\"round trip value\"}");+ assertEquals("round trip value",+ executor.resolvePath("States.Base64Decode(States.Base64Encode($.s))", root).asText());+ }++ @Test+ void base64DecodeInvalidInputIsIntrinsicFailure() {+ assertIntrinsicFailure(obj(), "States.Base64Decode('not base64!!!')");+ }++ @Test+ void base64DecodeRejectsEmbeddedWhitespace() throws Exception {+ // The Basic decoder rejects embedded line breaks (the MIME decoder would silently ignore+ // them). Pinned so the deliberate Basic-vs-MIME choice cannot regress unnoticed.+ JsonNode root = mapper.readTree("{\"b\":\"RGF0\\nYQ==\"}");+ assertIntrinsicFailure(root, "States.Base64Decode($.b)");+ }++ @Test+ void base64DecodeAtExactly10000CharsSucceeds() {+ ObjectNode root = mapper.createObjectNode();+ root.put("b", "A".repeat(10_000)); // valid base64 (len % 4 == 0), decodes fine+ assertFalse(executor.resolvePath("States.Base64Decode($.b)", root).isNull());+ }++ @Test+ void base64DecodeOver10000CharsIsIntrinsicFailure() {+ ObjectNode root = mapper.createObjectNode();+ root.put("b", "A".repeat(10_004)); // valid alphabet + length, so the cap (not invalidity) fires+ assertIntrinsicFailure(root, "States.Base64Decode($.b)");+ }++ @Test+ void base64DecodeWrongArgumentCountIsIntrinsicFailure() {+ assertIntrinsicFailure(obj(), "States.Base64Decode()");+ }++ // ---------- C. States.StringSplit ----------++ @Test+ void stringSplitMatchesAwsDocExample() throws Exception {+ JsonNode root = mapper.readTree("{\"inputString\":\"This.is+a,test=string\",\"splitter\":\".+,=\"}");+ JsonNode out = executor.resolvePath("States.StringSplit($.inputString, $.splitter)", root);+ assertTrue(out.isArray());+ assertEquals(5, out.size());+ assertEquals("This", out.get(0).asText());+ assertEquals("is", out.get(1).asText());+ assertEquals("a", out.get(2).asText());+ assertEquals("test", out.get(3).asText());+ assertEquals("string", out.get(4).asText());+ }++ @Test+ void stringSplitWithQuotedLiteralArguments() {+ // The comma inside the '.+,=' literal is inside quotes, so the quote-aware splitter does not+ // treat it as an argument separator.+ JsonNode out = executor.resolvePath(+ "States.StringSplit('This.is+a,test=string', '.+,=')", obj());+ assertEquals(5, out.size());+ assertEquals("string", out.get(4).asText());+ }++ @Test+ void stringSplitOmitsEmptySegments() throws Exception {+ JsonNode root = mapper.readTree("{\"s\":\",,a,,b,,\"}");+ JsonNode out = executor.resolvePath("States.StringSplit($.s, ',')", root);+ assertEquals(2, out.size());+ assertEquals("a", out.get(0).asText());+ assertEquals("b", out.get(1).asText());+ }++ @Test+ void stringSplitOfOnlyDelimitersYieldsEmptyArray() throws Exception {+ JsonNode root = mapper.readTree("{\"s\":\"...\"}");+ JsonNode out = executor.resolvePath("States.StringSplit($.s, '.')", root);+ assertTrue(out.isArray());+ assertEquals(0, out.size());+ }++ @Test+ void stringSplitOnSupplementaryCharacterDelimiter() throws Exception {+ // Delimiter is a single astral character (😀 U+1F600).+ JsonNode root = mapper.readTree("{\"s\":\"a😀b😀c\",\"d\":\"😀\"}");+ JsonNode out = executor.resolvePath("States.StringSplit($.s, $.d)", root);+ assertEquals(3, out.size());+ assertEquals("a", out.get(0).asText());+ assertEquals("b", out.get(1).asText());+ assertEquals("c", out.get(2).asText());+ }++ @Test+ void stringSplitDoesNotMatchSharedSurrogateHalf() throws Exception {+ // Input 😁 (U+1F601) and delimiter 😀 (U+1F600) share the high surrogate \uD83D. A naive+ // UTF-16 char scan would split on that shared half and corrupt the input; the code-point+ // scan must leave 😁 intact.+ JsonNode root = mapper.readTree("{\"s\":\"😁\",\"d\":\"😀\"}");+ JsonNode out = executor.resolvePath("States.StringSplit($.s, $.d)", root);+ assertEquals(1, out.size());+ assertEquals("😁", out.get(0).asText());+ }++ @Test+ void stringSplitEmptyDelimiterIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"s\":\"abc\"}"), "States.StringSplit($.s, '')");+ }++ @Test+ void stringSplitNonStringArgumentIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"n\":7}"), "States.StringSplit($.n, ',')");+ }++ @Test+ void stringSplitWrongArgumentCountIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"s\":\"a,b\"}"), "States.StringSplit($.s)");+ }++ // ---------- D. States.ArrayGetItem ----------++ @Test+ void arrayGetItemReturnsZeroBasedElement() throws Exception {+ JsonNode root = mapper.readTree("{\"arr\":[1,2,3,4,5,6,7,8,9],\"index\":5}");+ assertEquals(6, executor.resolvePath("States.ArrayGetItem($.arr, $.index)", root).asInt());+ }++ @Test+ void arrayGetItemReturnsComplexElementUnchanged() throws Exception {+ JsonNode root = mapper.readTree("{\"arr\":[{\"k\":1},{\"k\":2}]}");+ JsonNode out = executor.resolvePath("States.ArrayGetItem($.arr, 1)", root);+ assertTrue(out.isObject());+ assertEquals(2, out.path("k").asInt());+ }++ @Test+ void arrayGetItemIndexEqualToLengthIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"arr\":[1,2,3]}"), "States.ArrayGetItem($.arr, 3)");+ }++ @Test+ void arrayGetItemNegativeIndexIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"arr\":[1,2,3]}"), "States.ArrayGetItem($.arr, -1)");+ }++ @Test+ void arrayGetItemNonIntegerIndexIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"arr\":[1,2,3]}"), "States.ArrayGetItem($.arr, 1.5)");+ }++ @Test+ void arrayGetItemHugeIntegerIndexIsIntrinsicFailure() throws Exception {+ // 18446744073709551616 is a BigIntegerNode: isIntegralNumber() is true but canConvertToInt()+ // is false, and asInt() would silently wrap to 0 and return element 1. Must fail instead.+ JsonNode root = mapper.readTree("{\"arr\":[1,2,3],\"i\":18446744073709551616}");+ assertIntrinsicFailure(root, "States.ArrayGetItem($.arr, $.i)");+ }++ @Test+ void arrayGetItemNonArrayFirstArgumentIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"s\":\"notarray\"}"), "States.ArrayGetItem($.s, 0)");+ }++ @Test+ void arrayGetItemWrongArgumentCountIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"arr\":[1,2,3]}"), "States.ArrayGetItem($.arr)");+ }++ // ---------- E. States.Hash ----------++ @Test+ void hashSha256ProducesLowercaseHexDigest() throws Exception {+ JsonNode root = mapper.readTree("{\"data\":\"input data\"}");+ assertEquals("b4a697a057313163aee33cd8d40c66e9f0f177e00cac2de32475ffff6169c3e3",+ executor.resolvePath("States.Hash($.data, 'SHA-256')", root).asText());+ }++ @Test+ void hashSha1Digest() throws Exception {+ // AWS's doc example prints a 39-char typo (missing a digit); this is the true SHA-1 digest.+ JsonNode root = mapper.readTree("{\"data\":\"input data\"}");+ assertEquals("aaff4a450a104cd177d28d18d74485e8cae074b7",+ executor.resolvePath("States.Hash($.data, 'SHA-1')", root).asText());+ }++ @Test+ void hashMd5Sha384Sha512Digests() throws Exception {+ JsonNode root = mapper.readTree("{\"data\":\"input data\"}");+ assertEquals("812f45842bc6d66ee14572ce20db8e86",+ executor.resolvePath("States.Hash($.data, 'MD5')", root).asText());+ assertEquals("d28a7d5cf25a74f11a50a18452b75e04bb3d70c9dd0510d6123aa008c756511b87525bdc835ebb27e1fb9e9374a15562",+ executor.resolvePath("States.Hash($.data, 'SHA-384')", root).asText());+ assertEquals("6ce4adb348546d4f449c4d25aad9a7c9cb711d9e91982d3f0b29ca2f3f47d4ce2deba23bf2954f0f1d593fc50283731a533d30d425402d4f91316d871303aac4",+ executor.resolvePath("States.Hash($.data, 'SHA-512')", root).asText());+ }++ @Test+ void hashUnknownAlgorithmWithoutHyphenIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"data\":\"input data\"}"),+ "States.Hash($.data, 'SHA256')");+ }++ @Test+ void hashLowercaseAlgorithmIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"data\":\"input data\"}"),+ "States.Hash($.data, 'sha-256')");+ }++ @Test+ void hashOver10000CharsIsIntrinsicFailure() {+ ObjectNode root = mapper.createObjectNode();+ root.put("data", "a".repeat(10_001));+ assertIntrinsicFailure(root, "States.Hash($.data, 'SHA-256')");+ }++ @Test+ void hashNonStringDataIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"n\":5}"), "States.Hash($.n, 'SHA-256')");+ }++ @Test+ void hashWrongArgumentCountIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"data\":\"x\"}"), "States.Hash($.data)");+ }++ // ---------- I. Code-review hardening: leading-zero hex, plan-promised omissions, trailing comma ----------++ @Test+ void hashPreservesLeadingZeroNibbles() throws Exception {+ // MD5("v787") begins with two zero nibbles; a new BigInteger(1, digest).toString(16)+ // implementation would drop them and return 30 hex chars instead of the fixed-width 32.+ JsonNode root = mapper.readTree("{\"data\":\"v787\"}");+ assertEquals("0003ec0d0c76934ba8a8b39809c825b3",+ executor.resolvePath("States.Hash($.data, 'MD5')", root).asText());+ }++ @Test+ void base64DecodeNonStringArgumentIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"n\":5}"), "States.Base64Decode($.n)");+ }++ @Test+ void stringSplitOfEmptyStringYieldsEmptyArray() throws Exception {+ JsonNode out = executor.resolvePath("States.StringSplit($.s, ',')", mapper.readTree("{\"s\":\"\"}"));+ assertTrue(out.isArray());+ assertEquals(0, out.size());+ }++ @Test+ void arrayGetItemStringIndexIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"arr\":[1,2,3],\"i\":\"1\"}"),+ "States.ArrayGetItem($.arr, $.i)");+ }++ @Test+ void hashAtExactly10000CharsSucceeds() {+ ObjectNode root = mapper.createObjectNode();+ root.put("data", "a".repeat(10_000));+ assertEquals(64, executor.resolvePath("States.Hash($.data, 'SHA-256')", root).asText().length());+ }++ @Test+ void hashNonStringAlgorithmIsIntrinsicFailure() throws Exception {+ assertIntrinsicFailure(mapper.readTree("{\"data\":\"x\",\"algo\":5}"),+ "States.Hash($.data, $.algo)");+ }++ @Test+ void trailingCommaIsIntrinsicFailure() throws Exception {+ // The trailing-comma guard is load-bearing: splitIntrinsicArgs drops a trailing empty token,+ // so an arity check alone would not reject a stray comma.+ assertIntrinsicFailure(mapper.readTree("{\"a\":\"x\"}"), "States.Base64Encode($.a,)");+ assertIntrinsicFailure(mapper.readTree("{\"s\":\"a,b\"}"), "States.StringSplit($.s, ',',)");+ }++ // ---------- F. Parameters-path wiring (resolveParameters -> resolvePath -> evaluateIntrinsic) ----------++ @Test+ void intrinsicResolvesInsidePassStateParameters() throws Exception {+ JsonNode params = mapper.readTree("{\"encoded.$\":\"States.Base64Encode($.data)\"}");+ JsonNode input = mapper.readTree("{\"data\":\"Data to encode\"}");+ JsonNode out = executor.resolveParameters(params, input, null);+ assertEquals("RGF0YSB0byBlbmNvZGU=", out.path("encoded").asText());+ }++ @Test+ void newAndExistingIntrinsicsResolveTogetherInParameters() throws Exception {+ JsonNode params = mapper.readTree(+ "{\"item.$\":\"States.ArrayGetItem($.arr, 1)\",\"len.$\":\"States.ArrayLength($.arr)\"}");+ JsonNode input = mapper.readTree("{\"arr\":[10,20,30]}");+ JsonNode out = executor.resolveParameters(params, input, null);+ assertEquals(20, out.path("item").asInt());+ assertEquals(3, out.path("len").asInt());+ }++ // ---------- G. Execution-level catchability (full doExecute loop via executeSync) ----------++ @Test+ void intrinsicFailureIsCatchableEndToEnd() {+ // A States.IntrinsicFailure raised inside a Pass state's Parameters must be catchable; a+ // reverted implementation raises the uncatchable States.Runtime and this state machine FAILs.+ Execution exec = run("""+ {+ "StartAt": "Try",+ "States": {+ "Try": {+ "Type": "Pass",+ "Parameters": {"decoded.$": "States.Base64Decode($.bad)"},+ "Next": "Unexpected",+ "Catch": [{"ErrorEquals": ["States.IntrinsicFailure"], "Next": "Recover"}]+ },+ "Unexpected": {"Type": "Fail", "Cause": "intrinsic unexpectedly succeeded"},+ "Recover": {"Type": "Pass", "End": true}+ }+ }+ """, "{\"bad\":\"not base64!!!\"}");+ assertEquals("SUCCEEDED", exec.getStatus());+ }++ @Test+ void intrinsicFailureWithoutCatchFailsExecutionWithIntrinsicFailure() {+ Execution exec = run("""+ {+ "StartAt": "Try",+ "States": {+ "Try": {+ "Type": "Pass",+ "Parameters": {"decoded.$": "States.Base64Decode($.bad)"},+ "End": true+ }+ }+ }+ """, "{\"bad\":\"not base64!!!\"}");+ 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;+ }++ // ---------- H. Regression: the nine pre-existing intrinsics still resolve ----------++ @Test+ void existingIntrinsicsStillResolve() throws Exception {+ assertEquals(1, executor.resolvePath("States.StringToJson($.s)",+ mapper.readTree("{\"s\":\"{\\\"a\\\":1}\"}")).path("a").asInt());+ assertEquals("{\"a\":1}", executor.resolvePath("States.JsonToString($.o)",+ mapper.readTree("{\"o\":{\"a\":1}}")).asText());+ assertEquals("Hello world", executor.resolvePath("States.Format('Hello {}', $.n)",+ mapper.readTree("{\"n\":\"world\"}")).asText());+ JsonNode arr = executor.resolvePath("States.Array(1, $.n)", mapper.readTree("{\"n\":2}"));+ assertEquals(2, arr.size());+ assertEquals(1, arr.get(0).asInt());+ assertEquals(2, arr.get(1).asInt());+ assertEquals(3, executor.resolvePath("States.ArrayLength($.arr)",+ mapper.readTree("{\"arr\":[1,2,3]}")).asInt());+ assertEquals(5, executor.resolvePath("States.MathAdd($.a, $.b)",+ mapper.readTree("{\"a\":2,\"b\":3}")).asLong());+ assertTrue(executor.resolvePath("States.ArrayContains($.arr, $.v)",+ mapper.readTree("{\"arr\":[1,2,3],\"v\":2}")).asBoolean());+ assertTrue(executor.resolvePath("States.UUID()", obj()).asText()+ .matches("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"));+ JsonNode merged = executor.resolvePath("States.JsonMerge($.a, $.b, false)",+ mapper.readTree("{\"a\":{\"x\":1},\"b\":{\"y\":2}}"));+ assertEquals(1, merged.path("x").asInt());+ assertEquals(2, merged.path("y").asInt());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.javanew file mode 100644index 0000000000..4f3f0230c9--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorNestedStartExecutionTest.java@@ -0,0 +1,165 @@+package io.github.hectorvent.floci.services.stepfunctions;++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 com.fasterxml.jackson.databind.ObjectMapper;+import jakarta.enterprise.inject.Instance;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;++import java.util.ArrayList;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++/**+ * End-to-end coverage for nested {@code states:startExecution}: the parent's resolved {@code Input} and+ * {@code Name} reach the child {@code StartExecution} correctly. Verifies the fix: a+ * {@code States.JsonToString} Input is passed as JSON text (child {@code $} becomes an object), a plain+ * string stays a string, {@code Name}/{@code Name.$} are honored (previously ignored), and a supplied+ * {@code Name} that does not resolve to a non-empty string fails rather than silently generating one.+ *+ * <p>CI-only: constructing {@link AslExecutor} pulls in Vert.x, unavailable in the offline sandbox. The+ * encoding/provenance logic itself is covered locally by {@link NestedExecutionInputTest}.+ */+class AslExecutorNestedStartExecutionTest {++ private final ObjectMapper mapper = new ObjectMapper();+ private AslExecutor executor;+ private StepFunctionsService childSfn;++ @BeforeEach+ @SuppressWarnings("unchecked")+ void setUp() {+ childSfn = mock(StepFunctionsService.class);+ Instance<StepFunctionsService> sfnInstance = mock(Instance.class);+ when(sfnInstance.get()).thenReturn(childSfn);+ Execution childExec = new Execution();+ childExec.setExecutionArn("arn:aws:states:us-east-1:000000000000:execution:child:e1");+ childExec.setStatus("RUNNING");+ childExec.setStartDate(1.0);+ when(childSfn.startExecution(any(), any(), any(), any())).thenReturn(childExec);++ 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),+ sfnInstance,+ mock(EmulatorConfig.class),+ null, null);+ }++ private Execution runParent(String parentDefinition, String input) {+ StateMachine sm = new StateMachine();+ sm.setName("parent");+ sm.setStateMachineArn("arn:aws:states:us-east-1:000000000000:stateMachine:parent");+ sm.setRoleArn("arn:aws:iam::000000000000:role/r");+ sm.setDefinition(parentDefinition);+ Execution exec = new Execution();+ exec.setName("parent-exec");+ exec.setExecutionArn("arn:aws:states:us-east-1:000000000000:execution:parent:pe");+ exec.setStateMachineArn(sm.getStateMachineArn());+ exec.setInput(input);+ executor.executeSync(sm, exec, new ArrayList<HistoryEvent>(), (u, e) -> {+ });+ return exec;+ }++ /** Returns {capturedName, capturedChildInput} from the single child startExecution call. */+ private String[] captureChildStart(String parentDefinition, String input) {+ runParent(parentDefinition, input);+ ArgumentCaptor<String> name = ArgumentCaptor.forClass(String.class);+ ArgumentCaptor<String> childInput = ArgumentCaptor.forClass(String.class);+ verify(childSfn).startExecution(any(), name.capture(), childInput.capture(), any());+ return new String[]{name.getValue(), childInput.getValue()};+ }++ private static String parent(String parametersJson) {+ return "{\"StartAt\":\"Nest\",\"States\":{\"Nest\":{\"Type\":\"Task\","+ + "\"Resource\":\"arn:aws:states:::states:startExecution\","+ + "\"Parameters\":" + parametersJson + ",\"End\":true}}}";+ }++ private static final String CHILD_ARN =+ "arn:aws:states:us-east-1:000000000000:stateMachine:child";++ @Test+ void jsonToStringInputBecomesObjectAndNameIsHonored() throws Exception {+ String[] captured = captureChildStart(+ parent("{\"StateMachineArn\":\"" + CHILD_ARN + "\","+ + "\"Input.$\":\"States.JsonToString($.payload)\",\"Name\":\"child-run-1\"}"),+ "{\"payload\":{\"a\":1}}");+ assertEquals("child-run-1", captured[0], "Name must be honored (was ignored/null before)");+ assertTrue(mapper.readTree(captured[1]).isObject(), "JsonToString Input must reach child as an object");+ assertEquals(1, mapper.readTree(captured[1]).get("a").asInt());+ }++ @Test+ void objectPathInputStaysObject() throws Exception {+ String[] captured = captureChildStart(+ parent("{\"StateMachineArn\":\"" + CHILD_ARN + "\",\"Input.$\":\"$.payload\"}"),+ "{\"payload\":{\"a\":1}}");+ assertNull(captured[0], "no Name -> child gets a generated name (null passed through)");+ assertTrue(mapper.readTree(captured[1]).isObject());+ }++ @Test+ void plainStringInputStaysString() throws Exception {+ String[] captured = captureChildStart(+ parent("{\"StateMachineArn\":\"" + CHILD_ARN + "\",\"Input.$\":\"$.s\"}"),+ "{\"s\":\"hello\"}");+ assertTrue(mapper.readTree(captured[1]).isTextual(), "a plain string Input must not be turned into an object");+ assertEquals("hello", mapper.readTree(captured[1]).asText());+ }++ @Test+ void nameDollarIsHonored() throws Exception {+ String[] captured = captureChildStart(+ parent("{\"StateMachineArn\":\"" + CHILD_ARN + "\",\"Input\":{},\"Name.$\":\"$.nm\"}"),+ "{\"nm\":\"dynamic-name\"}");+ assertEquals("dynamic-name", captured[0]);+ }++ @Test+ void suppliedNonStringNameFailsExecutionAndDoesNotLaunch() {+ // A supplied Name that does not resolve to a non-empty string is a runtime error, not a silent+ // fall-through to a generated name; the child must not be launched.+ Execution exec = runParent(+ parent("{\"StateMachineArn\":\"" + CHILD_ARN + "\",\"Input\":{},\"Name\":{}}"),+ "{}");+ assertEquals("FAILED", exec.getStatus());+ assertEquals("States.Runtime", exec.getError());+ verify(childSfn, never()).startExecution(any(), any(), any(), any());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultPathTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultPathTest.javanew file mode 100644index 0000000000..b1aa009ae1--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorResultPathTest.java@@ -0,0 +1,128 @@+package io.github.hectorvent.floci.services.stepfunctions;++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 com.fasterxml.jackson.databind.ObjectMapper;+import jakarta.enterprise.inject.Instance;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.ArrayList;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.Mockito.mock;++/**+ * End-to-end coverage for the ResultPath fix: a non-applicable ResultPath fails the execution with+ * {@code States.ResultPathMatchFailure} (was a silent input discard), the error is catchable via a+ * Parallel state's {@code Catch}, and object inputs merge unchanged.+ *+ * <p>CI-only: constructing {@link AslExecutor} pulls in Vert.x (absent in the offline sandbox). The merge+ * logic is covered locally by {@link ResultPathMergeTest}.+ */+class AslExecutorResultPathTest {++ 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 Execution run(String definition, String input) {+ StateMachine sm = new StateMachine();+ sm.setName("rp");+ sm.setStateMachineArn("arn:aws:states:us-east-1:000000000000:stateMachine:rp");+ sm.setRoleArn("arn:aws:iam::000000000000:role/r");+ sm.setDefinition(definition);+ Execution exec = new Execution();+ exec.setName("rp-exec");+ exec.setExecutionArn("arn:aws:states:us-east-1:000000000000:execution:rp:e");+ exec.setStateMachineArn(sm.getStateMachineArn());+ exec.setInput(input);+ executor.executeSync(sm, exec, new ArrayList<HistoryEvent>(), (u, e) -> {+ });+ return exec;+ }++ @Test+ void nonObjectInputWithObjectResultPathFailsExecution() {+ Execution exec = run(+ "{\"StartAt\":\"P\",\"States\":{\"P\":{\"Type\":\"Pass\",\"ResultPath\":\"$.x\",\"End\":true}}}",+ "\"just-a-string\"");+ assertEquals("FAILED", exec.getStatus());+ assertEquals("States.ResultPathMatchFailure", exec.getError());+ }++ @Test+ void objectInputMergesNormally() {+ Execution exec = run(+ "{\"StartAt\":\"P\",\"States\":{\"P\":{\"Type\":\"Pass\",\"Result\":{\"r\":1},"+ + "\"ResultPath\":\"$.x\",\"End\":true}}}",+ "{\"k\":1}");+ assertEquals("SUCCEEDED", exec.getStatus());+ }++ @Test+ void resultPathMatchFailureIsUncaughtInParallelWithoutCatch() {+ Execution exec = run(+ "{\"StartAt\":\"P\",\"States\":{\"P\":{\"Type\":\"Parallel\","+ + "\"Branches\":[{\"StartAt\":\"B\",\"States\":{\"B\":{\"Type\":\"Pass\",\"End\":true}}}],"+ + "\"ResultPath\":\"$.x\",\"End\":true}}}",+ "\"just-a-string\"");+ assertEquals("FAILED", exec.getStatus());+ assertEquals("States.ResultPathMatchFailure", exec.getError());+ }++ @Test+ void resultPathMatchFailureIsCatchableInParallel() {+ Execution exec = run(+ "{\"StartAt\":\"P\",\"States\":{\"P\":{\"Type\":\"Parallel\","+ + "\"Branches\":[{\"StartAt\":\"B\",\"States\":{\"B\":{\"Type\":\"Pass\",\"End\":true}}}],"+ + "\"ResultPath\":\"$.x\","+ + "\"Catch\":[{\"ErrorEquals\":[\"States.ResultPathMatchFailure\"],\"Next\":\"Recover\"}],"+ + "\"End\":true},"+ + "\"Recover\":{\"Type\":\"Pass\",\"End\":true}}}",+ "\"just-a-string\"");+ assertEquals("SUCCEEDED", exec.getStatus());+ }++ @Test+ void catcherResultPathFailureReportsResultPathMatchFailureNotRuntime() {+ // A matched Catcher whose own ResultPath cannot apply to the (non-object) input must terminate+ // with States.ResultPathMatchFailure, not a relabeled States.Runtime from the outer handler.+ Execution exec = run(+ "{\"StartAt\":\"P\",\"States\":{\"P\":{\"Type\":\"Parallel\","+ + "\"Branches\":[{\"StartAt\":\"F\",\"States\":{\"F\":{\"Type\":\"Fail\","+ + "\"Error\":\"BranchErr\",\"Cause\":\"x\"}}}],"+ + "\"Catch\":[{\"ErrorEquals\":[\"States.ALL\"],\"Next\":\"Recover\",\"ResultPath\":\"$.error\"}],"+ + "\"End\":true},"+ + "\"Recover\":{\"Type\":\"Pass\",\"End\":true}}}",+ "\"just-a-string\"");+ assertEquals("FAILED", exec.getStatus());+ assertEquals("States.ResultPathMatchFailure", exec.getError());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/ChoiceOperatorsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/ChoiceOperatorsTest.javanew file mode 100644index 0000000000..3932792666--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/ChoiceOperatorsTest.java@@ -0,0 +1,443 @@+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.BooleanNode;+import com.fasterxml.jackson.databind.node.IntNode;+import com.fasterxml.jackson.databind.node.MissingNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import com.fasterxml.jackson.databind.node.TextNode;+import org.junit.jupiter.api.Test;++import java.util.ArrayList;+import java.util.List;+import java.util.Set;++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;++/**+ * Unit tests for {@link ChoiceOperators}: the extracted, dependency-light Choice comparator+ * evaluator + validator. Exercises all 39 data-test operators, type strictness, RFC3339 timestamp+ * handling, missing-path/unknown-operator errors, And/Or/Not, and structural validation. Runs as+ * plain JUnit5 (no Quarkus), which is what makes it executable in this sandbox.+ *+ * <p>JSON literals are written with single quotes and converted via {@link #j} to keep them readable.+ */+class ChoiceOperatorsTest {++ private static final ObjectMapper OM = new ObjectMapper();++ /** Single-quoted JSON -> double-quoted, for readable literals (no test datum contains a single quote). */+ private static String j(String singleQuoted) {+ return singleQuoted.replace('\'', '"');+ }++ private static ChoiceOperators.PathResolver resolverFor(JsonNode input) {+ return path -> {+ if (path == null || path.equals("$")) {+ return input;+ }+ if (!path.startsWith("$.")) {+ return MissingNode.getInstance();+ }+ return input.at("/" + path.substring(2).replace(".", "/"));+ };+ }++ private static boolean eval(String ruleJson, String inputJson) throws Exception {+ return ChoiceOperators.evaluate(OM.readTree(ruleJson), resolverFor(OM.readTree(inputJson)));+ }++ private static List<String> validate(String ruleJson) throws Exception {+ List<String> errors = new ArrayList<>();+ ChoiceOperators.validateChoiceRule("/States/C/Choices/0", OM.readTree(ruleJson), true, errors);+ return errors;+ }++ // ──────────────────────────── Inventory ────────────────────────────++ @Test+ void inventoryIs39DataTestOperators() {+ assertEquals(39, ChoiceOperators.DATA_TEST_OPERATORS.size(),+ "expected 39 documented data-test operators");+ for (String op : List.of("NumericGreaterThanEqualsPath", "NumericLessThanEqualsPath",+ "StringGreaterThanPath", "StringLessThanEqualsPath",+ "TimestampGreaterThanEquals", "TimestampLessThanPath", "IsTimestamp")) {+ assertTrue(ChoiceOperators.DATA_TEST_OPERATORS.contains(op), "missing " + op);+ }+ }++ @Test+ void everyOperatorValidatesWithAWellFormedRule() {+ for (String op : ChoiceOperators.DATA_TEST_OPERATORS) {+ ObjectNode rule = OM.createObjectNode();+ rule.put("Variable", "$.a");+ rule.set(op, validOperandFor(op));+ rule.put("Next", "X");+ List<String> errs = new ArrayList<>();+ ChoiceOperators.validateChoiceRule("/c/0", rule, true, errs);+ assertTrue(errs.isEmpty(), op + " should validate cleanly but got: " + errs);+ }+ }++ private static JsonNode validOperandFor(String op) {+ if (ChoiceOperators.TYPE_TEST_OPERATORS.contains(op)) {+ return BooleanNode.TRUE;+ }+ if (op.endsWith("Path")) {+ return TextNode.valueOf("$.b");+ }+ if (ChoiceOperators.NUMERIC_OPERATORS.contains(op)) {+ return IntNode.valueOf(1);+ }+ if (ChoiceOperators.TIMESTAMP_OPERATORS.contains(op)) {+ return TextNode.valueOf("2016-08-18T17:33:00Z");+ }+ if (ChoiceOperators.BOOLEAN_OPERATORS.contains(op)) {+ return BooleanNode.TRUE;+ }+ return TextNode.valueOf("x"); // String family incl. StringMatches+ }++ // ──────────────────────────── Numeric ────────────────────────────++ @Test+ void numericGreaterThanEqualsPath_handoffMatrix() throws Exception {+ String rule = j("{'Variable':'$.a','NumericGreaterThanEqualsPath':'$.b'}");+ assertTrue(eval(rule, j("{'a':5,'b':3}"))); // 5 >= 3+ assertTrue(eval(rule, j("{'a':3,'b':3}"))); // 3 >= 3+ assertFalse(eval(rule, j("{'a':2,'b':3}"))); // 2 >= 3 is false+ }++ @Test+ void numericComparators() throws Exception {+ assertTrue(eval(j("{'Variable':'$.a','NumericEquals':5}"), j("{'a':5}")));+ assertTrue(eval(j("{'Variable':'$.a','NumericEquals':5}"), j("{'a':5.0}"))); // 5 == 5.0+ assertTrue(eval(j("{'Variable':'$.a','NumericLessThan':5}"), j("{'a':4}")));+ assertFalse(eval(j("{'Variable':'$.a','NumericLessThan':5}"), j("{'a':5}")));+ assertTrue(eval(j("{'Variable':'$.a','NumericLessThanEquals':5}"), j("{'a':5}")));+ assertTrue(eval(j("{'Variable':'$.a','NumericGreaterThan':5}"), j("{'a':6}")));+ assertTrue(eval(j("{'Variable':'$.a','NumericEqualsPath':'$.b'}"), j("{'a':7,'b':7}")));+ }++ // ──────────────────────────── String ────────────────────────────++ @Test+ void stringComparators() throws Exception {+ assertTrue(eval(j("{'Variable':'$.a','StringEquals':'x'}"), j("{'a':'x'}")));+ assertTrue(eval(j("{'Variable':'$.a','StringLessThan':'b'}"), j("{'a':'a'}")));+ assertTrue(eval(j("{'Variable':'$.a','StringGreaterThan':'a'}"), j("{'a':'b'}")));+ assertTrue(eval(j("{'Variable':'$.a','StringLessThanEquals':'b'}"), j("{'a':'b'}")));+ assertTrue(eval(j("{'Variable':'$.a','StringGreaterThanEquals':'b'}"), j("{'a':'b'}")));+ assertTrue(eval(j("{'Variable':'$.a','StringGreaterThanEqualsPath':'$.b'}"), j("{'a':'m','b':'m'}")));+ assertTrue(eval(j("{'Variable':'$.a','StringMatches':'foo*baz'}"), j("{'a':'fooBARbaz'}")));+ assertFalse(eval(j("{'Variable':'$.a','StringMatches':'foo*baz'}"), j("{'a':'fooBAR'}")));+ }++ // ──────────────────────────── Boolean ────────────────────────────++ @Test+ void booleanComparators() throws Exception {+ assertTrue(eval(j("{'Variable':'$.a','BooleanEquals':true}"), j("{'a':true}")));+ assertFalse(eval(j("{'Variable':'$.a','BooleanEquals':true}"), j("{'a':false}")));+ assertTrue(eval(j("{'Variable':'$.a','BooleanEqualsPath':'$.b'}"), j("{'a':true,'b':true}")));+ }++ // ──────────────────────────── Timestamp ────────────────────────────++ @Test+ void timestampComparators_and_offsetEquivalence() throws Exception {+ assertTrue(eval(j("{'Variable':'$.a','TimestampEquals':'2016-08-18T17:33:00Z'}"),+ j("{'a':'2016-08-18T17:33:00Z'}")));+ // 17:33Z == 18:33+01:00 (same instant)+ assertTrue(eval(j("{'Variable':'$.a','TimestampEquals':'2016-08-18T18:33:00+01:00'}"),+ j("{'a':'2016-08-18T17:33:00Z'}")));+ assertTrue(eval(j("{'Variable':'$.a','TimestampLessThan':'2016-08-18T17:33:01Z'}"),+ j("{'a':'2016-08-18T17:33:00Z'}")));+ assertTrue(eval(j("{'Variable':'$.a','TimestampGreaterThanEquals':'2016-08-18T17:33:00Z'}"),+ j("{'a':'2016-08-18T17:33:00Z'}")));+ assertTrue(eval(j("{'Variable':'$.a','TimestampEqualsPath':'$.b'}"),+ j("{'a':'2016-08-18T17:33:00Z','b':'2016-08-18T17:33:00Z'}")));+ }++ // ──────────────────────────── Type predicates ────────────────────────────++ @Test+ void typeTests() throws Exception {+ assertTrue(eval(j("{'Variable':'$.a','IsNull':true}"), j("{'a':null}")));+ assertFalse(eval(j("{'Variable':'$.a','IsNull':true}"), j("{'a':5}")));+ assertTrue(eval(j("{'Variable':'$.a','IsString':true}"), j("{'a':'x'}")));+ assertTrue(eval(j("{'Variable':'$.a','IsNumeric':true}"), j("{'a':5}")));+ assertTrue(eval(j("{'Variable':'$.a','IsBoolean':true}"), j("{'a':true}")));+ assertTrue(eval(j("{'Variable':'$.a','IsTimestamp':true}"), j("{'a':'2016-08-18T17:33:00Z'}")));+ assertFalse(eval(j("{'Variable':'$.a','IsTimestamp':true}"), j("{'a':'not-a-date'}")));+ }++ @Test+ void isPresentTrueFalse_neverThrowsOnMissing() throws Exception {+ assertTrue(eval(j("{'Variable':'$.a','IsPresent':true}"), j("{'a':1}")));+ assertTrue(eval(j("{'Variable':'$.a','IsPresent':true}"), j("{'a':null}"))); // explicit null is present+ assertFalse(eval(j("{'Variable':'$.missing','IsPresent':true}"), j("{'a':1}")));+ assertTrue(eval(j("{'Variable':'$.missing','IsPresent':false}"), j("{'a':1}")));+ }++ // ──────────────────────────── Type strictness ────────────────────────────++ @Test+ void typeMismatchesAreFalseNotCoerced() throws Exception {+ assertFalse(eval(j("{'Variable':'$.a','NumericEquals':5}"), j("{'a':'5'}"))); // string vs numeric+ assertFalse(eval(j("{'Variable':'$.a','StringEquals':'5'}"), j("{'a':5}"))); // numeric vs string+ assertFalse(eval(j("{'Variable':'$.a','BooleanEquals':true}"), j("{'a':'true'}")));+ assertFalse(eval(j("{'Variable':'$.a','TimestampEquals':'2016-08-18T17:33:00Z'}"),+ j("{'a':'not-a-date'}")));+ }++ // ──────────────────────────── Missing path / unknown operator ────────────────────────────++ @Test+ void missingVariablePathThrows_forNonPresenceOperators() {+ assertThrows(ChoiceOperators.ChoiceEvaluationException.class,+ () -> eval(j("{'Variable':'$.missing','NumericEquals':5}"), j("{'a':1}")));+ assertThrows(ChoiceOperators.ChoiceEvaluationException.class,+ () -> eval(j("{'Variable':'$.missing','IsNull':true}"), j("{'a':1}")));+ }++ @Test+ void missingOperandPathThrows() {+ assertThrows(ChoiceOperators.ChoiceEvaluationException.class,+ () -> eval(j("{'Variable':'$.a','NumericEqualsPath':'$.missing'}"), j("{'a':1}")));+ }++ @Test+ void unknownOperatorThrowsAtRuntime() {+ assertThrows(ChoiceOperators.ChoiceEvaluationException.class,+ () -> eval(j("{'Variable':'$.a','NumericSpicyThan':5}"), j("{'a':1}")));+ }++ // ──────────────────────────── RFC3339 lexical gate ────────────────────────────++ @Test+ void rfc3339InvalidFormsAreRejected() throws Exception {+ for (String bad : List.of(+ "2016-08-18t17:33:00z", // lowercase t/z+ "2024-01-01", // bare date+ "2024-01-01T00:00Z", // missing seconds+ "2024-01-01T00:00:00+01", // truncated offset+ "2024-01-01T00:00:00+0100", // non-colonized offset+ "2024-01-01T00:00:00", // no offset+ "2024-13-01T00:00:00Z")) { // month 13+ assertFalse(eval(j("{'Variable':'$.a','IsTimestamp':true}"),+ OM.createObjectNode().put("a", bad).toString()), "should reject: " + bad);+ }+ }++ // ──────────────────────────── Logical operators ────────────────────────────++ @Test+ void logicalOperators() throws Exception {+ String and = j("{'And':[{'Variable':'$.a','NumericGreaterThan':0},{'Variable':'$.b','StringEquals':'x'}]}");+ assertTrue(eval(and, j("{'a':1,'b':'x'}")));+ assertFalse(eval(and, j("{'a':1,'b':'y'}")));+ String or = j("{'Or':[{'Variable':'$.a','NumericGreaterThan':10},{'Variable':'$.b','StringEquals':'x'}]}");+ assertTrue(eval(or, j("{'a':1,'b':'x'}")));+ String not = j("{'Not':{'Variable':'$.a','NumericLessThan':3}}");+ assertTrue(eval(not, j("{'a':5}")));+ assertFalse(eval(not, j("{'a':2}")));+ }++ // ──────────────────────────── Validation ────────────────────────────++ @Test+ void validation_inventedComparatorBesideValidIsRejected() throws Exception {+ List<String> errs = validate(j("{'Variable':'$.a','NumericEquals':1,'NumericSpicyThan':2,'Next':'X'}"));+ assertFalse(errs.isEmpty(), "invented comparator beside a valid one must be rejected");+ }++ @Test+ void validation_rejectsBadShapes() throws Exception {+ assertFalse(validate(j("{'Variable':'$.a','NumericEquals':1,'StringEquals':'y','Next':'X'}")).isEmpty(),+ "two data-test operators");+ assertFalse(validate(j("{'And':[],'Next':'X'}")).isEmpty(), "empty And");+ assertFalse(validate(j("{'Not':[{'Variable':'$.a','IsNull':true}],'Next':'X'}")).isEmpty(),+ "Not must be an object, not array");+ assertFalse(validate(j("{'Variable':'$.a','NumericEquals':1}")).isEmpty(),+ "top-level rule missing Next");+ assertFalse(validate(j("{'And':[{'Variable':'$.a','IsNull':true,'Next':'Y'}],'Next':'X'}")).isEmpty(),+ "Next forbidden on nested operand");+ assertFalse(validate(j("{'Variable':'$.a','NumericEquals':'5','Next':'X'}")).isEmpty(),+ "numeric operator with string operand");+ assertFalse(validate(j("{'Variable':'$.a','TimestampEquals':'nope','Next':'X'}")).isEmpty(),+ "timestamp operator with non-timestamp operand");+ assertFalse(validate(j("{'Variable':'$.a','StringEqualsPath':'notapath','Next':'X'}")).isEmpty(),+ "path operator with non-path operand");+ assertFalse(validate(j("{'And':[{'Variable':'$.a','IsNull':true}],'Variable':'$.b','Next':'X'}")).isEmpty(),+ "logical rule must not carry Variable");+ assertFalse(validate(j("{'Variable':'$.a','IsNull':true,'Bogus':1,'Next':'X'}")).isEmpty(),+ "unsupported field");+ }++ @Test+ void validation_wellFormedRulesPass() throws Exception {+ assertTrue(validate(j("{'Variable':'$.a','NumericGreaterThanEqualsPath':'$.b','Next':'X'}")).isEmpty());+ assertTrue(validate(+ j("{'And':[{'Variable':'$.a','NumericEquals':1},{'Variable':'$.b','IsPresent':true}],'Next':'X'}"))+ .isEmpty());+ assertTrue(validate(j("{'Not':{'Variable':'$.a','StringEquals':'x'},'Next':'X'}")).isEmpty());+ }++ // ──────────────────────────── Authoritative inventory ────────────────────────────++ @Test+ void dataTestOperatorsMatchAuthoritativeLiteralSet() {+ // Independent literal list: must equal the production set exactly (not self-referential).+ Set<String> expected = Set.of(+ "StringEquals", "StringEqualsPath", "StringLessThan", "StringLessThanPath",+ "StringGreaterThan", "StringGreaterThanPath", "StringLessThanEquals", "StringLessThanEqualsPath",+ "StringGreaterThanEquals", "StringGreaterThanEqualsPath", "StringMatches",+ "NumericEquals", "NumericEqualsPath", "NumericLessThan", "NumericLessThanPath",+ "NumericGreaterThan", "NumericGreaterThanPath", "NumericLessThanEquals", "NumericLessThanEqualsPath",+ "NumericGreaterThanEquals", "NumericGreaterThanEqualsPath",+ "BooleanEquals", "BooleanEqualsPath",+ "TimestampEquals", "TimestampEqualsPath", "TimestampLessThan", "TimestampLessThanPath",+ "TimestampGreaterThan", "TimestampGreaterThanPath", "TimestampLessThanEquals",+ "TimestampLessThanEqualsPath", "TimestampGreaterThanEquals", "TimestampGreaterThanEqualsPath",+ "IsNull", "IsPresent", "IsNumeric", "IsString", "IsBoolean", "IsTimestamp");+ assertEquals(expected, ChoiceOperators.DATA_TEST_OPERATORS);+ }++ // ──────────────────────────── Every operator: a true and a false ────────────────────────────++ private void assertOpEval(String op, JsonNode operand, String trueInput, String falseInput) throws Exception {+ ObjectNode rule = OM.createObjectNode();+ rule.put("Variable", "$.a");+ rule.set(op, operand);+ assertTrue(ChoiceOperators.evaluate(rule, resolverFor(OM.readTree(j(trueInput)))),+ op + " should match " + trueInput);+ assertFalse(ChoiceOperators.evaluate(rule, resolverFor(OM.readTree(j(falseInput)))),+ op + " should not match " + falseInput);+ }++ @Test+ void everyOperatorEvaluatesTrueAndFalse() throws Exception {+ String TS = "2016-08-18T17:33:00Z";+ String TS0 = "2016-08-18T17:32:59Z";+ String TS1 = "2016-08-18T17:33:01Z";+ JsonNode m = TextNode.valueOf("m");+ JsonNode five = IntNode.valueOf(5);+ JsonNode t = BooleanNode.TRUE;+ JsonNode pb = TextNode.valueOf("$.b");+ JsonNode pts = TextNode.valueOf(TS);+ // String (non-path)+ assertOpEval("StringEquals", m, "{'a':'m'}", "{'a':'n'}");+ assertOpEval("StringLessThan", m, "{'a':'a'}", "{'a':'z'}");+ assertOpEval("StringGreaterThan", m, "{'a':'z'}", "{'a':'a'}");+ assertOpEval("StringLessThanEquals", m, "{'a':'m'}", "{'a':'z'}");+ assertOpEval("StringGreaterThanEquals", m, "{'a':'m'}", "{'a':'a'}");+ assertOpEval("StringMatches", TextNode.valueOf("f*"), "{'a':'foo'}", "{'a':'bar'}");+ // String (path, operand -> $.b = "m")+ assertOpEval("StringEqualsPath", pb, "{'a':'m','b':'m'}", "{'a':'n','b':'m'}");+ assertOpEval("StringLessThanPath", pb, "{'a':'a','b':'m'}", "{'a':'z','b':'m'}");+ assertOpEval("StringGreaterThanPath", pb, "{'a':'z','b':'m'}", "{'a':'a','b':'m'}");+ assertOpEval("StringLessThanEqualsPath", pb, "{'a':'m','b':'m'}", "{'a':'z','b':'m'}");+ assertOpEval("StringGreaterThanEqualsPath", pb, "{'a':'m','b':'m'}", "{'a':'a','b':'m'}");+ // Numeric (non-path)+ assertOpEval("NumericEquals", five, "{'a':5}", "{'a':6}");+ assertOpEval("NumericLessThan", five, "{'a':4}", "{'a':5}");+ assertOpEval("NumericGreaterThan", five, "{'a':6}", "{'a':5}");+ assertOpEval("NumericLessThanEquals", five, "{'a':5}", "{'a':6}");+ assertOpEval("NumericGreaterThanEquals", five, "{'a':5}", "{'a':4}");+ // Numeric (path)+ assertOpEval("NumericEqualsPath", pb, "{'a':5,'b':5}", "{'a':6,'b':5}");+ assertOpEval("NumericLessThanPath", pb, "{'a':4,'b':5}", "{'a':5,'b':5}");+ assertOpEval("NumericGreaterThanPath", pb, "{'a':6,'b':5}", "{'a':5,'b':5}");+ assertOpEval("NumericLessThanEqualsPath", pb, "{'a':5,'b':5}", "{'a':6,'b':5}");+ assertOpEval("NumericGreaterThanEqualsPath", pb, "{'a':5,'b':5}", "{'a':2,'b':5}");+ // Boolean+ assertOpEval("BooleanEquals", t, "{'a':true}", "{'a':false}");+ assertOpEval("BooleanEqualsPath", pb, "{'a':true,'b':true}", "{'a':false,'b':true}");+ // Timestamp (non-path, operand TS)+ assertOpEval("TimestampEquals", pts, "{'a':'" + TS + "'}", "{'a':'" + TS1 + "'}");+ assertOpEval("TimestampLessThan", pts, "{'a':'" + TS0 + "'}", "{'a':'" + TS + "'}");+ assertOpEval("TimestampGreaterThan", pts, "{'a':'" + TS1 + "'}", "{'a':'" + TS + "'}");+ assertOpEval("TimestampLessThanEquals", pts, "{'a':'" + TS + "'}", "{'a':'" + TS1 + "'}");+ assertOpEval("TimestampGreaterThanEquals", pts, "{'a':'" + TS + "'}", "{'a':'" + TS0 + "'}");+ // Timestamp (path, $.b = TS)+ assertOpEval("TimestampEqualsPath", pb, "{'a':'" + TS + "','b':'" + TS + "'}", "{'a':'" + TS1 + "','b':'" + TS + "'}");+ assertOpEval("TimestampLessThanPath", pb, "{'a':'" + TS0 + "','b':'" + TS + "'}", "{'a':'" + TS + "','b':'" + TS + "'}");+ assertOpEval("TimestampGreaterThanPath", pb, "{'a':'" + TS1 + "','b':'" + TS + "'}", "{'a':'" + TS + "','b':'" + TS + "'}");+ assertOpEval("TimestampLessThanEqualsPath", pb, "{'a':'" + TS + "','b':'" + TS + "'}", "{'a':'" + TS1 + "','b':'" + TS + "'}");+ assertOpEval("TimestampGreaterThanEqualsPath", pb, "{'a':'" + TS + "','b':'" + TS + "'}", "{'a':'" + TS0 + "','b':'" + TS + "'}");+ // Type predicates+ assertOpEval("IsNull", t, "{'a':null}", "{'a':5}");+ assertOpEval("IsPresent", t, "{'a':1}", "{}");+ assertOpEval("IsNumeric", t, "{'a':5}", "{'a':'x'}");+ assertOpEval("IsString", t, "{'a':'x'}", "{'a':5}");+ assertOpEval("IsBoolean", t, "{'a':true}", "{'a':5}");+ assertOpEval("IsTimestamp", t, "{'a':'" + TS + "'}", "{'a':'x'}");+ }++ // ──────────────────────────── StringMatches escapes ────────────────────────────++ @Test+ void stringMatches_escapeSemantics() throws Exception {+ // \* is a literal asterisk+ ObjectNode litStar = OM.createObjectNode();+ litStar.put("Variable", "$.a");+ litStar.put("StringMatches", "a\\*b"); // glob: a \* b+ assertTrue(ChoiceOperators.evaluate(litStar, resolverFor(OM.readTree(j("{'a':'a*b'}")))));+ assertFalse(ChoiceOperators.evaluate(litStar, resolverFor(OM.readTree(j("{'a':'aXb'}")))));+ // \\ is a literal backslash+ ObjectNode litBackslash = OM.createObjectNode();+ litBackslash.put("Variable", "$.a");+ litBackslash.put("StringMatches", "a\\\\b"); // glob: a \\ b+ assertTrue(ChoiceOperators.evaluate(litBackslash, resolverFor(OM.readTree("{\"a\":\"a\\\\b\"}"))));+ // dangling escape -> error+ ObjectNode dangling = OM.createObjectNode();+ dangling.put("Variable", "$.a");+ dangling.put("StringMatches", "abc\\");+ assertThrows(ChoiceOperators.ChoiceEvaluationException.class,+ () -> ChoiceOperators.evaluate(dangling, resolverFor(OM.readTree(j("{'a':'abc'}")))));+ // illegal escape -> error, at validation time too+ assertFalse(validate(j("{'Variable':'$.a','StringMatches':'a\\\\q','Next':'X'}")).isEmpty());+ }++ // ──────────────────────────── Reference-path & Assign validation ────────────────────────────++ @Test+ void validation_rejectsBadReferencePathsAndAssign() throws Exception {+ assertFalse(validate(j("{'Variable':'not-a-path','NumericEquals':1,'Next':'X'}")).isEmpty(),+ "Variable must be a reference path");+ assertFalse(validate(j("{'Variable':'$.','NumericEquals':1,'Next':'X'}")).isEmpty(),+ "'$.' is not a valid reference path");+ assertFalse(validate(j("{'Variable':'$.a','StringEqualsPath':'$[','Next':'X'}")).isEmpty(),+ "'$[' is not a valid reference-path operand");+ assertFalse(validate(j("{'Variable':'$.a','IsNull':true,'Assign':5,'Next':'X'}")).isEmpty(),+ "Assign must be an object");+ assertTrue(validate(j("{'Variable':'$.a[0].b','NumericEquals':1,'Next':'X'}")).isEmpty(),+ "valid indexed reference path accepted");+ assertTrue(ChoiceOperators.isReferencePath("$"));+ assertTrue(ChoiceOperators.isReferencePath("$.a.b"));+ assertTrue(ChoiceOperators.isReferencePath("$[0]"));+ assertFalse(ChoiceOperators.isReferencePath("$."));+ assertFalse(ChoiceOperators.isReferencePath("$["));+ assertFalse(ChoiceOperators.isReferencePath("nope"));+ }++ // ──────────────────────────── Runtime backstop for malformed persisted rules ────────────────────────────++ @Test+ void runtimeBackstopRejectsMalformedRules() {+ // two data-test operators+ assertThrows(ChoiceOperators.ChoiceEvaluationException.class,+ () -> eval(j("{'Variable':'$.a','StringEquals':'x','NumericEquals':1}"), j("{'a':'x'}")));+ // a valid operator plus an invented field+ assertThrows(ChoiceOperators.ChoiceEvaluationException.class,+ () -> eval(j("{'Variable':'$.a','StringEquals':'x','BogusThan':1}"), j("{'a':'x'}")));+ // no operator at all+ assertThrows(ChoiceOperators.ChoiceEvaluationException.class,+ () -> eval(j("{'Variable':'$.a'}"), j("{'a':'x'}")));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/NestedExecutionInputTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/NestedExecutionInputTest.javanew file mode 100644index 0000000000..927c4a0d5d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/NestedExecutionInputTest.java@@ -0,0 +1,106 @@+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.MissingNode;+import com.fasterxml.jackson.databind.node.TextNode;+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.assertNull;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * Unit tests for {@link NestedExecutionInput}: the shared intrinsic function-name parse, the+ * States.JsonToString provenance check, and the child-input encoding matrix. Plain JUnit5 + Jackson,+ * so it runs in the offline sandbox (unlike the Vert.x-bound AslExecutor end-to-end path).+ */+class NestedExecutionInputTest {++ private static final ObjectMapper OM = new ObjectMapper();++ private static String j(String singleQuoted) {+ return singleQuoted.replace('\'', '"');+ }++ // ── intrinsicFunctionName (shared with AslExecutor.evaluateIntrinsic) ──++ @Test+ void intrinsicFunctionName_parsesAndToleratesWhitespace() {+ assertEquals("States.JsonToString", NestedExecutionInput.intrinsicFunctionName("States.JsonToString($.x)"));+ assertEquals("States.JsonToString", NestedExecutionInput.intrinsicFunctionName("States.JsonToString ($.x)"));+ assertEquals("States.Format", NestedExecutionInput.intrinsicFunctionName("States.Format(States.JsonToString($.x))"));+ assertNull(NestedExecutionInput.intrinsicFunctionName("$.x")); // not a call+ assertNull(NestedExecutionInput.intrinsicFunctionName(null));+ }++ // ── provenance ──++ @Test+ void isJsonToStringInput_detectsTopLevelJsonToString() {+ assertTrue(NestedExecutionInput.isJsonToStringInput(node(j("{'Input.$':'States.JsonToString($.x)'}"))));+ assertTrue(NestedExecutionInput.isJsonToStringInput(node(j("{'Input.$':'States.JsonToString ($.x)'}"))));+ assertFalse(NestedExecutionInput.isJsonToStringInput(node(j("{'Input.$':'$.y'}"))), "plain path");+ assertFalse(NestedExecutionInput.isJsonToStringInput(node(j("{'Input.$':'States.Format(States.JsonToString($.x))'}"))),+ "wrapped: not top-level JsonToString");+ assertFalse(NestedExecutionInput.isJsonToStringInput(node(j("{'Input':{'a':1}}"))), "literal Input, no Input.$");+ assertFalse(NestedExecutionInput.isJsonToStringInput(null));+ assertFalse(NestedExecutionInput.isJsonToStringInput(TextNode.valueOf("x")), "non-object");+ }++ // ── childInput encoding matrix (assert the CHILD's parsed $ type) ──++ @Test+ void childInput_matrix() throws Exception {+ // Row 1/2: object literal or .$ -> object => child $ is an object+ JsonNode row12 = NestedExecutionInput.childInput(node(j("{'a':1}")), false, OM).transform(this::parse);+ assertTrue(row12.isObject());+ assertEquals(1, row12.get("a").asInt());++ // Row 3: States.JsonToString(object) -> the JSON text is used verbatim => child $ is an OBJECT (the fix)+ JsonNode row3 = parse(NestedExecutionInput.childInput(TextNode.valueOf(j("{'a':1}")), true, OM));+ assertTrue(row3.isObject(), "JsonToString(object) must yield an object in the child");+ assertEquals(1, row3.get("a").asInt());++ // Row 4: plain string "hello" (not JsonToString) => child $ is the string "hello"+ JsonNode row4 = parse(NestedExecutionInput.childInput(TextNode.valueOf("hello"), false, OM));+ assertTrue(row4.isTextual());+ assertEquals("hello", row4.asText());++ // Row 5: string that LOOKS like JSON but is NOT from JsonToString => stays a string (distinct from row 3)+ JsonNode row5 = parse(NestedExecutionInput.childInput(TextNode.valueOf(j("{'a':1}")), false, OM));+ assertTrue(row5.isTextual(), "a JSON-looking string without JsonToString provenance must stay a string");+ assertEquals(j("{'a':1}"), row5.asText());++ // Row 6: States.JsonToString(string) -> JSON text of a string is a quoted string => child $ is that string+ JsonNode row6 = parse(NestedExecutionInput.childInput(TextNode.valueOf(j("'hi'")), true, OM));+ assertTrue(row6.isTextual());+ assertEquals("hi", row6.asText());++ // Row 7: missing Input => "{}"+ assertEquals("{}", NestedExecutionInput.childInput(MissingNode.getInstance(), true, OM));+ assertEquals("{}", NestedExecutionInput.childInput(null, false, OM));+ }++ @Test+ void childInput_provenanceTrueButNonJsonValueIsQuotedNotVerbatim() throws Exception {+ // Collision-template edge: provenance says JsonToString but the winning value isn't JSON text.+ // It must be quoted (a valid JSON string), never emitted verbatim (which parseInput would drop to {}).+ JsonNode child = parse(NestedExecutionInput.childInput(TextNode.valueOf("hello"), true, OM));+ assertTrue(child.isTextual());+ assertEquals("hello", child.asText());+ }++ private JsonNode node(String json) {+ try {+ return OM.readTree(json);+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }++ private JsonNode parse(String json) {+ return node(json);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/ResultPathMergeTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/ResultPathMergeTest.javanew file mode 100644index 0000000000..365ab8f24f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/ResultPathMergeTest.java@@ -0,0 +1,70 @@+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.assertThrows;++/**+ * Unit tests for {@link ResultPathMerge}: the extracted ResultPath merge, including the AWS+ * {@code States.ResultPathMatchFailure} case (previously a silent input-discard) and the documented+ * residuals. Plain JUnit5 + Jackson, so it runs in the offline sandbox.+ */+class ResultPathMergeTest {++ private static final ObjectMapper OM = new ObjectMapper();++ private static String j(String singleQuoted) {+ return singleQuoted.replace('\'', '"');+ }++ private JsonNode n(String json) {+ try {+ return OM.readTree(json);+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }++ @Test+ void nullResultPathKeepsInput() {+ JsonNode input = n(j("{'a':1}"));+ assertEquals(input, ResultPathMerge.merge(input, null, n(j("{'b':2}")), OM));+ assertEquals(input, ResultPathMerge.merge(input, "null", n(j("{'b':2}")), OM), "literal 'null' keeps input");+ }++ @Test+ void dollarReplacesWithResult() {+ JsonNode result = n(j("{'b':2}"));+ assertEquals(result, ResultPathMerge.merge(n(j("{'a':1}")), "$", result, OM));+ }++ @Test+ void objectInputMergesAtPath() {+ JsonNode out = ResultPathMerge.merge(n(j("{'a':1}")), "$.r", n(j("{'b':2}")), OM);+ assertEquals(1, out.get("a").asInt());+ assertEquals(2, out.get("r").get("b").asInt());+ }++ @Test+ void objectInputMergesAtNestedPath() {+ JsonNode out = ResultPathMerge.merge(n("{}"), "$.a.b", n("5"), OM);+ assertEquals(5, out.get("a").get("b").asInt());+ }++ @Test+ void nonObjectInputWithObjectMemberPathRaisesResultPathMatchFailure() {+ // The fix: string / array / number input + a $.field ResultPath is a match failure, not a silent discard.+ assertThrows(ResultPathMerge.ResultPathMatchException.class,+ () -> ResultPathMerge.merge(n(j("'foo'")), "$.x", n(j("'r'")), OM));+ assertThrows(ResultPathMerge.ResultPathMatchException.class,+ () -> ResultPathMerge.merge(n("[1,2]"), "$.x", n(j("'r'")), OM));+ assertThrows(ResultPathMerge.ResultPathMatchException.class,+ () -> ResultPathMerge.merge(n("5"), "$.x", n(j("'r'")), OM));+ }++ // Note: the $[...] and scalar-intermediate residuals are intentionally NOT asserted here (per the+ // scope decision they are documented in ResultPathMerge, not encoded as correct behavior).+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionIdempotencyTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionIdempotencyTest.javanew file mode 100644index 0000000000..47b185e83f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionIdempotencyTest.java@@ -0,0 +1,114 @@+package io.github.hectorvent.floci.services.stepfunctions;++import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.stepfunctions.model.Activity;+import io.github.hectorvent.floci.services.stepfunctions.model.Execution;+import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;+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.assertThrows;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doReturn;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++/**+ * The StartExecution idempotency DECISION for {@link StepFunctionsService}, over a real service with+ * in-memory stores. Each test pre-seeds an existing execution so StartExecution takes the+ * return-existing / conflict branch, which resolves before {@code aslExecutor.executeAsync}, so the+ * executor is never touched (it cannot be loaded in this offline sandbox: it needs Vert.x). The+ * create-and-launch path and the concurrency race are covered by+ * {@code StepFunctionsServiceStartExecutionRaceTest} (CI-only).+ */+class StepFunctionsServiceStartExecutionIdempotencyTest {++ private static final String SM_ARN = "arn:aws:states:us-east-1:000000000000:stateMachine:test-sm";+ private static final String REGION = "us-east-1";++ private AccountAwareStorageBackend<Execution> execStore;++ private StepFunctionsService buildService(String smType) {+ AccountAwareStorageBackend<StateMachine> smStore = AccountAwareStorageBackend.inMemory("000000000000");+ execStore = AccountAwareStorageBackend.inMemory("000000000000");+ AccountAwareStorageBackend<Activity> actStore = AccountAwareStorageBackend.inMemory("000000000000");++ StorageFactory factory = mock(StorageFactory.class);+ doReturn(smStore).doReturn(execStore).doReturn(actStore)+ .when(factory).create(anyString(), anyString(), any());++ RegionResolver region = mock(RegionResolver.class);+ when(region.buildArn(eq("states"), any(), anyString()))+ .thenAnswer(i -> "arn:aws:states:us-east-1:000000000000:" + i.getArgument(2));++ // aslExecutor is null: the return-existing / conflict branches never reach executeAsync, and a+ // null field is never dereferenced (AslExecutor cannot be class-loaded here: it needs Vert.x).+ StepFunctionsService svc =+ new StepFunctionsService(factory, region, null, new ObjectMapper(), mock(SfnMockLoader.class));++ StateMachine sm = new StateMachine();+ sm.setStateMachineArn(SM_ARN);+ sm.setName("test-sm");+ sm.setRoleArn("arn:aws:iam::000000000000:role/r");+ sm.setType(smType);+ sm.setDefinition("{\"StartAt\":\"P\",\"States\":{\"P\":{\"Type\":\"Pass\",\"End\":true}}}");+ smStore.put(SM_ARN, sm);+ return svc;+ }++ private void seedExecution(String name, String input, String status) {+ Execution exec = new Execution();+ exec.setExecutionArn("arn:aws:states:us-east-1:000000000000:execution:test-sm:" + name);+ exec.setStateMachineArn(SM_ARN);+ exec.setName(name);+ exec.setInput(input);+ exec.setStatus(status);+ exec.setStartDate(1234567.0); // distinctive: the idempotent return must preserve the ORIGINAL start date+ execStore.put(exec.getExecutionArn(), exec);+ }++ @Test+ void sameNameSameInputWhileRunningReturnsExisting() {+ StepFunctionsService service = buildService("STANDARD");+ seedExecution("run", "{\"a\":1}", "RUNNING");+ Execution result = service.startExecution(SM_ARN, "run", "{\"a\":1}", REGION);+ assertEquals("arn:aws:states:us-east-1:000000000000:execution:test-sm:run", result.getExecutionArn());+ assertEquals("RUNNING", result.getStatus());+ // Must be the ORIGINAL execution (with its original startDate), not a freshly built one.+ assertEquals(1234567.0, result.getStartDate());+ }++ @Test+ void sameNameDifferentInputConflicts() {+ StepFunctionsService service = buildService("STANDARD");+ seedExecution("run", "{\"a\":1}", "RUNNING");+ AwsException ex = assertThrows(AwsException.class,+ () -> service.startExecution(SM_ARN, "run", "{\"a\":2}", REGION));+ assertEquals("ExecutionAlreadyExists", ex.getErrorCode());+ }++ @Test+ void sameNameAfterCloseConflicts() {+ StepFunctionsService service = buildService("STANDARD");+ seedExecution("run", "{\"a\":1}", "SUCCEEDED");+ AwsException ex = assertThrows(AwsException.class,+ () -> service.startExecution(SM_ARN, "run", "{\"a\":1}", REGION));+ assertEquals("ExecutionAlreadyExists", ex.getErrorCode());+ }++ @Test+ void expressGetsNoIdempotentReturn() {+ StepFunctionsService service = buildService("EXPRESS");+ seedExecution("run", "{\"a\":1}", "RUNNING");+ // STANDARD-only idempotency: EXPRESS with the same name+input still conflicts (it does not take the+ // return-existing branch). AWS actually allows EXPRESS name reuse: a known divergence, out of scope.+ assertThrows(AwsException.class,+ () -> service.startExecution(SM_ARN, "run", "{\"a\":1}", REGION));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionRaceTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionRaceTest.javanew file mode 100644index 0000000000..8dcb9f7155--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsServiceStartExecutionRaceTest.java@@ -0,0 +1,218 @@+package io.github.hectorvent.floci.services.stepfunctions;++import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.stepfunctions.model.Execution;+import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;+import com.fasterxml.jackson.databind.ObjectMapper;+import org.junit.jupiter.api.Test;++import java.util.ArrayList;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.CopyOnWriteArrayList;+import java.util.concurrent.CyclicBarrier;+import java.util.concurrent.ExecutorService;+import java.util.concurrent.Executors;+import java.util.concurrent.Future;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.function.Predicate;+import java.util.stream.Collectors;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doReturn;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++/**+ * Concurrency-race coverage for {@code StartExecution}: concurrent same-name starts must launch exactly+ * once (the check-and-create is serialized). The execution store's {@code get} is delayed to widen the+ * check→create window, so the {@code executeAsync} count deterministically distinguishes a serialized+ * implementation (exactly one launch) from an unserialized one (one launch per thread). The test fails+ * if the lock is removed.+ *+ * <p>CI-only: {@code mock(AslExecutor.class)} forces AslExecutor to load, which needs Vert.x (absent in+ * the offline sandbox). The idempotency DECISION runs locally in+ * {@code StepFunctionsServiceStartExecutionIdempotencyTest}.+ */+class StepFunctionsServiceStartExecutionRaceTest {++ private static final String SM_ARN = "arn:aws:states:us-east-1:000000000000:stateMachine:test-sm";+ private static final String ACCOUNT = "000000000000";+ private static final String REGION = "us-east-1";+ private static final int N = 16;++ /** In-memory StorageBackend whose get() sleeps, widening the check→create window to expose an unserialized create. */+ private static final class DelayStore<V> implements StorageBackend<String, V> {+ private final Map<String, V> map = new ConcurrentHashMap<>();+ private final long getDelayMillis;++ DelayStore(long getDelayMillis) {+ this.getDelayMillis = getDelayMillis;+ }++ @Override+ public void put(String key, V value) {+ map.put(key, value);+ }++ @Override+ public Optional<V> get(String key) {+ if (getDelayMillis > 0) {+ try {+ Thread.sleep(getDelayMillis);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ }+ }+ return Optional.ofNullable(map.get(key));+ }++ @Override+ public void delete(String key) {+ map.remove(key);+ }++ @Override+ public List<V> scan(Predicate<String> keyFilter) {+ return map.entrySet().stream().filter(e -> keyFilter.test(e.getKey()))+ .map(Map.Entry::getValue).collect(Collectors.toList());+ }++ @Override+ public Set<String> keys() {+ return map.keySet();+ }++ @Override+ public void flush() {+ }++ @Override+ public void load() {+ }++ @Override+ public void clear() {+ map.clear();+ }+ }++ private record Fixture(StepFunctionsService service, AslExecutor executor) {+ }++ private Fixture build() {+ // StorageFactory.create() is declared to return AccountAwareStorageBackend, so the delayed+ // backends must be wrapped in one: stubbing a bare DelayStore is a WrongTypeOfReturnValue that+ // fails build() before any thread starts. The wrapper is what the service gets in production too.+ AccountAwareStorageBackend<StateMachine> smStore =+ new AccountAwareStorageBackend<>(new DelayStore<>(0), null, ACCOUNT);+ AccountAwareStorageBackend<Execution> execStore =+ new AccountAwareStorageBackend<>(new DelayStore<>(100), null, ACCOUNT); // widen check->create window+ AccountAwareStorageBackend<Object> actStore =+ new AccountAwareStorageBackend<>(new DelayStore<>(0), null, ACCOUNT);++ StorageFactory factory = mock(StorageFactory.class);+ doReturn(smStore).doReturn(execStore).doReturn(actStore)+ .when(factory).create(anyString(), anyString(), any());++ RegionResolver region = mock(RegionResolver.class);+ when(region.buildArn(eq("states"), any(), anyString()))+ .thenAnswer(i -> "arn:aws:states:us-east-1:000000000000:" + i.getArgument(2));++ AslExecutor executor = mock(AslExecutor.class);+ StepFunctionsService service =+ new StepFunctionsService(factory, region, executor, new ObjectMapper(), mock(SfnMockLoader.class));++ StateMachine sm = new StateMachine();+ sm.setStateMachineArn(SM_ARN);+ sm.setName("test-sm");+ sm.setRoleArn("arn:aws:iam::000000000000:role/r");+ sm.setType("STANDARD");+ sm.setDefinition("{\"StartAt\":\"P\",\"States\":{\"P\":{\"Type\":\"Pass\",\"End\":true}}}");+ smStore.put(SM_ARN, sm);+ return new Fixture(service, executor);+ }++ private void runConcurrently(java.util.function.IntConsumer body) throws Exception {+ CyclicBarrier barrier = new CyclicBarrier(N);+ ExecutorService pool = Executors.newFixedThreadPool(N);+ List<Future<?>> futures = new ArrayList<>();+ try {+ for (int i = 0; i < N; i++) {+ final int idx = i;+ futures.add(pool.submit(() -> {+ try {+ barrier.await();+ body.accept(idx);+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }));+ }+ for (Future<?> f : futures) {+ f.get(30, TimeUnit.SECONDS);+ }+ } finally {+ pool.shutdownNow();+ }+ }++ @Test+ void concurrentSameNameSameInputLaunchesExactlyOnce() throws Exception {+ Fixture fx = build();+ List<String> arns = new CopyOnWriteArrayList<>();+ List<Throwable> errors = new CopyOnWriteArrayList<>();+ runConcurrently(i -> {+ try {+ arns.add(fx.service().startExecution(SM_ARN, "race", "{\"a\":1}", REGION).getExecutionArn());+ } catch (Throwable t) {+ errors.add(t);+ }+ });+ assertTrue(errors.isEmpty(), "no same-input start should error: " + errors);+ assertEquals(N, arns.size());+ assertEquals(1, arns.stream().distinct().count(), "all resolve to one execution");+ // The lock's teeth: without serialization every thread would create + launch.+ verify(fx.executor(), times(1)).executeAsync(any(), any(), any(), any(), any());+ }++ @Test+ void concurrentSameNameDistinctInputsLaunchesOnceRestConflict() throws Exception {+ Fixture fx = build();+ AtomicInteger successes = new AtomicInteger();+ AtomicInteger conflicts = new AtomicInteger();+ List<Throwable> unexpected = new CopyOnWriteArrayList<>();+ runConcurrently(i -> {+ try {+ fx.service().startExecution(SM_ARN, "race", "{\"a\":" + i + "}", REGION);+ successes.incrementAndGet();+ } catch (AwsException e) {+ if ("ExecutionAlreadyExists".equals(e.getErrorCode())) {+ conflicts.incrementAndGet();+ } else {+ unexpected.add(e);+ }+ } catch (Throwable t) {+ unexpected.add(t);+ }+ });+ assertTrue(unexpected.isEmpty(), "only ExecutionAlreadyExists expected: " + unexpected);+ assertEquals(1, successes.get(), "exactly one distinct-input start wins");+ assertEquals(N - 1, conflicts.get(), "the rest conflict");+ verify(fx.executor(), times(1)).executeAsync(any(), any(), any(), any(), any());+ }+}