Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

thegagne53dd7a68dd79
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
index d4f821cad3..a4fe7b8209 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
@@ -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;
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.java
index 8f83f4f4a1..20cc982d03 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngine.java
@@ -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 ──────────
/**
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java
index b54581a236..f758be5923 100644
--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java
@@ -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);
-
- String currentStateName = startAt;
- while (currentStateName != null) {
- JsonNode stateDef = states.path(currentStateName);
- if (stateDef.isMissingNode()) {
- throw new RuntimeException("State not found: " + currentStateName);
- }
+ executor.submit(() -> doExecute(sm, exec, history, onUpdate));
+ }
+
+ /**
+ * 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);
+
+ String currentStateName = startAt;
+ while (currentStateName != null) {
+ JsonNode stateDef = states.path(currentStateName);
+ if (stateDef.isMissingNode()) {
+ throw new RuntimeException("State not found: " + currentStateName);
+ }
- // Update per-state context fields
- updateStateContext(execContext, currentStateName);
+ String type = stateDef.path("Type").asText();
+ addEvent(history, eventId, stateEnteredEventType(type), null,
+ Map.of("name", currentStateName, "input", currentInput.toString()));
- 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()));
+ // Update per-state context fields
+ updateStateContext(execContext, currentStateName);
- currentInput = stateResult.output();
- currentStateName = stateResult.nextState();
+ 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()));
- 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;
+ 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);
+ 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);
- }
- });
+ } 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;
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEvaluator.java
index 9041325392..63cf4a6c18 100644
--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEvaluator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEvaluator.java
@@ -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;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java
index a6aafbf830..72ef6ed23b 100644
--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java
@@ -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();
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java
index 0fdad0febc..b18b9f48f3 100644
--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java
@@ -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) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.java
index ad3607e7b2..89627429e7 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/VtlTemplateEngineTest.java
@@ -32,25 +32,25 @@ class VtlTemplateEngineTest {
@Test
void passthrough_nullTemplate() {
- String result = engine.evaluate(null, ctx("{\"key\":\"value\"}"));
+ String result = engine.evaluate(null, ctx("{\"key\":\"value\"}")).body();
assertEquals("{\"key\":\"value\"}", result);
}
@Test
void passthrough_emptyTemplate() {
- String result = engine.evaluate("", ctx("{\"key\":\"value\"}"));
+ String result = engine.evaluate("", ctx("{\"key\":\"value\"}")).body();
assertEquals("{\"key\":\"value\"}", result);
}
@Test
void inputBody() {
- String result = engine.evaluate("$input.body()", ctx("{\"key\":\"value\"}"));
+ String result = engine.evaluate("$input.body()", ctx("{\"key\":\"value\"}")).body();
assertEquals("{\"key\":\"value\"}", result);
}
@Test
void inputJson_root() {
- String result = engine.evaluate("$input.json('$')", ctx("{\"name\":\"Alice\",\"age\":30}"));
+ String result = engine.evaluate("$input.json('$')", ctx("{\"name\":\"Alice\",\"age\":30}")).body();
// Should return the full body as JSON
assertTrue(result.contains("Alice"));
assertTrue(result.contains("30"));
@@ -58,38 +58,38 @@ class VtlTemplateEngineTest {
@Test
void inputJson_nested() {
- String result = engine.evaluate("$input.json('$.name')", ctx("{\"name\":\"Bob\"}"));
+ String result = engine.evaluate("$input.json('$.name')", ctx("{\"name\":\"Bob\"}")).body();
assertEquals("\"Bob\"", result);
}
@Test
void inputPath() {
- String result = engine.evaluate("$input.path('$.name')", ctx("{\"name\":\"Carol\"}"));
+ String result = engine.evaluate("$input.path('$.name')", ctx("{\"name\":\"Carol\"}")).body();
assertEquals("Carol", result);
}
@Test
void inputParams() {
- String result = engine.evaluate("$input.params().querystring.limit", ctx("{}"));
+ String result = engine.evaluate("$input.params().querystring.limit", ctx("{}")).body();
assertEquals("10", result);
}
@Test
void utilEscapeJavaScript_singleQuotes() {
String body = "{\"msg\":\"hello 'world'\"}";
- String result = engine.evaluate("$util.escapeJavaScript($input.body())", ctx(body));
+ String result = engine.evaluate("$util.escapeJavaScript($input.body())", ctx(body)).body();
assertTrue(result.contains("\\'world\\'"), "Single quotes should be escaped: " + result);
}
@Test
void utilEscapeJavaScript_doubleQuotes() {
- String result = engine.evaluate("$util.escapeJavaScript('he said \"hi\"')", ctx("{}"));
+ String result = engine.evaluate("$util.escapeJavaScript('he said \"hi\"')", ctx("{}")).body();
assertEquals("he said \\\"hi\\\"", result);
}
@Test
void utilEscapeJavaScript_forwardSlash() {
- String result = engine.evaluate("$util.escapeJavaScript('a/b/c')", ctx("{}"));
+ String result = engine.evaluate("$util.escapeJavaScript('a/b/c')", ctx("{}")).body();
assertEquals("a\\/b\\/c", result);
}
@@ -124,19 +124,19 @@ class VtlTemplateEngineTest {
@Test
void utilUrlEncodeDecode() {
- String result = engine.evaluate("$util.urlEncode('hello world')", ctx("{}"));
+ String result = engine.evaluate("$util.urlEncode('hello world')", ctx("{}")).body();
assertEquals("hello+world", result);
- String decoded = engine.evaluate("$util.urlDecode('hello+world')", ctx("{}"));
+ String decoded = engine.evaluate("$util.urlDecode('hello+world')", ctx("{}")).body();
assertEquals("hello world", decoded);
}
@Test
void utilBase64EncodeDecode() {
- String encoded = engine.evaluate("$util.base64Encode('test data')", ctx("{}"));
+ String encoded = engine.evaluate("$util.base64Encode('test data')", ctx("{}")).body();
assertEquals("dGVzdCBkYXRh", encoded);
- String decoded = engine.evaluate("$util.base64Decode('dGVzdCBkYXRh')", ctx("{}"));
+ String decoded = engine.evaluate("$util.base64Decode('dGVzdCBkYXRh')", ctx("{}")).body();
assertEquals("test data", decoded);
}
@@ -144,13 +144,13 @@ class VtlTemplateEngineTest {
void contextVariables() {
String result = engine.evaluate(
"$context.stage:$context.httpMethod:$context.resourcePath:$context.requestId",
- ctx("{}"));
+ ctx("{}")).body();
assertEquals("prod:POST:/users:req-123", result);
}
@Test
void contextIdentity() {
- String result = engine.evaluate("$context.identity.sourceIp", ctx("{}"));
+ String result = engine.evaluate("$context.identity.sourceIp", ctx("{}")).body();
assertEquals("127.0.0.1", result);
}
@@ -159,7 +159,7 @@ class VtlTemplateEngineTest {
VtlTemplateEngine.VtlContext svCtx = new VtlTemplateEngine.VtlContext(
"{}", Map.of(), Map.of(), Map.of(), "prod", "GET", "/",
"req-1", "000000000000", Map.of("tableName", "my-table"));
- String result = engine.evaluate("$stageVariables.tableName", svCtx);
+ String result = engine.evaluate("$stageVariables.tableName", svCtx).body();
assertEquals("my-table", result);
}
@@ -168,7 +168,7 @@ class VtlTemplateEngineTest {
String template = """
{"stateMachineArn": "arn:aws:states:us-east-1:000:sm:test", "input": "$util.escapeJavaScript($input.json('$'))"}""";
String body = "{\"id\":\"123\",\"message\":\"hello\"}";
- String result = engine.evaluate(template, ctx(body));
+ String result = engine.evaluate(template, ctx(body)).body();
assertTrue(result.contains("arn:aws:states:us-east-1:000:sm:test"));
assertTrue(result.contains("\\\"id\\\""));
@@ -183,34 +183,34 @@ class VtlTemplateEngineTest {
String template = """
#set($body = $input.path('$'))
{"value": "$body.name"}""";
- String result = engine.evaluate(template, ctx("{\"name\":\"Dave\"}")).trim();
+ String result = engine.evaluate(template, ctx("{\"name\":\"Dave\"}")).body().trim();
assertTrue(result.contains("Dave"));
}
@Test
void inputJson_arrayIndex() {
String body = "{\"items\":[{\"id\":\"first\"},{\"id\":\"second\"}]}";
- String result = engine.evaluate("$input.json('$.items[0].id')", ctx(body));
+ String result = engine.evaluate("$input.json('$.items[0].id')", ctx(body)).body();
assertEquals("\"first\"", result);
}
@Test
void inputJson_arrayIndexNested() {
String body = "{\"data\":[[[\"deep\"]]]}";
- String result = engine.evaluate("$input.json('$.data[0][0][0]')", ctx(body));
+ String result = engine.evaluate("$input.json('$.data[0][0][0]')", ctx(body)).body();
assertEquals("\"deep\"", result);
}
@Test
void inputPath_arrayIndex() {
String body = "{\"users\":[{\"name\":\"Eve\"},{\"name\":\"Frank\"}]}";
- String result = engine.evaluate("$input.path('$.users[1].name')", ctx(body));
+ String result = engine.evaluate("$input.path('$.users[1].name')", ctx(body)).body();
assertEquals("Frank", result);
}
@Test
void nullBody() {
- String result = engine.evaluate("$input.body()", ctx(null));
+ String result = engine.evaluate("$input.body()", ctx(null)).body();
assertEquals("", result);
}
@@ -221,7 +221,7 @@ class VtlTemplateEngineTest {
String body = "{\"names\":[\"Alice\",\"Bob\",\"Carol\"]}";
String template = "#set($names = $input.path('$.names'))\n"
+ "[#foreach($name in $names)\"$name\"#if($foreach.hasNext),#end#end]";
- String result = engine.evaluate(template, ctx(body)).trim();
+ String result = engine.evaluate(template, ctx(body)).body().trim();
assertEquals("[\"Alice\",\"Bob\",\"Carol\"]", result);
}
@@ -233,7 +233,7 @@ class VtlTemplateEngineTest {
+ "{\"results\": [#foreach($item in $items)"
+ "{\"key\": \"$item.id\"}#if($foreach.hasNext),#end"
+ "#end]}";
- String result = engine.evaluate(template, ctx(body)).trim();
+ String result = engine.evaluate(template, ctx(body)).body().trim();
assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
var node = assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
assertEquals(2, node.path("results").size());
@@ -247,7 +247,7 @@ class VtlTemplateEngineTest {
String body = "{\"type\":\"premium\"}";
String template = "#set($type = $input.path('$.type'))\n"
+ "#if($type == 'premium')PREMIUM#else STANDARD#end";
- String result = engine.evaluate(template, ctx(body)).trim();
+ String result = engine.evaluate(template, ctx(body)).body().trim();
assertEquals("PREMIUM", result);
}
@@ -256,7 +256,7 @@ class VtlTemplateEngineTest {
String body = "{\"type\":\"basic\"}";
String template = "#set($type = $input.path('$.type'))\n"
+ "#if($type == 'premium')PREMIUM#else STANDARD#end";
- String result = engine.evaluate(template, ctx(body)).trim();
+ String result = engine.evaluate(template, ctx(body)).body().trim();
assertEquals("STANDARD", result);
}
@@ -266,7 +266,7 @@ class VtlTemplateEngineTest {
String body = "{\"name\":\"test\"}";
String template = "#set($desc = $input.path('$.description'))\n"
+ "#if($desc && $desc != '')HAS_DESC#else NO_DESC#end";
- String result = engine.evaluate(template, ctx(body)).trim();
+ String result = engine.evaluate(template, ctx(body)).body().trim();
assertEquals("NO_DESC", result);
}
@@ -278,7 +278,7 @@ class VtlTemplateEngineTest {
String body = "{\"orderId\":\"123\",\"amount\":99.95}";
String template = """
{"QueueUrl": "http://localhost:4566/000000000000/my-queue", "MessageBody": "$util.escapeJavaScript($input.json('$'))"}""";
- String result = engine.evaluate(template, ctx(body));
+ String result = engine.evaluate(template, ctx(body)).body();
assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
var node = assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
assertEquals("http://localhost:4566/000000000000/my-queue", node.path("QueueUrl").asText());
@@ -295,7 +295,7 @@ class VtlTemplateEngineTest {
"req-456", "000000000000", Map.of("tableName", "orders"));
String template = """
{"TableName": "$stageVariables.tableName", "KeyConditionExpression": "pk = :pk", "ExpressionAttributeValues": {":pk": {"S": "$input.params().querystring.userId"}}}""";
- String result = engine.evaluate(template, queryCtx);
+ String result = engine.evaluate(template, queryCtx).body();
var node = assertDoesNotThrow(() -> new ObjectMapper().readTree(result));
assertEquals("orders", node.path("TableName").asText());
assertEquals("user-42", node.path("ExpressionAttributeValues").path(":pk").path("S").asText());
@@ -305,13 +305,13 @@ class VtlTemplateEngineTest {
@Test
void inputParams_headerAccess() {
- String result = engine.evaluate("$input.params().header.Authorization", ctx("{}"));
+ String result = engine.evaluate("$input.params().header.Authorization", ctx("{}")).body();
assertEquals("Bearer xyz", result);
}
@Test
void inputParams_pathAccess() {
- String result = engine.evaluate("$input.params().path.proxy", ctx("{}"));
+ String result = engine.evaluate("$input.params().path.proxy", ctx("{}")).body();
assertEquals("users/123", result);
}
@@ -319,7 +319,7 @@ class VtlTemplateEngineTest {
void inputParams_allTypes() {
// Access all three param types in one template
String template = "$input.params().querystring.limit|$input.params().path.proxy|$input.params().header.get('Content-Type')";
- String result = engine.evaluate(template, ctx("{}"));
+ String result = engine.evaluate(template, ctx("{}")).body();
assertTrue(result.startsWith("10|users/123|"), "Should contain all param types: " + result);
}
@@ -329,25 +329,25 @@ class VtlTemplateEngineTest {
@Test
void inputParams_shorthand_querystring() {
- String result = engine.evaluate("$input.params('limit')", ctx("{}"));
+ String result = engine.evaluate("$input.params('limit')", ctx("{}")).body();
assertEquals("10", result);
}
@Test
void inputParams_shorthand_path() {
- String result = engine.evaluate("$input.params('proxy')", ctx("{}"));
+ String result = engine.evaluate("$input.params('proxy')", ctx("{}")).body();
assertEquals("users/123", result);
}
@Test
void inputParams_shorthand_header() {
- String result = engine.evaluate("$input.params('Authorization')", ctx("{}"));
+ String result = engine.evaluate("$input.params('Authorization')", ctx("{}")).body();
assertEquals("Bearer xyz", result);
}
@Test
void inputParams_shorthand_notFound() {
- String result = engine.evaluate("$input.params('nonexistent')", ctx("{}"));
+ String result = engine.evaluate("$input.params('nonexistent')", ctx("{}")).body();
assertEquals("", result);
}
@@ -359,21 +359,56 @@ class VtlTemplateEngineTest {
Map.of("shared", "query-val"),
Map.of("shared", "path-val"),
"prod", "GET", "/", "req-1", "000000000000", Map.of());
- String result = engine.evaluate("$input.params('shared')", overlapCtx);
+ String result = engine.evaluate("$input.params('shared')", overlapCtx).body();
assertEquals("query-val", result);
}
@Test
void utilParseJson_navigateResult() {
String template = "#set($parsed = $util.parseJson('{\"a\":{\"b\":\"deep\"}}'))\n$parsed.a.b";
- String result = engine.evaluate(template, ctx("{}")).trim();
+ String result = engine.evaluate(template, ctx("{}")).body().trim();
assertEquals("deep", result);
}
@Test
void utilParseJson_withArray() {
String template = "#set($parsed = $util.parseJson('[1,2,3]'))\n$parsed.size()";
- String result = engine.evaluate(template, ctx("{}")).trim();
+ String result = engine.evaluate(template, ctx("{}")).body().trim();
assertEquals("3", result);
}
+
+ // ──────────── $context.responseOverride ────────────
+
+ @Test
+ void responseOverride_status() {
+ String template = "#set($context.responseOverride.status = 404)\nnot found";
+ VtlTemplateEngine.EvaluateResult result = engine.evaluate(template, ctx("{}"));
+ assertEquals(404, result.statusOverride());
+ assertTrue(result.body().contains("not found"));
+ }
+
+ @Test
+ void responseOverride_header() {
+ String template = "#set($context.responseOverride.header[\"Content-Type\"] = \"application/problem+json\")\nerror";
+ VtlTemplateEngine.EvaluateResult result = engine.evaluate(template, ctx("{}"));
+ assertEquals("application/problem+json", result.headerOverrides().get("Content-Type"));
+ }
+
+ @Test
+ void responseOverride_statusAndHeader() {
+ String template = """
+ #set($context.responseOverride.status = 500)
+ #set($context.responseOverride.header["X-Error"] = "internal")
+ body""";
+ VtlTemplateEngine.EvaluateResult result = engine.evaluate(template, ctx("{}"));
+ assertEquals(500, result.statusOverride());
+ assertEquals("internal", result.headerOverrides().get("X-Error"));
+ }
+
+ @Test
+ void responseOverride_notSet_returnsNulls() {
+ VtlTemplateEngine.EvaluateResult result = engine.evaluate("hello", ctx("{}"));
+ assertNull(result.statusOverride());
+ assertTrue(result.headerOverrides().isEmpty());
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEdgeCaseTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEdgeCaseTest.java
index 8860983535..e3b44fcfff 100644
--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEdgeCaseTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/JsonataEdgeCaseTest.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
+import java.util.List;
import java.util.Map;
import static com.dashjoin.jsonata.Jsonata.jsonata;
@@ -53,10 +54,6 @@ class JsonataEdgeCaseTest {
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");
}
@@ -68,9 +65,6 @@ class JsonataEdgeCaseTest {
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");
}
@@ -97,7 +91,6 @@ class JsonataEdgeCaseTest {
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
@@ -106,7 +99,6 @@ class JsonataEdgeCaseTest {
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
@@ -115,7 +107,6 @@ class JsonataEdgeCaseTest {
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;
@@ -140,7 +131,100 @@ class JsonataEdgeCaseTest {
frame.bind("states", asMap);
Object result = expr.evaluate(null, frame);
- // System.out.println("[Test 4] sum of scores: " + result);
assertEquals(60, ((Number) result).intValue());
}
+
+ // ---------------------------------------------------------------
+ // 5. Singleton sequence: 1-element array accessed via path
+ // ---------------------------------------------------------------
+ @Test
+ void singleElementArray_propertyAccess_preservedNotReduced() throws Exception {
+ // JSONata singleton-sequence rule: when path navigation through an array yields
+ // a 1-element sequence, it is reduced to the single element.
+ // BUT direct property access on an object (not an array) should NOT reduce.
+ //
+ // $states.result.Items where Items = [{...}] — $states.result is a plain object,
+ // so .Items should return the List as-is, NOT the single element.
+ var input = Map.of("result", Map.of(
+ "Items", List.of(Map.of("id", "item1", "name", "Widget One")),
+ "Count", 1
+ ));
+
+ var expr = jsonata("$states.result.Items");
+ var frame = expr.createFrame();
+ frame.bind("states", input);
+ Object result = expr.evaluate(null, frame);
+
+ // The result must be the List itself, not the single element within it.
+ assertInstanceOf(List.class, result,
+ "1-element Items array must be returned as a List (no singleton reduction)");
+ assertEquals(1, ((List<?>) result).size());
+ }
+
+ @Test
+ void multiElementArray_propertyAccess_returnsList() throws Exception {
+ var input = Map.of("result", Map.of(
+ "Items", List.of(
+ Map.of("id", "item1"),
+ Map.of("id", "item2")
+ )
+ ));
+
+ var expr = jsonata("$states.result.Items");
+ var frame = expr.createFrame();
+ frame.bind("states", input);
+ Object result = expr.evaluate(null, frame);
+
+ assertInstanceOf(List.class, result,
+ "Multi-element Items array must remain a List");
+ assertEquals(2, ((List<?>) result).size());
+ }
+
+ // ---------------------------------------------------------------
+ // 6. Path-mapping transformation: 1-element sequence from object construction
+ // e.g. items.{"field": value} — this CAN singleton-reduce in JSONata spec
+ // ---------------------------------------------------------------
+ @Test
+ void objectMapping_singleElement_behaviorDocumented() throws Exception {
+ // JSONata spec: when you do array.{key: value}, you get a sequence.
+ // A 1-element sequence IS singleton-reduced to the single element.
+ // This is correct JSONata behavior (and what AWS does too).
+ // To force an array, callers should use [$states.result.Items.{"id": id}]
+ // or $toArray(...) if available.
+ var input = Map.of("result", Map.of(
+ "Items", List.of(Map.of("id", "item1", "name", "Widget One"))
+ ));
+
+ var expr = jsonata("$states.result.Items.{\"id\": id, \"name\": name}");
+ var frame = expr.createFrame();
+ frame.bind("states", input);
+ Object result = expr.evaluate(null, frame);
+
+ // 1-element object-mapping sequence IS singleton-reduced to a plain object (Map).
+ // This matches both the JSONata spec and real AWS Step Functions behavior.
+ // Callers that need an array must wrap in []: [$states.result.Items.{"id": id}]
+ assertInstanceOf(Map.class, result, "1-element object-mapping should be singleton-reduced to a Map");
+ @SuppressWarnings("unchecked")
+ Map<String, Object> mapped = (Map<String, Object>) result;
+ assertEquals("item1", mapped.get("id"));
+ assertEquals("Widget One", mapped.get("name"));
+ }
+
+ @Test
+ void objectMapping_singleElement_wrappedInArray_forcesArray() throws Exception {
+ // Workaround: wrap the mapping expression in [] to force array output.
+ // [$states.result.Items.{"id": id}] — even for 1-element sequences, result is an array.
+ var input = Map.of("result", Map.of(
+ "Items", List.of(Map.of("id", "item1", "name", "Widget One"))
+ ));
+
+ var expr = jsonata("[$states.result.Items.{\"id\": id, \"name\": name}]");
+ var frame = expr.createFrame();
+ frame.bind("states", input);
+ Object result = expr.evaluate(null, frame);
+
+ assertInstanceOf(List.class, result,
+ "Wrapping in [] must force array output even for 1-element sequence");
+ assertEquals(1, ((List<?>) result).size());
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsDynamoDbIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsDynamoDbIntegrationTest.java
index 409bccd339..96762dc72b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsDynamoDbIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsDynamoDbIntegrationTest.java
@@ -492,6 +492,57 @@ class StepFunctionsDynamoDbIntegrationTest {
assertEquals("200", result.path("Attributes").path("score").path("N").asText());
}
+ // ──────────────── Optimized Integration: putItem + getItem ────────────────
+
+ @Test
+ @Order(71)
+ void optimized_putAndGetItem() throws Exception {
+ // Put via optimized integration
+ executeSfnOptimized("opt-put", "dynamodb:putItem", """
+ {
+ "TableName": "%s",
+ "Item": {
+ "pk": {"S": "opt-get-test"},
+ "sk": {"S": "row"},
+ "value": {"S": "hello"}
+ }
+ }
+ """.formatted(TABLE_NAME));
+
+ // Get via optimized integration — must return the item, not {}
+ String output = executeSfnOptimized("opt-get", "dynamodb:getItem", """
+ {
+ "TableName": "%s",
+ "Key": {
+ "pk": {"S": "opt-get-test"},
+ "sk": {"S": "row"}
+ }
+ }
+ """.formatted(TABLE_NAME));
+
+ JsonNode result = mapper.readTree(output);
+ assertTrue(result.has("Item"), "Optimized getItem must return Item field");
+ assertEquals("hello", result.path("Item").path("value").path("S").asText());
+ }
+
+ @Test
+ @Order(72)
+ void optimized_getItem_notFound_returnsEmptyObject() throws Exception {
+ String output = executeSfnOptimized("opt-get-missing", "dynamodb:getItem", """
+ {
+ "TableName": "%s",
+ "Key": {
+ "pk": {"S": "does-not-exist"},
+ "sk": {"S": "nope"}
+ }
+ }
+ """.formatted(TABLE_NAME));
+
+ JsonNode result = mapper.readTree(output);
+ // AWS returns {} (no Item field) when item does not exist
+ assertFalse(result.has("Item"), "Not-found getItem must return empty object (no Item field)");
+ }
+
// ──────────────── Error Handling ────────────────
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonataIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonataIntegrationTest.java
index 86cb1305b9..18986e902e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonataIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonataIntegrationTest.java
@@ -227,6 +227,65 @@ class StepFunctionsJsonataIntegrationTest {
assertTrue(output.contains("value"));
}
+ @Test
+ void jsonataPassState_withResult_rejected() {
+ // AWS rejects Result in JSONata states (SCHEMA_VALIDATION_FAILED).
+ // Result is a JSONPath-only field; the JSONata equivalent is Output.
+ String definition = """
+ {
+ "QueryLanguage": "JSONata",
+ "StartAt": "SetResult",
+ "States": {
+ "SetResult": {
+ "Type": "Pass",
+ "Result": {"status": "ok", "code": 200},
+ "End": true
+ }
+ }
+ }
+ """;
+
+ given()
+ .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
+ .contentType(SFN_CONTENT_TYPE)
+ .body(String.format("""
+ {"name":"jsonata-result-test","definition":%s,"roleArn":"%s","type":"STANDARD"}
+ """, quote(definition), ROLE_ARN))
+ .when().post("/")
+ .then().statusCode(400);
+ }
+
+ @Test
+ void jsonataPassState_withParameters_rejected() {
+ // AWS rejects Parameters in JSONata states (SCHEMA_VALIDATION_FAILED).
+ // Parameters is a JSONPath-only field; the JSONata equivalent is Arguments.
+ String definition = """
+ {
+ "QueryLanguage": "JSONata",
+ "StartAt": "PrepareData",
+ "States": {
+ "PrepareData": {
+ "Type": "Pass",
+ "Parameters": {
+ "created_at.$": "$$.Execution.StartTime"
+ },
+ "Output": {"processed": true},
+ "End": true
+ }
+ }
+ }
+ """;
+
+ given()
+ .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
+ .contentType(SFN_CONTENT_TYPE)
+ .body(String.format("""
+ {"name":"jsonata-parameters-test","definition":%s,"roleArn":"%s","type":"STANDARD"}
+ """, quote(definition), ROLE_ARN))
+ .when().post("/")
+ .then().statusCode(400);
+ }
+
// ──────────────── Helpers ────────────────
private String createStateMachine(String name, String definition) {