feat(stepfunctions): support workflow variables in JSONPath states (#7106)

This commit is contained in:
syedali032-creator authored and GitHub committed 2026-11-03 08:32:00 -04:00
1 parent d7797bf56d
commit 25780c051e
3 files changed
+425 -8

No files matched your search

@@ -134,6 +134,7 @@ import java.util.function.Consumer;
import java.util.function.IntFunction;
import java.util.function.LongSupplier;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
@ApplicationScoped
@@ -728,6 +729,27 @@ public class AslExecutor {
JsonNode stateDef, JsonNode input, StateMachine sm,
String topLevelQueryLanguage, JsonNode context, ObjectNode variables,
long executionDeadlineNanos) throws Exception {
// JSONPath states read and Assign workflow variables through JSONPATH_SCOPE (see there).
JsonPathScope previousScope = JSONPATH_SCOPE.get();
JsonPathScope scope = isJsonata(stateDef, topLevelQueryLanguage) ? null
: new JsonPathScope(variables, context, objectMapper.createObjectNode());
JSONPATH_SCOPE.set(scope);
try {
StateResult result = runEnteredStateBody(chain, name, enteredEventId, type, stateDef, input, sm,
topLevelQueryLanguage, context, variables, executionDeadlineNanos);
if (scope != null) {
variables.setAll(scope.pendingAssignments());
}
return result;
} finally {
restoreJsonPathScope(previousScope);
}
}
private StateResult runEnteredStateBody(HistoryChain chain, String name, long enteredEventId, String type,
JsonNode stateDef, JsonNode input, StateMachine sm,
String topLevelQueryLanguage, JsonNode context, ObjectNode variables,
long executionDeadlineNanos) throws Exception {
updateStateContext(context, name);
boolean jsonata = isJsonata(stateDef, topLevelQueryLanguage);
StateResult result;
@@ -810,6 +832,10 @@ public class AslExecutor {
return executeState(name, type, stateDef, input, chain, sm, jsonata,
topLevelQueryLanguage, context, variables, executionDeadlineNanos);
} catch (FailStateException raised) {
JsonPathScope scope = JSONPATH_SCOPE.get();
if (scope != null) {
scope.pendingAssignments().removeAll();
}
FailStateException e = raised.attributedTo(name, enteredEventId);
if (!raised.hasFinalCause()) {
publishEvaluationFailedEvent(chain, name, e);
@@ -920,6 +946,7 @@ public class AslExecutor {
result = stateDef.get("Result");
}
applyJsonPathAssign(stateDef, result);
JsonNode output = mergeResult(stateDef, input, result);
output = applyOutputPath(stateDef, output, context);
return new StateResult(output, stateDef.path("Next").asText(null));
@@ -1051,7 +1078,8 @@ public class AslExecutor {
JsonNode output = applyJsonataOutput(stateDef, input, taskResult, context, variables);
return new StateResult(output, stateDef.path("Next").asText(null));
} else {
// ResultSelector transforms the raw result before ResultPath merges it into the state input.
// Assign reads the raw task result; ResultSelector transforms it before ResultPath merges it.
applyJsonPathAssign(stateDef, taskResult);
if (stateDef.has("ResultSelector")) {
taskResult = resolveParameters(stateDef.get("ResultSelector"), taskResult, context);
}
@@ -2875,6 +2903,8 @@ public class AslExecutor {
JsonNode choices = stateDef.path("Choices");
for (JsonNode choice : choices) {
if (evaluateCondition(choice, effectiveInput, context)) {
// A matched rule carries its own Assign; the state-level one applies on the Default path.
applyJsonPathAssign(choice, effectiveInput);
JsonNode output = applyOutputPath(stateDef, effectiveInput, context);
return new StateResult(output, choice.path("Next").asText());
}
@@ -2882,6 +2912,7 @@ public class AslExecutor {
// Default branch
String defaultState = stateDef.path("Default").asText(null);
if (defaultState != null) {
applyJsonPathAssign(stateDef, effectiveInput);
JsonNode output = applyOutputPath(stateDef, effectiveInput, context);
return new StateResult(output, defaultState);
}
@@ -2902,7 +2933,7 @@ public class AslExecutor {
private StateResult executeWaitState(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context,
ObjectNode variables, long executionDeadlineNanos)
throws InterruptedException {
throws Exception {
long waitNanos = 0;
JsonNode effectiveInput = input;
if (jsonata) {
@@ -2948,6 +2979,7 @@ public class AslExecutor {
JsonNode output = applyJsonataOutput(stateDef, input, null, context, variables);
return new StateResult(output, stateDef.path("Next").asText(null));
}
applyJsonPathAssign(stateDef, effectiveInput);
JsonNode output = applyOutputPath(stateDef, effectiveInput, context);
return new StateResult(output, stateDef.path("Next").asText(null));
}
@@ -3176,7 +3208,8 @@ public class AslExecutor {
return new StateResult(output, stateDef.path("Next").asText(null));
}
// ResultSelector transforms the raw branch results before ResultPath merges them in.
// Assign reads the raw branch results; ResultSelector transforms them before ResultPath merges them in.
applyJsonPathAssign(stateDef, results);
JsonNode selected = stateDef.has("ResultSelector")
? resolveParameters(stateDef.get("ResultSelector"), results, context)
: results;
@@ -3324,7 +3357,7 @@ public class AslExecutor {
iterInput = jsonata
? jsonataEvaluator.resolveTemplate(itemTransform, "ItemSelector",
buildStatesVar(mapInput, null, iterContext), variables)
: resolveParameters(itemTransform, mapInput, iterContext);
: resolveMapItemParameters(itemTransform, mapInput, iterContext, variables);
}
if (!distributed) {
iterationChain.publishIterationStart("MapIterationStarted", Map.of("name", name, "index", i));
@@ -3468,7 +3501,8 @@ public class AslExecutor {
return new StateResult(output, stateDef.path("Next").asText(null));
}
// ResultSelector transforms the raw iteration results before ResultPath merges them in.
// Assign reads the raw iteration results; ResultSelector transforms them before ResultPath merges them in.
applyJsonPathAssign(stateDef, mapResult);
JsonNode selected = stateDef.has("ResultSelector")
? resolveParameters(stateDef.get("ResultSelector"), mapResult, context)
: mapResult;
@@ -4457,6 +4491,79 @@ public class AslExecutor {
return resolvePath(path, input, context);
}
/**
* Workflow variables of the JSONPath state running on this thread. AWS lets JSONPath states read
* variables through {@code $name} / {@code $name.path} references and write them with
* {@code Assign}; the JSONPath resolvers have no {@code variables} parameter, so
* {@link #runEnteredState} exposes the state's scope here for the duration of the state
* (Map iterations and Parallel branches run their own states, so each sees its own scope).
* Not set for JSONata states, which use {@code variables} directly.
*/
private static final ThreadLocal<JsonPathScope> JSONPATH_SCOPE = new ThreadLocal<>();
private record JsonPathScope(ObjectNode variables, JsonNode context, ObjectNode pendingAssignments) {
}
private static void restoreJsonPathScope(JsonPathScope previousScope) {
if (previousScope == null) {
JSONPATH_SCOPE.remove();
} else {
JSONPATH_SCOPE.set(previousScope);
}
}
private JsonNode resolveMapItemParameters(JsonNode template, JsonNode input, JsonNode context,
ObjectNode variables) throws Exception {
JsonPathScope previousScope = JSONPATH_SCOPE.get();
JSONPATH_SCOPE.set(new JsonPathScope(variables, context, objectMapper.createObjectNode()));
try {
return resolveParameters(template, input, context);
} finally {
restoreJsonPathScope(previousScope);
}
}
/**
* Resolves a JSONPath workflow-variable reference ({@code $name}, {@code $name.field},
* {@code $name[0]}), or returns {@code null} when {@code path} is not one ({@code $}, {@code $.},
* {@code $[}, {@code $$}). An unknown variable fails the state with States.Runtime, as on AWS.
*/
private JsonNode resolveVariableReference(String path) {
if (path == null || path.startsWith("$$") || path.startsWith("$.") || path.startsWith("$[")) {
return null;
}
Matcher m = ChoiceOperators.variableReferenceMatcher(path);
if (!m.matches()) {
return null;
}
JsonPathScope scope = JSONPATH_SCOPE.get();
JsonNode value = scope == null ? null : scope.variables().get(m.group(1));
if (value == null) {
throw new FailStateException("States.Runtime",
"The JSONPath variable reference '" + path + "' refers to an undefined variable '" + m.group(1) + "'");
}
String rest = m.group(2);
return rest.isEmpty() ? value : resolvePathNode("$" + rest, value, null);
}
/**
* JSONPath {@code Assign}: evaluated against the state result (Pass: after Parameters/Result; Task,
* Map, Parallel: the raw result, before ResultSelector; Choice: the effective input; Catch: the error
* output; Wait: the effective input) with the variables as they were on state entry. Values stay
* pending until the state finishes successfully, so output processing cannot see its assignments.
*/
private void applyJsonPathAssign(JsonNode holder, JsonNode result) throws Exception {
JsonPathScope scope = JSONPATH_SCOPE.get();
if (scope == null || holder == null || !holder.has("Assign")) {
return;
}
JsonNode assigned = resolveParameters(holder.get("Assign"), result, scope.context());
if (assigned == null || !assigned.isObject()) {
throw new FailStateException("States.Runtime", "Assign must evaluate to an object");
}
scope.pendingAssignments().setAll((ObjectNode) assigned);
}
private JsonNode mergeResult(JsonNode stateDef, JsonNode input, JsonNode result) throws Exception {
if (!stateDef.has("ResultPath")) {
return result;
@@ -4564,6 +4671,10 @@ public class AslExecutor {
if (path.startsWith("States.")) {
return evaluateIntrinsic(path, root, context);
}
JsonNode variable = resolveVariableReference(path);
if (variable != null) {
return variable;
}
if ("$$".equals(path)) {
return context == null ? MissingNode.getInstance() : context;
}
@@ -4611,6 +4722,15 @@ public class AslExecutor {
if (path.startsWith("States.")) {
return evaluateIntrinsic(path, searchRoot, context);
}
String referencePath = path;
Matcher variable = ChoiceOperators.variableReferenceMatcher(path);
if (variable.matches()) {
searchRoot = resolveVariableReference("$" + variable.group(1));
path = "$" + variable.group(2);
if ("$".equals(path)) {
return searchRoot;
}
}
if (!path.startsWith("$.") && !path.startsWith("$[")) {
return NullNode.getInstance();
}
@@ -4619,7 +4739,7 @@ public class AslExecutor {
if (!value.isMissingNode()) {
return value;
}
throw unresolvedPayloadTemplateReference(path, fieldKey, reportedInput);
throw unresolvedPayloadTemplateReference(referencePath, fieldKey, reportedInput);
}
String[] parts = splitPathSegments(path);
if (containsWildcard(parts)) {
@@ -4633,7 +4753,7 @@ public class AslExecutor {
if (lookup.outOfRangeArrayIndex) {
return NullNode.getInstance();
}
throw unresolvedPayloadTemplateReference(path, fieldKey, reportedInput);
throw unresolvedPayloadTemplateReference(referencePath, fieldKey, reportedInput);
}
private static boolean isAdvancedJsonPath(String path) {
@@ -5824,7 +5944,8 @@ public class AslExecutor {
if (context != null && "$$".equals(arg)) {
return context;
}
if (arg.startsWith("$.") || arg.startsWith("$[") || "$".equals(arg)) {
if (ChoiceOperators.variableReferenceMatcher(arg).matches()
|| arg.startsWith("$.") || arg.startsWith("$[") || "$".equals(arg)) {
return resolveIntrinsicReference(arg, root, context, root);
}
if (arg.startsWith("States.")) {
@@ -6206,6 +6327,7 @@ public class AslExecutor {
catcher, "Catch[" + i + "]/", statesVar, errorOutput, variables);
return new StateResult(output, next);
}
applyJsonPathAssign(catcher, errorOutput);
return new StateResult(mergeResult(catcher, input, errorOutput), next);
}
return null;
@@ -10,6 +10,7 @@ import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
@@ -35,6 +36,9 @@ import java.util.regex.Pattern;
*/
public final class ChoiceOperators {
private static final Pattern VARIABLE_REFERENCE =
Pattern.compile("^\\$([_\\p{javaUnicodeIdentifierStart}][\\p{javaUnicodeIdentifierPart}]*)((?:[.\\[].*)?)$");
private ChoiceOperators() {
}
@@ -457,6 +461,10 @@ public final class ChoiceOperators {
}
}
static Matcher variableReferenceMatcher(String path) {
return VARIABLE_REFERENCE.matcher(path);
}
/**
* Pragmatic ASL reference-path syntax check: must start with {@code $} or {@code $$}; either root
* alone is valid; a longer path must be a sequence of non-empty {@code .segment} steps and balanced
@@ -467,6 +475,11 @@ public final class ChoiceOperators {
if (p == null || p.isEmpty() || p.charAt(0) != '$') {
return false;
}
// A JSONPath workflow variable ($name, $name.field, $name[0]) is a valid reference on AWS.
Matcher variable = variableReferenceMatcher(p);
if (variable.matches()) {
return variable.group(2).isEmpty() || isReferencePath("$" + variable.group(2));
}
if (p.startsWith("$$")) {
p = "$" + p.substring(2);
}
@@ -0,0 +1,282 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
import jakarta.enterprise.inject.Instance;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* JSONPath workflow variables: {@code Assign} on JSONPath states (evaluated against the state result,
* committed for later states) and {@code $name} / {@code $name.path} references in Parameters,
* intrinsic arguments and Choice rules, as AWS supports them for JSONPath (not only JSONata).
*/
class AslExecutorJsonPathVariablesTest {
private final ObjectMapper mapper = new ObjectMapper();
private AslExecutor executor;
@BeforeEach
void setUp() {
executor = AslExecutorFixture.builder().objectMapper(mapper).build();
}
private Execution run(String definition, String input) {
return AslExecutorFixture.runSync(executor, "us-east-1", "vars", definition, input, new ArrayList<>());
}
private JsonNode output(Execution exec) throws Exception {
return mapper.readTree(exec.getOutput());
}
@Test
void passAssignFromParametersIsReadByLaterStatesInIntrinsicsAndParameters() throws Exception {
// Assign's $ is the Pass result (after Parameters), not the raw input; literal values are allowed.
Execution exec = run("""
{"StartAt":"Extract","States":{
"Extract":{"Type":"Pass","Parameters":{"fileKey.$":"$.key"},
"Assign":{"projectId.$":"States.ArrayGetItem(States.StringSplit($.fileKey, '/'), 1)","baseUrl":"http://api/"},
"Next":"Use"},
"Use":{"Type":"Pass","Parameters":{
"url.$":"States.Format('{}projects/{}/status', $baseUrl, $projectId)",
"id.$":"$projectId"},"End":true}}}
""", "{\"key\":\"root/42/DWG/a.dwg\"}");
assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause());
assertEquals("http://api/projects/42/status", output(exec).path("url").asText());
assertEquals("42", output(exec).path("id").asText());
}
@Test
void choiceRuleTestsAVariableAndVariableFieldPaths() throws Exception {
Execution exec = run("""
{"StartAt":"Set","States":{
"Set":{"Type":"Pass","Assign":{"isDwg":true,"file":{"name":"a.dwg"}},"Next":"Route"},
"Route":{"Type":"Choice","Choices":[{"Variable":"$isDwg","BooleanEquals":true,"Next":"Dwg"}],"Default":"Gis"},
"Dwg":{"Type":"Pass","Parameters":{"route":"dwg","name.$":"$file.name"},"End":true},
"Gis":{"Type":"Pass","Parameters":{"route":"gis"},"End":true}}}
""", "{}");
assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause());
assertEquals("dwg", output(exec).path("route").asText());
assertEquals("a.dwg", output(exec).path("name").asText());
}
@ParameterizedTest
@ValueSource(strings = {"r\u00E9sultat", "\u53D8\u91CF", "e\u0301", "var\u0661", "\uD801\uDC00value", "_existing"})
void unicodeVariableNamesAreReadByParametersAndIntrinsics(String variableName) throws Exception {
Execution exec = run("""
{"StartAt":"Set","States":{
"Set":{"Type":"Pass","Assign":{"%s":"ok"},"Next":"Use"},
"Use":{"Type":"Pass","Parameters":{
"direct.$":"$%s",
"formatted.$":"States.Format('{}!', $%s)"},"End":true}}}
""".formatted(variableName, variableName, variableName), "{}");
assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause());
assertEquals("ok", output(exec).path("direct").asText());
assertEquals("ok!", output(exec).path("formatted").asText());
}
@ParameterizedTest
@ValueSource(strings = {"r\u00E9sultat", "\u53D8\u91CF", "e\u0301", "var\u0661", "\uD801\uDC00value", "_existing"})
void unicodeVariableNamesWithFieldAndIndexSuffixesWorkInChoice(String variableName) throws Exception {
assertTrue(ChoiceOperators.isReferencePath("$" + variableName + ".field[0]"));
Execution exec = run("""
{"StartAt":"Set","States":{
"Set":{"Type":"Pass","Assign":{"%s":{"field":[true]}},"Next":"Route"},
"Route":{"Type":"Choice","Choices":[{
"Variable":"$%s.field[0]","BooleanEquals":true,"Next":"Matched"}],
"Default":"Unmatched"},
"Matched":{"Type":"Pass","Result":"matched","End":true},
"Unmatched":{"Type":"Pass","Result":"unmatched","End":true}}}
""".formatted(variableName, variableName), "{}");
assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause());
assertEquals("matched", output(exec).asText());
}
@ParameterizedTest
@ValueSource(strings = {"1name", "\u0301name", "\uD83D\uDE00name"})
void variableNamesRejectInvalidFirstCharacter(String variableName) {
assertFalse(ChoiceOperators.isReferencePath("$" + variableName));
}
@Test
void assignEntriesSeeTheValuesFromStateEntry() throws Exception {
Execution exec = run("""
{"StartAt":"A","States":{
"A":{"Type":"Pass","Assign":{"x":1},"Next":"B"},
"B":{"Type":"Pass","Assign":{"x":2,"before.$":"$x"},"Next":"C"},
"C":{"Type":"Pass","Parameters":{"x.$":"$x","before.$":"$before"},"End":true}}}
""", "{}");
assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause());
assertEquals(2, output(exec).path("x").asInt());
assertEquals(1, output(exec).path("before").asInt());
}
@Test
void catchAssignReadsTheErrorOutput() throws Exception {
Execution exec = run("""
{"StartAt":"Boom","States":{
"Boom":{"Type":"Parallel","Branches":[{"StartAt":"F","States":{"F":{"Type":"Fail","Error":"Custom.Err","Cause":"bad"}}}],
"Catch":[{"ErrorEquals":["States.ALL"],"Assign":{"err.$":"$.Error"},"ResultPath":"$.caught","Next":"After"}],"End":true},
"After":{"Type":"Pass","Parameters":{"err.$":"$err"},"End":true}}}
""", "{}");
assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause());
assertEquals("Custom.Err", output(exec).path("err").asText());
}
@Test
void taskLikeAssignReadsTheRawResultNotTheResultSelectorOutput() throws Exception {
// As on AWS: Assign and ResultSelector both see the raw result, so both can read $.ResponseBody.
Execution exec = run("""
{"StartAt":"Call","States":{
"Call":{"Type":"Parallel","Branches":[{"StartAt":"B","States":{"B":{"Type":"Pass",
"Result":{"ResponseBody":{"tilesetId":"t-1"}},"End":true}}}],
"ResultSelector":{"selected.$":"$[0].ResponseBody.tilesetId"},
"Assign":{"tilesetId.$":"$[0].ResponseBody.tilesetId"},
"ResultPath":"$.apiResult","Next":"Use"},
"Use":{"Type":"Pass","Parameters":{"v.$":"$tilesetId","s.$":"$.apiResult.selected"},"End":true}}}
""", "{}");
assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause());
assertEquals("t-1", output(exec).path("v").asText());
assertEquals("t-1", output(exec).path("s").asText());
}
@Test
void undefinedVariableFailsWithStatesRuntime() {
Execution exec = run("""
{"StartAt":"Use","States":{"Use":{"Type":"Pass","Parameters":{"v.$":"$missing"},"End":true}}}
""", "{}");
assertEquals("FAILED", exec.getStatus());
assertEquals("States.Runtime", exec.getError());
assertTrue(exec.getCause().contains("missing"), exec.getCause());
}
@ParameterizedTest
@ValueSource(strings = {"Task", "Parallel", "Map"})
void resultSelectorReadsEntryVariablesAndNextStateReadsAssignments(String type) throws Exception {
SqsJsonHandler sqs = mock(SqsJsonHandler.class);
when(sqs.handle(anyString(), any(), anyString()))
.thenReturn(Response.ok(mapper.createObjectNode().put("MessageId", "message-1")).build());
executor = AslExecutorFixture.builder().objectMapper(mapper).sqsJsonHandler(sqs).build();
String work = "Task".equals(type)
? "\"Resource\":\"arn:aws:states:::sqs:sendMessage\",\"Parameters\":{\"QueueUrl\":\"http://localhost/queue\",\"MessageBody\":\"hello\"}"
: "Parallel".equals(type)
? "\"Branches\":[{\"StartAt\":\"Done\",\"States\":{\"Done\":{\"Type\":\"Pass\",\"End\":true}}}]"
: "\"ItemsPath\":\"$.items\",\"ItemProcessor\":{\"StartAt\":\"Done\",\"States\":{\"Done\":{\"Type\":\"Pass\",\"End\":true}}}";
Execution exec = run("""
{"StartAt":"Set","States":{
"Set":{"Type":"Pass","Assign":{"x":1},"Next":"Work"},
"Work":{"Type":"%s",%s,"Assign":{"x":2},
"ResultSelector":{"before.$":"$x"},"Next":"Use"},
"Use":{"Type":"Pass","Parameters":{"before.$":"$.before","after.$":"$x"},"End":true}}}
""".formatted(type, work), "{\"items\":[1,2]}");
assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause());
assertEquals(1, output(exec).path("before").asInt());
assertEquals(2, output(exec).path("after").asInt());
}
@ParameterizedTest
@ValueSource(strings = {"ItemSelector", "Parameters"})
void mapSelectorReadsOuterVariables(String selector) throws Exception {
Execution exec = run("""
{"StartAt":"Set","States":{
"Set":{"Type":"Pass","Assign":{"shared":"outer"},"Next":"Map"},
"Map":{"Type":"Map","ItemsPath":"$.items","%s":{"shared.$":"$shared","item.$":"$$.Map.Item.Value"},
"ItemProcessor":{"StartAt":"Use","States":{
"Use":{"Type":"Pass","Parameters":{"selected.$":"$.shared","inherited.$":"$shared"},"End":true}}},
"End":true}}}
""".formatted(selector), "{\"items\":[1,2]}");
assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause());
assertEquals(2, output(exec).size());
for (JsonNode item : output(exec)) {
assertEquals("outer", item.path("selected").asText());
assertEquals("outer", item.path("inherited").asText());
}
}
@ParameterizedTest
@ValueSource(strings = {"$obj.missing", "States.Format('{}', $obj.missing)", "States.Format('{}', $obj.items[2])"})
void missingVariableChildFailsWithStatesRuntime(String reference) {
Execution exec = run("""
{"StartAt":"Set","States":{
"Set":{"Type":"Pass","Assign":{"obj":{"items":[]}},"Next":"Use"},
"Use":{"Type":"Pass","Parameters":{"value.$":"%s"},"End":true}}}
""".formatted(reference), "{}");
assertEquals("FAILED", exec.getStatus());
assertEquals("States.Runtime", exec.getError());
}
@Test
void plainVariableArrayReferenceAllowsOutOfRangeIndex() throws Exception {
Execution exec = run("""
{"StartAt":"Set","States":{
"Set":{"Type":"Pass","Assign":{"items":[]},"Next":"Use"},
"Use":{"Type":"Pass","Parameters":{"value.$":"$items[2]"},"End":true}}}
""", "{}");
assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause());
assertTrue(output(exec).has("value"));
assertTrue(output(exec).get("value").isNull());
}
@Test
void waitAssignIsReadByNextState() throws Exception {
Execution exec = run("""
{"StartAt":"Wait","States":{
"Wait":{"Type":"Wait","Seconds":0,"Assign":{"saved.$":"$.value"},"Next":"Use"},
"Use":{"Type":"Pass","Parameters":{"value.$":"$saved"},"End":true}}}
""", "{\"value\":42}");
assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause());
assertEquals(42, output(exec).path("value").asInt());
}
@Test
void failedStateDiscardsAssignmentsBeforeCatchReadsEntryVariables() throws Exception {
Execution exec = run("""
{"StartAt":"Set","States":{
"Set":{"Type":"Pass","Assign":{"x":1},"Next":"Work"},
"Work":{"Type":"Parallel","Branches":[{"StartAt":"Done","States":{
"Done":{"Type":"Pass","End":true}}}],"Assign":{"x":2},"ResultPath":"$.items[2]",
"Catch":[{"ErrorEquals":["States.ResultPathMatchFailure"],"Assign":{"caught.$":"$x"},
"ResultPath":null,"Next":"Use"}],"Next":"Use"},
"Use":{"Type":"Pass","Parameters":{"x.$":"$x","caught.$":"$caught"},"End":true}}}
""", "{\"items\":[]}");
assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause());
assertEquals(1, output(exec).path("x").asInt());
assertEquals(1, output(exec).path("caught").asInt());
}
@Test
@SuppressWarnings("unchecked")
void distributedMapSelectorReadsOuterVariables() throws Exception {
Instance<StepFunctionsService> service = mock(Instance.class);
when(service.get()).thenReturn(mock(StepFunctionsService.class));
executor = AslExecutorFixture.builder().objectMapper(mapper).sfnService(service).build();
Execution exec = run("""
{"StartAt":"Set","States":{
"Set":{"Type":"Pass","Assign":{"shared":"outer"},"Next":"Map"},
"Map":{"Type":"Map","ItemsPath":"$.items","ItemSelector":{"shared.$":"$shared"},
"ItemProcessor":{"ProcessorConfig":{"Mode":"DISTRIBUTED","ExecutionType":"STANDARD"},
"StartAt":"Use","States":{"Use":{"Type":"Pass","End":true}}},"End":true}}}
""", "{\"items\":[1,2]}");
assertEquals("SUCCEEDED", exec.getStatus(), exec.getCause());
assertEquals(2, output(exec).size());
assertEquals("outer", output(exec).get(0).path("shared").asText());
}
}