feat(sfn): JSONata improvements, States.* intrinsics, DynamoDB ConditionExpression, StartSyncExecution (#205)

* feat(sfn): add StartSyncExecution and fix per-state QueryLanguage override

- Remove incorrect validation that blocked per-state QueryLanguage: JSONPath
  overrides when the top-level machine uses JSONata — AWS allows this
- Implement StartSyncExecution for EXPRESS state machines: extract doExecute
  from executeAsync, add executeSync that blocks until the execution finishes,
  wire up handler and service method
- Document remaining DynamoDB output shape issues (singleton unwrap, getItem
  key format) in issues/ for follow-up
This commit is contained in:
thegagne authored and GitHub committed 2026-04-04 21:08:31 -05:00
1 parent 858775c38e
commit 53dd7a68dd
10 files changed
+814 -147

No files matched your search

@@ -183,7 +183,7 @@ public class ApiGatewayExecuteController {
matched, integration, headers, uriInfo, body);
case "AWS" -> invokeAwsIntegration(region, httpMethod, path, proxy, stageName,
matched, integration, headers, uriInfo, body);
case "MOCK" -> invokeMock(integration);
case "MOCK" -> invokeMock(region, httpMethod, path, stageName, matched, integration, headers, uriInfo, body);
default -> Response.status(500)
.entity(jsonMessage("Unsupported integration type: " + integration.getType()))
.type(MediaType.APPLICATION_JSON).build();
@@ -413,6 +413,7 @@ public class ApiGatewayExecuteController {
ObjectNode pathParams = event.putObject("pathParameters");
if (proxy != null && !proxy.isEmpty()) pathParams.put("proxy", proxy);
extractPathParams(resourcePath, path).forEach(pathParams::put);
event.putNull("stageVariables");
@@ -505,6 +506,7 @@ public class ApiGatewayExecuteController {
}
Map<String, String> pathMap = new HashMap<>();
if (proxy != null && !proxy.isEmpty()) pathMap.put("proxy", proxy);
pathMap.putAll(extractPathParams(resource.getPath(), path));
VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
@@ -547,7 +549,7 @@ public class ApiGatewayExecuteController {
}
if (template != null) {
transformedBody = vtlEngine.evaluate(template, vtlCtx);
transformedBody = vtlEngine.evaluate(template, vtlCtx).body();
} else {
// No matching template for this Content-Type
String behavior = integration.getPassthroughBehavior();
@@ -667,6 +669,7 @@ public class ApiGatewayExecuteController {
// Determine final status code and body
int finalStatus;
String finalBody;
VtlTemplateEngine.EvaluateResult templateResult = null;
if (matchedResponse != null) {
finalStatus = Integer.parseInt(matchedResponse.statusCode());
@@ -679,7 +682,8 @@ public class ApiGatewayExecuteController {
VtlTemplateEngine.VtlContext responseMappingCtx = new VtlTemplateEngine.VtlContext(
responseBodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
resource.getPath(), requestId, "000000000000", null);
finalBody = vtlEngine.evaluate(responseTemplate, responseMappingCtx);
templateResult = vtlEngine.evaluate(responseTemplate, responseMappingCtx);
finalBody = templateResult.body();
} else {
finalBody = responseBodyStr;
}
@@ -691,11 +695,25 @@ public class ApiGatewayExecuteController {
finalBody = responseBodyStr;
}
// Apply $context.responseOverride assignments from the response template (if any).
if (templateResult != null) {
if (templateResult.statusOverride() != null) {
finalStatus = templateResult.statusOverride();
}
}
Response.ResponseBuilder rb = Response.status(finalStatus)
.entity(finalBody)
.type(MediaType.APPLICATION_JSON);
// Apply response parameter mapping (header mapping)
// Apply $context.responseOverride header assignments.
if (templateResult != null && !templateResult.headerOverrides().isEmpty()) {
for (Map.Entry<String, String> hdr : templateResult.headerOverrides().entrySet()) {
rb.header(hdr.getKey(), hdr.getValue());
}
}
// Apply response parameter mapping (header mapping from responseParameters config).
if (matchedResponse != null && matchedResponse.responseParameters() != null) {
Map<String, String> serviceResponseHeaders = new HashMap<>();
if (serviceResponse != null) {
@@ -764,18 +782,57 @@ public class ApiGatewayExecuteController {
// ──────────────────────────── MOCK ────────────────────────────
private Response invokeMock(Integration integration) {
private Response invokeMock(String region, String httpMethod, String path, String stageName,
ApiGatewayResource resource, Integration integration,
HttpHeaders headers, UriInfo uriInfo, byte[] body) {
// Use the "200" integration response if present, else return empty 200
IntegrationResponse ir = integration.getIntegrationResponses().get("200");
if (ir == null) {
return Response.ok().build();
}
String template = ir.responseTemplates() != null
? ir.responseTemplates().getOrDefault("application/json", "") : "";
return Response.status(Integer.parseInt(ir.statusCode()))
.entity(template)
.type(MediaType.APPLICATION_JSON)
.build();
if (template.isEmpty()) {
return Response.status(Integer.parseInt(ir.statusCode()))
.type(MediaType.APPLICATION_JSON)
.build();
}
// Evaluate the response template through VTL (supports $context.responseOverride etc.)
String requestId = UUID.randomUUID().toString();
String bodyStr = body != null && body.length > 0 ? new String(body) : null;
Map<String, String> headerMap = new HashMap<>();
for (Map.Entry<String, List<String>> e : headers.getRequestHeaders().entrySet()) {
if (!e.getValue().isEmpty()) headerMap.put(e.getKey(), e.getValue().get(0));
}
Map<String, String> queryMap = new HashMap<>();
for (Map.Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {
if (!e.getValue().isEmpty()) queryMap.put(e.getKey(), e.getValue().get(0));
}
Map<String, String> pathMap = new HashMap<>(extractPathParams(resource.getPath(), path));
VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
bodyStr, headerMap, queryMap, pathMap, stageName, httpMethod,
resource.getPath(), requestId, "000000000000", null);
VtlTemplateEngine.EvaluateResult result = vtlEngine.evaluate(template, vtlCtx);
int status = result.statusOverride() != null
? result.statusOverride()
: Integer.parseInt(ir.statusCode());
Response.ResponseBuilder rb = Response.status(status)
.entity(result.body())
.type(MediaType.APPLICATION_JSON);
for (Map.Entry<String, String> hdr : result.headerOverrides().entrySet()) {
rb.header(hdr.getKey(), hdr.getValue());
}
return rb.build();
}
// ──────────────────────────── API Gateway v2 dispatch ────────────────────────────
@@ -1013,7 +1070,7 @@ public class ApiGatewayExecuteController {
/**
* Finds the best-matching resource for {@code requestPath}.
* Priority: exact match > wildcard/proxy+ match.
* Priority: exact match > template path match (e.g. /items/{id}) > proxy+ wildcard.
*/
private ApiGatewayResource matchResource(List<ApiGatewayResource> resources, String requestPath) {
// 1. Exact match
@@ -1022,7 +1079,15 @@ public class ApiGatewayExecuteController {
return r;
}
}
// 2. Wildcard / {proxy+} — any resource whose pathPart contains "{"
// 2. Template path match — /items/{id} matches /items/anything
for (ApiGatewayResource r : resources) {
if (r.getPath() != null && r.getPath().contains("{") && !r.getPath().contains("{proxy+}")) {
if (pathMatchesTemplate(r.getPath(), requestPath)) {
return r;
}
}
}
// 3. Proxy+ wildcard — {proxy+} matches any remaining path
for (ApiGatewayResource r : resources) {
if (r.getPathPart() != null && r.getPathPart().contains("{")) {
return r;
@@ -1030,4 +1095,41 @@ public class ApiGatewayExecuteController {
}
return null;
}
/**
* Returns true if {@code requestPath} matches the template path (e.g. {@code /items/{id}}).
* Segments wrapped in {@code {}} match any single path segment.
*/
private boolean pathMatchesTemplate(String templatePath, String requestPath) {
String[] tParts = templatePath.split("/", -1);
String[] rParts = requestPath.split("/", -1);
if (tParts.length != rParts.length) return false;
for (int i = 0; i < tParts.length; i++) {
if (tParts[i].startsWith("{") && tParts[i].endsWith("}")) continue; // wildcard segment
if (!tParts[i].equals(rParts[i])) return false;
}
return true;
}
/**
* Extracts named path parameters from a matched template path.
* Given template {@code /items/{id}} and request {@code /items/item-1}, returns {@code {id=item-1}}.
*/
private Map<String, String> extractPathParams(String templatePath, String requestPath) {
Map<String, String> params = new HashMap<>();
if (templatePath == null || requestPath == null) return params;
String[] tParts = templatePath.split("/", -1);
String[] rParts = requestPath.split("/", -1);
if (tParts.length != rParts.length) return params;
for (int i = 0; i < tParts.length; i++) {
String t = tParts[i];
if (t.startsWith("{") && t.endsWith("}")) {
String name = t.substring(1, t.length() - 1);
if (!name.endsWith("+")) { // skip {proxy+}
params.put(name, rParts[i]);
}
}
}
return params;
}
}
@@ -41,30 +41,45 @@ public class VtlTemplateEngine {
engine.init();
}
/**
* Result returned by {@link #evaluate(String, VtlContext)} that carries both the
* rendered template body and any {@code $context.responseOverride} values the template
* set during evaluation.
*/
public record EvaluateResult(
String body,
Integer statusOverride,
Map<String, String> headerOverrides
) {}
/**
* Evaluates a VTL template with the given request context.
*
* @param template the VTL template string
* @param ctx the request context
* @return the evaluated template output
* @return result containing the rendered body and any {@code $context.responseOverride} assignments
*/
public String evaluate(String template, VtlContext ctx) {
public EvaluateResult evaluate(String template, VtlContext ctx) {
ResponseOverride override = new ResponseOverride();
if (template == null || template.isEmpty()) {
return ctx.body() != null ? ctx.body() : "";
return new EvaluateResult(ctx.body() != null ? ctx.body() : "", null, Map.of());
}
VelocityContext vc = new VelocityContext();
vc.put("input", new InputVariable(ctx, objectMapper));
vc.put("util", new UtilVariable(objectMapper));
vc.put("context", buildContextMap(ctx));
vc.put("context", buildContextMap(ctx, override));
vc.put("stageVariables", ctx.stageVariables() != null ? ctx.stageVariables() : Map.of());
StringWriter writer = new StringWriter();
engine.evaluate(vc, writer, "apigw-template", template);
return writer.toString();
return new EvaluateResult(
writer.toString(),
override.getStatus(),
override.getHeader().isEmpty() ? Map.of() : Map.copyOf(override.getHeader()));
}
private Map<String, Object> buildContextMap(VtlContext ctx) {
private Map<String, Object> buildContextMap(VtlContext ctx, ResponseOverride responseOverride) {
Map<String, Object> map = new HashMap<>();
map.put("requestId", ctx.requestId());
map.put("stage", ctx.stage());
@@ -76,9 +91,41 @@ public class VtlTemplateEngine {
identity.put("sourceIp", "127.0.0.1");
map.put("identity", identity);
map.put("responseOverride", responseOverride);
return map;
}
/**
* Mutable holder for {@code $context.responseOverride} assignments made inside VTL templates.
*
* <p>Velocity calls the JavaBean setters when a template contains:
* <pre>{@code
* #set($context.responseOverride.status = 500)
* #set($context.responseOverride.header["Content-Type"] = "application/problem+json")
* }</pre>
*
* <p>The first form calls {@link #setStatus(Integer)}.
* The second form calls {@link #getHeader()} (which returns a mutable Map) followed by
* {@code map.put("Content-Type", "application/problem+json")}.
*/
public static class ResponseOverride {
private Integer status;
private final Map<String, String> header = new HashMap<>();
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Map<String, String> getHeader() {
return header;
}
}
// ────────── Context variable classes ──────────
/**
@@ -69,82 +69,102 @@ public class AslExecutor {
*/
public void executeAsync(StateMachine sm, Execution exec, List<HistoryEvent> history,
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
executor.submit(() -> {
try {
AtomicLong eventId = new AtomicLong(history.size());
JsonNode definition = objectMapper.readTree(sm.getDefinition());
JsonNode states = definition.path("States");
String startAt = definition.path("StartAt").asText();
String topLevelQueryLanguage = definition.path("QueryLanguage").asText("JSONPath");
JsonNode currentInput = parseInput(exec.getInput());
JsonNode execContext = buildContext(exec, sm);
executor.submit(() -> doExecute(sm, exec, history, onUpdate));
}
String currentStateName = startAt;
while (currentStateName != null) {
JsonNode stateDef = states.path(currentStateName);
if (stateDef.isMissingNode()) {
throw new RuntimeException("State not found: " + currentStateName);
}
/**
* Runs execution synchronously on the calling thread. Blocks until the execution completes.
*/
public void executeSync(StateMachine sm, Execution exec, List<HistoryEvent> history,
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
try {
Future<?> f = executor.submit(() -> doExecute(sm, exec, history, onUpdate));
f.get(300, TimeUnit.SECONDS);
} catch (java.util.concurrent.TimeoutException e) {
exec.setStatus("TIMED_OUT");
exec.setStopDate(System.currentTimeMillis() / 1000.0);
onUpdate.accept(exec, history);
} catch (Exception e) {
LOG.warnv("Sync execution wait failed for {0}: {1}", exec.getExecutionArn(), e.getMessage());
}
}
String type = stateDef.path("Type").asText();
addEvent(history, eventId, stateEnteredEventType(type), null,
Map.of("name", currentStateName, "input", currentInput.toString()));
private void doExecute(StateMachine sm, Execution exec, List<HistoryEvent> history,
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
try {
AtomicLong eventId = new AtomicLong(history.size());
JsonNode definition = objectMapper.readTree(sm.getDefinition());
JsonNode states = definition.path("States");
String startAt = definition.path("StartAt").asText();
String topLevelQueryLanguage = definition.path("QueryLanguage").asText("JSONPath");
JsonNode currentInput = parseInput(exec.getInput());
JsonNode execContext = buildContext(exec, sm);
// Update per-state context fields
updateStateContext(execContext, currentStateName);
try {
boolean jsonata = isJsonata(stateDef, topLevelQueryLanguage);
StateResult stateResult = executeState(currentStateName, type, stateDef, currentInput,
history, eventId, sm, jsonata, topLevelQueryLanguage, execContext);
addEvent(history, eventId, stateExitedEventType(type), eventId.get() - 1,
Map.of("name", currentStateName, "output", stateResult.output().toString()));
currentInput = stateResult.output();
currentStateName = stateResult.nextState();
if ("Succeed".equals(type) || stateDef.path("End").asBoolean(false)) {
currentStateName = null;
}
} catch (FailStateException e) {
exec.setStatus("FAILED");
exec.setStopDate(System.currentTimeMillis() / 1000.0);
String failError = e.error != null ? e.error : "States.Runtime";
String failCause = e.cause != null ? e.cause : "";
exec.setError(failError);
exec.setCause(failCause);
addEvent(history, eventId, "ExecutionFailed", null,
Map.of("error", failError, "cause", failCause));
onUpdate.accept(exec, history);
return;
} catch (Exception e) {
exec.setStatus("FAILED");
exec.setStopDate(System.currentTimeMillis() / 1000.0);
String runtimeError = "States.Runtime";
String runtimeCause = e.getMessage() != null ? e.getMessage() : "Unknown error";
exec.setError(runtimeError);
exec.setCause(runtimeCause);
addEvent(history, eventId, "ExecutionFailed", null,
Map.of("error", runtimeError, "cause", runtimeCause));
onUpdate.accept(exec, history);
return;
}
String currentStateName = startAt;
while (currentStateName != null) {
JsonNode stateDef = states.path(currentStateName);
if (stateDef.isMissingNode()) {
throw new RuntimeException("State not found: " + currentStateName);
}
exec.setStatus("SUCCEEDED");
exec.setOutput(currentInput.toString());
exec.setStopDate(System.currentTimeMillis() / 1000.0);
addEvent(history, eventId, "ExecutionSucceeded", null,
Map.of("output", currentInput.toString()));
onUpdate.accept(exec, history);
String type = stateDef.path("Type").asText();
addEvent(history, eventId, stateEnteredEventType(type), null,
Map.of("name", currentStateName, "input", currentInput.toString()));
} catch (Exception e) {
LOG.warnv("ASL execution failed for {0}: {1}", exec.getExecutionArn(), e.getMessage());
exec.setStatus("FAILED");
exec.setStopDate(System.currentTimeMillis() / 1000.0);
onUpdate.accept(exec, history);
// Update per-state context fields
updateStateContext(execContext, currentStateName);
try {
boolean jsonata = isJsonata(stateDef, topLevelQueryLanguage);
StateResult stateResult = executeState(currentStateName, type, stateDef, currentInput,
history, eventId, sm, jsonata, topLevelQueryLanguage, execContext);
addEvent(history, eventId, stateExitedEventType(type), eventId.get() - 1,
Map.of("name", currentStateName, "output", stateResult.output().toString()));
currentInput = stateResult.output();
currentStateName = stateResult.nextState();
if ("Succeed".equals(type) || stateDef.path("End").asBoolean(false)) {
currentStateName = null;
}
} catch (FailStateException e) {
exec.setStatus("FAILED");
exec.setStopDate(System.currentTimeMillis() / 1000.0);
String failError = e.error != null ? e.error : "States.Runtime";
String failCause = e.cause != null ? e.cause : "";
exec.setError(failError);
exec.setCause(failCause);
addEvent(history, eventId, "ExecutionFailed", null,
Map.of("error", failError, "cause", failCause));
onUpdate.accept(exec, history);
return;
} catch (Exception e) {
exec.setStatus("FAILED");
exec.setStopDate(System.currentTimeMillis() / 1000.0);
String runtimeError = "States.Runtime";
String runtimeCause = e.getMessage() != null ? e.getMessage() : "Unknown error";
exec.setError(runtimeError);
exec.setCause(runtimeCause);
addEvent(history, eventId, "ExecutionFailed", null,
Map.of("error", runtimeError, "cause", runtimeCause));
onUpdate.accept(exec, history);
return;
}
}
});
exec.setStatus("SUCCEEDED");
exec.setOutput(currentInput.toString());
exec.setStopDate(System.currentTimeMillis() / 1000.0);
addEvent(history, eventId, "ExecutionSucceeded", null,
Map.of("output", currentInput.toString()));
onUpdate.accept(exec, history);
} catch (Exception e) {
LOG.warnv("ASL execution failed for {0}: {1}", exec.getExecutionArn(), e.getMessage());
exec.setStatus("FAILED");
exec.setStopDate(System.currentTimeMillis() / 1000.0);
onUpdate.accept(exec, history);
}
}
private StateResult executeState(String name, String type, JsonNode stateDef, JsonNode input,
@@ -292,7 +312,13 @@ public class AslExecutor {
switch (operation) {
case "putItem" -> {
JsonNode item = input.path("Item");
dynamoDbService.putItem(tableName, item, region);
String conditionExpr = input.has("ConditionExpression")
? input.get("ConditionExpression").asText() : null;
JsonNode exprAttrNames = input.has("ExpressionAttributeNames")
? input.get("ExpressionAttributeNames") : null;
JsonNode exprAttrValues = input.has("ExpressionAttributeValues")
? input.get("ExpressionAttributeValues") : null;
dynamoDbService.putItem(tableName, item, conditionExpr, exprAttrNames, exprAttrValues, region);
return objectMapper.createObjectNode();
}
case "getItem" -> {
@@ -306,9 +332,34 @@ public class AslExecutor {
}
case "deleteItem" -> {
JsonNode key = input.path("Key");
dynamoDbService.deleteItem(tableName, key, region);
String conditionExpr = input.has("ConditionExpression")
? input.get("ConditionExpression").asText() : null;
JsonNode exprAttrNames = input.has("ExpressionAttributeNames")
? input.get("ExpressionAttributeNames") : null;
JsonNode exprAttrValues = input.has("ExpressionAttributeValues")
? input.get("ExpressionAttributeValues") : null;
dynamoDbService.deleteItem(tableName, key, conditionExpr, exprAttrNames, exprAttrValues, region);
return objectMapper.createObjectNode();
}
case "scan" -> {
String filterExpression = input.has("FilterExpression")
? input.get("FilterExpression").asText() : null;
JsonNode exprAttrNames = input.has("ExpressionAttributeNames")
? input.get("ExpressionAttributeNames") : null;
JsonNode exprAttrValues = input.has("ExpressionAttributeValues")
? input.get("ExpressionAttributeValues") : null;
Integer limit = input.has("Limit") ? input.get("Limit").asInt() : null;
JsonNode scanFilter = input.has("ScanFilter") ? input.get("ScanFilter") : null;
DynamoDbService.ScanResult scanResult = dynamoDbService.scan(
tableName, filterExpression, exprAttrNames, exprAttrValues, scanFilter, limit, null, region);
ObjectNode response = objectMapper.createObjectNode();
com.fasterxml.jackson.databind.node.ArrayNode items = objectMapper.createArrayNode();
scanResult.items().forEach(items::add);
response.set("Items", items);
response.put("Count", scanResult.items().size());
response.put("ScannedCount", scanResult.scannedCount());
return response;
}
case "updateItem" -> {
JsonNode key = input.path("Key");
JsonNode attributeUpdates = input.has("AttributeUpdates")
@@ -770,6 +821,9 @@ public class AslExecutor {
if (path == null || "$".equals(path)) {
return root;
}
if (path.startsWith("States.")) {
return evaluateIntrinsic(path, root);
}
if (!path.startsWith("$.")) {
return NullNode.getInstance();
}
@@ -793,6 +847,156 @@ public class AslExecutor {
return current.isMissingNode() ? NullNode.getInstance() : current;
}
/**
* Evaluate a JSONPath-mode intrinsic function (States.*).
* Supports: States.StringToJson, States.JsonToString, States.Format,
* States.Array, States.ArrayLength, States.MathAdd, States.UUID.
* Throws FailStateException("States.Runtime") for unrecognized functions.
*/
private JsonNode evaluateIntrinsic(String expr, JsonNode root) {
int parenOpen = expr.indexOf('(');
int parenClose = expr.lastIndexOf(')');
if (parenOpen < 0 || parenClose < 0) {
throw new FailStateException("States.Runtime", "Malformed intrinsic function: " + expr);
}
String fnName = expr.substring(0, parenOpen).trim();
String argsStr = expr.substring(parenOpen + 1, parenClose).trim();
return switch (fnName) {
case "States.StringToJson" -> {
JsonNode arg = resolveIntrinsicArg(argsStr, root);
try {
yield objectMapper.readTree(arg.asText());
} catch (Exception e) {
throw new FailStateException("States.Runtime",
"States.StringToJson could not parse: " + arg.asText());
}
}
case "States.JsonToString" -> {
JsonNode arg = resolveIntrinsicArg(argsStr, root);
try {
yield objectMapper.getNodeFactory().textNode(objectMapper.writeValueAsString(arg));
} catch (Exception e) {
throw new FailStateException("States.Runtime", "States.JsonToString failed: " + e.getMessage());
}
}
case "States.Format" -> {
List<String> parts = splitIntrinsicArgs(argsStr);
if (parts.isEmpty()) {
throw new FailStateException("States.Runtime", "States.Format requires at least one argument");
}
String template = unquoteString(parts.get(0));
StringBuilder sb = new StringBuilder();
int argIdx = 1;
for (int i = 0; i < template.length(); i++) {
if (i + 1 < template.length() && template.charAt(i) == '{' && template.charAt(i + 1) == '}') {
if (argIdx >= parts.size()) {
throw new FailStateException("States.Runtime", "States.Format: not enough arguments");
}
JsonNode argVal = resolveIntrinsicArg(parts.get(argIdx++).trim(), root);
sb.append(argVal.isTextual() ? argVal.asText() : argVal.toString());
i++; // skip '}'
} else {
sb.append(template.charAt(i));
}
}
yield objectMapper.getNodeFactory().textNode(sb.toString());
}
case "States.Array" -> {
List<String> parts = splitIntrinsicArgs(argsStr);
ArrayNode arr = objectMapper.createArrayNode();
for (String part : parts) {
arr.add(resolveIntrinsicArg(part.trim(), root));
}
yield arr;
}
case "States.ArrayLength" -> {
JsonNode arg = resolveIntrinsicArg(argsStr, root);
if (!arg.isArray()) {
throw new FailStateException("States.Runtime", "States.ArrayLength requires an array");
}
yield objectMapper.getNodeFactory().numberNode(arg.size());
}
case "States.MathAdd" -> {
List<String> parts = splitIntrinsicArgs(argsStr);
if (parts.size() != 2) {
throw new FailStateException("States.Runtime", "States.MathAdd requires exactly 2 arguments");
}
JsonNode a = resolveIntrinsicArg(parts.get(0).trim(), root);
JsonNode b = resolveIntrinsicArg(parts.get(1).trim(), root);
yield objectMapper.getNodeFactory().numberNode(a.asLong() + b.asLong());
}
case "States.UUID" -> {
yield objectMapper.getNodeFactory().textNode(java.util.UUID.randomUUID().toString());
}
default -> throw new FailStateException("States.Runtime",
"Unsupported intrinsic function: " + fnName);
};
}
/**
* Resolve a single intrinsic argument: either a $.path reference, a quoted string literal,
* or a numeric literal.
*/
private JsonNode resolveIntrinsicArg(String arg, JsonNode root) {
arg = arg.trim();
if (arg.startsWith("$.") || "$".equals(arg)) {
return resolvePath(arg, root);
}
if (arg.startsWith("'") && arg.endsWith("'")) {
return objectMapper.getNodeFactory().textNode(arg.substring(1, arg.length() - 1));
}
if (arg.startsWith("\"") && arg.endsWith("\"")) {
return objectMapper.getNodeFactory().textNode(arg.substring(1, arg.length() - 1));
}
try {
return objectMapper.getNodeFactory().numberNode(Long.parseLong(arg));
} catch (NumberFormatException e1) {
try {
return objectMapper.getNodeFactory().numberNode(Double.parseDouble(arg));
} catch (NumberFormatException e2) {
// fall through: treat as bare path
return resolvePath(arg, root);
}
}
}
/**
* Split a comma-separated intrinsic args string, respecting nested parentheses and quoted strings.
*/
private List<String> splitIntrinsicArgs(String argsStr) {
List<String> result = new ArrayList<>();
int depth = 0;
boolean inSingleQuote = false;
boolean inDoubleQuote = false;
int start = 0;
for (int i = 0; i < argsStr.length(); i++) {
char c = argsStr.charAt(i);
if (c == '\'' && !inDoubleQuote) inSingleQuote = !inSingleQuote;
else if (c == '"' && !inSingleQuote) inDoubleQuote = !inDoubleQuote;
else if (!inSingleQuote && !inDoubleQuote) {
if (c == '(') depth++;
else if (c == ')') depth--;
else if (c == ',' && depth == 0) {
result.add(argsStr.substring(start, i).trim());
start = i + 1;
}
}
}
if (start < argsStr.length()) {
result.add(argsStr.substring(start).trim());
}
return result;
}
private String unquoteString(String s) {
s = s.trim();
if ((s.startsWith("'") && s.endsWith("'")) || (s.startsWith("\"") && s.endsWith("\""))) {
return s.substring(1, s.length() - 1);
}
return s;
}
private void setPath(ObjectNode root, String path, JsonNode value) {
if (!path.startsWith("$.") && !"$".equals(path)) {
return;
@@ -12,6 +12,8 @@ import jakarta.inject.Inject;
import java.util.Iterator;
import java.util.Map;
import static io.github.hectorvent.floci.services.stepfunctions.AslExecutor.FailStateException;
import static com.dashjoin.jsonata.Jsonata.jsonata;
/**
@@ -50,6 +52,15 @@ public class JsonataEvaluator {
/**
* Evaluate a single JSONata expression string with $states bound.
* The expression may or may not have {% %} delimiters.
*
* <p><b>Singleton sequence reduction:</b>
* Both real AWS Step Functions and the JSONata spec apply singleton sequence reduction:
* a 1-element sequence produced by an object-mapping expression (e.g.
* {@code $states.result.Items.{"id": id}}) is reduced to the single object rather than
* remaining a 1-element array. Floci's behavior matches AWS.
*
* <p>To force an array regardless of element count, wrap in {@code [...]}, e.g.
* {@code [$states.result.Items.{"id": id}]}.
*/
JsonNode evaluate(String expression, JsonNode statesVar) {
String expr = isExpression(expression) ? unwrap(expression) : expression;
@@ -87,14 +98,28 @@ public class JsonataEvaluator {
Iterator<Map.Entry<String, JsonNode>> fields = template.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> entry = fields.next();
resolved.set(entry.getKey(), resolveTemplate(entry.getValue(), statesVar));
JsonNode value = resolveTemplate(entry.getValue(), statesVar);
// Per JSONata spec: undefined (null) values are omitted from object output,
// matching real AWS Step Functions behavior.
if (value != null && !value.isNull() && !value.isMissingNode()) {
resolved.set(entry.getKey(), value);
}
}
return resolved;
}
if (template.isArray()) {
ArrayNode resolved = objectMapper.createArrayNode();
for (JsonNode element : template) {
resolved.add(resolveTemplate(element, statesVar));
for (int i = 0; i < template.size(); i++) {
JsonNode element = template.get(i);
JsonNode value = resolveTemplate(element, statesVar);
// 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()) {
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);
}
return resolved;
}
@@ -33,6 +33,7 @@ public class StepFunctionsJsonHandler {
case "ListStateMachines" -> handleListStateMachines(request, region);
case "DeleteStateMachine" -> handleDeleteStateMachine(request);
case "StartExecution" -> handleStartExecution(request, region);
case "StartSyncExecution" -> handleStartSyncExecution(request, region);
case "DescribeExecution" -> handleDescribeExecution(request);
case "ListExecutions" -> handleListExecutions(request);
case "StopExecution" -> handleStopExecution(request);
@@ -105,6 +106,27 @@ public class StepFunctionsJsonHandler {
return Response.ok(response).build();
}
private Response handleStartSyncExecution(JsonNode request, String region) {
Execution exec = service.startSyncExecution(
request.path("stateMachineArn").asText(),
request.path("name").asText(null),
request.path("input").asText(null),
region
);
ObjectNode response = objectMapper.createObjectNode();
response.put("executionArn", exec.getExecutionArn());
response.put("stateMachineArn", exec.getStateMachineArn());
response.put("name", exec.getName());
response.put("status", exec.getStatus());
response.put("startDate", exec.getStartDate());
if (exec.getStopDate() != null) response.put("stopDate", exec.getStopDate());
if (exec.getInput() != null) response.put("input", exec.getInput());
if (exec.getOutput() != null) response.put("output", exec.getOutput());
if (exec.getError() != null) response.put("error", exec.getError());
if (exec.getCause() != null) response.put("cause", exec.getCause());
return Response.ok(response).build();
}
private Response handleDescribeExecution(JsonNode request) {
Execution exec = service.describeExecution(request.path("executionArn").asText());
ObjectNode response = objectMapper.createObjectNode();
@@ -14,6 +14,9 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@@ -29,6 +32,8 @@ public class StepFunctionsService {
private final AslExecutor aslExecutor;
private final ObjectMapper objectMapper;
// Fields that are valid only in JSONPath mode. Validated against real AWS:
// creating a JSONata state machine with any of these fields returns SCHEMA_VALIDATION_FAILED.
private static final Set<String> JSONPATH_ONLY_FIELDS = Set.of(
"InputPath", "OutputPath", "ResultPath", "ResultSelector", "Parameters", "Result", "ItemsPath");
@@ -122,6 +127,44 @@ public class StepFunctionsService {
return exec;
}
public Execution startSyncExecution(String stateMachineArn, String name, String input, String region) {
StateMachine sm = describeStateMachine(stateMachineArn);
if (!"EXPRESS".equals(sm.getType())) {
throw new AwsException("StateMachineTypeNotSupported",
"StartSyncExecution is only supported for EXPRESS state machines", 400);
}
String execName = (name != null && !name.isBlank()) ? name : UUID.randomUUID().toString();
// Real AWS express execution ARN format: express:<smName>:<startDate>:<execName>
// where startDate is ISO-8601 UTC, e.g. 2024-01-15T10:30:00.123Z
String startDate = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.withZone(ZoneOffset.UTC)
.format(Instant.now());
String arn = regionResolver.buildArn("states", region,
"express:" + sm.getName() + ":" + startDate + ":" + execName);
Execution exec = new Execution();
exec.setExecutionArn(arn);
exec.setStateMachineArn(stateMachineArn);
exec.setName(execName);
exec.setInput(input);
exec.setStatus("RUNNING");
List<HistoryEvent> history = new ArrayList<>();
HistoryEvent startEvent = new HistoryEvent();
startEvent.setId(1L);
startEvent.setType("ExecutionStarted");
startEvent.setDetails(Map.of("input", input != null ? input : "{}",
"roleArn", sm.getRoleArn() != null ? sm.getRoleArn() : ""));
history.add(startEvent);
aslExecutor.executeSync(sm, exec, history, (updatedExec, updatedHistory) -> {
LOG.infov("Sync execution {0} completed with status {1}", updatedExec.getExecutionArn(), updatedExec.getStatus());
});
return exec;
}
public Execution describeExecution(String arn) {
return executionStore.get(arn)
.orElseThrow(() -> new AwsException("ExecutionDoesNotExist", "Execution does not exist", 400));
@@ -205,11 +248,6 @@ public class StepFunctionsService {
String stateQL = stateDef.path("QueryLanguage").asText(null);
boolean stateIsJsonata = stateQL != null ? "JSONata".equals(stateQL) : topLevelJsonata;
// Cannot override to JSONPath when top-level is JSONata
if (topLevelJsonata && "JSONPath".equals(stateQL)) {
errors.add("'QueryLanguage' can not be 'JSONPath' if set to 'JSONata' for whole state machine at /States/" + stateName);
}
// JSONPath-only fields are not allowed when the state uses JSONata
if (stateIsJsonata) {
for (String field : JSONPATH_ONLY_FIELDS) {