feat(stepfunctions): close ASL gaps in intrinsics, Choice, StartExecution and ResultPath (#3002)

* feat(stepfunctions): add Base64Encode/Base64Decode/StringSplit/ArrayGetItem/Hash intrinsics

Add five JSONPath-mode Amazon States Language intrinsic functions to
AslExecutor.evaluateIntrinsic, following the existing States.JsonMerge pattern.
Previously these aborted execution with States.Runtime "Unsupported intrinsic function".

- Base64Encode/Base64Decode: RFC 4648 Basic (unwrapped) codec, UTF-8, 10,000 code-point
  input cap; invalid base64 -> States.IntrinsicFailure.
- StringSplit: delimiter is a set of code points; empty segments omitted.
- ArrayGetItem: zero-based; rejects non-integer, negative, and out-of-range indexes.
- Hash: lowercase hex digest via an explicit MD5/SHA-1/SHA-256/SHA-384/SHA-512 allow-list
  checked before MessageDigest, 10,000 code-point cap.

All argument and data validation failures raise the catchable States.IntrinsicFailure;
States.Runtime remains reserved for malformed/unrecognized calls. Adds
AslExecutorIntrinsicFunctionsTest covering AWS doc examples, edge cases, execution-level
Catch behavior, Parameters-path wiring, and a nine-existing-intrinsic regression.

* fix(stepfunctions): implement all 39 Choice comparators type-strictly and reject invalid rules

floci's Choice state implemented only 18 of the 39 documented ASL data-test
comparators. Any unrecognised comparator — NumericGreaterThanEqualsPath, the
String*Path ordering variants, the entire Timestamp* family, IsTimestamp — fell
off the end of the comparison chain and evaluated silently false, so the Choice
took its Default branch. A workflow routing on >= (or any missing comparator)
silently took the wrong path with no error, log line, or execution-history
annotation.

Changes:
- Add ChoiceOperators: the single source of truth for the 39 data-test operators,
  their type-strict evaluation, and Choice-rule validation, shared by the runtime
  evaluator (AslExecutor.evaluateCondition) and the Create/Update/Validate path
  (StepFunctionsService.validateState) so the two can no longer disagree.
- Implement the 21 missing comparators (String ordering, Numeric *Path
  LessThanEquals/GreaterThanEquals, the full Timestamp* family, IsTimestamp).
- Make comparisons type-strict: a mismatched JSON type compares false rather than
  coercing (previously a missing path compared equal to numeric 0 / boolean false,
  and numeric 5 matched string "5"). Numeric compares via BigDecimal; timestamps
  via an RFC3339 lexical gate then instant comparison; StringMatches honours the
  \* and \\ escapes and rejects a dangling/illegal escape.
- Reject invalid Choice rules at CreateStateMachine / UpdateStateMachine /
  ValidateStateMachineDefinition (unknown field, not exactly one operator, wrong
  operand type, invalid reference path, malformed And/Or/Not, misplaced Next), and
  raise States.Runtime at evaluation time for a malformed rule or a missing
  reference path instead of silently returning false.

AWS Compatibility: verified against the ASL Choice-state specification — all *Path
and Timestamp* comparators, RFC3339 timestamps (uppercase T/Z, instant
comparison), and rejection of unknown comparators at create time (AWS returns
InvalidDefinition / SCHEMA_VALIDATION_FAILED) with a runtime States.Runtime
backstop for already-persisted definitions. Behaviour change: definitions that
previously relied on loose coercion or a silent-false unknown comparator now fail
loudly, matching AWS. Known limitations: leap-second and >9-fractional-digit
timestamps are treated as invalid.

* fix(stepfunctions): make StartExecution idempotent and race-free for STANDARD workflows

floci's StartExecution rejected any name collision with ExecutionAlreadyExists and
performed its check-and-create without synchronization. AWS instead treats a
STANDARD StartExecution with the same name AND the same input, while the original
is still RUNNING, as an idempotent success that returns the original execution;
only a different input (or a closed execution with that name) is a conflict. The
unsynchronized check also let two concurrent same-name starts both create and
launch an execution.

- Serialize the execution check-and-create under a dedicated lock so concurrent
  same-name StartExecution calls cannot both create and launch; executeAsync runs
  outside the lock, only on the create path.
- Return the existing execution for a STANDARD workflow when the prior execution is
  RUNNING and the input is identical (exact wire-string match); otherwise throw
  ExecutionAlreadyExists. EXPRESS workflows keep the conflict behaviour (AWS gives
  EXPRESS no idempotency guarantee).

AWS Compatibility: verified against the StartExecution API idempotency contract
(STANDARD-only; same name + same input while RUNNING returns the original
execution; a different input or a closed execution with that name conflicts).
Known limitations: closed execution names are not made reusable after AWS's 90-day
uniqueness window (floci conflicts for the process lifetime, which matches AWS
within any realistic emulator session); the StartExecution lock is a single global
monitor rather than per-execution-name.

* fix(stepfunctions): honor Name and JsonToString Input in nested startExecution

The optimized states:startExecution integration ignored the Task's Name (always
generating a random execution name) and re-serialized the resolved Input
unconditionally, so an Input built with States.JsonToString(<object>) was
double-encoded: the child execution received a JSON string literal instead of the
intended object.

