feat: add JSONata query language support for Step Functions (#84)

Thanks again, @thegagne!
This is a great addition to Floci. Your continued support really makes a difference. Hope to see you around soon!

---
* feat: add JSONata query language support for Step Functions

Add JSONata as an alternative query language for Step Functions, matching
the AWS feature launched in late 2024. When a state machine definition
sets "QueryLanguage": "JSONata", the JSONPath fields (InputPath,
Parameters, ResultSelector, ResultPath, OutputPath) are replaced by
Arguments and Output, with expressions wrapped in {% %} delimiters.

Implementation:
- Add dashjoin jsonata-java 0.9.9 dependency (zero-dep, 160KB)
- New JsonataEvaluator: handles {% %} expression evaluation, Jackson↔Map
  conversion, $states variable binding, recursive template resolution
- AslExecutor: dual query language branches for all state types (Pass,
  Task, Choice, Wait, Map, Parallel, Succeed, Fail)
- $states.input, $states.result, $states.context (Execution, StateMachine,
  State metadata) all supported
- Definition validation: rejects JSONPath-only fields in JSONata mode,
  rejects JSONata→JSONPath per-state override (only JSONPath→JSONata
  is allowed, matching AWS behavior)

All behavior validated against real AWS Step Functions.

* fix: return error and cause fields in DescribeExecution response

DescribeExecution was not returning the error and cause fields for
failed executions. AWS includes these in the response so the SDK can
surface them via DescribeExecutionResponse.error() and .cause().

Add error/cause fields to the Execution model and include them in the
JSON handler response when present.
This commit is contained in:
thegagne authored and GitHub committed 2026-03-26 13:18:32 -05:00
1 parent 26facf26e5
commit f82b370ab2
9 files changed
+1041 -37

No files matched your search

@@ -0,0 +1,146 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.dashjoin.jsonata.Jsonata.jsonata;
import static org.junit.jupiter.api.Assertions.*;
/**
* Edge-case tests exercising the dashjoin jsonata-java library directly
* (bypassing the project's JsonataEvaluator wrapper).
*/
class JsonataEdgeCaseTest {
private final ObjectMapper mapper = new ObjectMapper();
// ---------------------------------------------------------------
// 1. Object-constructor expression: {"name": $states.input.name}
// ---------------------------------------------------------------
@Test
void objectConstructor_returnsMap() throws Exception {
var input = Map.of("input", Map.of("name", "Alice", "age", 30));
var expr = jsonata("{\"name\": $states.input.name, \"age\": $states.input.age}");
var frame = expr.createFrame();
frame.bind("states", input);
Object result = expr.evaluate(null, frame);
assertNotNull(result, "Expected a non-null result from object constructor");
assertInstanceOf(Map.class, result, "Object constructor should yield a Map");
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) result;
assertEquals("Alice", map.get("name"));
assertEquals(30, ((Number) map.get("age")).intValue());
}
// ---------------------------------------------------------------
// 2. Missing field: does it return null, throw, or something else?
// ---------------------------------------------------------------
@Test
void missingField_returnsNullNotThrows() throws Exception {
var input = Map.of("input", Map.of("name", "Alice"));
var expr = jsonata("$states.input.nonexistent");
var frame = expr.createFrame();
frame.bind("states", input);
Object result = expr.evaluate(null, frame);
// System.out.println("[Test 2] missing field result class: " + (result == null ? "null (Java null)" : result.getClass().getName()));
// System.out.println("[Test 2] missing field result value: " + result);
// Key question: is it Java null?
assertNull(result, "Accessing a missing field should return Java null");
}
@Test
void missingVariable_returnsNull() throws Exception {
// No binding at all for $states
var expr = jsonata("$states.input.name");
var frame = expr.createFrame();
Object result = expr.evaluate(null, frame);
// System.out.println("[Test 2b] unbound variable result class: " + (result == null ? "null (Java null)" : result.getClass().getName()));
// System.out.println("[Test 2b] unbound variable result value: " + result);
assertNull(result, "Accessing an unbound variable should return Java null");
}
// ---------------------------------------------------------------
// 3. Nested object binding with deep path access
// ---------------------------------------------------------------
@Test
void deepNestedAccess_works() throws Exception {
// Build a deeply nested structure
Map<String, Object> nested = new LinkedHashMap<>();
nested.put("input", Map.of(
"user", Map.of(
"address", Map.of(
"city", "Springfield",
"zip", "62704"
),
"tags", java.util.List.of("admin", "active")
)
));
// Deep path access
var expr1 = jsonata("$states.input.user.address.city");
var frame1 = expr1.createFrame();
frame1.bind("states", nested);
Object city = expr1.evaluate(null, frame1);
// System.out.println("[Test 3a] deep path city: " + city);
assertEquals("Springfield", city);
// Access into an array element
var expr2 = jsonata("$states.input.user.tags[0]");
var frame2 = expr2.createFrame();
frame2.bind("states", nested);
Object firstTag = expr2.evaluate(null, frame2);
// System.out.println("[Test 3b] deep path tags[0]: " + firstTag);
assertEquals("admin", firstTag);
// Construct an object from deep paths
var expr3 = jsonata("{\"city\": $states.input.user.address.city, \"firstTag\": $states.input.user.tags[0]}");
var frame3 = expr3.createFrame();
frame3.bind("states", nested);
Object combined = expr3.evaluate(null, frame3);
// System.out.println("[Test 3c] combined object: " + combined);
assertInstanceOf(Map.class, combined);
@SuppressWarnings("unchecked")
Map<String, Object> combinedMap = (Map<String, Object>) combined;
assertEquals("Springfield", combinedMap.get("city"));
assertEquals("admin", combinedMap.get("firstTag"));
}
// ---------------------------------------------------------------
// Bonus: what does convertValue look like round-tripping?
// ---------------------------------------------------------------
@Test
void convertValue_jacksonToMapRoundTrip() throws Exception {
var jsonNode = mapper.readTree("""
{"input": {"name": "Bob", "scores": [10, 20, 30]}}
""");
@SuppressWarnings("unchecked")
Map<String, Object> asMap = mapper.convertValue(jsonNode, Map.class);
var expr = jsonata("$sum($states.input.scores)");
var frame = expr.createFrame();
frame.bind("states", asMap);
Object result = expr.evaluate(null, frame);
// System.out.println("[Test 4] sum of scores: " + result);
assertEquals(60, ((Number) result).intValue());
}
}
@@ -0,0 +1,176 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.NullNode;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class JsonataEvaluatorTest {
private JsonataEvaluator evaluator;
private ObjectMapper objectMapper;
@BeforeEach
void setUp() {
objectMapper = new ObjectMapper();
evaluator = new JsonataEvaluator(objectMapper);
}
@Test
void isExpression_valid() {
assertTrue(JsonataEvaluator.isExpression("{% $states.input.x %}"));
assertTrue(JsonataEvaluator.isExpression("{%$states.input%}"));
assertTrue(JsonataEvaluator.isExpression("{% $states.input %}"));
}
@Test
void isExpression_invalid() {
assertFalse(JsonataEvaluator.isExpression(null));
assertFalse(JsonataEvaluator.isExpression("hello"));
assertFalse(JsonataEvaluator.isExpression("{% incomplete"));
assertFalse(JsonataEvaluator.isExpression("incomplete %}"));
// Not a pure expression — AWS does not support string interpolation
assertFalse(JsonataEvaluator.isExpression("Hello {% name %} welcome"));
}
@Test
void unwrap_stripsDelimitersAndTrims() {
assertEquals("$states.input.x", JsonataEvaluator.unwrap("{% $states.input.x %}"));
assertEquals("1 + 2", JsonataEvaluator.unwrap("{%1 + 2%}"));
}
@Test
void evaluate_simpleArithmetic() {
JsonNode statesVar = objectMapper.createObjectNode();
JsonNode result = evaluator.evaluate("{% 1 + 2 %}", statesVar);
assertEquals(3, result.asInt());
}
@Test
void evaluate_stringConcatenation() {
JsonNode statesVar = objectMapper.createObjectNode();
JsonNode result = evaluator.evaluate("{% 'hello' & ' ' & 'world' %}", statesVar);
assertEquals("hello world", result.asText());
}
@Test
void evaluate_statesInputAccess() throws Exception {
JsonNode statesVar = objectMapper.readTree("""
{"input": {"name": "Alice", "age": 30}}
""");
JsonNode result = evaluator.evaluate("{% $states.input.name %}", statesVar);
assertEquals("Alice", result.asText());
}
@Test
void evaluate_statesResultAccess() throws Exception {
JsonNode statesVar = objectMapper.readTree("""
{"input": {"x": 1}, "result": {"value": 42}}
""");
JsonNode result = evaluator.evaluate("{% $states.result.value %}", statesVar);
assertEquals(42, result.asInt());
}
@Test
void evaluate_booleanExpression() throws Exception {
JsonNode statesVar = objectMapper.readTree("""
{"input": {"score": 85}}
""");
JsonNode result = evaluator.evaluate("{% $states.input.score > 50 %}", statesVar);
assertTrue(result.asBoolean());
}
@Test
void evaluate_returnsNullForMissingField() throws Exception {
JsonNode statesVar = objectMapper.readTree("""
{"input": {"name": "Alice"}}
""");
JsonNode result = evaluator.evaluate("{% $states.input.missing %}", statesVar);
assertTrue(result.isNull());
}
@Test
void resolveTemplate_nonExpressionStringPassesThrough() throws Exception {
JsonNode template = objectMapper.readTree("\"plain text\"");
JsonNode statesVar = objectMapper.createObjectNode();
JsonNode result = evaluator.resolveTemplate(template, statesVar);
assertEquals("plain text", result.asText());
}
@Test
void resolveTemplate_evaluatesExpressionInString() throws Exception {
JsonNode template = objectMapper.readTree("\"{% 1 + 1 %}\"");
JsonNode statesVar = objectMapper.createObjectNode();
JsonNode result = evaluator.resolveTemplate(template, statesVar);
assertEquals(2, result.asInt());
}
@Test
void resolveTemplate_walksObjectAndEvaluatesExpressions() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"greeting": "{% 'Hello ' & $states.input.name %}",
"static": "unchanged",
"count": 42
}
""");
JsonNode statesVar = objectMapper.readTree("""
{"input": {"name": "Bob"}}
""");
JsonNode result = evaluator.resolveTemplate(template, statesVar);
assertTrue(result.isObject());
assertEquals("Hello Bob", result.get("greeting").asText());
assertEquals("unchanged", result.get("static").asText());
assertEquals(42, result.get("count").asInt());
}
@Test
void resolveTemplate_walksArrayAndEvaluatesExpressions() throws Exception {
JsonNode template = objectMapper.readTree("""
["{% $states.input.a %}", "static", "{% $states.input.b %}"]
""");
JsonNode statesVar = objectMapper.readTree("""
{"input": {"a": 1, "b": 2}}
""");
JsonNode result = evaluator.resolveTemplate(template, statesVar);
assertTrue(result.isArray());
assertEquals(1, result.get(0).asInt());
assertEquals("static", result.get(1).asText());
assertEquals(2, result.get(2).asInt());
}
@Test
void resolveTemplate_nonPureExpressionPassesThrough() throws Exception {
// AWS does not support string interpolation — non-pure expressions pass through as-is
JsonNode template = objectMapper.readTree("\"Hello {% $states.input.name %}, you are {% $states.input.age %} years old\"");
JsonNode statesVar = objectMapper.readTree("""
{"input": {"name": "Alice", "age": 30}}
""");
JsonNode result = evaluator.resolveTemplate(template, statesVar);
assertTrue(result.isTextual());
assertEquals("Hello {% $states.input.name %}, you are {% $states.input.age %} years old", result.asText());
}
@Test
void resolveTemplate_pureExpressionReturnsObject() throws Exception {
JsonNode template = objectMapper.readTree("\"{% $states.input %}\"");
JsonNode statesVar = objectMapper.readTree("""
{"input": {"name": "Alice", "age": 30}}
""");
JsonNode result = evaluator.resolveTemplate(template, statesVar);
assertTrue(result.isObject());
assertEquals("Alice", result.get("name").asText());
}
@Test
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());
}
}
@@ -0,0 +1,301 @@
package io.github.hectorvent.floci.services.stepfunctions;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.config.EncoderConfig;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
class StepFunctionsJsonataIntegrationTest {
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";
@BeforeAll
static void configureRestAssured() {
RestAssured.config = RestAssured.config().encoderConfig(
EncoderConfig.encoderConfig()
.encodeContentTypeAs(SFN_CONTENT_TYPE, ContentType.TEXT));
}
@Test
void passStateWithJsonataOutput() throws Exception {
// A Pass state that transforms input using JSONata Output field
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Transform",
"States": {
"Transform": {
"Type": "Pass",
"Output": {
"greeting": "{% 'Hello ' & $states.input.name %}",
"doubled": "{% $states.input.value * 2 %}"
},
"End": true
}
}
}
""";
String smArn = createStateMachine("jsonata-pass-test", definition);
String execArn = startExecution(smArn, "{\"name\": \"World\", \"value\": 21}");
String output = waitForExecution(execArn);
assertTrue(output.contains("Hello World"));
assertTrue(output.contains("42"));
}
@Test
void choiceStateWithJsonataCondition() throws Exception {
// Choice state using JSONata Condition instead of Variable/StringEquals
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "CheckType",
"States": {
"CheckType": {
"Type": "Choice",
"Choices": [
{
"Condition": "{% $states.input.type = 'premium' %}",
"Next": "PremiumPath"
},
{
"Condition": "{% $states.input.type = 'basic' %}",
"Next": "BasicPath"
}
],
"Default": "DefaultPath"
},
"PremiumPath": {
"Type": "Pass",
"Output": {"result": "premium"},
"End": true
},
"BasicPath": {
"Type": "Pass",
"Output": {"result": "basic"},
"End": true
},
"DefaultPath": {
"Type": "Pass",
"Output": {"result": "default"},
"End": true
}
}
}
""";
String smArn = createStateMachine("jsonata-choice-test", definition);
// Test premium path
String execArn = startExecution(smArn, "{\"type\": \"premium\"}");
String output = waitForExecution(execArn);
assertTrue(output.contains("premium"));
// Test basic path
execArn = startExecution(smArn, "{\"type\": \"basic\"}");
output = waitForExecution(execArn);
assertTrue(output.contains("basic"));
// Test default path
execArn = startExecution(smArn, "{\"type\": \"unknown\"}");
output = waitForExecution(execArn);
assertTrue(output.contains("default"));
}
@Test
void mapStateWithJsonataItems() throws Exception {
// Map state using JSONata Items field instead of ItemsPath
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "MapItems",
"States": {
"MapItems": {
"Type": "Map",
"Items": "{% $states.input.numbers %}",
"ItemProcessor": {
"StartAt": "Double",
"States": {
"Double": {
"Type": "Pass",
"End": true
}
}
},
"End": true
}
}
}
""";
String smArn = createStateMachine("jsonata-map-test", definition);
String execArn = startExecution(smArn, "{\"numbers\": [1, 2, 3]}");
String output = waitForExecution(execArn);
// Map passes each item through, result is array [1, 2, 3]
assertTrue(output.contains("[1,2,3]"));
}
@Test
void statesInputVariableAccess() throws Exception {
// Verify $states.input gives access to the state's input
String definition = """
{
"QueryLanguage": "JSONata",
"StartAt": "Extract",
"States": {
"Extract": {
"Type": "Pass",
"Output": {
"firstName": "{% $states.input.user.first %}",
"lastName": "{% $states.input.user.last %}",
"fullName": "{% $states.input.user.first & ' ' & $states.input.user.last %}"
},
"End": true
}
}
}
""";
String smArn = createStateMachine("jsonata-states-input-test", definition);
String execArn = startExecution(smArn, "{\"user\": {\"first\": \"Jane\", \"last\": \"Doe\"}}");
String output = waitForExecution(execArn);
assertTrue(output.contains("Jane"));
assertTrue(output.contains("Doe"));
assertTrue(output.contains("Jane Doe"));
}
@Test
void mixedModeDefaultJsonPathWithPerStateJsonata() throws Exception {
// Default JSONPath (no top-level QueryLanguage) with one state overriding to JSONata
String definition = """
{
"StartAt": "JsonPathState",
"States": {
"JsonPathState": {
"Type": "Pass",
"Next": "JsonataState"
},
"JsonataState": {
"Type": "Pass",
"QueryLanguage": "JSONata",
"Output": {
"value": "{% $states.input.x + $states.input.y %}"
},
"End": true
}
}
}
""";
String smArn = createStateMachine("jsonata-mixed-test", definition);
String execArn = startExecution(smArn, "{\"x\": 10, \"y\": 20}");
String output = waitForExecution(execArn);
assertTrue(output.contains("30"));
}
@Test
void backwardCompatibility_jsonPathStillWorks() throws Exception {
// No QueryLanguage field — default JSONPath behavior must work
String definition = """
{
"StartAt": "PassThrough",
"States": {
"PassThrough": {
"Type": "Pass",
"InputPath": "$.data",
"ResultPath": "$.result",
"End": true
}
}
}
""";
String smArn = createStateMachine("jsonpath-compat-test", definition);
String execArn = startExecution(smArn, "{\"data\": {\"key\": \"value\"}}");
String output = waitForExecution(execArn);
assertTrue(output.contains("key"));
assertTrue(output.contains("value"));
}
// ──────────────── Helpers ────────────────
private String createStateMachine(String name, String definition) {
Response resp = given()
.header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
.contentType(SFN_CONTENT_TYPE)
.body(String.format("""
{
"name": "%s",
"definition": %s,
"roleArn": "%s"
}
""", name, quote(definition), ROLE_ARN))
.when()
.post("/");
resp.then().statusCode(200);
return resp.jsonPath().getString("stateMachineArn");
}
private String startExecution(String smArn, String input) {
Response resp = given()
.header("X-Amz-Target", "AWSStepFunctions.StartExecution")
.contentType(SFN_CONTENT_TYPE)
.body(String.format("""
{
"stateMachineArn": "%s",
"input": %s
}
""", smArn, quote(input)))
.when()
.post("/");
resp.then().statusCode(200);
return resp.jsonPath().getString("executionArn");
}
private String waitForExecution(String execArn) throws InterruptedException {
for (int i = 0; i < 50; i++) {
Response resp = given()
.header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
.contentType(SFN_CONTENT_TYPE)
.body(String.format("""
{ "executionArn": "%s" }
""", execArn))
.when()
.post("/");
String status = resp.jsonPath().getString("status");
if ("SUCCEEDED".equals(status)) {
return resp.jsonPath().getString("output");
}
if ("FAILED".equals(status) || "ABORTED".equals(status)) {
fail("Execution " + status + ": " + resp.body().asString());
}
Thread.sleep(100);
}
fail("Execution did not complete within timeout");
return null;
}
/**
* JSON-encode a string value (escape and wrap in quotes) for embedding
* inside a JSON body where the field expects a string.
*/
private static String quote(String raw) {
return "\"" + raw
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t")
+ "\"";
}
}