mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(stepfunctions): support JSONata workflow variables (Assign) (#1824)
* feat(stepfunctions): support JSONata workflow variables (Assign) Add support for execution-scoped workflow variables in JSONata state machines. States may declare an `Assign` field whose values are evaluated as JSONata and stored as variables that later states reference as top-level `$name` bindings. An execution-scoped `variables` object is threaded through every state executor and mutated in place, so assignments persist across states. Parallel branches and Map iterations each receive an isolated copy, so assignments inside them do not leak back to the parent scope, matching AWS. Within a state, `Assign` is evaluated before `Output`, so a state's own `Output` (and all later states) observe the newly assigned variables, matching AWS evaluation order. Assign is currently supported for JSONata states only; JSONPath-mode Assign is left as a follow-up. Closes #1507 Co-authored-by: Juri Duval <27741935+Mulgish@users.noreply.github.com> * fix(stepfunctions): resolve JSONata Assign against the state-entry scope Variable references in a state, including the state's own Output, must resolve against the values the variables held on state entry. Assign and Output are now both evaluated against the pre-assignment scope, and the new values are committed afterwards, so they first become visible to the next state. Verified against a recorded AWS execution (localstack's AWS-validated BASE_EVALUATION_ORDER_PASS_STATE snapshot): a state that assigns answer="<omitted>" while reading $answer in its own output still emits the state-entry value 42. Workflow variables are also bound alongside $states rather than inside it, since AWS reserves $states for input/result/errorOutput/context. Tests: - assignedVariablesAreNotVisibleUntilTheNextState replaces assignedVariableVisibleToSameStateOutput, which asserted the inverse. It follows the evaluation-order example from the AWS docs: from $x=3, $a=6, the block {"x": "{% $a %}", "nextX": "{% $x %}"} ends with $x=6 and $nextX=3 while the assigning state's Output still emits 3. - variablesAssignedInsideMapDoNotLeakToParentScope now uses a distinct inner variable name, mirroring AWS's own BASE_SCOPE_MAP fixture; AWS rejects an inner scope reusing an outer-scope variable name. * feat(stepfunctions): apply JSONata Assign in Choice rules, Wait states and Catch blocks Assign was only committed via applyJsonataOutput, which Choice and Wait never call, so an Assign on either state was silently dropped and Catch blocks could not assign at all. AWS supports Assign on Pass, Task, Map, Parallel, Choice and Wait, plus inside Choice rules and Catch fields. - Choice: a matched rule applies its own Assign and Output; the state-level ones apply only on the Default path. - Wait: applies Assign and Output. - Catch: applies Assign and Output with $states.errorOutput bound, into the scope the catching state lives in. - Bind $states after the workflow variables so a variable named "states" cannot clobber the reserved binding. Assign, Choice-rule and Catch blocks all keep the AWS evaluation rule already in place for states: every expression is evaluated against the values held on state entry, and the new values are committed only afterwards. --------- Co-authored-by: Juri Duval <27741935+Mulgish@users.noreply.github.com>
This commit is contained in:
1 parent
f93e0290b7
commit
3ec4dc65f2
3 files changed
+467
-54
No files matched your search
@@ -225,6 +225,9 @@ public class AslExecutor {
|
||||
String topLevelQueryLanguage = definition.path("QueryLanguage").asText("JSONPath");
|
||||
JsonNode currentInput = parseInput(exec.getInput());
|
||||
JsonNode execContext = buildContext(exec, sm);
|
||||
// Execution-scoped JSONata variables (the Assign field). Mutated in place as states
|
||||
// assign, so later states observe earlier assignments.
|
||||
ObjectNode variables = objectMapper.createObjectNode();
|
||||
|
||||
String currentStateName = startAt;
|
||||
while (currentStateName != null) {
|
||||
@@ -240,10 +243,10 @@ public class AslExecutor {
|
||||
// Update per-state context fields
|
||||
updateStateContext(execContext, currentStateName);
|
||||
|
||||
boolean jsonata = isJsonata(stateDef, topLevelQueryLanguage);
|
||||
try {
|
||||
boolean jsonata = isJsonata(stateDef, topLevelQueryLanguage);
|
||||
StateResult stateResult = executeState(currentStateName, type, stateDef, currentInput,
|
||||
history, eventId, sm, jsonata, topLevelQueryLanguage, execContext);
|
||||
history, eventId, sm, jsonata, topLevelQueryLanguage, execContext, variables);
|
||||
addEvent(history, eventId, stateExitedEventType(type), eventId.get() - 1,
|
||||
Map.of("name", currentStateName, "output", stateResult.output().toString()));
|
||||
|
||||
@@ -254,7 +257,7 @@ public class AslExecutor {
|
||||
currentStateName = null;
|
||||
}
|
||||
} catch (FailStateException e) {
|
||||
StateResult caught = handleCatch(stateDef, currentInput, e);
|
||||
StateResult caught = handleCatch(stateDef, currentInput, e, jsonata, execContext, variables);
|
||||
if (caught != null) {
|
||||
addEvent(history, eventId, stateExitedEventType(type), eventId.get() - 1,
|
||||
Map.of("name", currentStateName, "output", caught.output().toString()));
|
||||
@@ -296,24 +299,26 @@ public class AslExecutor {
|
||||
|
||||
private StateResult executeState(String name, String type, JsonNode stateDef, JsonNode input,
|
||||
List<HistoryEvent> history, AtomicLong eventId, StateMachine sm,
|
||||
boolean jsonata, String topLevelQueryLanguage, JsonNode context) throws Exception {
|
||||
boolean jsonata, String topLevelQueryLanguage, JsonNode context,
|
||||
ObjectNode variables) throws Exception {
|
||||
return switch (type) {
|
||||
case "Pass" -> executePassState(stateDef, input, jsonata, context);
|
||||
case "Task" -> executeTaskState(name, stateDef, input, history, eventId, sm, jsonata, context);
|
||||
case "Choice" -> executeChoiceState(stateDef, input, jsonata, context);
|
||||
case "Wait" -> executeWaitState(stateDef, input, jsonata, context);
|
||||
case "Succeed" -> executeSucceedState(stateDef, input, jsonata, context);
|
||||
case "Fail" -> executeFail(stateDef, input, jsonata, context);
|
||||
case "Parallel" -> executeParallelState(name, stateDef, input, sm, jsonata, topLevelQueryLanguage, context);
|
||||
case "Map" -> executeMapState(name, stateDef, input, sm, jsonata, topLevelQueryLanguage, context);
|
||||
case "Pass" -> executePassState(stateDef, input, jsonata, context, variables);
|
||||
case "Task" -> executeTaskState(name, stateDef, input, history, eventId, sm, jsonata, context, variables);
|
||||
case "Choice" -> executeChoiceState(stateDef, input, jsonata, context, variables);
|
||||
case "Wait" -> executeWaitState(stateDef, input, jsonata, context, variables);
|
||||
case "Succeed" -> executeSucceedState(stateDef, input, jsonata, context, variables);
|
||||
case "Fail" -> executeFail(stateDef, input, jsonata, context, variables);
|
||||
case "Parallel" -> executeParallelState(name, stateDef, input, sm, jsonata, topLevelQueryLanguage, context, variables);
|
||||
case "Map" -> executeMapState(name, stateDef, input, sm, jsonata, topLevelQueryLanguage, context, variables);
|
||||
default -> new StateResult(input, stateDef.path("Next").asText(null));
|
||||
};
|
||||
}
|
||||
|
||||
private StateResult executePassState(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context) throws Exception {
|
||||
private StateResult executePassState(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context,
|
||||
ObjectNode variables) throws Exception {
|
||||
if (jsonata) {
|
||||
JsonNode result = stateDef.has("Result") ? stateDef.get("Result") : input;
|
||||
JsonNode output = applyJsonataOutput(stateDef, input, result, context);
|
||||
JsonNode output = applyJsonataOutput(stateDef, input, result, context, variables);
|
||||
return new StateResult(output, stateDef.path("Next").asText(null));
|
||||
}
|
||||
|
||||
@@ -336,7 +341,7 @@ public class AslExecutor {
|
||||
|
||||
private StateResult executeTaskState(String stateName, JsonNode stateDef, JsonNode input,
|
||||
List<HistoryEvent> history, AtomicLong eventId, StateMachine sm,
|
||||
boolean jsonata, JsonNode context) throws Exception {
|
||||
boolean jsonata, JsonNode context, ObjectNode variables) throws Exception {
|
||||
String resource = stateDef.path("Resource").asText();
|
||||
boolean isWaitForToken = resource.endsWith(".waitForTaskToken");
|
||||
String effectiveResource = isWaitForToken
|
||||
@@ -358,7 +363,7 @@ public class AslExecutor {
|
||||
JsonNode effectiveInput = input;
|
||||
if (stateDef.has("Arguments")) {
|
||||
JsonNode statesVar = buildStatesVar(input, null, context);
|
||||
effectiveInput = jsonataEvaluator.resolveTemplate(stateDef.get("Arguments"), statesVar);
|
||||
effectiveInput = jsonataEvaluator.resolveTemplate(stateDef.get("Arguments"), statesVar, variables);
|
||||
}
|
||||
taskResult = invokeResource(effectiveResource, effectiveInput, sm, taskToken);
|
||||
} else {
|
||||
@@ -374,7 +379,7 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
if (jsonata) {
|
||||
JsonNode output = applyJsonataOutput(stateDef, input, taskResult, context);
|
||||
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.
|
||||
@@ -1149,22 +1154,28 @@ public class AslExecutor {
|
||||
};
|
||||
}
|
||||
|
||||
private StateResult executeChoiceState(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context) throws Exception {
|
||||
private StateResult executeChoiceState(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context,
|
||||
ObjectNode variables) throws Exception {
|
||||
if (jsonata) {
|
||||
JsonNode statesVar = buildStatesVar(input, null, context);
|
||||
JsonNode choices = stateDef.path("Choices");
|
||||
for (JsonNode choice : choices) {
|
||||
String condition = choice.path("Condition").asText(null);
|
||||
if (condition != null) {
|
||||
JsonNode result = jsonataEvaluator.evaluate(condition, statesVar);
|
||||
JsonNode result = jsonataEvaluator.evaluate(condition, statesVar, variables);
|
||||
if (result.isBoolean() && result.asBoolean()) {
|
||||
return new StateResult(input, choice.path("Next").asText());
|
||||
// A matched rule carries its own Assign and Output; the state-level ones
|
||||
// belong to the Default path and do not run here.
|
||||
JsonNode output = applyJsonataAssignAndOutput(choice, statesVar, input, variables);
|
||||
return new StateResult(output, choice.path("Next").asText());
|
||||
}
|
||||
}
|
||||
}
|
||||
String defaultState = stateDef.path("Default").asText(null);
|
||||
if (defaultState != null) {
|
||||
return new StateResult(input, defaultState);
|
||||
// No rule matched: the state-level Assign and Output apply on the Default path.
|
||||
JsonNode output = applyJsonataAssignAndOutput(stateDef, statesVar, input, variables);
|
||||
return new StateResult(output, defaultState);
|
||||
}
|
||||
throw new FailStateException("States.NoChoiceMatched", "No choice rule matched and no default state");
|
||||
}
|
||||
@@ -1267,14 +1278,15 @@ public class AslExecutor {
|
||||
return false;
|
||||
}
|
||||
|
||||
private StateResult executeWaitState(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context) throws InterruptedException {
|
||||
private StateResult executeWaitState(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context,
|
||||
ObjectNode variables) throws InterruptedException {
|
||||
int seconds = 0;
|
||||
if (jsonata) {
|
||||
if (stateDef.has("Seconds")) {
|
||||
JsonNode secondsNode = stateDef.get("Seconds");
|
||||
if (secondsNode.isTextual() && JsonataEvaluator.isExpression(secondsNode.asText())) {
|
||||
JsonNode statesVar = buildStatesVar(input, null, context);
|
||||
JsonNode result = jsonataEvaluator.evaluate(secondsNode.asText(), statesVar);
|
||||
JsonNode result = jsonataEvaluator.evaluate(secondsNode.asText(), statesVar, variables);
|
||||
seconds = Math.min(result.asInt(), MAX_WAIT_SECONDS);
|
||||
} else {
|
||||
seconds = Math.min(secondsNode.asInt(), MAX_WAIT_SECONDS);
|
||||
@@ -1292,34 +1304,41 @@ public class AslExecutor {
|
||||
if (seconds > 0) {
|
||||
TimeUnit.SECONDS.sleep(seconds);
|
||||
}
|
||||
if (jsonata) {
|
||||
JsonNode output = applyJsonataOutput(stateDef, input, null, context, variables);
|
||||
return new StateResult(output, stateDef.path("Next").asText(null));
|
||||
}
|
||||
return new StateResult(input, stateDef.path("Next").asText(null));
|
||||
}
|
||||
|
||||
private StateResult executeSucceedState(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context) {
|
||||
private StateResult executeSucceedState(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context,
|
||||
ObjectNode variables) {
|
||||
if (jsonata) {
|
||||
JsonNode output = applyJsonataOutput(stateDef, input, input, context);
|
||||
JsonNode output = applyJsonataOutput(stateDef, input, input, context, variables);
|
||||
return new StateResult(output, null);
|
||||
}
|
||||
return new StateResult(applyOutputPath(stateDef, input, input), null);
|
||||
}
|
||||
|
||||
private StateResult executeFail(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context) {
|
||||
private StateResult executeFail(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context,
|
||||
ObjectNode variables) {
|
||||
String error = stateDef.path("Error").asText(null);
|
||||
String cause = stateDef.path("Cause").asText(null);
|
||||
if (jsonata) {
|
||||
JsonNode statesVar = buildStatesVar(input, null, context);
|
||||
if (error != null && JsonataEvaluator.isExpression(error)) {
|
||||
error = jsonataEvaluator.evaluate(error, statesVar).asText();
|
||||
error = jsonataEvaluator.evaluate(error, statesVar, variables).asText();
|
||||
}
|
||||
if (cause != null && JsonataEvaluator.isExpression(cause)) {
|
||||
cause = jsonataEvaluator.evaluate(cause, statesVar).asText();
|
||||
cause = jsonataEvaluator.evaluate(cause, statesVar, variables).asText();
|
||||
}
|
||||
}
|
||||
throw new FailStateException(error, cause);
|
||||
}
|
||||
|
||||
private StateResult executeParallelState(String name, JsonNode stateDef, JsonNode input, StateMachine sm,
|
||||
boolean jsonata, String topLevelQueryLanguage, JsonNode context) throws Exception {
|
||||
boolean jsonata, String topLevelQueryLanguage, JsonNode context,
|
||||
ObjectNode variables) throws Exception {
|
||||
JsonNode branches = stateDef.path("Branches");
|
||||
List<Future<JsonNode>> futures = new ArrayList<>();
|
||||
|
||||
@@ -1327,12 +1346,16 @@ public class AslExecutor {
|
||||
String startAt = branch.path("StartAt").asText();
|
||||
JsonNode branchStates = branch.path("States");
|
||||
JsonNode capturedInput = input;
|
||||
// Each branch gets an isolated copy of the current variables: assignments inside a
|
||||
// branch are scoped to that branch and do not leak back to the parent after the state.
|
||||
ObjectNode branchVariables = variables.deepCopy();
|
||||
|
||||
// Run each branch on its own worker thread under the execution's account: the request
|
||||
// scope is thread-bound, so without this a branch's Task integrations would resolve to
|
||||
// the default account rather than the execution's.
|
||||
futures.add(executor.submit(() -> callUnderExecutionAccount(sm,
|
||||
() -> executeBranch(startAt, branchStates, capturedInput, sm, topLevelQueryLanguage, context))));
|
||||
() -> executeBranch(startAt, branchStates, capturedInput, sm, topLevelQueryLanguage, context,
|
||||
branchVariables))));
|
||||
}
|
||||
|
||||
int timeoutSeconds = stateDef.path("TimeoutSeconds").asInt(0);
|
||||
@@ -1358,7 +1381,7 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
if (jsonata) {
|
||||
JsonNode output = applyJsonataOutput(stateDef, input, results, context);
|
||||
JsonNode output = applyJsonataOutput(stateDef, input, results, context, variables);
|
||||
return new StateResult(output, stateDef.path("Next").asText(null));
|
||||
}
|
||||
|
||||
@@ -1372,7 +1395,8 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
private StateResult executeMapState(String name, JsonNode stateDef, JsonNode input, StateMachine sm,
|
||||
boolean jsonata, String topLevelQueryLanguage, JsonNode context) throws Exception {
|
||||
boolean jsonata, String topLevelQueryLanguage, JsonNode context,
|
||||
ObjectNode variables) throws Exception {
|
||||
if (stateDef.has("ItemReader")) {
|
||||
String mode = stateDef.path("ItemProcessor").path("ProcessorConfig").path("Mode").asText("INLINE");
|
||||
if (!"DISTRIBUTED".equals(mode)) {
|
||||
@@ -1380,7 +1404,7 @@ public class AslExecutor {
|
||||
"The ItemReader, ItemBatcher and ResultWriter fields are not supported for INLINE maps");
|
||||
}
|
||||
}
|
||||
ResolvedMapItems resolvedItems = resolveMapItems(stateDef, input, jsonata, context);
|
||||
ResolvedMapItems resolvedItems = resolveMapItems(stateDef, input, jsonata, context, variables);
|
||||
JsonNode items = resolvedItems.items();
|
||||
|
||||
if (!items.isArray()) {
|
||||
@@ -1420,12 +1444,15 @@ public class AslExecutor {
|
||||
// $ in ItemSelector resolves against the Map state's effective input, not the item.
|
||||
iterInput = resolveParameters(itemTransform, mapInput, iterContext);
|
||||
}
|
||||
results.add(executeBranch(startAt, iteratorStates, iterInput, sm, topLevelQueryLanguage, iterContext));
|
||||
// Each iteration gets an isolated copy of the current variables; assignments inside an
|
||||
// iteration are scoped to that iteration and do not leak back to the parent scope.
|
||||
results.add(executeBranch(startAt, iteratorStates, iterInput, sm, topLevelQueryLanguage, iterContext,
|
||||
variables.deepCopy()));
|
||||
index++;
|
||||
}
|
||||
|
||||
if (jsonata) {
|
||||
JsonNode output = applyJsonataOutput(stateDef, input, results, context);
|
||||
JsonNode output = applyJsonataOutput(stateDef, input, results, context, variables);
|
||||
return new StateResult(output, stateDef.path("Next").asText(null));
|
||||
}
|
||||
|
||||
@@ -1439,19 +1466,19 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
private ResolvedMapItems resolveMapItems(JsonNode stateDef, JsonNode input,
|
||||
boolean jsonata, JsonNode context) throws Exception {
|
||||
boolean jsonata, JsonNode context, ObjectNode variables) throws Exception {
|
||||
if (jsonata && stateDef.has("Items")) {
|
||||
JsonNode itemsNode = stateDef.get("Items");
|
||||
if (itemsNode.isTextual() && JsonataEvaluator.isExpression(itemsNode.asText())) {
|
||||
JsonNode statesVar = buildStatesVar(input, null, context);
|
||||
return new ResolvedMapItems(jsonataEvaluator.evaluate(itemsNode.asText(), statesVar),
|
||||
return new ResolvedMapItems(jsonataEvaluator.evaluate(itemsNode.asText(), statesVar, variables),
|
||||
MapItemsSource.DEFAULT);
|
||||
}
|
||||
return new ResolvedMapItems(itemsNode, MapItemsSource.DEFAULT);
|
||||
}
|
||||
|
||||
if (stateDef.has("ItemReader")) {
|
||||
return resolveItemReaderItems(stateDef.get("ItemReader"), input, context, jsonata);
|
||||
return resolveItemReaderItems(stateDef.get("ItemReader"), input, context, jsonata, variables);
|
||||
}
|
||||
|
||||
JsonNode itemsPath = stateDef.path("ItemsPath");
|
||||
@@ -1460,7 +1487,8 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
private ResolvedMapItems resolveItemReaderItems(JsonNode itemReader, JsonNode input,
|
||||
JsonNode context, boolean jsonata) throws Exception {
|
||||
JsonNode context, boolean jsonata,
|
||||
ObjectNode variables) throws Exception {
|
||||
String resource = itemReader.path("Resource").asText(null);
|
||||
if ("arn:aws:states:::s3:listObjectsV2".equals(resource)) {
|
||||
throw new FailStateException("States.ItemReaderFailed",
|
||||
@@ -1479,7 +1507,7 @@ public class AslExecutor {
|
||||
JsonNode resolvedParameters;
|
||||
if (jsonata && itemReader.has("Arguments")) {
|
||||
JsonNode statesVar = buildStatesVar(input, null, context);
|
||||
resolvedParameters = jsonataEvaluator.resolveTemplate(itemReader.get("Arguments"), statesVar);
|
||||
resolvedParameters = jsonataEvaluator.resolveTemplate(itemReader.get("Arguments"), statesVar, variables);
|
||||
} else {
|
||||
JsonNode parameters = itemReader.path("Parameters");
|
||||
resolvedParameters = resolveParameters(parameters, input, context);
|
||||
@@ -1552,7 +1580,7 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
private JsonNode executeBranch(String startAt, JsonNode states, JsonNode input, StateMachine sm,
|
||||
String topLevelQueryLanguage, JsonNode context) throws Exception {
|
||||
String topLevelQueryLanguage, JsonNode context, ObjectNode variables) throws Exception {
|
||||
List<HistoryEvent> ignored = new ArrayList<>();
|
||||
AtomicLong eventId = new AtomicLong(0);
|
||||
JsonNode currentInput = input;
|
||||
@@ -1568,9 +1596,9 @@ public class AslExecutor {
|
||||
StateResult result;
|
||||
try {
|
||||
result = executeState(currentState, type, stateDef, currentInput, ignored, eventId, sm,
|
||||
stateJsonata, topLevelQueryLanguage, context);
|
||||
stateJsonata, topLevelQueryLanguage, context, variables);
|
||||
} catch (FailStateException e) {
|
||||
StateResult caught = handleCatch(stateDef, currentInput, e);
|
||||
StateResult caught = handleCatch(stateDef, currentInput, e, stateJsonata, context, variables);
|
||||
if (caught == null) {
|
||||
throw e;
|
||||
}
|
||||
@@ -1608,6 +1636,16 @@ public class AslExecutor {
|
||||
return states;
|
||||
}
|
||||
|
||||
/**
|
||||
* $states inside a Catch block: errorOutput is bound in addition to input and context, and is the
|
||||
* only place AWS makes it available.
|
||||
*/
|
||||
private JsonNode buildCatchStatesVar(JsonNode input, JsonNode errorOutput, JsonNode context) {
|
||||
ObjectNode states = (ObjectNode) buildStatesVar(input, null, context);
|
||||
states.set("errorOutput", errorOutput);
|
||||
return states;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the $states.context object for an execution.
|
||||
* Contains Execution metadata (Id, Input, Name, RoleArn, StartTime).
|
||||
@@ -1644,15 +1682,60 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply JSONata Output field. If Output is present, resolve it as a template with $states bound.
|
||||
* If absent, use the result directly (or input if result is null).
|
||||
* Apply the JSONata Assign and Output fields of a state.
|
||||
*
|
||||
* <p>Every variable reference in a state — including the state's own Output — resolves against
|
||||
* the values the variables held on state entry. Assign and Output are therefore both evaluated
|
||||
* against the pre-assignment scope, and the new values are committed only afterwards, becoming
|
||||
* visible to the <em>next</em> state. A state's Output never observes that same state's Assign.
|
||||
*
|
||||
* <p>This also makes assignments within one Assign block independent of each other: given
|
||||
* {@code $x=3, $a=6} and {@code {"x": "{% $a %}", "nextX": "{% $x %}"}}, AWS ends with
|
||||
* {@code $x=6, $nextX=3}.
|
||||
*
|
||||
* <p>Output, when present, is resolved as a template with $states bound; when absent, the result
|
||||
* is passed through directly (or input if result is null).
|
||||
*/
|
||||
private JsonNode applyJsonataOutput(JsonNode stateDef, JsonNode input, JsonNode result, JsonNode context) {
|
||||
if (!stateDef.has("Output")) {
|
||||
return result != null ? result : input;
|
||||
}
|
||||
private JsonNode applyJsonataOutput(JsonNode holder, JsonNode input, JsonNode result, JsonNode context,
|
||||
ObjectNode variables) {
|
||||
JsonNode statesVar = buildStatesVar(input, result, context);
|
||||
return jsonataEvaluator.resolveTemplate(stateDef.get("Output"), statesVar);
|
||||
return applyJsonataAssignAndOutput(holder, statesVar, result != null ? result : input, variables);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply the Assign and Output fields of anything that can carry them: a state, a Choice rule, or
|
||||
* a Catch block. {@code fallbackOutput} is the value that becomes the output when Output is absent.
|
||||
*/
|
||||
private JsonNode applyJsonataAssignAndOutput(JsonNode holder, JsonNode statesVar, JsonNode fallbackOutput,
|
||||
ObjectNode variables) {
|
||||
JsonNode assigned = evaluateJsonataAssign(holder, statesVar, variables);
|
||||
JsonNode output = holder.has("Output")
|
||||
? jsonataEvaluator.resolveTemplate(holder.get("Output"), statesVar, variables)
|
||||
: fallbackOutput;
|
||||
commitJsonataAssign(assigned, variables);
|
||||
return output;
|
||||
}
|
||||
|
||||
private JsonNode evaluateJsonataAssign(JsonNode holder, JsonNode statesVar, ObjectNode variables) {
|
||||
if (!holder.has("Assign")) {
|
||||
return null;
|
||||
}
|
||||
JsonNode assigned = jsonataEvaluator.resolveTemplate(holder.get("Assign"), statesVar, variables);
|
||||
if (assigned == null || !assigned.isObject()) {
|
||||
throw new FailStateException("States.Runtime", "Assign must evaluate to an object");
|
||||
}
|
||||
return assigned;
|
||||
}
|
||||
|
||||
private void commitJsonataAssign(JsonNode assigned, ObjectNode variables) {
|
||||
if (assigned == null) {
|
||||
return;
|
||||
}
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = assigned.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
variables.set(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Path resolution ────────────────────────────
|
||||
@@ -2099,7 +2182,8 @@ public class AslExecutor {
|
||||
Map.of("error", failError, "cause", failCause));
|
||||
}
|
||||
|
||||
private StateResult handleCatch(JsonNode stateDef, JsonNode input, FailStateException failure) throws Exception {
|
||||
private StateResult handleCatch(JsonNode stateDef, JsonNode input, FailStateException failure,
|
||||
boolean jsonata, JsonNode context, ObjectNode variables) throws Exception {
|
||||
JsonNode catchers = stateDef.path("Catch");
|
||||
if (!catchers.isArray()) {
|
||||
return null;
|
||||
@@ -2117,6 +2201,14 @@ public class AslExecutor {
|
||||
ObjectNode errorOutput = objectMapper.createObjectNode();
|
||||
errorOutput.put("Error", error);
|
||||
errorOutput.put("Cause", cause);
|
||||
if (jsonata) {
|
||||
// The catch block's input is the error output, and a Catch's Assign writes into the
|
||||
// scope the catching state lives in — so for a Parallel or Map it lands in the outer
|
||||
// scope, not the branch scope that failed.
|
||||
JsonNode statesVar = buildCatchStatesVar(input, errorOutput, context);
|
||||
JsonNode output = applyJsonataAssignAndOutput(catcher, statesVar, errorOutput, variables);
|
||||
return new StateResult(output, next);
|
||||
}
|
||||
return new StateResult(mergeResult(catcher, input, errorOutput), next);
|
||||
}
|
||||
return null;
|
||||
|
||||
+23
-3
@@ -63,10 +63,26 @@ public class JsonataEvaluator {
|
||||
* {@code [$states.result.Items.{"id": id}]}.
|
||||
*/
|
||||
JsonNode evaluate(String expression, JsonNode statesVar) {
|
||||
return evaluate(expression, statesVar, null);
|
||||
}
|
||||
|
||||
JsonNode evaluate(String expression, JsonNode statesVar, JsonNode variables) {
|
||||
String expr = isExpression(expression) ? unwrap(expression) : expression;
|
||||
try {
|
||||
Jsonata jsonataExpr = jsonata(expr);
|
||||
Jsonata.Frame frame = jsonataExpr.createFrame();
|
||||
// Workflow variables (the Assign field) are referenced as top-level $name in AWS's
|
||||
// JSONata dialect, e.g. $CheckpointCount. They are bound alongside $states, never
|
||||
// inside it: AWS reserves $states for input/result/errorOutput/context only. $states is
|
||||
// bound last so that reservation holds even if a definition assigns a variable named
|
||||
// "states", which AWS rejects but Floci does not yet validate.
|
||||
if (variables != null && variables.isObject()) {
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = variables.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
frame.bind(entry.getKey(), toObject(entry.getValue()));
|
||||
}
|
||||
}
|
||||
frame.bind("states", toObject(statesVar));
|
||||
Object result = jsonataExpr.evaluate(null, frame);
|
||||
return toJsonNode(result);
|
||||
@@ -83,13 +99,17 @@ public class JsonataEvaluator {
|
||||
* All other strings pass through unchanged.
|
||||
*/
|
||||
JsonNode resolveTemplate(JsonNode template, JsonNode statesVar) {
|
||||
return resolveTemplate(template, statesVar, null);
|
||||
}
|
||||
|
||||
JsonNode resolveTemplate(JsonNode template, JsonNode statesVar, JsonNode variables) {
|
||||
if (template == null || template.isNull() || template.isMissingNode()) {
|
||||
return template;
|
||||
}
|
||||
if (template.isTextual()) {
|
||||
String text = template.asText();
|
||||
if (isExpression(text)) {
|
||||
return evaluate(text, statesVar);
|
||||
return evaluate(text, statesVar, variables);
|
||||
}
|
||||
return template;
|
||||
}
|
||||
@@ -98,7 +118,7 @@ public class JsonataEvaluator {
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = template.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
JsonNode value = resolveTemplate(entry.getValue(), statesVar);
|
||||
JsonNode value = resolveTemplate(entry.getValue(), statesVar, variables);
|
||||
// Per JSONata spec: undefined (null) values are omitted from object output,
|
||||
// matching real AWS Step Functions behavior.
|
||||
if (value != null && !value.isNull() && !value.isMissingNode()) {
|
||||
@@ -111,7 +131,7 @@ public class JsonataEvaluator {
|
||||
ArrayNode resolved = objectMapper.createArrayNode();
|
||||
for (int i = 0; i < template.size(); i++) {
|
||||
JsonNode element = template.get(i);
|
||||
JsonNode value = resolveTemplate(element, statesVar);
|
||||
JsonNode value = resolveTemplate(element, statesVar, variables);
|
||||
// Per real AWS behavior: undefined array elements fail the execution.
|
||||
// Unlike object fields (which are omitted), undefined in an array is a runtime error.
|
||||
if (value == null || value.isNull() || value.isMissingNode()) {
|
||||
|
||||
Reference in new issue
Block a user