- Add NestedExecutionInput: the child-input encoding + a States.JsonToString
  provenance check, plus the intrinsic function-name parse SHARED with
  AslExecutor.evaluateIntrinsic so provenance and evaluation cannot drift.
- Encode the child input by provenance: a value produced by States.JsonToString is
  JSON text used verbatim as the wire input (the child parses it back to an object);
  any other value is serialized as a JSON value (an object stays an object; a plain
  or JSON-looking string stays a JSON string literal). A missing Input yields {}.
- Honor Name / Name.$ instead of passing null. A supplied Name that does not resolve
  to a non-empty string fails with States.Runtime rather than silently generating a
  name; a truly omitted Name still generates one.

AWS Compatibility: matches the ASL payload-template and StartExecution semantics for a
nested execution's input and name (verified against the ASL spec's type-preserving
payload templates and the documented States.JsonToString "string containing JSON
text"). Behaviour change: a States.JsonToString(<object>) Input now reaches the child
as an object (previously a string); object / .$ / plain-string Inputs are unchanged.
Scope: JSONata Arguments and colliding Input/Input.$ templates are out of scope (the
latter's runtime behaviour is made safe).

* fix(stepfunctions): raise States.ResultPathMatchFailure instead of discarding state input

When a state's ResultPath addresses an object member ($.field) but the state input is
not a JSON object, floci silently discarded the input and returned the bare result.
AWS instead fails the execution with States.ResultPathMatchFailure.

- Extract the ResultPath merge (and its setPath helper) into ResultPathMerge so the
  merge rules are unit-testable without the full executor.
- Raise States.ResultPathMatchFailure for a non-object input combined with a
  $.-member ResultPath (previously a silent input discard). null / "null" / "$"
  ResultPaths and object-input merges are unchanged.
- Propagate a failure raised while applying a matched Catcher's own ResultPath with
  its real error name rather than relabeling it States.Runtime.

AWS Compatibility: matches the ASL ResultPath spec (a non-applicable ResultPath is
States.ResultPathMatchFailure, not a silent discard). Behaviour change: a state (or
Catcher) with a $.field ResultPath over a scalar/array input now fails instead of
silently dropping the input. Known residuals: $[...]-style ResultPaths are not applied,
and a $.a.b path whose $.a is a scalar is overwritten rather than failing.

* style(stepfunctions): remove em dashes from lines this branch adds

AGENTS.md, Documentation Style: "No em-dashes anywhere, in any content. Use
colons, commas, or periods." Seventeen lines added by this branch used one. All
of them sit in files the branch creates, so they also trip the doc-style
workflow, which scans newly added files.

Scoped strictly to lines this branch adds. The em dashes main already carries on
untouched lines in AslExecutor and StepFunctionsService are left alone. Several
clauses are reworded rather than resegmented where a bare colon or comma read
badly, for instance the appositive in the AslExecutorChoiceRuntimeTest header.

Three commit message lines on this branch still contain an em dash. Rewriting
those would require a force-push, so they are left as they are.
This commit is contained in:
Guilherme Scaranse authored and GitHub committed 2026-09-04 10:29:03 -04:00
1 parent 73deb13c01
commit 352d89ff2d
14 files changed
+2882 -149

No files matched your search

@@ -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 integration
String 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;
// 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());
}
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();
}
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;
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());
}
if ("$".equals(resultPath)) {
return result;
}
// Merge result into input at the given path
if (!input.isObject()) {
return result;
}
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 ────────────────────────────
/**
@@ -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;
}
}
@@ -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;
}
}
}
@@ -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);
}
}
@@ -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,30 +530,43 @@ 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);
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);
}
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);
}
var exec = new Execution();
exec.setExecutionArn(arn);
exec.setStateMachineArn(selection.stateMachineArn());
exec.setName(execName);
exec.setInput(input);
exec.setStatus("RUNNING");
executionStore.put(arn, exec);
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);
LOG.infov("Started execution: {0}", arn);
// The executor appends to this same history, so the cache entry put above is already the
@@ -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")) {