* fix(stepfunctions): keep a JSONata expression's explicit null in the output
A JSONata expression evaluating to JSON null lost its key, exactly as an
expression that returned nothing did. Real AWS answers {"v":null} to
Output {"v":"{% null %}"} and keeps the null in a nested object, in an
array, in Assign and in a Task's Arguments.
dashjoin flattens JSONata's null marker into a Java null unless
outputConvertNulls is off, which made the two indistinguishable inside the
evaluator. With it off, $states and the workflow variables bind through
toJsonataValue so an input null stays a null the expression can see, the
result is walked back with the marker mapped to a JSON null and a Java null
mapped to a missing node, and resolveTemplate drops only the missing node.
Closes #2664
* fix(stepfunctions): resolve a whole JSONata field that returned nothing to a null
A MissingNode is how the evaluator says "this expression returned nothing", and
resolveTemplate handed it straight to the executor when the whole Output or
Arguments field was that one expression. exec.setOutput writes the state output
with toString(), and a MissingNode writes itself as the empty string, so
DescribeExecution answered "output": "" instead of JSON.
resolveTemplate is now the boundary and answers a JSON value: a whole field that
returned nothing is a null, which is what it was before the marker existed. The
recursion moves to the private resolveTemplateNode, where "returned nothing" is
still itself in the two positions that read it, an object field it drops and an
array element it fails the state on.
AWS fails such a state with States.QueryEvaluationError; that is #2665 and stays
open.
* test(stepfunctions): read $string() with no argument as nothing, not as null
* docs(stepfunctions): mark the key dropped by an expression that returned nothing as a deviation
---------
Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
10 KiB
Step Functions
Protocol: AWS JSON 1.0 (X-Amz-Target: AWSStepFunctions.*)
Endpoint: POST http://localhost:4566/
Supported Actions
| Action | Description |
|---|---|
CreateStateMachine |
Create a state machine (Standard or Express) |
UpdateStateMachine |
Update definition, role, logging, tracing, or encryption settings and optionally publish a version |
DescribeStateMachine |
Get state machine definition and metadata |
ListStateMachines |
List all state machines |
DeleteStateMachine |
Delete a state machine |
PublishStateMachineVersion |
- |
ListStateMachineVersions |
- |
DeleteStateMachineVersion |
- |
ValidateStateMachineDefinition |
Validate an ASL definition without creating a state machine |
StartExecution |
Start a new execution |
StartSyncExecution |
- |
DescribeExecution |
Get execution status and output |
ListExecutions |
List executions for a state machine |
StopExecution |
Stop a running execution |
GetExecutionHistory |
Get the full event history of an execution |
SendTaskSuccess |
Report task success (for .waitForTaskToken tasks) |
SendTaskFailure |
Report task failure |
SendTaskHeartbeat |
Send a heartbeat for long-running tasks |
CreateActivity |
- |
DeleteActivity |
- |
DescribeActivity |
- |
ListActivities |
- |
GetActivityTask |
- |
ListTagsForResource |
- |
TagResource |
- |
UntagResource |
- |
UpdateStateMachine returns the new revision ID and update timestamp. CloudFormation updates
definition, role, logging, tracing, encryption, and tags without replacing the state machine;
changes to StateMachineName or StateMachineType use replacement semantics.
Map concurrency
Map states honor MaxConcurrency and, for JSONPath state machines, MaxConcurrencyPath.
JSONata state machines may supply MaxConcurrency as an expression. A value of 0, or an
omitted value, uses the AWS service ceiling: 40 concurrent iterations for Inline Map states and
10,000 for Distributed Map states. MaxConcurrency: 1 runs iterations sequentially.
Results remain in input order even when iterations finish out of order. If an iteration fails, the Map state fails promptly, cancels its active sibling iterations, and does not start queued iterations.
Retry policies
Task, Parallel, and Map states honor their Retry field. ErrorEquals matching
follows AWS semantics, including the States.ALL and States.TaskFailed wildcards.
States.Runtime is never retried. AWS defaults apply when fields are omitted
(MaxAttempts 3, IntervalSeconds 1, BackoffRate 2.0), MaxDelaySeconds is honored,
and each retrier keeps its own attempt counter. Retry is evaluated before Catch, and
$$.State.RetryCount increments per attempt. Attempt counts, defaults, and backoff
timing were verified against real AWS Step Functions.
JitterStrategy supports NONE (the default) and FULL. FULL draws the delay
uniformly between zero and the computed delay, as on AWS. One deviation. The delay
between attempts is capped at 30 seconds, the same cap Floci applies to Wait states,
so emulated runs stay fast.
JSONata nulls
An expression that evaluates to JSON null produces a value, not a missing one. It keeps its key
in Output, in Assign and in a Task's Arguments, at any nesting depth, and it stays in place as
an array element:
"Output": {"v": "{% $states.input.bar %}"} on input {"bar": null} -> {"v": null}
The same null is a value inside the expression too: $exists() on it is true and $type() on it
is "null". Only an expression that returns nothing loses its key, which is what
$states.input.absent and the functions listed below that evaluate to undefined do.
Two deviations. $count() on a JSON null answers 0; AWS answers 1. And dropping the key of an
expression that returned nothing is Floci's own behaviour: AWS fails the state instead, with
States.QueryEvaluationError and The JSONata expression '$states.input.absent' specified for the field 'Output/v' returned nothing (undefined).
JSONata functions
State machines with "QueryLanguage": "JSONata" reach the six functions Step Functions adds on
top of the JSONata language, alongside every function JSONata itself provides.
| Function | Returns |
|---|---|
$parse(jsonString) |
the deserialized value; the replacement for $eval, which AWS disables |
$partition(array, chunkSize) |
array split into chunks of chunkSize, the last one holding the remainder |
$range(start, end, step) |
the values from start to end, inclusive when step lands on end |
$hash(str, algorithm) |
the hex digest of str; algorithm is MD5, SHA-1, SHA-256, SHA-384 or SHA-512, case-sensitive |
$random(seed) |
a number in [0, 1), reproducible under the optional integer seed |
$uuid() |
a v4 UUID |
Three behaviours are worth knowing before reading an unexpected result, and all three are AWS's:
- A non-integer argument is rounded towards zero, so
$range(-1.7, 2, 1)starts at-1and$partition(items, 2.9)chunks by 2. - Several arguments evaluate to undefined rather than failing: a chunk size of zero, an empty
array, a
$rangewith nostepor with a step whose sign disagrees with the direction, and a$hashwith no algorithm. An undefined value is then dropped from the surroundingOutputobject, so the field goes missing instead of the state failing. $rangecollapses a single-element range to the bare number, not a one-element array.
JSONata's own $string follows AWS's number notation: a whole number is written out in full below
1e21 and in exponent notation from there, on both signs, so $string(1e20) is
100000000000000000000 and $string(1e21) is 1e+21.
Evaluation is bounded, as it is on AWS: one expression may run for five seconds and nest 500
levels deep, and past either the state fails with States.QueryEvaluationError. Both bounds sit
well above what AWS itself accepts, so an expression that evaluates there evaluates here. AWS
refuses a non-tail-recursive function past a nesting depth near 100, and the largest sequence it
accepts evaluates here in about a tenth of a second.
One deviation. AWS also bounds the memory an expression may use, refusing
[1..900000] ~> $count() with Expression evaluation memory limit exceeded while accepting the
same expression at 800,000 elements. Floci bounds time and depth but not memory, and its ranges
are lazy, so that expression answers immediately at any size.
Mocked service integrations
Floci supports the Step Functions Local mock configuration format
(MockConfigFile.json). This lets a Task state return a predefined result or error
instead of calling the integrated service. It is the standard way to unit test Catch
and Retry branches, and it also lets you execute state machines whose integrations
Floci does not implement yet.
Point SFN_MOCK_CONFIG at the mock configuration file and start an execution against
<stateMachineArn>#<testCaseName>:
# docker run -e SFN_MOCK_CONFIG=/tmp/mock.json -v ./MockConfigFile.json:/tmp/mock.json ...
aws stepfunctions start-execution \
--state-machine-arn "$SM_ARN#Throw422" \
--input '{}' \
--endpoint-url $AWS_ENDPOINT_URL
{
"StateMachines": {
"Test": { "TestCases": { "Throw422": { "Call API": "ApiFailure" } } }
},
"MockedResponses": {
"ApiFailure": {
"0": { "Throw": { "Error": "ApiGateway.422", "Cause": "Unprocessable" } }
},
"ApiSuccess": {
"0-1": { "Return": { "StatusCode": 200, "ResponseBody": { "id": 1 } } }
}
}
}
Each test case maps a state name to a MockedResponses entry. Each mocked response is
keyed by retry attempt ("0", "1", or a range like "1-2"), so a state can fail on
the first attempt and succeed on a retry. Return supplies the task result. Throw
fails the task with the given Error and Cause, which flow through Retry and
Catch unchanged. States not named in the test case run their real integration, so
mocked and real service calls can be combined in one execution. The file is re-read
when it changes, so it can be edited without restarting Floci.
Behavior was verified against Step Functions Local 2.0.0. As there, StartSyncExecution
rejects a test case suffix with UnsupportedOperation and does not strip a bare trailing
#, a bare trailing # on StartExecution runs the execution unmocked, and a retry
attempt with no mocked entry fails the execution with States.Runtime. One intentional deviation: Floci reports an unknown test case and any
invalid mock configuration (unparseable file, bad attempt key, missing MockedResponses
entry, Return and Throw together, Throw without Error) as a structured 400 error
at StartExecution. Step Functions Local instead returns a plain HTTP 500 for most of
these and starts the execution only to fail it with States.Runtime for the last two.
Configuration
| Variable | Default | Description |
|---|---|---|
FLOCI_SERVICES_STEPFUNCTIONS_ENABLED |
true |
Enable or disable the service |
SFN_MOCK_CONFIG |
unset | Path to a Step Functions Local compatible mock configuration file (alias: FLOCI_SERVICES_STEPFUNCTIONS_MOCK_CONFIG_FILE) |
Examples
export AWS_ENDPOINT_URL=http://localhost:4566
# Create a state machine
SM_ARN=$(aws stepfunctions create-state-machine \
--name my-workflow \
--definition '{
"Comment": "Simple workflow",
"StartAt": "HelloWorld",
"States": {
"HelloWorld": {
"Type": "Pass",
"Result": {"message": "Hello, World!"},
"End": true
}
}
}' \
--role-arn arn:aws:iam::000000000000:role/step-functions-role \
--query stateMachineArn --output text \
--endpoint-url $AWS_ENDPOINT_URL)
# Start an execution
EXEC_ARN=$(aws stepfunctions start-execution \
--state-machine-arn $SM_ARN \
--input '{"key":"value"}' \
--query executionArn --output text \
--endpoint-url $AWS_ENDPOINT_URL)
# Check status
aws stepfunctions describe-execution \
--execution-arn $EXEC_ARN \
--endpoint-url $AWS_ENDPOINT_URL
# Get event history
aws stepfunctions get-execution-history \
--execution-arn $EXEC_ARN \
--endpoint-url $AWS_ENDPOINT_URL