mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
fix(stepfunctions): fail the state when a JSONata expression returns nothing (#2689)
* fix(stepfunctions): fail the state when a JSONata expression returns nothing An expression that returned nothing lost its key and the execution carried on down the happy path. Real AWS fails the state with States.QueryEvaluationError, names the field the expression was written in and a Catch on that error fires. Three of the positions changed control flow rather than data: a Choice took Default, a Wait did not wait, and a Task sent its request with the argument omitted. evaluateField evaluates one expression and fails the state on a missing node. resolveTemplate calls it at every leaf, carrying the field it is inside and extending it with /key per object key and [i] per array index, so the cause names Output/a/b[0][1] the way AWS does. Choices[n]/Condition, Seconds, Error, Cause, MaxConcurrency and Items call it directly. Three pieces go with it, all of them things a missing node used to need. An undefined array element was a States.Runtime special case with its own wording; AWS answers States.QueryEvaluationError and Output/values[0], the same shape as every other position. resolveTemplateNode existed to let resolveTemplate turn a whole field that returned nothing into a null, so the output would still serialize; there is no output to serialize once the state fails. And the two ResultWriter guards fired only on a key resolveTemplate had dropped, which can no longer happen. An explicit JSON null is a value and still succeeds, everywhere. Closes #2665 * fix(stepfunctions): name a Choice rule's and a Catch clause's own fields under their index A matched Choices[i] rule and a matching Catch[i] clause carry their own Assign and Output, and applyJsonataAssignAndOutput named them 'Output' and 'Assign' as if they were the state's. AWS names them under the rule or the clause: Choices[1]/Output/v, Choices[0]/Assign/x and Catch[1]/Output/v, each measured on the account. The index is the position in Choices or Catch, not the position among the entries that matched. The Catch label was unobservable until now. doExecute calls handleCatch from inside its own catch (FailStateException), so an expression failure raised while resolving the clause's own Output escaped both that clause and its sibling catch (Exception), reaching the method-level handler that answers States.Runtime with the raw message. The execution now fails with the clause's own error, which is what AWS reports and what the clause was catching no longer is. * test(stepfunctions): follow the field path through the crashing evaluator stub * test(stepfunctions): put the Catch clause under test on a Task, as AWS requires aCatchClauseNamesItsOwnOutputUnderTheClauseIndex carried Catch on a Pass state, which AWS refuses: validate-state-machine-definition answers SCHEMA_VALIDATION_FAILED, "Field 'Catch' is not supported" at /States/Boom. The label the test pins is right, Catch[1]/Output/v, and the state now fails on its own Arguments the way the measured execution did, so the definition is one AWS accepts. * docs(stepfunctions): drop the deviation this change removes The key dropped by an expression that returned nothing is no longer Floci's own behaviour: the state fails, as the section below records. --------- Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
This commit is contained in:
1 parent
5534460492
commit
ea11e67719
8 files changed
+585
-131
No files matched your search
@@ -77,13 +77,34 @@ an array element:
|
||||
```
|
||||
|
||||
The same `null` is a value inside the expression too: `$exists()` on it is true and `$type()` on it
|
||||
is `"null"`. Only an expression that returns nothing loses its key, which is what
|
||||
`$states.input.absent` and the functions listed below that evaluate to undefined do.
|
||||
is `"null"`.
|
||||
|
||||
Two deviations. `$count()` on a JSON null answers `0`; AWS answers `1`. And dropping the key of an
|
||||
expression that returned nothing is Floci's own behaviour: AWS fails the state instead, with
|
||||
`States.QueryEvaluationError` and `The JSONata expression '$states.input.absent' specified for the
|
||||
field 'Output/v' returned nothing (undefined).`
|
||||
One deviation. `$count()` on a JSON null answers `0`; AWS answers `1`.
|
||||
|
||||
## An expression that returns nothing fails the state
|
||||
|
||||
An expression that returns nothing, which is what `$states.input.absent` and the functions listed
|
||||
below that evaluate to undefined do, is not a missing value the state carries on without. It fails
|
||||
the state with `States.QueryEvaluationError`, naming the field it was written in, and a `Catch` on
|
||||
that error fires:
|
||||
|
||||
```
|
||||
"Output": {"v": "{% $states.input.absent %}"}
|
||||
-> States.QueryEvaluationError
|
||||
The JSONata expression '$states.input.absent' specified for the field 'Output/v'
|
||||
returned nothing (undefined).
|
||||
```
|
||||
|
||||
The field is named relative to the state, with `/` before each object key and `[i]` for each array
|
||||
index: `Output`, `Output/a/b[0]`, `Assign/x`, `Arguments/MessageGroupId`, `Choices[1]/Condition`,
|
||||
`Seconds`, `Error`, `Cause`, `Items`, `MaxConcurrency`. A matched `Choice` rule and a matching
|
||||
`Catch` clause carry their own `Assign` and `Output`, which are named under the rule or clause:
|
||||
`Choices[1]/Output/v`, `Choices[0]/Assign/x`, `Catch[1]/Output/v`. A `Choice` stops at the first rule
|
||||
that matches, so an undefined condition in a later rule is never evaluated.
|
||||
|
||||
One deviation. AWS prefixes the cause of a real execution with
|
||||
`An error occurred while executing the state '<name>' (entered at the event id #<n>).`; Floci
|
||||
returns the cause without it, which is the form AWS's own `TestState` returns.
|
||||
|
||||
## JSONata functions
|
||||
|
||||
@@ -105,8 +126,8 @@ Three behaviours are worth knowing before reading an unexpected result, and all
|
||||
`$partition(items, 2.9)` chunks by 2.
|
||||
- Several arguments evaluate to undefined rather than failing: a chunk size of zero, an empty
|
||||
array, a `$range` with no `step` or with a step whose sign disagrees with the direction, and a
|
||||
`$hash` with no algorithm. An undefined value is then dropped from the surrounding `Output`
|
||||
object, so the field goes missing instead of the state failing.
|
||||
`$hash` with no algorithm. The argument itself does not fail; the field the expression was
|
||||
written in does, under `States.QueryEvaluationError`, as the section above records.
|
||||
- `$range` collapses a single-element range to the bare number, not a one-element array.
|
||||
|
||||
JSONata's own `$string` follows AWS's number notation: a whole number is written out in full below
|
||||
|
||||
@@ -391,7 +391,16 @@ public class AslExecutor {
|
||||
currentStateName = null;
|
||||
}
|
||||
} catch (FailStateException e) {
|
||||
StateResult caught = handleCatch(stateDef, currentInput, e, jsonata, execContext, variables);
|
||||
StateResult caught = null;
|
||||
FailStateException failure = e;
|
||||
try {
|
||||
caught = handleCatch(stateDef, currentInput, e, jsonata, execContext, variables);
|
||||
} catch (FailStateException catchClauseFailure) {
|
||||
// A matching Catch clause carries its own Assign and Output, and an
|
||||
// expression there can fail. AWS reports that failure, not the error the
|
||||
// clause was catching, and no later clause catches it.
|
||||
failure = catchClauseFailure;
|
||||
}
|
||||
if (caught != null) {
|
||||
addEvent(history, eventId, stateExitedEventType(type), eventId.get() - 1,
|
||||
Map.of("name", currentStateName, "output", caught.output().toString()));
|
||||
@@ -399,7 +408,7 @@ public class AslExecutor {
|
||||
currentStateName = caught.nextState();
|
||||
continue;
|
||||
}
|
||||
failExecution(exec, history, eventId, e);
|
||||
failExecution(exec, history, eventId, failure);
|
||||
onUpdate.accept(exec, history);
|
||||
return;
|
||||
}
|
||||
@@ -593,7 +602,8 @@ public class AslExecutor {
|
||||
var effectiveInput = input;
|
||||
if (stateDef.has("Arguments")) {
|
||||
var statesVar = buildStatesVar(input, null, context);
|
||||
effectiveInput = jsonataEvaluator.resolveTemplate(stateDef.get("Arguments"), statesVar, variables);
|
||||
effectiveInput = jsonataEvaluator.resolveTemplate(
|
||||
stateDef.get("Arguments"), "Arguments", statesVar, variables);
|
||||
}
|
||||
taskResult = mockedSteps != null
|
||||
? mockedTaskResult(mockedSteps, stateName, attempt)
|
||||
@@ -1650,14 +1660,17 @@ public class AslExecutor {
|
||||
if (jsonata) {
|
||||
JsonNode statesVar = buildStatesVar(input, null, context);
|
||||
JsonNode choices = stateDef.path("Choices");
|
||||
for (JsonNode choice : choices) {
|
||||
for (int i = 0; i < choices.size(); i++) {
|
||||
JsonNode choice = choices.get(i);
|
||||
String condition = choice.path("Condition").asText(null);
|
||||
if (condition != null) {
|
||||
JsonNode result = jsonataEvaluator.evaluate(condition, statesVar, variables);
|
||||
JsonNode result = jsonataEvaluator.evaluateField(
|
||||
condition, "Choices[" + i + "]/Condition", statesVar, variables);
|
||||
if (result.isBoolean() && result.asBoolean()) {
|
||||
// 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);
|
||||
JsonNode output = applyJsonataAssignAndOutput(
|
||||
choice, "Choices[" + i + "]/", statesVar, input, variables);
|
||||
return new StateResult(output, choice.path("Next").asText());
|
||||
}
|
||||
}
|
||||
@@ -1665,7 +1678,7 @@ public class AslExecutor {
|
||||
String defaultState = stateDef.path("Default").asText(null);
|
||||
if (defaultState != null) {
|
||||
// No rule matched: the state-level Assign and Output apply on the Default path.
|
||||
JsonNode output = applyJsonataAssignAndOutput(stateDef, statesVar, input, variables);
|
||||
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");
|
||||
@@ -1777,7 +1790,8 @@ public class AslExecutor {
|
||||
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, variables);
|
||||
JsonNode result = jsonataEvaluator.evaluateField(
|
||||
secondsNode.asText(), "Seconds", statesVar, variables);
|
||||
seconds = Math.min(result.asInt(), MAX_WAIT_SECONDS);
|
||||
} else {
|
||||
seconds = Math.min(secondsNode.asInt(), MAX_WAIT_SECONDS);
|
||||
@@ -1818,10 +1832,10 @@ public class AslExecutor {
|
||||
if (jsonata) {
|
||||
JsonNode statesVar = buildStatesVar(input, null, context);
|
||||
if (error != null && JsonataEvaluator.isExpression(error)) {
|
||||
error = jsonataEvaluator.evaluate(error, statesVar, variables).asText();
|
||||
error = jsonataEvaluator.evaluateField(error, "Error", statesVar, variables).asText();
|
||||
}
|
||||
if (cause != null && JsonataEvaluator.isExpression(cause)) {
|
||||
cause = jsonataEvaluator.evaluate(cause, statesVar, variables).asText();
|
||||
cause = jsonataEvaluator.evaluateField(cause, "Cause", statesVar, variables).asText();
|
||||
}
|
||||
}
|
||||
throw new FailStateException(error, cause);
|
||||
@@ -2031,7 +2045,7 @@ public class AslExecutor {
|
||||
if (jsonata && value.isTextual() && JsonataEvaluator.isExpression(value.asText())) {
|
||||
jsonataExpression = true;
|
||||
JsonNode statesVar = buildStatesVar(mapInput, null, context);
|
||||
value = jsonataEvaluator.evaluate(value.asText(), statesVar, variables);
|
||||
value = jsonataEvaluator.evaluateField(value.asText(), "MaxConcurrency", statesVar, variables);
|
||||
}
|
||||
} else {
|
||||
return 0;
|
||||
@@ -2118,19 +2132,8 @@ public class AslExecutor {
|
||||
// InputPath, which is supplied by executeMapState.
|
||||
JsonNode loc;
|
||||
if (jsonata && writer.has("Arguments")) {
|
||||
JsonNode arguments = writer.get("Arguments");
|
||||
loc = jsonataEvaluator.resolveTemplate(
|
||||
arguments, buildStatesVar(input, null, context), variables);
|
||||
if (arguments.isObject()) {
|
||||
if (arguments.has("Bucket") && !loc.has("Bucket")) {
|
||||
throw new FailStateException("States.QueryEvaluationError",
|
||||
"ResultWriter Bucket must resolve to a string");
|
||||
}
|
||||
if (arguments.has("Prefix") && !loc.has("Prefix")) {
|
||||
throw new FailStateException("States.QueryEvaluationError",
|
||||
"ResultWriter Prefix must resolve to a string");
|
||||
}
|
||||
}
|
||||
loc = jsonataEvaluator.resolveTemplate(writer.get("Arguments"), "ResultWriter/Arguments",
|
||||
buildStatesVar(input, null, context), variables);
|
||||
} else if (writer.has("Parameters")) {
|
||||
loc = resolveParameters(writer.get("Parameters"), input, context);
|
||||
} else {
|
||||
@@ -2287,7 +2290,8 @@ public class AslExecutor {
|
||||
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, variables),
|
||||
return new ResolvedMapItems(
|
||||
jsonataEvaluator.evaluateField(itemsNode.asText(), "Items", statesVar, variables),
|
||||
MapItemsSource.DEFAULT);
|
||||
}
|
||||
return new ResolvedMapItems(itemsNode, MapItemsSource.DEFAULT);
|
||||
@@ -2323,7 +2327,8 @@ public class AslExecutor {
|
||||
JsonNode resolvedParameters;
|
||||
if (jsonata && itemReader.has("Arguments")) {
|
||||
JsonNode statesVar = buildStatesVar(input, null, context);
|
||||
resolvedParameters = jsonataEvaluator.resolveTemplate(itemReader.get("Arguments"), statesVar, variables);
|
||||
resolvedParameters = jsonataEvaluator.resolveTemplate(
|
||||
itemReader.get("Arguments"), "ItemReader/Arguments", statesVar, variables);
|
||||
} else {
|
||||
JsonNode parameters = itemReader.path("Parameters");
|
||||
resolvedParameters = resolveParameters(parameters, input, context);
|
||||
@@ -2519,28 +2524,35 @@ public class AslExecutor {
|
||||
private JsonNode applyJsonataOutput(JsonNode holder, JsonNode input, JsonNode result, JsonNode context,
|
||||
ObjectNode variables) {
|
||||
JsonNode statesVar = buildStatesVar(input, result, context);
|
||||
return applyJsonataAssignAndOutput(holder, statesVar, result != null ? result : input, variables);
|
||||
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.
|
||||
* a Catch clause. {@code fallbackOutput} is the value that becomes the output when Output is absent.
|
||||
*
|
||||
* <p>{@code holderPrefix} is what AWS puts before the holder's own field names in the cause of a
|
||||
* States.QueryEvaluationError: empty for a state, {@code "Choices[1]/"} for the second Choice
|
||||
* rule, {@code "Catch[1]/"} for the second Catch clause. AWS names a rule's own Output
|
||||
* {@code Choices[1]/Output/v}, not {@code Output/v}.
|
||||
*/
|
||||
private JsonNode applyJsonataAssignAndOutput(JsonNode holder, JsonNode statesVar, JsonNode fallbackOutput,
|
||||
ObjectNode variables) {
|
||||
JsonNode assigned = evaluateJsonataAssign(holder, statesVar, variables);
|
||||
private JsonNode applyJsonataAssignAndOutput(JsonNode holder, String holderPrefix, JsonNode statesVar,
|
||||
JsonNode fallbackOutput, ObjectNode variables) {
|
||||
JsonNode assigned = evaluateJsonataAssign(holder, holderPrefix, statesVar, variables);
|
||||
JsonNode output = holder.has("Output")
|
||||
? jsonataEvaluator.resolveTemplate(holder.get("Output"), statesVar, variables)
|
||||
? jsonataEvaluator.resolveTemplate(holder.get("Output"), holderPrefix + "Output", statesVar, variables)
|
||||
: fallbackOutput;
|
||||
commitJsonataAssign(assigned, variables);
|
||||
return output;
|
||||
}
|
||||
|
||||
private JsonNode evaluateJsonataAssign(JsonNode holder, JsonNode statesVar, ObjectNode variables) {
|
||||
private JsonNode evaluateJsonataAssign(JsonNode holder, String holderPrefix, JsonNode statesVar,
|
||||
ObjectNode variables) {
|
||||
if (!holder.has("Assign")) {
|
||||
return null;
|
||||
}
|
||||
JsonNode assigned = jsonataEvaluator.resolveTemplate(holder.get("Assign"), statesVar, variables);
|
||||
JsonNode assigned = jsonataEvaluator.resolveTemplate(
|
||||
holder.get("Assign"), holderPrefix + "Assign", statesVar, variables);
|
||||
if (assigned == null || !assigned.isObject()) {
|
||||
throw new FailStateException("States.Runtime", "Assign must evaluate to an object");
|
||||
}
|
||||
@@ -3385,7 +3397,8 @@ public class AslExecutor {
|
||||
}
|
||||
String error = failure.error != null ? failure.error : "States.Runtime";
|
||||
String cause = failure.cause != null ? failure.cause : "";
|
||||
for (JsonNode catcher : catchers) {
|
||||
for (int i = 0; i < catchers.size(); i++) {
|
||||
JsonNode catcher = catchers.get(i);
|
||||
if (!catchMatches(catcher, error)) {
|
||||
continue;
|
||||
}
|
||||
@@ -3401,7 +3414,8 @@ public class AslExecutor {
|
||||
// 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);
|
||||
JsonNode output = applyJsonataAssignAndOutput(
|
||||
catcher, "Catch[" + i + "]/", statesVar, errorOutput, variables);
|
||||
return new StateResult(output, next);
|
||||
}
|
||||
return new StateResult(mergeResult(catcher, input, errorOutput), next);
|
||||
|
||||
+33
-35
@@ -256,33 +256,46 @@ public class JsonataEvaluator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk a JSON template (Arguments or Output), evaluating any {% %} strings found.
|
||||
* Evaluate the single expression an ASL field holds, failing the state when it returns nothing.
|
||||
* AWS names the field in the cause and a {@code Catch} on States.QueryEvaluationError fires:
|
||||
* a Wait whose Seconds returned nothing does not wait zero seconds, it fails.
|
||||
*
|
||||
* <p>{@code field} is the field's path relative to the state, as AWS writes it: {@code Seconds},
|
||||
* {@code Choices[1]/Condition}, {@code Output/a/b}.
|
||||
*/
|
||||
JsonNode evaluateField(String expression, String field, JsonNode statesVar, JsonNode variables) {
|
||||
JsonNode value = evaluate(expression, statesVar, variables);
|
||||
if (value.isMissingNode()) {
|
||||
throw new FailStateException("States.QueryEvaluationError",
|
||||
"The JSONata expression '" + (isExpression(expression) ? unwrap(expression) : expression)
|
||||
+ "' specified for the field '" + field + "' returned nothing (undefined).");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk a JSON template (Arguments, Output or Assign), evaluating any {% %} strings found.
|
||||
* Non-expression values pass through unchanged.
|
||||
*
|
||||
* Only pure {% expression %} strings are evaluated (can return any JSON type).
|
||||
* All other strings pass through unchanged.
|
||||
*
|
||||
* <p>{@code field} is the template's own field name, which the walk extends with {@code /key}
|
||||
* per object key and {@code [i]} per array index so a failing expression is named the way AWS
|
||||
* names it: {@code Output/a/b[0][1]}.
|
||||
*/
|
||||
JsonNode resolveTemplate(JsonNode template, JsonNode statesVar) {
|
||||
return resolveTemplate(template, statesVar, null);
|
||||
JsonNode resolveTemplate(JsonNode template, String field, JsonNode statesVar) {
|
||||
return resolveTemplate(template, field, statesVar, null);
|
||||
}
|
||||
|
||||
JsonNode resolveTemplate(JsonNode template, JsonNode statesVar, JsonNode variables) {
|
||||
JsonNode resolveTemplate(JsonNode template, String field, JsonNode statesVar, JsonNode variables) {
|
||||
if (template == null || template.isMissingNode()) {
|
||||
return template;
|
||||
}
|
||||
JsonNode resolved = resolveTemplateNode(template, statesVar, variables);
|
||||
// A resolved Output or Arguments is serialized as it stands, and a missing node writes
|
||||
// itself as the empty string, which no client can parse. "Returned nothing" is a value only
|
||||
// in the positions resolveTemplateNode reads it in: an object field it drops, an array
|
||||
// element it fails the state on. As the whole field there is nothing to drop it from.
|
||||
return resolved.isMissingNode() ? NullNode.getInstance() : resolved;
|
||||
}
|
||||
|
||||
private JsonNode resolveTemplateNode(JsonNode template, JsonNode statesVar, JsonNode variables) {
|
||||
if (template.isTextual()) {
|
||||
String text = template.asText();
|
||||
if (isExpression(text)) {
|
||||
return evaluate(text, statesVar, variables);
|
||||
return evaluateField(text, field, statesVar, variables);
|
||||
}
|
||||
return template;
|
||||
}
|
||||
@@ -291,30 +304,15 @@ public class JsonataEvaluator {
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = template.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = fields.next();
|
||||
JsonNode value = resolveTemplateNode(entry.getValue(), statesVar, variables);
|
||||
// Per JSONata spec: an expression that returned nothing is omitted from object
|
||||
// output, matching real AWS Step Functions behavior. A JSON null is a value and
|
||||
// keeps its key: AWS answers {"v":null} to Output {"v":"{% null %}"}.
|
||||
if (!value.isMissingNode()) {
|
||||
resolved.set(entry.getKey(), value);
|
||||
}
|
||||
resolved.set(entry.getKey(),
|
||||
resolveTemplate(entry.getValue(), field + "/" + entry.getKey(), statesVar, variables));
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
if (template.isArray()) {
|
||||
ArrayNode resolved = objectMapper.createArrayNode();
|
||||
for (int i = 0; i < template.size(); i++) {
|
||||
JsonNode element = template.get(i);
|
||||
JsonNode value = resolveTemplateNode(element, statesVar, variables);
|
||||
// Per real AWS behavior: an array element that returned nothing fails the execution.
|
||||
// Unlike object fields (which are omitted), undefined in an array is a runtime error.
|
||||
// A JSON null is a value and stays: AWS answers [null,1] to ["{% null %}",1].
|
||||
if (value.isMissingNode()) {
|
||||
String expr = element.isTextual() ? element.asText() : element.toString();
|
||||
throw new FailStateException("States.Runtime",
|
||||
"The JSONata expression '" + expr + "' at array index " + i + " returned nothing (undefined).");
|
||||
}
|
||||
resolved.add(value);
|
||||
resolved.add(resolveTemplate(template.get(i), field + "[" + i + "]", statesVar, variables));
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
@@ -336,9 +334,9 @@ public class JsonataEvaluator {
|
||||
|
||||
/**
|
||||
* The evaluation result. A Java null is the expression returning nothing, which
|
||||
* {@link #resolveTemplateNode} drops from an object; the JSONata null marker is a JSON null,
|
||||
* which it keeps. Nested inside an object or an array there is no undefined, so every null
|
||||
* there is a JSON null.
|
||||
* {@link #evaluateField} fails the state on; the JSONata null marker is a JSON null, which is a
|
||||
* value like any other. Nested inside an object or an array there is no undefined, so every
|
||||
* null there is a JSON null.
|
||||
*/
|
||||
private JsonNode toJsonNode(Object value) {
|
||||
return value == null ? MissingNode.getInstance() : fromJsonataValue(value);
|
||||
|
||||
+1
-1
@@ -64,7 +64,7 @@ class AslExecutorErrorTerminationTest {
|
||||
}
|
||||
|
||||
@Override
|
||||
JsonNode resolveTemplate(JsonNode template, JsonNode statesVar, JsonNode variables) {
|
||||
JsonNode resolveTemplate(JsonNode template, String field, JsonNode statesVar, JsonNode variables) {
|
||||
throw new LinkageError(ERROR_MESSAGE);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-3
@@ -288,7 +288,7 @@ class AslExecutorHttpInvokeTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonataArgumentsSendAnExplicitNullAndOmitOnlyWhatReturnedNothing() throws Exception {
|
||||
void jsonataArgumentsSendAnExplicitNull() throws Exception {
|
||||
// AWS keeps the null in the arguments a Task is invoked with: TestState TRACE reports
|
||||
// afterArguments {"FunctionName":"nope","Payload":{"v":null}} for Payload {"v":"{% null %}"}.
|
||||
Execution execution = run("""
|
||||
@@ -307,7 +307,6 @@ class AslExecutorHttpInvokeTest {
|
||||
},
|
||||
"RequestBody": {
|
||||
"fromInput": "{%% $lookup($states.input, 'customerId') %%}",
|
||||
"returnedNothing": "{%% $states.input.absent %%}",
|
||||
"active": true
|
||||
}
|
||||
},
|
||||
@@ -324,7 +323,6 @@ class AslExecutorHttpInvokeTest {
|
||||
assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause());
|
||||
JsonNode body = objectMapper.readTree(onlyRequest().body());
|
||||
assertTrue(body.path("fromInput").isNull(), body.toString());
|
||||
assertTrue(body.path("returnedNothing").isMissingNode(), body.toString());
|
||||
assertTrue(body.path("active").asBoolean());
|
||||
}
|
||||
|
||||
|
||||
+13
-5
@@ -402,19 +402,27 @@ class AslExecutorResultWriterTest {
|
||||
assertEquals("States.QueryEvaluationError", nestedBucketFailure.error);
|
||||
assertTrue(nestedBucketFailure.getMessage().contains("Bucket must resolve to a string"));
|
||||
|
||||
JsonNode nestedPrefixStateDef = mapper.readTree("""
|
||||
verify(s3Service, org.mockito.Mockito.never())
|
||||
.putObject(anyString(), anyString(), any(byte[].class), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDestinationExpressionReturningNothingFailsBeforeWriting() throws Exception {
|
||||
JsonNode stateDef = mapper.readTree("""
|
||||
{"Type":"Map",
|
||||
"ResultWriter":{"Resource":"arn:aws:states:::s3:putObject",
|
||||
"Arguments":{"Bucket":"b","Prefix":"{% $states.input.missing %}"}}}
|
||||
""");
|
||||
AslExecutor.FailStateException nestedPrefixFailure = assertThrows(
|
||||
|
||||
AslExecutor.FailStateException failure = assertThrows(
|
||||
AslExecutor.FailStateException.class,
|
||||
() -> executor.applyResultWriter("Process", nestedPrefixStateDef, mapper.createObjectNode(),
|
||||
() -> executor.applyResultWriter("Process", stateDef, mapper.createObjectNode(),
|
||||
arr("{\"ok\":true}"), mapper.createArrayNode(), List.of(),
|
||||
sm, context, true));
|
||||
assertEquals("States.QueryEvaluationError", nestedPrefixFailure.error);
|
||||
assertTrue(nestedPrefixFailure.getMessage().contains("Prefix must resolve to a string"));
|
||||
|
||||
assertEquals("States.QueryEvaluationError", failure.error);
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
|
||||
+ "'ResultWriter/Arguments/Prefix' returned nothing (undefined).", failure.cause);
|
||||
verify(s3Service, org.mockito.Mockito.never())
|
||||
.putObject(anyString(), anyString(), any(byte[].class), anyString(), any());
|
||||
}
|
||||
|
||||
+72
-29
@@ -6,6 +6,11 @@ import com.fasterxml.jackson.databind.node.NullNode;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@@ -97,7 +102,7 @@ class JsonataEvaluatorTest {
|
||||
void resolveTemplate_nonExpressionStringPassesThrough() throws Exception {
|
||||
JsonNode template = objectMapper.readTree("\"plain text\"");
|
||||
JsonNode statesVar = objectMapper.createObjectNode();
|
||||
JsonNode result = evaluator.resolveTemplate(template, statesVar);
|
||||
JsonNode result = evaluator.resolveTemplate(template, "Output", statesVar);
|
||||
assertEquals("plain text", result.asText());
|
||||
}
|
||||
|
||||
@@ -105,7 +110,7 @@ class JsonataEvaluatorTest {
|
||||
void resolveTemplate_evaluatesExpressionInString() throws Exception {
|
||||
JsonNode template = objectMapper.readTree("\"{% 1 + 1 %}\"");
|
||||
JsonNode statesVar = objectMapper.createObjectNode();
|
||||
JsonNode result = evaluator.resolveTemplate(template, statesVar);
|
||||
JsonNode result = evaluator.resolveTemplate(template, "Output", statesVar);
|
||||
assertEquals(2, result.asInt());
|
||||
}
|
||||
|
||||
@@ -121,7 +126,7 @@ class JsonataEvaluatorTest {
|
||||
JsonNode statesVar = objectMapper.readTree("""
|
||||
{"input": {"name": "Bob"}}
|
||||
""");
|
||||
JsonNode result = evaluator.resolveTemplate(template, statesVar);
|
||||
JsonNode result = evaluator.resolveTemplate(template, "Output", statesVar);
|
||||
assertTrue(result.isObject());
|
||||
assertEquals("Hello Bob", result.get("greeting").asText());
|
||||
assertEquals("unchanged", result.get("static").asText());
|
||||
@@ -136,7 +141,7 @@ class JsonataEvaluatorTest {
|
||||
JsonNode statesVar = objectMapper.readTree("""
|
||||
{"input": {"a": 1, "b": 2}}
|
||||
""");
|
||||
JsonNode result = evaluator.resolveTemplate(template, statesVar);
|
||||
JsonNode result = evaluator.resolveTemplate(template, "Output", statesVar);
|
||||
assertTrue(result.isArray());
|
||||
assertEquals(1, result.get(0).asInt());
|
||||
assertEquals("static", result.get(1).asText());
|
||||
@@ -150,7 +155,7 @@ class JsonataEvaluatorTest {
|
||||
JsonNode statesVar = objectMapper.readTree("""
|
||||
{"input": {"name": "Alice", "age": 30}}
|
||||
""");
|
||||
JsonNode result = evaluator.resolveTemplate(template, statesVar);
|
||||
JsonNode result = evaluator.resolveTemplate(template, "Output", statesVar);
|
||||
assertTrue(result.isTextual());
|
||||
assertEquals("Hello {% $states.input.name %}, you are {% $states.input.age %} years old", result.asText());
|
||||
}
|
||||
@@ -161,7 +166,7 @@ class JsonataEvaluatorTest {
|
||||
JsonNode statesVar = objectMapper.readTree("""
|
||||
{"input": {"name": "Alice", "age": 30}}
|
||||
""");
|
||||
JsonNode result = evaluator.resolveTemplate(template, statesVar);
|
||||
JsonNode result = evaluator.resolveTemplate(template, "Output", statesVar);
|
||||
assertTrue(result.isObject());
|
||||
assertEquals("Alice", result.get("name").asText());
|
||||
}
|
||||
@@ -170,9 +175,9 @@ class JsonataEvaluatorTest {
|
||||
void resolveTemplate_primitivesPassThrough() throws Exception {
|
||||
JsonNode statesVar = objectMapper.createObjectNode();
|
||||
|
||||
assertEquals(42, evaluator.resolveTemplate(objectMapper.readTree("42"), statesVar).asInt());
|
||||
assertTrue(evaluator.resolveTemplate(objectMapper.readTree("true"), statesVar).asBoolean());
|
||||
assertTrue(evaluator.resolveTemplate(NullNode.getInstance(), statesVar).isNull());
|
||||
assertEquals(42, evaluator.resolveTemplate(objectMapper.readTree("42"), "Output", statesVar).asInt());
|
||||
assertTrue(evaluator.resolveTemplate(objectMapper.readTree("true"), "Output", statesVar).asBoolean());
|
||||
assertTrue(evaluator.resolveTemplate(NullNode.getInstance(), "Output", statesVar).isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -804,18 +809,17 @@ class JsonataEvaluatorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExplicitNullKeepsItsKeyAndOnlyWhatReturnedNothingIsDropped() throws Exception {
|
||||
void anExplicitNullKeepsItsKey() throws Exception {
|
||||
JsonNode statesVar = objectMapper.readTree("""
|
||||
{"input": {"bar": null}}
|
||||
""");
|
||||
JsonNode template = objectMapper.readTree("""
|
||||
{"fromInput": "{% $lookup($states.input, 'bar') %}",
|
||||
"returnedNothing": "{% $states.input.absent %}",
|
||||
"kept": 1}
|
||||
""");
|
||||
|
||||
assertEquals("{\"fromInput\":null,\"kept\":1}",
|
||||
evaluator.resolveTemplate(template, statesVar).toString());
|
||||
evaluator.resolveTemplate(template, "Output", statesVar).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -826,34 +830,23 @@ class JsonataEvaluatorTest {
|
||||
""");
|
||||
|
||||
assertEquals("{\"outer\":{\"fromExpression\":null,\"kept\":1}}",
|
||||
evaluator.resolveTemplate(template, statesVar).toString());
|
||||
evaluator.resolveTemplate(template, "Output", statesVar).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWholeTemplateIsANullWhetherItEvaluatedToNullOrReturnedNothing() throws Exception {
|
||||
void aWholeTemplateEvaluatingToNullIsANull() throws Exception {
|
||||
JsonNode statesVar = objectMapper.createObjectNode();
|
||||
|
||||
assertTrue(evaluator.resolveTemplate(objectMapper.readTree("\"{% null %}\""), statesVar).isNull());
|
||||
// AWS fails the second one with States.QueryEvaluationError, which #2665 covers. Until then
|
||||
// it is a null and not a missing node: an Output or Arguments is serialized as it stands,
|
||||
// and a missing node writes itself as the empty string rather than as JSON.
|
||||
assertTrue(evaluator.resolveTemplate(objectMapper.readTree("\"{% $states.input.absent %}\""), statesVar)
|
||||
.isNull());
|
||||
assertTrue(evaluator.resolveTemplate(objectMapper.readTree("\"{% null %}\""), "Output", statesVar).isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExplicitNullIsAnArrayElementWhileNothingStillFailsTheState() throws Exception {
|
||||
void anExplicitNullIsAnArrayElement() throws Exception {
|
||||
JsonNode statesVar = objectMapper.createObjectNode();
|
||||
|
||||
assertEquals("{\"values\":[null,1]}", evaluator.resolveTemplate(objectMapper.readTree("""
|
||||
{"values": ["{% null %}", 1]}
|
||||
"""), statesVar).toString());
|
||||
|
||||
AslExecutor.FailStateException failure = assertThrows(AslExecutor.FailStateException.class,
|
||||
() -> evaluator.resolveTemplate(objectMapper.readTree("""
|
||||
{"values": ["{% $states.input.absent %}"]}
|
||||
"""), statesVar));
|
||||
assertTrue(failure.cause.contains("returned nothing (undefined)"), failure.cause);
|
||||
"""), "Output", statesVar).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -862,7 +855,7 @@ class JsonataEvaluatorTest {
|
||||
|
||||
assertEquals("{\"literal\":null,\"kept\":1}", evaluator.resolveTemplate(objectMapper.readTree("""
|
||||
{"literal": null, "kept": 1}
|
||||
"""), statesVar).toString());
|
||||
"""), "Output", statesVar).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -885,4 +878,54 @@ class JsonataEvaluatorTest {
|
||||
assertTrue(evaluator.evaluate("{% $nullVariable %}", statesVar, variables).isNull());
|
||||
assertTrue(evaluator.evaluate("{% $exists($nullVariable) %}", statesVar, variables).asBoolean());
|
||||
}
|
||||
|
||||
/**
|
||||
* The field path AWS names in the cause: the ASL field the template came from, a {@code /}
|
||||
* before every object key below it and {@code [i]} appended for every array index. Measured on
|
||||
* TestState, one Pass or one Assign per row.
|
||||
*/
|
||||
static Stream<Arguments> templatesWhoseExpressionReturnsNothing() {
|
||||
return Stream.of(
|
||||
Arguments.of("{\"v\": \"{% $states.input.missing %}\"}", "Output", "Output/v"),
|
||||
Arguments.of("{\"a\": {\"b\": \"{% $states.input.missing %}\"}}", "Output", "Output/a/b"),
|
||||
Arguments.of("\"{% $states.input.missing %}\"", "Output", "Output"),
|
||||
Arguments.of("{\"values\": [\"{% $states.input.missing %}\", 1]}", "Output", "Output/values[0]"),
|
||||
Arguments.of("{\"a\": {\"b\": [[1, \"{% $states.input.missing %}\"]]}}", "Output", "Output/a/b[0][1]"),
|
||||
Arguments.of("{\"x\": {\"y\": \"{% $states.input.missing %}\"}}", "Assign", "Assign/x/y"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("templatesWhoseExpressionReturnsNothing")
|
||||
void anExpressionReturningNothingFailsTheStateNamingTheFieldPath(String template, String field,
|
||||
String expectedFieldPath) throws Exception {
|
||||
JsonNode statesVar = objectMapper.readTree("{\"input\": {}}");
|
||||
|
||||
AslExecutor.FailStateException failure = assertThrows(AslExecutor.FailStateException.class,
|
||||
() -> evaluator.resolveTemplate(objectMapper.readTree(template), field, statesVar));
|
||||
|
||||
assertEquals("States.QueryEvaluationError", failure.error);
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field '"
|
||||
+ expectedFieldPath + "' returned nothing (undefined).", failure.cause);
|
||||
}
|
||||
|
||||
@Test
|
||||
void evaluateFieldNamesTheFieldOfAPositionThatHoldsASingleExpression() throws Exception {
|
||||
JsonNode statesVar = objectMapper.readTree("{\"input\": {}}");
|
||||
|
||||
AslExecutor.FailStateException failure = assertThrows(AslExecutor.FailStateException.class,
|
||||
() -> evaluator.evaluateField("{% $states.input.missing %}", "Seconds", statesVar, null));
|
||||
|
||||
assertEquals("States.QueryEvaluationError", failure.error);
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Seconds' "
|
||||
+ "returned nothing (undefined).", failure.cause);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExplicitNullIsAValueAndKeepsEveryPositionEvaluating() throws Exception {
|
||||
JsonNode statesVar = objectMapper.readTree("{\"input\": {\"bar\": null}}");
|
||||
|
||||
assertTrue(evaluator.evaluateField("{% null %}", "Seconds", statesVar, null).isNull());
|
||||
assertEquals("{\"v\":null}", evaluator.resolveTemplate(
|
||||
objectMapper.readTree("{\"v\": \"{% $states.input.bar %}\"}"), "Output", statesVar).toString());
|
||||
}
|
||||
}
|
||||
+386
-14
@@ -1226,10 +1226,9 @@ class StepFunctionsJsonataIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void outputKeepsAnExplicitNullInEveryPositionAndDropsOnlyWhatReturnedNothing() throws Exception {
|
||||
void outputKeepsAnExplicitNullInEveryPosition() throws Exception {
|
||||
// AWS returns {"v":null} for an expression that evaluates to JSON null, in an object field,
|
||||
// nested, as an array element and as a literal. Only an expression that returned nothing
|
||||
// loses its key.
|
||||
// nested, as an array element and as a literal.
|
||||
String definition = """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
@@ -1242,8 +1241,7 @@ class StepFunctionsJsonataIntegrationTest {
|
||||
"fromLiteralExpression": "{% null %}",
|
||||
"literal": null,
|
||||
"nested": {"inner": "{% null %}", "kept": 1},
|
||||
"values": ["{% null %}", 1],
|
||||
"returnedNothing": "{% $states.input.absent %}"
|
||||
"values": ["{% null %}", 1]
|
||||
},
|
||||
"End": true
|
||||
}
|
||||
@@ -1260,7 +1258,381 @@ class StepFunctionsJsonataIntegrationTest {
|
||||
assertTrue(output.path("literal").isNull(), output.toString());
|
||||
assertTrue(output.path("nested").path("inner").isNull(), output.toString());
|
||||
assertEquals("[null,1]", output.path("values").toString());
|
||||
assertTrue(output.path("returnedNothing").isMissingNode(), output.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void outputExpressionReturningNothingFailsTheStateAndIsCatchable() throws Exception {
|
||||
// Real AWS on the same definition: States.QueryEvaluationError, "An error occurred while
|
||||
// executing the state 'Transform' (entered at the event id #2). The JSONata expression
|
||||
// '$states.input.missing' specified for the field 'Output/v' returned nothing (undefined)."
|
||||
// Floci does not yet render the "An error occurred while executing the state" prefix (#2668).
|
||||
String definition = """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
"StartAt": "Transform",
|
||||
"States": {
|
||||
"Transform": {
|
||||
"Type": "Pass",
|
||||
"Output": {"v": "{% $states.input.missing %}"},
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
String smArn = createStateMachine("jsonata-output-returned-nothing-test", definition);
|
||||
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
|
||||
|
||||
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Output/v' "
|
||||
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
|
||||
|
||||
String catching = definition.replace("\"End\": true",
|
||||
"""
|
||||
"Catch": [{"ErrorEquals": ["States.QueryEvaluationError"], "Next": "Caught"}],
|
||||
"Next": "Unreached"
|
||||
},
|
||||
"Unreached": {"Type": "Fail", "Error": "UnexpectedSuccess"},
|
||||
"Caught": {"Type": "Pass", "Output": {"caught": true}, "End": true""");
|
||||
String catchingArn = createStateMachine("jsonata-output-returned-nothing-catch-test", catching);
|
||||
JsonNode caught = objectMapper.readTree(waitForExecution(startExecution(catchingArn, "{}")));
|
||||
|
||||
assertTrue(caught.path("caught").asBoolean(), caught.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void assignExpressionReturningNothingFailsTheState() throws Exception {
|
||||
// Real AWS names 'Assign/x' for this definition; before this guard the variable was never
|
||||
// bound and the next state read it as missing.
|
||||
String definition = """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
"StartAt": "Bind",
|
||||
"States": {
|
||||
"Bind": {
|
||||
"Type": "Pass",
|
||||
"Assign": {"x": "{% $states.input.missing %}"},
|
||||
"Next": "Read"
|
||||
},
|
||||
"Read": {"Type": "Pass", "Output": {"got": "{% $x %}"}, "End": true}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
String smArn = createStateMachine("jsonata-assign-returned-nothing-test", definition);
|
||||
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
|
||||
|
||||
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Assign/x' "
|
||||
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void taskArgumentReturningNothingFailsTheStateBeforeTheRequestIsSent() throws Exception {
|
||||
// Real AWS names 'Arguments/MessageGroupId' and fails before reaching SQS, which is why the
|
||||
// queue url below never has to exist. Before this guard Floci sent the message without it.
|
||||
String definition = """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
"StartAt": "Send",
|
||||
"States": {
|
||||
"Send": {
|
||||
"Type": "Task",
|
||||
"Resource": "arn:aws:states:::sqs:sendMessage",
|
||||
"Arguments": {
|
||||
"QueueUrl": "http://localhost:4566/000000000000/absent-queue",
|
||||
"MessageBody": "m",
|
||||
"MessageGroupId": "{% $states.input.missing %}"
|
||||
},
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
String smArn = createStateMachine("jsonata-arguments-returned-nothing-test", definition);
|
||||
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
|
||||
|
||||
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
|
||||
+ "'Arguments/MessageGroupId' returned nothing (undefined).",
|
||||
failure.jsonPath().getString("cause"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void choiceConditionReturningNothingFailsTheStateInsteadOfTakingDefault() throws Exception {
|
||||
// Real AWS names the rule by its index, 'Choices[1]/Condition', and evaluates the rules in
|
||||
// order, so the first rule being false is what makes the second one run.
|
||||
String definition = """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
"StartAt": "Pick",
|
||||
"States": {
|
||||
"Pick": {
|
||||
"Type": "Choice",
|
||||
"Choices": [
|
||||
{"Condition": "{% false %}", "Next": "First"},
|
||||
{"Condition": "{% $states.input.missing %}", "Next": "Second"}
|
||||
],
|
||||
"Default": "Fallback"
|
||||
},
|
||||
"First": {"Type": "Pass", "Output": {"went": "First"}, "End": true},
|
||||
"Second": {"Type": "Pass", "Output": {"went": "Second"}, "End": true},
|
||||
"Fallback": {"Type": "Pass", "Output": {"went": "Fallback"}, "End": true}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
String smArn = createStateMachine("jsonata-condition-returned-nothing-test", definition);
|
||||
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
|
||||
|
||||
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
|
||||
+ "'Choices[1]/Condition' returned nothing (undefined).", failure.jsonPath().getString("cause"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChoiceRuleAfterTheMatchingOneIsNeverEvaluated() throws Exception {
|
||||
// AWS succeeds on this definition: the first rule matches, so the undefined condition in the
|
||||
// second one is never reached. The guard must not turn rule order into a failure.
|
||||
String definition = """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
"StartAt": "Pick",
|
||||
"States": {
|
||||
"Pick": {
|
||||
"Type": "Choice",
|
||||
"Choices": [
|
||||
{"Condition": "{% true %}", "Next": "First"},
|
||||
{"Condition": "{% $states.input.missing %}", "Next": "Second"}
|
||||
],
|
||||
"Default": "Fallback"
|
||||
},
|
||||
"First": {"Type": "Pass", "Output": {"went": "First"}, "End": true},
|
||||
"Second": {"Type": "Pass", "Output": {"went": "Second"}, "End": true},
|
||||
"Fallback": {"Type": "Pass", "Output": {"went": "Fallback"}, "End": true}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
String smArn = createStateMachine("jsonata-condition-short-circuit-test", definition);
|
||||
JsonNode output = objectMapper.readTree(waitForExecution(startExecution(smArn, "{}")));
|
||||
|
||||
assertEquals("First", output.path("went").asText(), output.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMatchedChoiceRuleNamesItsOwnOutputUnderTheRuleIndex() throws Exception {
|
||||
// Real AWS names 'Choices[1]/Output/v': a rule's own Output is a field of the rule, not the
|
||||
// state-level Output, and the index is the rule's position in Choices.
|
||||
String definition = """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
"StartAt": "Pick",
|
||||
"States": {
|
||||
"Pick": {
|
||||
"Type": "Choice",
|
||||
"Choices": [
|
||||
{"Condition": "{% false %}", "Next": "First"},
|
||||
{"Condition": "{% true %}",
|
||||
"Output": {"v": "{% $states.input.missing %}"}, "Next": "First"}
|
||||
],
|
||||
"Default": "Fallback"
|
||||
},
|
||||
"First": {"Type": "Pass", "End": true},
|
||||
"Fallback": {"Type": "Pass", "End": true}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
String smArn = createStateMachine("jsonata-choice-rule-output-nothing-test", definition);
|
||||
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
|
||||
|
||||
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
|
||||
+ "'Choices[1]/Output/v' returned nothing (undefined).", failure.jsonPath().getString("cause"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMatchedChoiceRuleNamesItsOwnAssignUnderTheRuleIndex() throws Exception {
|
||||
// Real AWS names 'Choices[0]/Assign/x' for a rule's own Assign.
|
||||
String definition = """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
"StartAt": "Pick",
|
||||
"States": {
|
||||
"Pick": {
|
||||
"Type": "Choice",
|
||||
"Choices": [
|
||||
{"Condition": "{% true %}",
|
||||
"Assign": {"x": "{% $states.input.missing %}"}, "Next": "First"}
|
||||
],
|
||||
"Default": "Fallback"
|
||||
},
|
||||
"First": {"Type": "Pass", "End": true},
|
||||
"Fallback": {"Type": "Pass", "End": true}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
String smArn = createStateMachine("jsonata-choice-rule-assign-nothing-test", definition);
|
||||
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
|
||||
|
||||
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
|
||||
+ "'Choices[0]/Assign/x' returned nothing (undefined).", failure.jsonPath().getString("cause"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCatchClauseNamesItsOwnOutputUnderTheClauseIndex() throws Exception {
|
||||
// Real AWS names 'Catch[1]/Output/v': a clause's own Output is a field of the clause, and the
|
||||
// index is its position in Catch, not its position among the clauses that matched. Measured
|
||||
// with a real execution: TestState answers CAUGHT_ERROR and omits the output rather than
|
||||
// failing. Catch belongs to a Task, which AWS rejects on a Pass, so the state below fails on
|
||||
// its own Arguments and the clause catches that.
|
||||
String definition = """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
"StartAt": "Boom",
|
||||
"States": {
|
||||
"Boom": {
|
||||
"Type": "Task",
|
||||
"Resource": "arn:aws:states:::sqs:sendMessage",
|
||||
"Arguments": {
|
||||
"QueueUrl": "http://localhost:4566/000000000000/absent-queue",
|
||||
"MessageBody": "m",
|
||||
"MessageGroupId": "{% $states.input.missing %}"
|
||||
},
|
||||
"Catch": [
|
||||
{"ErrorEquals": ["States.Timeout"], "Next": "Caught"},
|
||||
{"ErrorEquals": ["States.QueryEvaluationError"],
|
||||
"Output": {"v": "{% $states.input.missing %}"}, "Next": "Caught"}
|
||||
],
|
||||
"End": true
|
||||
},
|
||||
"Caught": {"Type": "Pass", "End": true}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
String smArn = createStateMachine("jsonata-catch-output-nothing-test", definition);
|
||||
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
|
||||
|
||||
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
|
||||
+ "'Catch[1]/Output/v' returned nothing (undefined).", failure.jsonPath().getString("cause"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void waitSecondsReturningNothingFailsTheStateInsteadOfNotWaiting() throws Exception {
|
||||
// Real AWS names 'Seconds'. Before this guard the expression resolved to zero and the state
|
||||
// did not wait at all.
|
||||
String definition = """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
"StartAt": "Pause",
|
||||
"States": {
|
||||
"Pause": {"Type": "Wait", "Seconds": "{% $states.input.missing %}", "End": true}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
String smArn = createStateMachine("jsonata-wait-returned-nothing-test", definition);
|
||||
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
|
||||
|
||||
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Seconds' "
|
||||
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failErrorAndCauseReturningNothingFailTheStateWithTheQueryEvaluationError() throws Exception {
|
||||
// Real AWS names 'Error' and 'Cause'. The Fail state's own error is replaced by the
|
||||
// evaluation failure, so a Catch on States.QueryEvaluationError fires instead of one on the
|
||||
// error the definition meant to raise.
|
||||
String definition = """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
"StartAt": "Stop",
|
||||
"States": {
|
||||
"Stop": {"Type": "Fail", "Error": "%s", "Cause": "%s"}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
Response errorFailure = waitForExecutionFailure(startExecution(
|
||||
createStateMachine("jsonata-fail-error-returned-nothing-test",
|
||||
definition.formatted("{% $states.input.missing %}", "boom")), "{}"));
|
||||
assertEquals("States.QueryEvaluationError", errorFailure.jsonPath().getString("error"));
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Error' "
|
||||
+ "returned nothing (undefined).", errorFailure.jsonPath().getString("cause"));
|
||||
|
||||
Response causeFailure = waitForExecutionFailure(startExecution(
|
||||
createStateMachine("jsonata-fail-cause-returned-nothing-test",
|
||||
definition.formatted("Boom", "{% $states.input.missing %}")), "{}"));
|
||||
assertEquals("States.QueryEvaluationError", causeFailure.jsonPath().getString("error"));
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Cause' "
|
||||
+ "returned nothing (undefined).", causeFailure.jsonPath().getString("cause"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapItemsReturningNothingFailsTheStateInsteadOfIteratingNothing() throws Exception {
|
||||
// Real AWS names 'Items'.
|
||||
String definition = """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
"StartAt": "Fan",
|
||||
"States": {
|
||||
"Fan": {
|
||||
"Type": "Map",
|
||||
"Items": "{% $states.input.missing %}",
|
||||
"ItemProcessor": {
|
||||
"StartAt": "P",
|
||||
"States": {"P": {"Type": "Pass", "End": true}}
|
||||
},
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
String smArn = createStateMachine("jsonata-map-items-returned-nothing-test", definition);
|
||||
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
|
||||
|
||||
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Items' "
|
||||
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapMaxConcurrencyReturningNothingFailsTheStateNamingTheField() throws Exception {
|
||||
// Real AWS names 'MaxConcurrency'. Before this guard the undefined value reached the
|
||||
// non-negative-integer check and failed with Floci's own wording instead of AWS's.
|
||||
String definition = """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
"StartAt": "Fan",
|
||||
"States": {
|
||||
"Fan": {
|
||||
"Type": "Map",
|
||||
"Items": [1, 2],
|
||||
"MaxConcurrency": "{% $states.input.missing %}",
|
||||
"ItemProcessor": {
|
||||
"StartAt": "P",
|
||||
"States": {"P": {"Type": "Pass", "End": true}}
|
||||
},
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
String smArn = createStateMachine("jsonata-map-maxconcurrency-returned-nothing-test", definition);
|
||||
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
|
||||
|
||||
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field "
|
||||
+ "'MaxConcurrency' returned nothing (undefined).", failure.jsonPath().getString("cause"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1298,10 +1670,9 @@ class StepFunctionsJsonataIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWholeOutputThatReturnedNothingStaysReadableJson() throws Exception {
|
||||
// AWS fails this state with States.QueryEvaluationError, which #2665 covers. Until then the
|
||||
// execution succeeds, and what DescribeExecution hands back has to parse: an output field
|
||||
// holding the empty string is not JSON any client can read.
|
||||
void aWholeOutputThatReturnedNothingFailsTheState() throws Exception {
|
||||
// Real AWS names the whole field, 'Output', with no path below it. There is no output to
|
||||
// serialize once the state fails, which is what the null this used to resolve to stood in for.
|
||||
String definition = """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
@@ -1309,7 +1680,7 @@ class StepFunctionsJsonataIntegrationTest {
|
||||
"States": {
|
||||
"Transform": {
|
||||
"Type": "Pass",
|
||||
"Output": "{% $states.input.absent %}",
|
||||
"Output": "{% $states.input.missing %}",
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
@@ -1317,10 +1688,11 @@ class StepFunctionsJsonataIntegrationTest {
|
||||
""";
|
||||
|
||||
String smArn = createStateMachine("jsonata-whole-output-nothing-test", definition);
|
||||
String execArn = startExecution(smArn, "{}");
|
||||
String output = waitForExecution(execArn);
|
||||
Response failure = waitForExecutionFailure(startExecution(smArn, "{}"));
|
||||
|
||||
assertTrue(objectMapper.readTree(output).isNull(), output);
|
||||
assertEquals("States.QueryEvaluationError", failure.jsonPath().getString("error"));
|
||||
assertEquals("The JSONata expression '$states.input.missing' specified for the field 'Output' "
|
||||
+ "returned nothing (undefined).", failure.jsonPath().getString("cause"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user