mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
* feat(swf): add Simple Workflow Service emulation
Implements all 39 SWF operations over the JSON 1.0 protocol
(X-Amz-Target: SimpleWorkflowService.*): domain and type registration,
the workflow execution state machine, and the decider/worker task
lifecycle.
Behaviour was derived from botocore's swf-2012-01-25 model and verified
against the live service, which drove several details that are easy to
get wrong from the model alone:
- Faults carry a namespaced __type (com.amazonaws.swf.base.model#Fault)
in the body but the bare fault name in x-amzn-query-error. botocore
prefers the header, so a namespaced value there makes the CLI print
"com.amazonaws.swf.base.model#UnknownResourceFault" where SWF prints
"UnknownResourceFault". SwfException keeps the two spellings apart.
- Timestamps are epoch-second numbers, not ISO strings.
- Void operations answer 200 with an empty body rather than {}.
- An idle poll returns taskToken "" rather than omitting the member;
the SDKs read the empty token as "no task".
- ActivityTaskTimedOut reports startedEventId 0 for a task that never
started, and WorkflowExecutionStarted reports parentInitiatedEventId 0
on root executions, rather than omitting either member.
State machine:
- One decision task outstanding per execution. Events arriving while one
is outstanding set a pending flag that is satisfied when it completes,
so a signal cannot produce two concurrent decision tasks.
- Decisions apply in order; a decision after a closing decision is
dropped. A decision that cannot be applied appends its *Failed event
with the AWS cause and gives the decider a fresh task instead of
failing the request.
- Closing with open activities, timers, or children appends
UNHANDLED_DECISION and leaves the execution open.
- Timeouts (activity schedule-to-start, start-to-close,
schedule-to-close, heartbeat; decision start-to-close; execution
start-to-close; timers) expire from one background sweep rather than a
timer per task, so a restart leaves nothing to reconcile.
- Child executions link to their parent and report their outcome back;
the closing parent's childPolicy is applied to open children.
Tests: 29 unit tests drive timeout expiry through a controllable clock,
32 integration tests assert the wire shapes and fault strings captured
from the live service, and a compatibility suite exercises the same
flows through the AWS SDK v2 client so responses must deserialize into
the generated model and faults into typed exceptions.
Long polling, ScheduleLambdaFunction invocation, and retention-based
pruning are not implemented; docs/services/swf.md records each.
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): report the child-started event id on ChildWorkflowExecution* events
A ChildWorkflowExecution* event carries two correlation ids, and they point at
different events in the parent's history: initiatedEventId is the
StartChildWorkflowExecutionInitiated id, startedEventId is the
ChildWorkflowExecutionStarted id. Both were reported as the initiated id, so a
decider correlating a child's outcome on startedEventId matched the wrong event.
Verified against the live service, where a parent that starts one child and sees
it complete produces:
5 StartChildWorkflowExecutionInitiated
6 ChildWorkflowExecutionStarted {initiatedEventId: 5}
8 ChildWorkflowExecutionCompleted {initiatedEventId: 5, startedEventId: 6}
The child now records the parent's ChildWorkflowExecutionStarted id at start
time and reports it back on every ChildWorkflowExecution* event.
The integration test asserts both ids against the events they name rather than
against a "greater than zero" placeholder, and fails on the previous behaviour
with "startedEventId Expected: <6> Actual: <5>".
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): reject a decision batch whose closing decision is not last
RespondDecisionTaskCompleted accepted a batch with decisions after a closing
decision and silently dropped the remainder. The live service rejects the whole
batch instead:
HTTP 400
{"__type":"com.amazon.coral.validate#ValidationException",
"message":"Close must be last decision in list"}
Silently accepting it hides a decider bug and diverges on both the status code
and the response body, so a decider that ships a malformed batch sees success
locally and a 400 against AWS.
The batch is now validated before any state is mutated, matching the live
service's behaviour of leaving the decision task outstanding so the decider can
retry with a corrected batch. Note this fault is namespaced
com.amazon.coral.validate rather than com.amazonaws.swf.base.model.
Tests assert the status code, both fault spellings, the message, that no
DecisionTaskCompleted event is appended, and that the same task token still
works afterwards. They fail on the previous behaviour with "Expected status code
<400> but was <200>".
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): name the scheduled event when an activity task has already closed
An activity task token that resolves to a task which is no longer open reported
"Unknown or expired task token". The live service distinguishes the two cases: a
genuine token whose task has closed names the scheduled event instead, because
the token itself was valid.
Captured from the live service, heartbeating a task that a cancel had already
closed:
HTTP 400
{"__type":"com.amazonaws.swf.base.model#UnknownResourceFault",
"message":"Unknown activity, scheduledEventId = 5"}
Both cases are UnknownResourceFault, so SDK error typing was already correct and
only the message diverged — but a worker that logs or matches on the message sees
a different string locally than against AWS.
A token that never existed still reports the bad token; only a resolved token on
a closed task reports the scheduled event. This required keeping the token's map
entry when an activity closes, since removing it made both cases indistinguishable;
reuse is still refused by the existing open-state check.
Test asserts both branches and fails on the previous behaviour with "expected:
<Unknown activity, scheduledEventId = 5> but was: <Unknown or expired task token>".
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): serialize execution mutation per domain and guard the sweep interval
Addresses three review findings.
Concurrent StartWorkflowExecution calls for one workflowId all scanned for an
open run before any of them inserted, so each persisted its own run key. Eight
concurrent starts produced eight open runs where SWF admits one, and later
operations without a runId then selected an arbitrary run. The open-run check
and the insert are now one atomic step.
A closing execution mutates its parent (ChildWorkflowExecution* events) and its
children (childPolicy), but held only its own lock, so event-id allocation and
the history list raced. Six children closing against one parent reproduced
ConcurrentModificationException.
Both come from the same mismatch: the lock was per execution while the
invariants span an execution family. The lock is now per domain. A parent and a
child always share a domain, so one lock covers the family and never has to be
nested — nesting would deadlock, since a closing child takes its parent while a
closing parent takes its children. Per-domain granularity is sufficient here:
the emulator serves a single developer's workload, not production concurrency.
A zero or negative timeout-sweep interval reached scheduleWithFixedDelay, which
threw IllegalArgumentException out of the StartupEvent observer and stopped the
whole emulator becoming ready — one bad SWF setting taking down every other
service. A non-positive interval now falls back to 1s with a warning.
Tests fail on the previous behaviour with "expected: <1> but was: <8>",
ConcurrentModificationException, and IllegalArgumentException respectively.
Verified over the wire too: eight concurrent starts yield one success, seven
WorkflowExecutionAlreadyStartedFault, and one open run.
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): report the live service's TypeNotDeprecatedFault message
DeleteWorkflowType/DeleteActivityType against a still-registered type
reported the type descriptor, e.g. "WorkflowType=[name=W, version=1]". The
live service answers with prose instead, and uses the same wording for both
type kinds:
{"__type":"com.amazonaws.swf.base.model#TypeNotDeprecatedFault",
"message":"The type is currently registered and cannot be deleted in its
current state"}
Since both variants are identical, the two fault factories collapse into one.
The descriptor form is still correct for the other type faults
(TypeDeprecatedFault, TypeAlreadyExistsFault, UnknownResourceFault), which were
verified unchanged in the same probe.
Also adds integration coverage for the five actions that had none at either
test layer: DeprecateActivityType, UndeprecateActivityType, DeleteActivityType,
ListWorkflowTypes, and RespondActivityTaskFailed. Every assertion is taken from
a live-service capture, including that scheduling a deprecated activity type
appends ScheduleActivityTaskFailed with cause ACTIVITY_TYPE_DEPRECATED and
leaves the execution open, that ListWorkflowTypes filters by registration
status and name, and that a second RespondActivityTaskFailed on the same token
reports "Unknown activity, scheduledEventId = 5".
The message tests fail on the previous behaviour with "Expected: The type is
currently registered ... Actual: WorkflowType=[name=TestWf, version=1.0]".
Signed-off-by: Andre Kurait <akurait@amazon.com>
* feat(swf): invoke real Lambda functions for ScheduleLambdaFunction
The decision was recorded as ScheduleLambdaFunctionFailed with cause
LAMBDA_SERVICE_NOT_AVAILABLE_IN_REGION rather than invoking anything. SWF is
otherwise a pure coordination service — deciders and activity workers are the
user's own processes, so there is no user code for the emulator to run — but
ScheduleLambdaFunction is the one decision where SWF itself executes something,
and Floci already runs Lambda functions in containers. A decider that fans work
out to Lambda could not be exercised locally at all.
Floci now invokes the function through its own Lambda service, the same way the
EventBridge and Scheduler invokers do, and records the outcome. Verified against
the live service:
5 LambdaFunctionScheduled {control, id, input, name, startToCloseTimeout}
6 LambdaFunctionStarted {scheduledEventId: 5}
7 LambdaFunctionCompleted {result, scheduledEventId: 5, startedEventId: 6}
8 DecisionTaskScheduled
Four behaviours came from that capture and are easy to get wrong:
- A function that cannot be resolved is LambdaFunctionFailed with Lambda's own
error code as reason (ResourceNotFoundException) — not
ScheduleLambdaFunctionFailed — and it still reports Started first.
- An execution with no lambdaRole never starts the function at all: Scheduled is
followed by StartLambdaFunctionFailed with cause ASSUME_ROLE_FAILED and the
message "No IAM role is attached to the current workflow execution."
- lambdaRole resolves from StartWorkflowExecution's lambdaRole, falling back to
the workflow type's defaultLambdaRole, and is echoed in the started event.
- An absent input reaches the handler as {}, and reusing an id is accepted —
there is no ID_ALREADY_IN_USE for Lambda the way there is for activity ids.
SwfService takes a LambdaInvoker seam rather than LambdaService directly, so the
unit tests keep running without a Docker daemon while SwfLambdaInvoker wires the
real thing at runtime. The invocation is RequestResponse because the response
body is what gets recorded as result; the fire-and-forget invokers use Event for
the opposite reason.
The Lambda region comes from the execution's domain ARN, so a workflow in one
region does not invoke a function in another.
Tests: SwfServiceTest covers all four paths against a recording invoker and
fails on the previous behaviour with "the function must actually be invoked
==> expected: <1> but was: <0>". SwfLambdaIntegrationTest and the SDK
compatibility SwfLambdaTest deploy a real function and assert the recorded
result is what the container returned, so neither passes against a synthesised
event. Docker-backed cases live in their own class so a Docker-less run loses
only them rather than the whole SWF wire suite.
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): scope state by region and paginate the registration lists
Addresses two AWS compatibility gaps from review.
SWF names are unique per region, but storage keys were the bare name, so
registering a domain in us-east-1 made the same name in eu-west-1 fail as a
duplicate, and describe/list could return the first region's domain and ARN.
Verified against the live service: the same name registers in both regions with
independent descriptions and retention periods, each ARN naming its own region;
a type registered in one region answers UnknownResourceFault in the other; and
executions, including their runIds, do not cross.
Keys are now region-qualified — `<region>:<domain>` for domains,
`<region>:<domain>/<name>/<version>` for types, and
`<region>:<domain>/<workflowId>/<runId>` for executions — and every store scan
is prefixed by region. The region reaches the service on each call and is stored
on the execution, which is also what task tokens resolve through, so a token
issued in one region cannot address another's execution. The per-domain
mutation lock is region-qualified too; leaving it bare would have let two
regions serialize against each other, and would have disagreed with the
sweeper's own lock derived from the storage key.
ListDomains, ListWorkflowTypes and ListActivityTypes ignored maximumPageSize and
nextPageToken and returned everything. They now share one paging helper with the
history and execution listings. Details taken from live captures rather than the
docs: nextPageToken is absent on the final page even when that page is exactly
full, a maximumPageSize of 0 or absent means "no caller limit", above 1000 is
rejected rather than clamped, and a corrupt token answers
`ValidationException: Invalid token` instead of silently restarting at the first
page — which would make a paging loop repeat forever.
Adds AWS SDK regression tests (SwfRegionPaginationTest) driving two clients at
different regions against the same emulator, plus wire-level integration
coverage. Against the previous implementation those SDK tests fail with
DomainAlreadyExists on the second region, "maximumPageSize must cap the page: 5",
and nothing thrown for an oversized page size.
Signed-off-by: Andre Kurait <akurait@amazon.com>
* test(swf): pin reverseOrder as applying before pagination
The registration lists reverse the whole result set and then page it, so with
maximumPageSize=3 and reverseOrder=true the first page is the tail of the
ascending order. That was already the behaviour but nothing asserted it, and the
shared paging helper makes "page first, then reverse the page" an easy
regression to introduce.
Measured against the live service: 5 types at page size 3 reversed returns
Paged4, Paged3, Paged2 and then Paged1, Paged0. Injecting the page-then-reverse
ordering fails the new test with
"Expected: <[Paged4, Paged3, Paged2]>".
Signed-off-by: Andre Kurait <akurait@amazon.com>
* test(swf): cover region scoping at the wire level
The region-scoping tests went in at the service and SDK layers, but every
SwfIntegrationTest request omitted an Authorization header, so nothing asserted
that the region is read from the SigV4 credential scope — the step that decides
which region's state a call addresses.
Adds a wire test that sends a credential scope naming the region, covering the
same name registering in two regions with independent descriptions, retentions
and ARNs, a type being unknown in the other region, and a same-region
re-registration still faulting.
Against 7cc6c0f2 the test fails with
DomainAlreadyExistsFault / "Expected status code <200> but was <400>".
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): correct four decision, polling and locking cases from review
An invalid decision anywhere in a batch could still mutate the execution.
respondDecisionTaskCompleted appended DecisionTaskCompleted, dropped the token
and applied earlier decisions before applyDecision's default arm rejected an
unknown decisionType mid-loop, so [RecordMarker, NotARealDecision] grew the
history from 3 to 5 events and burned the token. A try/catch cannot undo that —
decisionTokens is a separate map and the history lands on the in-memory
execution — so the whole batch is now validated up front, extending the shape
requireCloseIsLastDecision already used. Both rules live in one requireValidBatch,
and the accepted types come from SwfConstants.DECISION_TYPES so the check and the
message quoting the enum set cannot drift.
PollForDecisionTask with a nextPageToken claimed a new task instead of paging the
original. AWS states that "calling PollForDecisionTask with a nextPageToken
doesn't return a new decision task", and the live service answers a continuation
with the same startedEventId, previousStartedEventId and workflowExecution, plus
the next contiguous history page. The continuation token now names the task it
belongs to, so a continuation resolves that task rather than polling again.
startAtPreviousStartedEvent was modeled but read nowhere; it now trims the window
to events from previousStartedEventId onward, which the live service treats as
inclusive.
A child that continued as new lost its parent. The successor was built from a
StartWorkflowExecutionRequest, which carries no parent fields, so its parent was
null and the parent kept tracking the closed run — never learning the successor's
outcome and never applying child policy to it. carryParentTo moves the parent
identifiers and repoints the parent's childExecutions entry before the successor's
WorkflowExecutionStarted is appended, so that event names the parent as it does
on the live service.
The Lambda invocation held the domain lock. That lock deliberately covers a whole
domain family, so a cold start stalled every unrelated execution in the domain.
A decision now queues the invocation, records LambdaFunctionScheduled and
LambdaFunctionStarted under the lock, and the invocation runs after the lock is
released; the outcome is recorded under the lock again, so the state transition
around the result stays atomic.
Guards, each failing on the code before it: the batch case with
"a rejected batch must not grow the history ==> expected: <3> but was: <5>", the
continue-as-new case with "the successor of a child must keep its parent ==>
expected: <wf-cn-parent> but was: <null>", the two polling cases on an empty
continuation response, and the liveness case by blocking inside the invoker and
signalling an unrelated execution in the same domain.
Signed-off-by: Andre Kurait <akurait@amazon.com>
* refactor(swf): collapse the paging helpers into one, and cap every operation
Three page-token codecs and three copies of the same offset/limit/token block had
accumulated across the history, execution and registration listings, plus a
fourth for the PollForDecisionTask continuation. There is now one Page record
with one encode/decode pair — the task token is an optional field, which is the
only thing the poll needed — and one pagedList helper the history and execution
listings reuse. Net 62 fewer lines in the service and handler.
Collapsing the two page-size methods surfaced a real divergence rather than just
shortening code: historyPageSize clamped an oversized maximumPageSize while the
registration lists rejected it. The live service rejects it everywhere, measured
on GetWorkflowExecutionHistory, ListOpenWorkflowExecutions and
PollForDecisionTask, and rejects a negative value with its own message
("greater than or equal to 0"). One pageSize method now serves all of them.
Signed-off-by: Andre Kurait <akurait@amazon.com>
* docs(swf): document batch atomicity, poll continuation and the page-size cap
The three behaviours the last two commits changed were only visible in the code: a decision batch is all-or-nothing, a PollForDecisionTask continuation pages the same task rather than claiming a new one (and startAtPreviousStartedEvent is inclusive), and the 1000 page-size cap applies to every paginated operation rather than only the registration lists.
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): render the decisionType enum set in the service's own order
The rejection message for an unknown decisionType listed the enum members in the
API model's order. The live service uses a different order, stable across
repeated calls, so a client comparing the message byte-for-byte saw a mismatch:
service: [CompleteWorkflowExecution, StartTimer, RequestCancelExternal...
model: [ScheduleActivityTask, RequestCancelActivityTask, CompleteWork...
Taken from four live responses rather than from the model. The guard now asserts
the whole message instead of a substring, and fails on the previous order with
the two strings diffed in full.
Signed-off-by: Andre Kurait <akurait@amazon.com>
* fix(swf): scope queued Lambda work to the request, not the thread
The queue of deferred invocations was a ThreadLocal drained after the domain lock
was released. On a pooled request thread that outlives the request: if anything
threw between queueing an invocation and draining, the work stayed on the thread
and the next decision response ran it — invoking a real function for a request
that had already failed, and recording the outcome against whatever state that
later execution was in.
The queue is now a local list created per call and threaded through
applyDecisions, so the drain is reachable only after the batch has been applied
and stored. A request that throws leaves the list unreferenced; there is no
cross-request carrier left to leak through.
Signed-off-by: Andre Kurait <akurait@amazon.com>
* test(swf): guard that a failed batch leaves no queued Lambda work
Reaches the leak window by failing the execution store after a Lambda has been queued and the history mutated, then issuing a second request on the same thread.
Signed-off-by: Andre Kurait <akurait@amazon.com>
---------
Signed-off-by: Andre Kurait <akurait@amazon.com>