From ecad6acf581213ef26513f10f2100a6d76409725 Mon Sep 17 00:00:00 2001 From: Andre Kurait Date: Fri, 14 Aug 2026 10:16:21 -0500 Subject: [PATCH] feat(swf): add Simple Workflow Service emulation (#2257) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 * 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 * 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 * 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: but was: ". Signed-off-by: Andre Kurait * 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 * 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 * 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 * 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 — `:` for domains, `://` for types, and `://` 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 * 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 * 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 * 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: but was: ", 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 * 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 * 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 * 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 * 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 * 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 --------- Signed-off-by: Andre Kurait --- README.md | 3 +- compatibility-tests/sdk-test-java/pom.xml | 4 + .../java/com/floci/test/TestFixtures.java | 17 + .../java/com/floci/test/SwfLambdaTest.java | 199 ++ .../floci/test/SwfRegionPaginationTest.java | 270 +++ .../src/test/java/com/floci/test/SwfTest.java | 403 +++ docs/services/swf.md | 262 ++ mkdocs.yml | 1 + .../floci/config/EmulatorConfig.java | 21 + .../floci/core/common/AwsJsonController.java | 7 +- .../core/common/ResolvedServiceCatalog.java | 4 + .../services/swf/LambdaInvocationResult.java | 12 + .../floci/services/swf/LambdaInvoker.java | 21 + .../floci/services/swf/SwfException.java | 30 + .../floci/services/swf/SwfFaults.java | 133 + .../floci/services/swf/SwfJsonHandler.java | 775 ++++++ .../floci/services/swf/SwfLambdaInvoker.java | 39 + .../floci/services/swf/SwfService.java | 2155 +++++++++++++++++ .../floci/services/swf/SwfTimeoutSweeper.java | 85 + .../services/swf/model/SwfActivityTask.java | 253 ++ .../services/swf/model/SwfActivityType.java | 139 ++ .../services/swf/model/SwfConstants.java | 95 + .../services/swf/model/SwfDecisionTask.java | 146 ++ .../floci/services/swf/model/SwfDomain.java | 89 + .../services/swf/model/SwfHistoryEvent.java | 82 + .../floci/services/swf/model/SwfTimer.java | 83 + .../swf/model/SwfWorkflowExecution.java | 355 +++ .../services/swf/model/SwfWorkflowType.java | 139 ++ src/main/resources/application.yml | 4 + .../services/swf/SwfIntegrationTest.java | 1810 ++++++++++++++ .../swf/SwfLambdaIntegrationTest.java | 245 ++ .../floci/services/swf/SwfServiceTest.java | 1311 ++++++++++ .../services/swf/SwfTimeoutSweeperTest.java | 64 + src/test/resources/application.yml | 4 + tools/docs/services.yaml | 4 + 35 files changed, 9262 insertions(+), 2 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfLambdaTest.java create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfRegionPaginationTest.java create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfTest.java create mode 100644 docs/services/swf.md create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/LambdaInvocationResult.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/LambdaInvoker.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/SwfException.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/SwfFaults.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/SwfJsonHandler.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/SwfLambdaInvoker.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/SwfService.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/SwfTimeoutSweeper.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/model/SwfActivityTask.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/model/SwfActivityType.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/model/SwfConstants.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/model/SwfDecisionTask.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/model/SwfDomain.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/model/SwfHistoryEvent.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/model/SwfTimer.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/model/SwfWorkflowExecution.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/swf/model/SwfWorkflowType.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/swf/SwfIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/swf/SwfLambdaIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/swf/SwfServiceTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/swf/SwfTimeoutSweeperTest.java diff --git a/README.md b/README.md index d498ad162e..78a2f3b7f7 100644 --- a/README.md +++ b/README.md @@ -220,7 +220,7 @@ Floci supports local emulation for application services, data services, eventing | Category | Services | |---|---| | Core app services | S3, SQS, SNS, DynamoDB, Lambda, IAM, KMS, Secrets Manager, SSM | -| Events and workflows | EventBridge, EventBridge Pipes, EventBridge Scheduler, Step Functions, CloudWatch Logs, CloudWatch Metrics | +| Events and workflows | EventBridge, EventBridge Pipes, EventBridge Scheduler, Step Functions, SWF, CloudWatch Logs, CloudWatch Metrics | | API and identity | API Gateway REST, API Gateway v2, AppSync, Cognito, ACM, Route53, Cloud Map | | Containers and compute | ECS, EC2, Lightsail, EKS, MWAA, ECR, CodeBuild, CodeDeploy, CodePipeline, AWS Batch, Auto Scaling, Application Auto Scaling, Elastic Beanstalk, ELB v2 | | Data, analytics, and AI | Athena, Glue, EMR, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Vectors, Textract, Transcribe, Bedrock Runtime | @@ -253,6 +253,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/ | Kinesis | In-process | Streams, shards, enhanced fan-out, split and merge | | Secrets Manager | In-process | Versioning, resource policies, tagging | | Step Functions | In-process | ASL execution, task tokens, execution history | +| SWF | In-process | Decision and activity tasks, timers, child workflows, timeouts, real Lambda invocation | | CloudFormation | In-process | Stacks, change sets, resource provisioning, StackSets (cross-account instances) | | EventBridge | In-process | Custom buses, rules, SQS, SNS and Lambda targets | | EventBridge Pipes | In-process | Poller-based integration connecting SQS, Kinesis, DynamoDB, and MSK sources to targets with optional filtering | diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml index 48dfb434ca..82772be5f7 100644 --- a/compatibility-tests/sdk-test-java/pom.xml +++ b/compatibility-tests/sdk-test-java/pom.xml @@ -132,6 +132,10 @@ software.amazon.awssdk sfn + + software.amazon.awssdk + swf + software.amazon.awssdk iam diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index 0eea320471..81c816eb1b 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -34,6 +34,7 @@ import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.ses.SesClient; import software.amazon.awssdk.services.sesv2.SesV2Client; import software.amazon.awssdk.services.sfn.SfnClient; +import software.amazon.awssdk.services.swf.SwfClient; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.ssm.SsmClient; @@ -589,6 +590,22 @@ public final class TestFixtures { .build(); } + public static SwfClient swfClient() { + return swfClient(REGION); + } + + /** + * SWF names are unique per region, so cross-region tests need two clients pointed at the + * same emulator with different regions. + */ + public static SwfClient swfClient(Region region) { + return SwfClient.builder() + .endpointOverride(ENDPOINT) + .region(region) + .credentialsProvider(CREDENTIALS) + .build(); + } + public static SesClient sesClient() { return SesClient.builder() .endpointOverride(ENDPOINT) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfLambdaTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfLambdaTest.java new file mode 100644 index 0000000000..3398e81135 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfLambdaTest.java @@ -0,0 +1,199 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.services.lambda.LambdaClient; +import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest; +import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest; +import software.amazon.awssdk.services.lambda.model.FunctionCode; +import software.amazon.awssdk.services.lambda.model.Runtime; +import software.amazon.awssdk.services.swf.SwfClient; +import software.amazon.awssdk.services.swf.model.ChildPolicy; +import software.amazon.awssdk.services.swf.model.Decision; +import software.amazon.awssdk.services.swf.model.DecisionType; +import software.amazon.awssdk.services.swf.model.EventType; +import software.amazon.awssdk.services.swf.model.GetWorkflowExecutionHistoryRequest; +import software.amazon.awssdk.services.swf.model.HistoryEvent; +import software.amazon.awssdk.services.swf.model.LambdaFunctionCompletedEventAttributes; +import software.amazon.awssdk.services.swf.model.LambdaFunctionScheduledEventAttributes; +import software.amazon.awssdk.services.swf.model.PollForDecisionTaskRequest; +import software.amazon.awssdk.services.swf.model.PollForDecisionTaskResponse; +import software.amazon.awssdk.services.swf.model.RegisterDomainRequest; +import software.amazon.awssdk.services.swf.model.RegisterWorkflowTypeRequest; +import software.amazon.awssdk.services.swf.model.RespondDecisionTaskCompletedRequest; +import software.amazon.awssdk.services.swf.model.ScheduleLambdaFunctionDecisionAttributes; +import software.amazon.awssdk.services.swf.model.StartWorkflowExecutionRequest; +import software.amazon.awssdk.services.swf.model.TaskList; +import software.amazon.awssdk.services.swf.model.WorkflowExecution; +import software.amazon.awssdk.services.swf.model.WorkflowType; + +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Drives SWF's ScheduleLambdaFunction decision through the AWS SDK against a real Lambda + * function that Floci runs in a container. + * + *

The point of doing this at the SDK layer is that the generated model has to accept what + * the emulator returns: the Lambda history events must deserialize into + * {@code LambdaFunctionScheduled/Started/Completed} with their typed + * {@code *EventAttributes} members populated, which a hand-rolled HTTP assertion cannot + * verify. + */ +@DisplayName("SWF Lambda decisions via the AWS SDK") +class SwfLambdaTest { + + private static final String SUFFIX = String.valueOf(System.nanoTime()); + private static final String DOMAIN = "sdk-swf-lambda-" + SUFFIX; + private static final String FUNCTION = "sdk-swf-fn-" + SUFFIX; + private static final String TASK_LIST = "sdk-lam-tl-" + SUFFIX; + private static final String ROLE = "arn:aws:iam::000000000000:role/swf-lambda-role"; + + private static SwfClient swf; + private static LambdaClient lambda; + + @BeforeAll + static void setUp() throws Exception { + swf = TestFixtures.swfClient(); + lambda = TestFixtures.lambdaClient(); + + lambda.createFunction(CreateFunctionRequest.builder() + .functionName(FUNCTION) + .runtime(Runtime.PYTHON3_12) + .role(ROLE) + .handler("handler.handler") + .timeout(30) + .code(FunctionCode.builder().zipFile(SdkBytes.fromByteArray(handlerZip())).build()) + .build()); + + swf.registerDomain(RegisterDomainRequest.builder() + .name(DOMAIN) + .workflowExecutionRetentionPeriodInDays("1") + .build()); + + swf.registerWorkflowType(RegisterWorkflowTypeRequest.builder() + .domain(DOMAIN) + .name("LambdaWf") + .version("1.0") + .defaultTaskList(TaskList.builder().name(TASK_LIST).build()) + .defaultTaskStartToCloseTimeout("300") + .defaultExecutionStartToCloseTimeout("900") + .defaultChildPolicy(ChildPolicy.TERMINATE) + // SWF needs a role to invoke Lambda with; without one the invocation never starts. + .defaultLambdaRole(ROLE) + .build()); + } + + @AfterAll + static void tearDown() { + try { + lambda.deleteFunction(DeleteFunctionRequest.builder().functionName(FUNCTION).build()); + } catch (RuntimeException ignored) { + // Best effort: leaving the function behind must not fail the suite. + } + } + + private static byte[] handlerZip() throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ZipOutputStream zip = new ZipOutputStream(baos)) { + zip.putNextEntry(new ZipEntry("handler.py")); + zip.write(("def handler(event, context):\n" + + " return {'doubled': [n * 2 for n in event.get('numbers', [])]}\n").getBytes()); + zip.closeEntry(); + } + return baos.toByteArray(); + } + + @Test + @DisplayName("ScheduleLambdaFunction runs the function and the SDK reads back its result") + void scheduleLambdaFunction() { + String runId = swf.startWorkflowExecution(StartWorkflowExecutionRequest.builder() + .domain(DOMAIN) + .workflowId("sdk-wf-lambda") + .workflowType(WorkflowType.builder().name("LambdaWf").version("1.0").build()) + .build()) + .runId(); + assertNotNull(runId); + + PollForDecisionTaskResponse task = null; + for (int attempt = 0; attempt < 20 && task == null; attempt++) { + PollForDecisionTaskResponse candidate = swf.pollForDecisionTask( + PollForDecisionTaskRequest.builder() + .domain(DOMAIN) + .taskList(TaskList.builder().name(TASK_LIST).build()) + .identity("sdk-decider") + .build()); + if (candidate.taskToken() != null && !candidate.taskToken().isEmpty()) { + task = candidate; + } + } + assertNotNull(task, "no decision task became available"); + + swf.respondDecisionTaskCompleted(RespondDecisionTaskCompletedRequest.builder() + .taskToken(task.taskToken()) + .decisions(Decision.builder() + .decisionType(DecisionType.SCHEDULE_LAMBDA_FUNCTION) + .scheduleLambdaFunctionDecisionAttributes( + ScheduleLambdaFunctionDecisionAttributes.builder() + .id("sdk-lam-1") + .name(FUNCTION) + .control("sdk-ctl") + .input("{\"numbers\": [1, 2, 3]}") + .startToCloseTimeout("30") + .build()) + .build()) + .build()); + + List events = swf.getWorkflowExecutionHistory( + GetWorkflowExecutionHistoryRequest.builder() + .domain(DOMAIN) + .execution(WorkflowExecution.builder() + .workflowId("sdk-wf-lambda").runId(runId).build()) + .build()) + .events(); + + HistoryEvent scheduled = eventOf(events, EventType.LAMBDA_FUNCTION_SCHEDULED); + HistoryEvent started = eventOf(events, EventType.LAMBDA_FUNCTION_STARTED); + HistoryEvent completed = eventOf(events, EventType.LAMBDA_FUNCTION_COMPLETED); + + // The generated model must populate the typed attribute members. + LambdaFunctionScheduledEventAttributes scheduledAttrs = + scheduled.lambdaFunctionScheduledEventAttributes(); + assertEquals("sdk-lam-1", scheduledAttrs.id()); + assertEquals(FUNCTION, scheduledAttrs.name()); + assertEquals("sdk-ctl", scheduledAttrs.control()); + assertEquals("30", scheduledAttrs.startToCloseTimeout()); + assertEquals(scheduled.eventId(), + started.lambdaFunctionStartedEventAttributes().scheduledEventId()); + + LambdaFunctionCompletedEventAttributes completedAttrs = + completed.lambdaFunctionCompletedEventAttributes(); + assertEquals(scheduled.eventId(), completedAttrs.scheduledEventId()); + assertEquals(started.eventId(), completedAttrs.startedEventId()); + + // Proof the container actually executed: the handler doubled the decider's input. + assertTrue(completedAttrs.result().contains("2") + && completedAttrs.result().contains("4") + && completedAttrs.result().contains("6"), + "expected the handler to double [1,2,3], got: " + completedAttrs.result()); + + assertEquals(EventType.DECISION_TASK_SCHEDULED, events.get(events.size() - 1).eventType()); + } + + private static HistoryEvent eventOf(List events, EventType type) { + return events.stream() + .filter(e -> type.equals(e.eventType())) + .findFirst() + .orElseThrow(() -> new AssertionError("no " + type + " in " + + events.stream().map(HistoryEvent::eventType).toList())); + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfRegionPaginationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfRegionPaginationTest.java new file mode 100644 index 0000000000..d5b4d9d5c6 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfRegionPaginationTest.java @@ -0,0 +1,270 @@ +package com.floci.test; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.swf.SwfClient; +import software.amazon.awssdk.services.swf.model.ActivityType; +import software.amazon.awssdk.services.swf.model.ChildPolicy; +import software.amazon.awssdk.services.swf.model.DescribeDomainRequest; +import software.amazon.awssdk.services.swf.model.DescribeWorkflowExecutionRequest; +import software.amazon.awssdk.services.swf.model.DescribeWorkflowTypeRequest; +import software.amazon.awssdk.services.swf.model.DomainAlreadyExistsException; +import software.amazon.awssdk.services.swf.model.ExecutionTimeFilter; +import software.amazon.awssdk.services.swf.model.ListActivityTypesRequest; +import software.amazon.awssdk.services.swf.model.ListActivityTypesResponse; +import software.amazon.awssdk.services.swf.model.ListDomainsRequest; +import software.amazon.awssdk.services.swf.model.ListDomainsResponse; +import software.amazon.awssdk.services.swf.model.ListOpenWorkflowExecutionsRequest; +import software.amazon.awssdk.services.swf.model.ListWorkflowTypesRequest; +import software.amazon.awssdk.services.swf.model.ListWorkflowTypesResponse; +import software.amazon.awssdk.services.swf.model.RegisterActivityTypeRequest; +import software.amazon.awssdk.services.swf.model.RegisterDomainRequest; +import software.amazon.awssdk.services.swf.model.RegisterWorkflowTypeRequest; +import software.amazon.awssdk.services.swf.model.RegistrationStatus; +import software.amazon.awssdk.services.swf.model.StartWorkflowExecutionRequest; +import software.amazon.awssdk.services.swf.model.SwfException; +import software.amazon.awssdk.services.swf.model.TaskList; +import software.amazon.awssdk.services.swf.model.UnknownResourceException; +import software.amazon.awssdk.services.swf.model.WorkflowExecution; +import software.amazon.awssdk.services.swf.model.WorkflowType; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Regression coverage for two AWS behaviours a single-region client cannot exercise: + * SWF names are unique per region, and the registration lists are paginated. + * + *

Both were measured against the live service before being asserted here. Region isolation + * needs two clients pointed at the same emulator with different {@code Region} values, which + * is exactly what an SDK-level test can express and a raw-HTTP test cannot do naturally. + */ +@DisplayName("SWF cross-region isolation and registration pagination via the AWS SDK") +class SwfRegionPaginationTest { + + private static final String SUFFIX = String.valueOf(System.nanoTime()); + private static final String DOMAIN = "sdk-region-" + SUFFIX; + + /** A fresh domain per test, registered in both regions, so tests never collide. */ + private static String freshDomain(String label) { + String name = "sdk-" + label + "-" + System.nanoTime(); + east.registerDomain(RegisterDomainRequest.builder() + .name(name).workflowExecutionRetentionPeriodInDays("1").build()); + return name; + } + private static final String TASK_LIST = "sdk-region-tl-" + SUFFIX; + + private static SwfClient east; + private static SwfClient west; + + @BeforeAll + static void setUp() { + east = TestFixtures.swfClient(Region.US_EAST_1); + west = TestFixtures.swfClient(Region.EU_WEST_1); + } + + private static void registerWorkflowType(SwfClient swf, String domain, String name) { + swf.registerWorkflowType(RegisterWorkflowTypeRequest.builder() + .domain(domain).name(name).version("1.0") + .defaultTaskList(TaskList.builder().name(TASK_LIST).build()) + .defaultTaskStartToCloseTimeout("300") + .defaultExecutionStartToCloseTimeout("900") + .defaultChildPolicy(ChildPolicy.TERMINATE) + .build()); + } + + @Test + @DisplayName("the same domain name registers independently in two regions") + void domainNamesAreUniquePerRegion() { + east.registerDomain(RegisterDomainRequest.builder() + .name(DOMAIN).description("east").workflowExecutionRetentionPeriodInDays("1").build()); + + // The maintainer's first report: this used to fail as a duplicate. + west.registerDomain(RegisterDomainRequest.builder() + .name(DOMAIN).description("west").workflowExecutionRetentionPeriodInDays("2").build()); + + var eastDomain = east.describeDomain(DescribeDomainRequest.builder().name(DOMAIN).build()); + var westDomain = west.describeDomain(DescribeDomainRequest.builder().name(DOMAIN).build()); + + assertEquals("east", eastDomain.domainInfo().description()); + assertEquals("west", westDomain.domainInfo().description()); + assertEquals("1", eastDomain.configuration().workflowExecutionRetentionPeriodInDays()); + assertEquals("2", westDomain.configuration().workflowExecutionRetentionPeriodInDays()); + + // Each ARN names its own region rather than leaking the first registration's. + assertTrue(eastDomain.domainInfo().arn().contains(":us-east-1:"), + eastDomain.domainInfo().arn()); + assertTrue(westDomain.domainInfo().arn().contains(":eu-west-1:"), + westDomain.domainInfo().arn()); + + // Re-registering within one region is still a duplicate. + assertThrows(DomainAlreadyExistsException.class, () -> + east.registerDomain(RegisterDomainRequest.builder() + .name(DOMAIN).workflowExecutionRetentionPeriodInDays("1").build())); + } + + @Test + @DisplayName("types and executions do not leak across regions") + void typesAndExecutionsAreIsolatedPerRegion() { + String domain = "sdk-isolate-" + System.nanoTime(); + east.registerDomain(RegisterDomainRequest.builder() + .name(domain).workflowExecutionRetentionPeriodInDays("1").build()); + west.registerDomain(RegisterDomainRequest.builder() + .name(domain).workflowExecutionRetentionPeriodInDays("1").build()); + + registerWorkflowType(east, domain, "EastOnly"); + + // Visible in its own region only. + assertTrue(typeNames(east.listWorkflowTypes(ListWorkflowTypesRequest.builder() + .domain(domain).registrationStatus(RegistrationStatus.REGISTERED).build())) + .contains("EastOnly")); + assertFalse(typeNames(west.listWorkflowTypes(ListWorkflowTypesRequest.builder() + .domain(domain).registrationStatus(RegistrationStatus.REGISTERED).build())) + .contains("EastOnly")); + assertThrows(UnknownResourceException.class, () -> + west.describeWorkflowType(DescribeWorkflowTypeRequest.builder() + .domain(domain) + .workflowType(WorkflowType.builder().name("EastOnly").version("1.0").build()) + .build())); + + // The same workflowId runs independently in each region. + registerWorkflowType(west, domain, "EastOnly"); + String eastRun = east.startWorkflowExecution(StartWorkflowExecutionRequest.builder() + .domain(domain).workflowId("wf-shared") + .workflowType(WorkflowType.builder().name("EastOnly").version("1.0").build()) + .build()) + .runId(); + String westRun = west.startWorkflowExecution(StartWorkflowExecutionRequest.builder() + .domain(domain).workflowId("wf-shared") + .workflowType(WorkflowType.builder().name("EastOnly").version("1.0").build()) + .build()) + .runId(); + assertNotEquals(eastRun, westRun); + + List eastOpen = east.listOpenWorkflowExecutions(ListOpenWorkflowExecutionsRequest.builder() + .domain(domain) + .startTimeFilter(ExecutionTimeFilter.builder() + .oldestDate(Instant.EPOCH).build()) + .build()) + .executionInfos().stream().map(i -> i.execution().runId()).toList(); + assertTrue(eastOpen.contains(eastRun)); + assertFalse(eastOpen.contains(westRun), "a west run must not appear in an east listing"); + + // A runId from the other region must not resolve. + assertThrows(UnknownResourceException.class, () -> + west.describeWorkflowExecution(DescribeWorkflowExecutionRequest.builder() + .domain(domain) + .execution(WorkflowExecution.builder() + .workflowId("wf-shared").runId(eastRun).build()) + .build())); + } + + @Test + @DisplayName("ListWorkflowTypes honours maximumPageSize and nextPageToken") + void listWorkflowTypesPaginates() { + String domain = freshDomain("pagewf"); + for (int i = 0; i < 5; i++) { + registerWorkflowType(east, domain, "PageWf" + i); + } + + List seen = new ArrayList<>(); + String token = null; + int pages = 0; + do { + ListWorkflowTypesResponse page = east.listWorkflowTypes(ListWorkflowTypesRequest.builder() + .domain(domain) + .registrationStatus(RegistrationStatus.REGISTERED) + .maximumPageSize(2) + .nextPageToken(token) + .build()); + assertTrue(page.typeInfos().size() <= 2, + "maximumPageSize must cap the page: " + page.typeInfos().size()); + seen.addAll(typeNames(page)); + token = page.nextPageToken(); + pages++; + } while (token != null && !token.isEmpty() && pages < 10); + + assertTrue(pages > 1, "5 types at page size 2 must span several pages, got " + pages); + assertNull(emptyToNull(token), "the final page must not carry a continuation token"); + for (int i = 0; i < 5; i++) { + assertTrue(seen.contains("PageWf" + i), "paging lost PageWf" + i + ": " + seen); + } + assertEquals(seen.size(), seen.stream().distinct().count(), "paging repeated an item: " + seen); + } + + @Test + @DisplayName("ListActivityTypes and ListDomains paginate the same way") + void listActivityTypesAndDomainsPaginate() { + String domain = freshDomain("pageact"); + for (int i = 0; i < 4; i++) { + east.registerActivityType(RegisterActivityTypeRequest.builder() + .domain(domain).name("PageAct" + i).version("1.0") + .defaultTaskList(TaskList.builder().name(TASK_LIST).build()) + .defaultTaskScheduleToStartTimeout("60") + .defaultTaskStartToCloseTimeout("60") + .defaultTaskScheduleToCloseTimeout("NONE") + .defaultTaskHeartbeatTimeout("NONE") + .build()); + } + + ListActivityTypesResponse firstActivities = east.listActivityTypes(ListActivityTypesRequest.builder() + .domain(domain).registrationStatus(RegistrationStatus.REGISTERED) + .maximumPageSize(3).build()); + assertEquals(3, firstActivities.typeInfos().size()); + assertTrue(firstActivities.nextPageToken() != null && !firstActivities.nextPageToken().isEmpty(), + "a partial listing must offer a continuation token"); + + ListActivityTypesResponse secondActivities = east.listActivityTypes(ListActivityTypesRequest.builder() + .domain(domain).registrationStatus(RegistrationStatus.REGISTERED) + .maximumPageSize(3).nextPageToken(firstActivities.nextPageToken()).build()); + List firstNames = firstActivities.typeInfos().stream() + .map(i -> i.activityType().name()).toList(); + for (var info : secondActivities.typeInfos()) { + assertFalse(firstNames.contains(info.activityType().name()), + "page 2 repeated " + info.activityType().name()); + } + + // ListDomains pages too; at least this domain exists, so page size 1 must cap it. + ListDomainsResponse domains = east.listDomains(ListDomainsRequest.builder() + .registrationStatus(RegistrationStatus.REGISTERED).maximumPageSize(1).build()); + assertEquals(1, domains.domainInfos().size()); + } + + @Test + @DisplayName("an oversized page size and a corrupt token are rejected") + void paginationInputsAreValidated() { + String domain = freshDomain("pagevalid"); + + // The live service caps maximumPageSize at 1000 rather than clamping silently. + SwfException tooBig = assertThrows(SwfException.class, () -> + east.listWorkflowTypes(ListWorkflowTypesRequest.builder() + .domain(domain).registrationStatus(RegistrationStatus.REGISTERED) + .maximumPageSize(1001).build())); + assertEquals("ValidationException", tooBig.awsErrorDetails().errorCode()); + + SwfException badToken = assertThrows(SwfException.class, () -> + east.listWorkflowTypes(ListWorkflowTypesRequest.builder() + .domain(domain).registrationStatus(RegistrationStatus.REGISTERED) + .nextPageToken("not-a-real-token").build())); + assertEquals("ValidationException", badToken.awsErrorDetails().errorCode()); + assertEquals("Invalid token", badToken.awsErrorDetails().errorMessage()); + } + + private static List typeNames(ListWorkflowTypesResponse response) { + return response.typeInfos().stream().map(i -> i.workflowType().name()).toList(); + } + + private static String emptyToNull(String value) { + return value == null || value.isEmpty() ? null : value; + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfTest.java new file mode 100644 index 0000000000..c6a3730d3a --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfTest.java @@ -0,0 +1,403 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import software.amazon.awssdk.services.swf.SwfClient; +import software.amazon.awssdk.services.swf.model.ActivityTaskCompletedEventAttributes; +import software.amazon.awssdk.services.swf.model.ActivityType; +import software.amazon.awssdk.services.swf.model.ChildPolicy; +import software.amazon.awssdk.services.swf.model.CloseStatus; +import software.amazon.awssdk.services.swf.model.Decision; +import software.amazon.awssdk.services.swf.model.DecisionType; +import software.amazon.awssdk.services.swf.model.DescribeDomainRequest; +import software.amazon.awssdk.services.swf.model.DescribeDomainResponse; +import software.amazon.awssdk.services.swf.model.DescribeWorkflowExecutionRequest; +import software.amazon.awssdk.services.swf.model.DescribeWorkflowExecutionResponse; +import software.amazon.awssdk.services.swf.model.DescribeWorkflowTypeRequest; +import software.amazon.awssdk.services.swf.model.DescribeWorkflowTypeResponse; +import software.amazon.awssdk.services.swf.model.DomainAlreadyExistsException; +import software.amazon.awssdk.services.swf.model.EventType; +import software.amazon.awssdk.services.swf.model.ExecutionStatus; +import software.amazon.awssdk.services.swf.model.GetWorkflowExecutionHistoryRequest; +import software.amazon.awssdk.services.swf.model.GetWorkflowExecutionHistoryResponse; +import software.amazon.awssdk.services.swf.model.PollForActivityTaskResponse; +import software.amazon.awssdk.services.swf.model.PollForDecisionTaskResponse; +import software.amazon.awssdk.services.swf.model.HistoryEvent; +import software.amazon.awssdk.services.swf.model.ListDomainsRequest; +import software.amazon.awssdk.services.swf.model.PollForActivityTaskRequest; +import software.amazon.awssdk.services.swf.model.PollForDecisionTaskRequest; +import software.amazon.awssdk.services.swf.model.RegisterActivityTypeRequest; +import software.amazon.awssdk.services.swf.model.RegisterDomainRequest; +import software.amazon.awssdk.services.swf.model.RegisterWorkflowTypeRequest; +import software.amazon.awssdk.services.swf.model.RegistrationStatus; +import software.amazon.awssdk.services.swf.model.RespondActivityTaskCompletedRequest; +import software.amazon.awssdk.services.swf.model.RespondDecisionTaskCompletedRequest; +import software.amazon.awssdk.services.swf.model.ScheduleActivityTaskDecisionAttributes; +import software.amazon.awssdk.services.swf.model.SignalWorkflowExecutionRequest; +import software.amazon.awssdk.services.swf.model.StartWorkflowExecutionRequest; +import software.amazon.awssdk.services.swf.model.TaskList; +import software.amazon.awssdk.services.swf.model.TerminateWorkflowExecutionRequest; +import software.amazon.awssdk.services.swf.model.TypeAlreadyExistsException; +import software.amazon.awssdk.services.swf.model.UnknownResourceException; +import software.amazon.awssdk.services.swf.model.WorkflowExecution; +import software.amazon.awssdk.services.swf.model.WorkflowExecutionAlreadyStartedException; +import software.amazon.awssdk.services.swf.model.WorkflowType; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Drives the SWF emulation with the real AWS SDK v2 client. + * + *

This is the check the raw-HTTP tests cannot make: the SDK must deserialize every + * response into its generated model (epoch-second timestamps into {@code Instant}, + * event attributes into the right {@code *EventAttributes} member) and map each fault + * onto its typed exception class. A response that is merely "valid JSON" fails here. + */ +@DisplayName("SWF workflow lifecycle") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SwfTest { + + private static final String DOMAIN = "sdk-swf-" + System.currentTimeMillis(); + private static final String TASK_LIST = "sdk-swf-tl"; + private static final WorkflowType WORKFLOW_TYPE = + WorkflowType.builder().name("SdkWorkflow").version("1.0").build(); + private static final ActivityType ACTIVITY_TYPE = + ActivityType.builder().name("SdkActivity").version("1.0").build(); + + private static SwfClient swf; + private static String runId; + + @BeforeAll + static void setup() { + swf = TestFixtures.swfClient(); + } + + @AfterAll + static void cleanup() { + if (swf != null) { + swf.close(); + } + } + + @Test + @Order(1) + @DisplayName("Register domain and describe it") + void registerDomain() { + swf.registerDomain(RegisterDomainRequest.builder() + .name(DOMAIN) + .description("sdk compatibility domain") + .workflowExecutionRetentionPeriodInDays("7") + .build()); + + DescribeDomainResponse described = swf.describeDomain( + DescribeDomainRequest.builder().name(DOMAIN).build()); + + assertThat(described.domainInfo().name()).isEqualTo(DOMAIN); + assertThat(described.domainInfo().status()).isEqualTo(RegistrationStatus.REGISTERED); + assertThat(described.domainInfo().arn()).contains(":/domain/" + DOMAIN); + assertThat(described.configuration().workflowExecutionRetentionPeriodInDays()).isEqualTo("7"); + + assertThat(swf.listDomains(ListDomainsRequest.builder() + .registrationStatus(RegistrationStatus.REGISTERED).build()) + .domainInfos()) + .anyMatch(info -> DOMAIN.equals(info.name())); + } + + @Test + @Order(2) + @DisplayName("Duplicate domain raises DomainAlreadyExistsException") + void duplicateDomainIsTyped() { + // The fault must arrive with the namespaced __type SWF uses, or the SDK falls back + // to a generic SwfException and this assertion fails. + assertThatThrownBy(() -> swf.registerDomain(RegisterDomainRequest.builder() + .name(DOMAIN) + .workflowExecutionRetentionPeriodInDays("7") + .build())) + .isInstanceOf(DomainAlreadyExistsException.class); + } + + @Test + @Order(3) + @DisplayName("Unknown domain raises UnknownResourceException") + void unknownDomainIsTyped() { + assertThatThrownBy(() -> swf.describeDomain( + DescribeDomainRequest.builder().name("sdk-swf-missing").build())) + .isInstanceOf(UnknownResourceException.class) + .hasMessageContaining("Unknown domain: sdk-swf-missing"); + } + + @Test + @Order(4) + @DisplayName("Register workflow and activity types with defaults") + void registerTypes() { + swf.registerWorkflowType(RegisterWorkflowTypeRequest.builder() + .domain(DOMAIN) + .name(WORKFLOW_TYPE.name()) + .version(WORKFLOW_TYPE.version()) + .defaultTaskList(TaskList.builder().name(TASK_LIST).build()) + .defaultTaskStartToCloseTimeout("60") + .defaultExecutionStartToCloseTimeout("3600") + .defaultChildPolicy(ChildPolicy.TERMINATE) + .build()); + + swf.registerActivityType(RegisterActivityTypeRequest.builder() + .domain(DOMAIN) + .name(ACTIVITY_TYPE.name()) + .version(ACTIVITY_TYPE.version()) + .defaultTaskList(TaskList.builder().name(TASK_LIST).build()) + .defaultTaskScheduleToStartTimeout("60") + .defaultTaskStartToCloseTimeout("300") + .build()); + + DescribeWorkflowTypeResponse described = swf.describeWorkflowType( + DescribeWorkflowTypeRequest.builder().domain(DOMAIN).workflowType(WORKFLOW_TYPE).build()); + + assertThat(described.typeInfo().status()).isEqualTo(RegistrationStatus.REGISTERED); + // creationDate arrives as an epoch-second number; the SDK models it as Instant, so a + // formatted date on the wire would fail to deserialize. + assertThat(described.typeInfo().creationDate()).isNotNull(); + assertThat(described.configuration().defaultTaskList().name()).isEqualTo(TASK_LIST); + assertThat(described.configuration().defaultChildPolicy()).isEqualTo(ChildPolicy.TERMINATE); + + assertThatThrownBy(() -> swf.registerWorkflowType(RegisterWorkflowTypeRequest.builder() + .domain(DOMAIN) + .name(WORKFLOW_TYPE.name()) + .version(WORKFLOW_TYPE.version()) + .build())) + .isInstanceOf(TypeAlreadyExistsException.class); + } + + @Test + @Order(5) + @DisplayName("Start execution seeds the initial history") + void startExecution() { + runId = swf.startWorkflowExecution(StartWorkflowExecutionRequest.builder() + .domain(DOMAIN) + .workflowId("sdk-wf-1") + .workflowType(WORKFLOW_TYPE) + .input("{\"sdk\":true}") + .tagList("sdk", "compat") + .build()) + .runId(); + assertThat(runId).isNotBlank(); + + GetWorkflowExecutionHistoryResponse history = swf.getWorkflowExecutionHistory(GetWorkflowExecutionHistoryRequest.builder() + .domain(DOMAIN) + .execution(execution()) + .build()); + + assertThat(history.events()).hasSize(2); + HistoryEvent started = history.events().get(0); + assertThat(started.eventId()).isEqualTo(1L); + assertThat(started.eventType()).isEqualTo(EventType.WORKFLOW_EXECUTION_STARTED); + assertThat(started.eventTimestamp()).isNotNull(); + assertThat(started.workflowExecutionStartedEventAttributes().input()).isEqualTo("{\"sdk\":true}"); + assertThat(started.workflowExecutionStartedEventAttributes().taskList().name()).isEqualTo(TASK_LIST); + assertThat(started.workflowExecutionStartedEventAttributes().tagList()).contains("sdk", "compat"); + assertThat(history.events().get(1).eventType()).isEqualTo(EventType.DECISION_TASK_SCHEDULED); + + assertThatThrownBy(() -> swf.startWorkflowExecution(StartWorkflowExecutionRequest.builder() + .domain(DOMAIN) + .workflowId("sdk-wf-1") + .workflowType(WORKFLOW_TYPE) + .build())) + .isInstanceOf(WorkflowExecutionAlreadyStartedException.class); + } + + @Test + @Order(6) + @DisplayName("Decider schedules an activity, worker completes it, decider closes the execution") + void deciderAndWorkerHandshake() { + PollForDecisionTaskResponse decisionTask = pollDecisionTask(); + assertThat(decisionTask.taskToken()).isNotBlank(); + assertThat(decisionTask.workflowExecution().runId()).isEqualTo(runId); + assertThat(decisionTask.workflowType().name()).isEqualTo(WORKFLOW_TYPE.name()); + assertThat(decisionTask.previousStartedEventId()).isZero(); + assertThat(decisionTask.events()).extracting(HistoryEvent::eventType) + .contains(EventType.DECISION_TASK_STARTED); + + swf.respondDecisionTaskCompleted(RespondDecisionTaskCompletedRequest.builder() + .taskToken(decisionTask.taskToken()) + .executionContext("sdk-step-1") + .decisions(Decision.builder() + .decisionType(DecisionType.SCHEDULE_ACTIVITY_TASK) + .scheduleActivityTaskDecisionAttributes( + ScheduleActivityTaskDecisionAttributes.builder() + .activityId("sdk-act-1") + .activityType(ACTIVITY_TYPE) + .input("{\"work\":1}") + .build()) + .build()) + .build()); + + PollForActivityTaskResponse activityTask = swf.pollForActivityTask(PollForActivityTaskRequest.builder() + .domain(DOMAIN) + .taskList(TaskList.builder().name(TASK_LIST).build()) + .identity("sdk-worker") + .build()); + assertThat(activityTask.taskToken()).isNotBlank(); + assertThat(activityTask.activityId()).isEqualTo("sdk-act-1"); + assertThat(activityTask.activityType().name()).isEqualTo(ACTIVITY_TYPE.name()); + assertThat(activityTask.input()).isEqualTo("{\"work\":1}"); + + swf.respondActivityTaskCompleted(RespondActivityTaskCompletedRequest.builder() + .taskToken(activityTask.taskToken()) + .result("{\"done\":true}") + .build()); + + PollForDecisionTaskResponse afterActivity = pollDecisionTask(); + assertThat(afterActivity.events()).extracting(HistoryEvent::eventType) + .contains(EventType.ACTIVITY_TASK_COMPLETED); + ActivityTaskCompletedEventAttributes completed = afterActivity.events().stream() + .filter(event -> event.eventType() == EventType.ACTIVITY_TASK_COMPLETED) + .findFirst() + .orElseThrow() + .activityTaskCompletedEventAttributes(); + assertThat(completed.result()).isEqualTo("{\"done\":true}"); + + swf.respondDecisionTaskCompleted(RespondDecisionTaskCompletedRequest.builder() + .taskToken(afterActivity.taskToken()) + .decisions(Decision.builder() + .decisionType(DecisionType.COMPLETE_WORKFLOW_EXECUTION) + .completeWorkflowExecutionDecisionAttributes(attrs -> attrs.result("{\"ok\":true}")) + .build()) + .build()); + + DescribeWorkflowExecutionResponse described = swf.describeWorkflowExecution( + DescribeWorkflowExecutionRequest.builder().domain(DOMAIN).execution(execution()).build()); + assertThat(described.executionInfo().executionStatus()).isEqualTo(ExecutionStatus.CLOSED); + assertThat(described.executionInfo().closeStatus()).isEqualTo(CloseStatus.COMPLETED); + assertThat(described.executionInfo().closeTimestamp()).isNotNull(); + assertThat(described.openCounts().openActivityTasks()).isZero(); + assertThat(described.latestExecutionContext()).isEqualTo("sdk-step-1"); + } + + @Test + @Order(7) + @DisplayName("History deserializes every event into its typed attributes") + void historyIsFullyTyped() { + List events = swf.getWorkflowExecutionHistory( + GetWorkflowExecutionHistoryRequest.builder() + .domain(DOMAIN).execution(execution()).build()) + .events(); + + assertThat(events).extracting(HistoryEvent::eventType).containsExactly( + EventType.WORKFLOW_EXECUTION_STARTED, + EventType.DECISION_TASK_SCHEDULED, + EventType.DECISION_TASK_STARTED, + EventType.DECISION_TASK_COMPLETED, + EventType.ACTIVITY_TASK_SCHEDULED, + EventType.ACTIVITY_TASK_STARTED, + EventType.ACTIVITY_TASK_COMPLETED, + EventType.DECISION_TASK_SCHEDULED, + EventType.DECISION_TASK_STARTED, + EventType.DECISION_TASK_COMPLETED, + EventType.WORKFLOW_EXECUTION_COMPLETED); + + // eventIds are contiguous from 1, as SWF guarantees. + for (int i = 0; i < events.size(); i++) { + assertThat(events.get(i).eventId()).isEqualTo(i + 1L); + } + + HistoryEvent scheduled = events.get(4); + assertThat(scheduled.activityTaskScheduledEventAttributes().activityId()).isEqualTo("sdk-act-1"); + assertThat(scheduled.activityTaskScheduledEventAttributes().startToCloseTimeout()).isEqualTo("300"); + assertThat(scheduled.activityTaskScheduledEventAttributes().taskList().name()).isEqualTo(TASK_LIST); + } + + @Test + @Order(8) + @DisplayName("Signal and terminate drive a second execution") + void signalAndTerminate() { + String signalRunId = swf.startWorkflowExecution(StartWorkflowExecutionRequest.builder() + .domain(DOMAIN) + .workflowId("sdk-wf-2") + .workflowType(WORKFLOW_TYPE) + .build()) + .runId(); + WorkflowExecution second = WorkflowExecution.builder() + .workflowId("sdk-wf-2").runId(signalRunId).build(); + + swf.signalWorkflowExecution(SignalWorkflowExecutionRequest.builder() + .domain(DOMAIN) + .workflowId("sdk-wf-2") + .runId(signalRunId) + .signalName("sdk-signal") + .input("{\"resume\":true}") + .build()); + + assertThat(swf.getWorkflowExecutionHistory(GetWorkflowExecutionHistoryRequest.builder() + .domain(DOMAIN).execution(second).build()) + .events()) + .filteredOn(event -> event.eventType() == EventType.WORKFLOW_EXECUTION_SIGNALED) + .singleElement() + .satisfies(event -> { + assertThat(event.workflowExecutionSignaledEventAttributes().signalName()) + .isEqualTo("sdk-signal"); + assertThat(event.workflowExecutionSignaledEventAttributes().input()) + .isEqualTo("{\"resume\":true}"); + }); + + swf.terminateWorkflowExecution(TerminateWorkflowExecutionRequest.builder() + .domain(DOMAIN) + .workflowId("sdk-wf-2") + .runId(signalRunId) + .reason("sdk-test") + .build()); + + assertThat(swf.describeWorkflowExecution(DescribeWorkflowExecutionRequest.builder() + .domain(DOMAIN).execution(second).build()) + .executionInfo().closeStatus()) + .isEqualTo(CloseStatus.TERMINATED); + } + + @Test + @Order(9) + @DisplayName("Counts and closed-execution listing reflect the finished work") + void countsAndListing() { + assertThat(swf.countClosedWorkflowExecutions(builder -> builder + .domain(DOMAIN) + .startTimeFilter(filter -> filter.oldestDate(java.time.Instant.EPOCH))) + .count()) + .isGreaterThanOrEqualTo(2); + + assertThat(swf.listClosedWorkflowExecutions(builder -> builder + .domain(DOMAIN) + .startTimeFilter(filter -> filter.oldestDate(java.time.Instant.EPOCH))) + .executionInfos()) + .extracting(info -> info.execution().workflowId()) + .contains("sdk-wf-1", "sdk-wf-2"); + } + + // ── helpers ───────────────────────────────────────────────────────────── + + private static WorkflowExecution execution() { + return WorkflowExecution.builder().workflowId("sdk-wf-1").runId(runId).build(); + } + + /** + * Polls until a task arrives. The emulator answers an idle poll immediately with an + * empty token rather than long-polling, so a decider loops instead of blocking. + */ + private static PollForDecisionTaskResponse pollDecisionTask() { + for (int attempt = 0; attempt < 20; attempt++) { + PollForDecisionTaskResponse task = swf.pollForDecisionTask(PollForDecisionTaskRequest.builder() + .domain(DOMAIN) + .taskList(TaskList.builder().name(TASK_LIST).build()) + .identity("sdk-decider") + .build()); + if (task.taskToken() != null && !task.taskToken().isEmpty()) { + return task; + } + } + throw new AssertionError("no decision task became available"); + } +} diff --git a/docs/services/swf.md b/docs/services/swf.md new file mode 100644 index 0000000000..b7f0ac851a --- /dev/null +++ b/docs/services/swf.md @@ -0,0 +1,262 @@ +# SWF + +**Protocol:** JSON 1.0 (`X-Amz-Target: SimpleWorkflowService.*`) +**Endpoint:** `POST http://localhost:4566/` + +Domains, workflow and activity type registration, and the workflow execution state +machine: decision tasks, activity tasks, timers, signals, child workflows, and timeouts. + +## Supported Actions + + +| Action | Description | +| --- | --- | +| `RegisterDomain` | Create a domain with a workflow-execution retention period | +| `DescribeDomain` | Get a domain's status, description, ARN, and retention configuration | +| `ListDomains` | List domains by registration status | +| `DeprecateDomain` | Deprecate a domain, blocking new registrations and executions | +| `UndeprecateDomain` | Return a deprecated domain to REGISTERED | +| `RegisterWorkflowType` | Register a workflow type and its execution defaults | +| `DescribeWorkflowType` | Get a workflow type's status and registered defaults | +| `ListWorkflowTypes` | List workflow types by registration status, optionally by name | +| `DeprecateWorkflowType` | Deprecate a workflow type, blocking new executions | +| `UndeprecateWorkflowType` | Return a deprecated workflow type to REGISTERED | +| `DeleteWorkflowType` | Delete a deprecated workflow type | +| `RegisterActivityType` | Register an activity type and its task timeout defaults | +| `DescribeActivityType` | Get an activity type's status and registered defaults | +| `ListActivityTypes` | List activity types by registration status, optionally by name | +| `DeprecateActivityType` | Deprecate an activity type, blocking new task scheduling | +| `UndeprecateActivityType` | Return a deprecated activity type to REGISTERED | +| `DeleteActivityType` | Delete a deprecated activity type | +| `StartWorkflowExecution` | Start an execution, resolving unset fields from the type defaults | +| `DescribeWorkflowExecution` | Get an execution's status, configuration, and open task counts | +| `GetWorkflowExecutionHistory` | Read an execution's history, paginated and optionally reversed | +| `ListOpenWorkflowExecutions` | List open executions with execution, type, tag, and time filters | +| `ListClosedWorkflowExecutions` | List closed executions, additionally filtered by close status | +| `CountOpenWorkflowExecutions` | Count open executions matching the same filters | +| `CountClosedWorkflowExecutions` | Count closed executions matching the same filters | +| `CountPendingActivityTasks` | Count activity tasks awaiting a worker on a task list | +| `CountPendingDecisionTasks` | Count decision tasks awaiting a decider on a task list | +| `PollForDecisionTask` | Claim a decision task with the execution history the decider needs | +| `RespondDecisionTaskCompleted` | Apply a decider's decisions in order | +| `PollForActivityTask` | Claim an activity task with its input | +| `RecordActivityTaskHeartbeat` | Report progress and learn whether cancellation was requested | +| `RespondActivityTaskCompleted` | Complete an activity task with a result | +| `RespondActivityTaskFailed` | Fail an activity task with a reason and details | +| `RespondActivityTaskCanceled` | Confirm an activity task was canceled | +| `SignalWorkflowExecution` | Deliver a signal to an open execution | +| `RequestCancelWorkflowExecution` | Ask an execution's decider to cancel it | +| `TerminateWorkflowExecution` | Close an execution immediately, applying its child policy | +| `ListTagsForResource` | List a domain's tags | +| `TagResource` | Add tags to a domain | +| `UntagResource` | Remove tags from a domain | + + +All 39 modeled operations are implemented. + +## Decisions + +`RespondDecisionTaskCompleted` applies decisions in order: + +| Decision | Behavior | +|----------|----------| +| `ScheduleActivityTask` | Schedules an activity task; timeouts fall back to the activity type's registration defaults | +| `RequestCancelActivityTask` | Requests cancellation; a task that has not started yet is canceled immediately | +| `CompleteWorkflowExecution` | Closes the execution as `COMPLETED` | +| `FailWorkflowExecution` | Closes the execution as `FAILED` | +| `CancelWorkflowExecution` | Closes the execution as `CANCELED` | +| `ContinueAsNewWorkflowExecution` | Closes the run as `CONTINUED_AS_NEW` and starts a successor run | +| `RecordMarker` | Appends `MarkerRecorded` | +| `StartTimer` / `CancelTimer` | Starts or cancels a timer; a due timer fires `TimerFired` | +| `SignalExternalWorkflowExecution` | Delivers a signal to another execution in the same domain | +| `RequestCancelExternalWorkflowExecution` | Requests cancellation of another execution | +| `StartChildWorkflowExecution` | Starts a child execution and reports its outcome back to the parent | +| `ScheduleLambdaFunction` | Invokes the function through Floci's Lambda service and records its result (see [Lambda functions](#lambda-functions)) | + +A decision that cannot be applied appends its `*Failed` event with the AWS cause +(`ACTIVITY_TYPE_DOES_NOT_EXIST`, `ACTIVITY_ID_ALREADY_IN_USE`, `TIMER_ID_UNKNOWN`, +`UNHANDLED_DECISION`, …) instead of failing the request, and the decider is given a +fresh decision task. A closing decision must be last in the batch: a batch with anything +after it is rejected with `ValidationException` ("Close must be last decision in list") and +no decision is applied. + +## Timeouts + +A background sweep expires timeouts and appends the matching event: + +| Timeout | Event | `timeoutType` | +|---------|-------|---------------| +| Activity schedule-to-start | `ActivityTaskTimedOut` | `SCHEDULE_TO_START` | +| Activity start-to-close | `ActivityTaskTimedOut` | `START_TO_CLOSE` | +| Activity schedule-to-close | `ActivityTaskTimedOut` | `SCHEDULE_TO_CLOSE` | +| Activity heartbeat | `ActivityTaskTimedOut` | `HEARTBEAT` | +| Decision task start-to-close | `DecisionTaskTimedOut` | `START_TO_CLOSE` | +| Workflow execution start-to-close | `WorkflowExecutionTimedOut` | `START_TO_CLOSE` | + +Any timeout other than the workflow's own schedules a new decision task. The literal +`NONE` disables a timeout, as in AWS. + +## Child policy + +When an execution closes, its `childPolicy` is applied to still-open children: +`TERMINATE` terminates them with cause `CHILD_POLICY_APPLIED`, `REQUEST_CANCEL` requests +cancellation, and `ABANDON` leaves them running. + +## Lambda functions + +`ScheduleLambdaFunction` runs a real function: Floci invokes it through its own Lambda +service, which executes it in a container exactly as an `Invoke` API call would, and records +the outcome in history. Deploy the function with the Lambda API first — SWF resolves it by +name in the region its domain was registered in. + +The execution needs a `lambdaRole`, taken from `StartWorkflowExecution`'s `lambdaRole` or, +when absent, the workflow type's `defaultLambdaRole`. The role is not evaluated as a policy; +its presence is what SWF requires in order to invoke. + +| Outcome | History | +|---|---| +| Success | `LambdaFunctionScheduled` → `LambdaFunctionStarted` → `LambdaFunctionCompleted` with the response as `result` | +| Handler raised | `…Scheduled` → `…Started` → `LambdaFunctionFailed` with `reason` `Handled`/`Unhandled` and the error payload as `details` | +| Function not found | `…Scheduled` → `…Started` → `LambdaFunctionFailed` with `reason` `ResourceNotFoundException` | +| No `lambdaRole` | `…Scheduled` → `StartLambdaFunctionFailed` with cause `ASSUME_ROLE_FAILED`; the function is never started | + +A decision with no `input` delivers `{}` to the handler, and reusing an `id` is accepted — +SWF does not report `ID_ALREADY_IN_USE` for Lambda invocations the way it does for activity +ids. Every outcome schedules a fresh decision task so the decider can react. + +## Regions + +SWF names are unique per region, so all state is region-scoped: registering `orders` in +`us-east-1` and again in `eu-west-1` creates two independent domains, each with its own +description, retention period, and ARN. Types, executions, and task tokens follow the same +rule — a `runId` from one region does not resolve in another, `ListDomains` and the type +listings only report the caller's region, and a decision or activity task is only handed to a +poller in the region that owns it. + +## Configuration + +```yaml +floci: + services: + swf: + enabled: true + timeout-sweep-enabled: true + timeout-sweep-interval-seconds: 1 +``` + +| Setting | Env var | Default | Description | +|---------|---------|---------|-------------| +| `enabled` | `FLOCI_SERVICES_SWF_ENABLED` | `true` | Enable the service | +| `timeout-sweep-enabled` | `FLOCI_SERVICES_SWF_TIMEOUT_SWEEP_ENABLED` | `true` | Run the background timeout sweep | +| `timeout-sweep-interval-seconds` | `FLOCI_SERVICES_SWF_TIMEOUT_SWEEP_INTERVAL_SECONDS` | `1` | Sweep interval | + +## Example + +Register a domain and the types an execution needs: + +```bash +aws --endpoint-url http://localhost:4566 swf register-domain \ + --name orders --workflow-execution-retention-period-in-days 7 + +aws --endpoint-url http://localhost:4566 swf register-workflow-type \ + --domain orders --name OrderWorkflow --workflow-version 1.0 \ + --default-task-list name=orders-tl \ + --default-task-start-to-close-timeout 60 \ + --default-execution-start-to-close-timeout 3600 \ + --default-child-policy TERMINATE + +aws --endpoint-url http://localhost:4566 swf register-activity-type \ + --domain orders --name ChargeCard --activity-version 1.0 \ + --default-task-list name=orders-tl \ + --default-task-schedule-to-start-timeout 60 \ + --default-task-start-to-close-timeout 300 +``` + +Start an execution: + +```bash +aws --endpoint-url http://localhost:4566 swf start-workflow-execution \ + --domain orders --workflow-id order-1234 \ + --workflow-type name=OrderWorkflow,version=1.0 \ + --input '{"orderId":"1234"}' +``` + +Poll as a decider and schedule the activity: + +```bash +aws --endpoint-url http://localhost:4566 swf poll-for-decision-task \ + --domain orders --task-list name=orders-tl --identity decider-1 > task.json + +TASK_TOKEN=$(jq -r .taskToken task.json) + +cat > decisions.json <<'EOF' +[{"decisionType": "ScheduleActivityTask", + "scheduleActivityTaskDecisionAttributes": { + "activityId": "charge-1", + "activityType": {"name": "ChargeCard", "version": "1.0"}, + "input": "{\"amount\":4200}"}}] +EOF + +aws --endpoint-url http://localhost:4566 swf respond-decision-task-completed \ + --task-token "$TASK_TOKEN" --decisions file://decisions.json +``` + +Poll as a worker and complete the activity: + +```bash +aws --endpoint-url http://localhost:4566 swf poll-for-activity-task \ + --domain orders --task-list name=orders-tl --identity worker-1 > activity.json + +ACTIVITY_TOKEN=$(jq -r .taskToken activity.json) + +aws --endpoint-url http://localhost:4566 swf respond-activity-task-completed \ + --task-token "$ACTIVITY_TOKEN" --result '{"charged":true}' +``` + +Read the history: + +```bash +aws --endpoint-url http://localhost:4566 swf get-workflow-execution-history \ + --domain orders --execution workflowId=order-1234,runId= +``` + +## Errors + +Faults use the AWS codes and messages, so SDK error handling works unchanged: + +| Fault | Raised by | +|-------|-----------| +| `UnknownResourceFault` | Unknown domain, type, execution, or task token; also an activity task token whose task has already closed, reported as `Unknown activity, scheduledEventId = N` | +| `DomainAlreadyExistsFault` | `RegisterDomain` for an existing domain; `UndeprecateDomain` on a registered domain | +| `DomainDeprecatedFault` | Registering into, or starting an execution in, a deprecated domain | +| `TypeAlreadyExistsFault` | Registering an existing type; undeprecating a registered type | +| `TypeDeprecatedFault` | Starting an execution of a deprecated workflow type | +| `TypeNotDeprecatedFault` | `DeleteWorkflowType` / `DeleteActivityType` before deprecation | +| `WorkflowExecutionAlreadyStartedFault` | `StartWorkflowExecution` while an execution with that `workflowId` is open | +| `DefaultUndefinedFault` | A required field is absent from both the request and the type's defaults | +| `TooManyTagsFault` | More than 50 tags on a domain | +| `ValidationException` | Missing required member, a value outside an enum, or a closing decision that is not last | + +## Limitations + +- **Long polling.** `PollForDecisionTask` and `PollForActivityTask` return immediately + instead of holding the connection for up to 60 seconds. Workers that loop on an empty + poll behave the same; workers that rely on the call blocking will spin. +- **Task tokens are in-memory.** Tokens do not survive a restart even under persistent + storage modes, matching the fact that SWF tokens are not durable handles. +- **Retention.** `workflowExecutionRetentionPeriodInDays` is stored and returned but + closed executions are not pruned. +- **Pagination.** `maximumPageSize` and `nextPageToken` are honored on every paginated + operation — the history, the execution listings, the registration listings (`ListDomains`, + `ListWorkflowTypes`, `ListActivityTypes`) and `PollForDecisionTask`. All of them apply the + service's 1000 cap, rejecting a larger value rather than clamping it. Tokens are opaque and + are not interchangeable with real SWF tokens. +- **`PollForDecisionTask` continuation.** A request carrying `nextPageToken` continues the + earlier poll instead of claiming a new task, so it returns the same `startedEventId`, + `previousStartedEventId` and `workflowExecution` with the next page of that task's history. + `startAtPreviousStartedEvent` trims the window to events from `previousStartedEventId` + onward, which the service treats as inclusive. +- **Decision batches are all-or-nothing.** A batch containing an unknown `decisionType`, or a + closing decision that is not last, is rejected with `ValidationException` before anything is + applied: no `DecisionTaskCompleted`, no earlier decision, and the task token stays claimable + for a corrected batch. diff --git a/mkdocs.yml b/mkdocs.yml index b220ae8a18..015029f406 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -90,6 +90,7 @@ nav: - Secrets Manager: services/secrets-manager.md - CloudFormation: services/cloudformation.md - Step Functions: services/step-functions.md + - SWF: services/swf.md - IAM: services/iam.md - STS: services/sts.md - ElastiCache: services/elasticache.md diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index eeac0f375d..a1414c77b9 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -550,6 +550,7 @@ public interface EmulatorConfig { KmsServiceConfig kms(); CognitoServiceConfig cognito(); StepFunctionsServiceConfig stepfunctions(); + SwfServiceConfig swf(); CloudFormationServiceConfig cloudformation(); AcmServiceConfig acm(); AthenaServiceConfig athena(); @@ -1080,6 +1081,26 @@ public interface EmulatorConfig { boolean allowPlaintextHttp(); } + interface SwfServiceConfig { + @WithDefault("true") + boolean enabled(); + + /** + * Run the background sweep that expires activity, decision, workflow and timer + * timeouts. Setting this to {@code false} leaves timeouts recorded but never + * fired, which is useful for tests that drive the clock themselves. + */ + @WithDefault("true") + boolean timeoutSweepEnabled(); + + /** + * How often the timeout sweep runs. SWF timeouts are specified in whole seconds, + * so a 1s sweep bounds the observable lateness of an expiry at one second. + */ + @WithDefault("1") + long timeoutSweepIntervalSeconds(); + } + interface CloudFormationServiceConfig { @WithDefault("true") boolean enabled(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java index 853a2d138a..5b3e40c751 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java @@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamsJsonHandler; import io.github.hectorvent.floci.services.sns.SnsJsonHandler; import io.github.hectorvent.floci.services.sqs.SqsJsonHandler; import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler; +import io.github.hectorvent.floci.services.swf.SwfJsonHandler; import jakarta.inject.Inject; import jakarta.ws.rs.*; import jakarta.ws.rs.core.Context; @@ -45,6 +46,7 @@ public class AwsJsonController { private final StepFunctionsJsonHandler sfnJsonHandler; private final CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler; private final CloudControlJsonHandler cloudControlJsonHandler; + private final SwfJsonHandler swfJsonHandler; @Inject public AwsJsonController(ObjectMapper objectMapper, ResolvedServiceCatalog catalog, @@ -54,7 +56,8 @@ public class AwsJsonController { SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler, StepFunctionsJsonHandler sfnJsonHandler, CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler, - CloudControlJsonHandler cloudControlJsonHandler) { + CloudControlJsonHandler cloudControlJsonHandler, + SwfJsonHandler swfJsonHandler) { this.objectMapper = objectMapper; this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); this.catalog = catalog; @@ -66,6 +69,7 @@ public class AwsJsonController { this.sfnJsonHandler = sfnJsonHandler; this.cloudWatchMetricsJsonHandler = cloudWatchMetricsJsonHandler; this.cloudControlJsonHandler = cloudControlJsonHandler; + this.swfJsonHandler = swfJsonHandler; } @POST @@ -110,6 +114,7 @@ public class AwsJsonController { case "sqs" -> sqsJsonHandler.handle(action, request, region); case "sns" -> snsJsonHandler.handle(action, request, region); case "states" -> sfnJsonHandler.handle(action, request, region); + case "swf" -> swfJsonHandler.handle(action, request, region); case "monitoring" -> cloudWatchMetricsJsonHandler.handle(action, request, region); case "cloudcontrol" -> cloudControlJsonHandler.handle(action, request, region); default -> null; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index 5ad0e0737c..b5d9384ac0 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -202,6 +202,10 @@ public class ResolvedServiceCatalog { "stepfunctions", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON, ServiceProtocol.CBOR), Set.of("AWSStepFunctions."), Set.of("states"), Set.of("SFN"), Set.of()), + descriptor("swf", "swf", config.services().swf().enabled(), true, + "swf", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, + protocols(ServiceProtocol.JSON), + Set.of("SimpleWorkflowService."), Set.of("swf"), Set.of(), Set.of()), descriptor("cloudformation", "cloudformation", config.services().cloudformation().enabled(), true, null, null, 5000L, null, ServiceProtocol.QUERY, protocols(ServiceProtocol.QUERY), diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/LambdaInvocationResult.java b/src/main/java/io/github/hectorvent/floci/services/swf/LambdaInvocationResult.java new file mode 100644 index 0000000000..2fb7b3b9df --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/LambdaInvocationResult.java @@ -0,0 +1,12 @@ +package io.github.hectorvent.floci.services.swf; + +/** + * A Lambda invocation's outcome, reduced to what SWF records in history. + * + * @param payload the function's response body, recorded as the LambdaFunctionCompleted + * {@code result} or, on a handler error, the Failed {@code details} + * @param functionError the Lambda {@code FunctionError} header ({@code Handled}/{@code Unhandled}), + * or {@code null} when the invocation succeeded + */ +record LambdaInvocationResult(String payload, String functionError) { +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/LambdaInvoker.java b/src/main/java/io/github/hectorvent/floci/services/swf/LambdaInvoker.java new file mode 100644 index 0000000000..784e0b27ed --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/LambdaInvoker.java @@ -0,0 +1,21 @@ +package io.github.hectorvent.floci.services.swf; + +/** + * The slice of Lambda invocation SWF needs, so {@link SwfService} depends on a two-method + * seam rather than on {@code LambdaService} itself. + * + *

This keeps the service unit-testable without a Docker daemon or the Lambda container + * stack: {@code SwfServiceTest} supplies a stub, while at runtime {@link SwfLambdaInvoker} + * delegates to the real Lambda service and its containers. + */ +interface LambdaInvoker { + + /** + * Invokes {@code functionName} synchronously and returns its response. + * + * @throws io.github.hectorvent.floci.core.common.AwsException if the function cannot be + * resolved or invoked, so the caller can record the AWS error code as the + * LambdaFunctionFailed {@code reason} + */ + LambdaInvocationResult invoke(String region, String functionName, byte[] payload); +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/SwfException.java b/src/main/java/io/github/hectorvent/floci/services/swf/SwfException.java new file mode 100644 index 0000000000..c666733321 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/SwfException.java @@ -0,0 +1,30 @@ +package io.github.hectorvent.floci.services.swf; + +import io.github.hectorvent.floci.core.common.AwsException; + +/** + * An SWF fault, which carries two different spellings of its name. + * + *

The response body's {@code __type} is namespaced + * ({@code com.amazonaws.swf.base.model#UnknownResourceFault}), while the + * {@code x-amzn-query-error} header carries the bare fault name. botocore prefers + * the header when both are present, so a namespaced value there makes the AWS CLI + * print {@code com.amazonaws.swf.base.model#UnknownResourceFault} as the error code + * where real SWF prints {@code UnknownResourceFault}. Keeping {@link #getErrorCode()} + * bare and overriding {@link #jsonType()} to add the namespace reproduces the live + * service on both surfaces. + */ +class SwfException extends AwsException { + + private final String jsonType; + + SwfException(String errorCode, String jsonType, String message, int httpStatus) { + super(errorCode, message, httpStatus); + this.jsonType = jsonType; + } + + @Override + public String jsonType() { + return jsonType; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/SwfFaults.java b/src/main/java/io/github/hectorvent/floci/services/swf/SwfFaults.java new file mode 100644 index 0000000000..aed81868ab --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/SwfFaults.java @@ -0,0 +1,133 @@ +package io.github.hectorvent.floci.services.swf; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.swf.model.SwfConstants; + +/** + * Factory for SWF faults. + * + *

SWF answers every modeled fault with HTTP 400 and a namespaced {@code __type} + * of {@code com.amazonaws.swf.base.model#} (validation failures use the + * Coral namespace instead). The AWS SDKs key on the part after {@code #}, so the + * namespace must be present for the response to deserialize into the typed + * exception the caller catches. + */ +final class SwfFaults { + + private SwfFaults() { + } + + static AwsException unknownDomain(String domain) { + return fault(SwfConstants.UNKNOWN_RESOURCE, "Unknown domain: " + domain); + } + + static AwsException unknownExecution(String workflowId, String runId) { + return fault(SwfConstants.UNKNOWN_RESOURCE, + "Unknown execution, workflowId = " + workflowId + ", runId = " + runId); + } + + static AwsException unknownExecution(String runId) { + return fault(SwfConstants.UNKNOWN_RESOURCE, "Unknown execution: WorkflowExecution=[runId=" + runId + "]"); + } + + static AwsException unknownWorkflowType(String name, String version) { + return fault(SwfConstants.UNKNOWN_RESOURCE, + "Unknown type: WorkflowType=[name=" + name + ", version=" + version + "]"); + } + + static AwsException unknownActivityType(String name, String version) { + return fault(SwfConstants.UNKNOWN_RESOURCE, + "Unknown type: ActivityType=[name=" + name + ", version=" + version + "]"); + } + + static AwsException unknownTaskToken() { + return fault(SwfConstants.UNKNOWN_RESOURCE, "Unknown or expired task token"); + } + + /** + * Raised when an activity task token resolves but the task is no longer open (completed, + * failed, canceled, or timed out). The live service names the scheduled event rather + * than reporting a bad token, since the token itself was valid. + */ + static AwsException unknownActivity(long scheduledEventId) { + return fault(SwfConstants.UNKNOWN_RESOURCE, + "Unknown activity, scheduledEventId = " + scheduledEventId); + } + + static AwsException domainAlreadyExists(String domain) { + return fault(SwfConstants.DOMAIN_ALREADY_EXISTS, domain); + } + + static AwsException domainDeprecated(String domain) { + return fault(SwfConstants.DOMAIN_DEPRECATED, domain); + } + + static AwsException workflowTypeAlreadyExists(String name, String version) { + return fault(SwfConstants.TYPE_ALREADY_EXISTS, + "WorkflowType=[name=" + name + ", version=" + version + "]"); + } + + static AwsException activityTypeAlreadyExists(String name, String version) { + return fault(SwfConstants.TYPE_ALREADY_EXISTS, + "ActivityType=[name=" + name + ", version=" + version + "]"); + } + + static AwsException workflowTypeDeprecated(String name, String version) { + return fault(SwfConstants.TYPE_DEPRECATED, + "WorkflowType=[name=" + name + ", version=" + version + "]"); + } + + static AwsException activityTypeDeprecated(String name, String version) { + return fault(SwfConstants.TYPE_DEPRECATED, + "ActivityType=[name=" + name + ", version=" + version + "]"); + } + + /** + * Raised by DeleteWorkflowType/DeleteActivityType before the type is deprecated. Unlike + * the other type faults, the live service answers with prose rather than the type + * descriptor, and uses the same wording for both workflow and activity types. + */ + static AwsException typeNotDeprecated() { + return fault(SwfConstants.TYPE_NOT_DEPRECATED, + "The type is currently registered and cannot be deleted in its current state"); + } + + /** + * The live service returns this fault with an empty message; the runId of the + * already-open execution is not disclosed. + */ + static AwsException executionAlreadyStarted() { + return fault(SwfConstants.WORKFLOW_EXECUTION_ALREADY_STARTED, ""); + } + + static AwsException defaultUndefined(String field) { + return fault(SwfConstants.DEFAULT_UNDEFINED, field); + } + + /** + * The live service rejects a corrupt {@code nextPageToken} with this exact message rather + * than returning the first page. + */ + static AwsException invalidPageToken() { + return validation("Invalid token"); + } + + static AwsException validation(String message) { + return new SwfException(SwfConstants.VALIDATION, + SwfConstants.VALIDATION_NAMESPACE + SwfConstants.VALIDATION, message, 400); + } + + static AwsException validationConstraint(String value, String field, String constraint) { + return validation("1 validation error detected: Value '" + value + "' at '" + field + + "' failed to satisfy constraint: " + constraint); + } + + static AwsException missingRequired(String field) { + return validation("1 validation error detected: Value null at '" + field + + "' failed to satisfy constraint: Member must not be null"); + } + + static AwsException fault(String code, String message) { + return new SwfException(code, SwfConstants.FAULT_NAMESPACE + code, message, 400); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/SwfJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/swf/SwfJsonHandler.java new file mode 100644 index 0000000000..0e1d2c7db9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/SwfJsonHandler.java @@ -0,0 +1,775 @@ +package io.github.hectorvent.floci.services.swf; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.swf.SwfService.Decision; +import io.github.hectorvent.floci.services.swf.SwfService.ExecutionFilter; +import io.github.hectorvent.floci.services.swf.SwfService.StartWorkflowExecutionRequest; +import io.github.hectorvent.floci.services.swf.model.SwfActivityTask; +import io.github.hectorvent.floci.services.swf.model.SwfActivityType; +import io.github.hectorvent.floci.services.swf.model.SwfDecisionTask; +import io.github.hectorvent.floci.services.swf.model.SwfDomain; +import io.github.hectorvent.floci.services.swf.model.SwfHistoryEvent; +import io.github.hectorvent.floci.services.swf.model.SwfWorkflowExecution; +import io.github.hectorvent.floci.services.swf.model.SwfWorkflowType; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.Response; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.function.Function; +import java.util.Map; +import java.util.Optional; + +/** + * Translates the SWF JSON 1.0 wire protocol to and from {@link SwfService}. + * + *

Two wire details this class is responsible for: + *

    + *
  • Timestamps are epoch-second numbers, not ISO strings — the AWS SDKs parse + * {@code 1.786560427599E9} and reject a formatted date.
  • + *
  • Operations SWF models with no output shape must answer HTTP 200 with an + * empty body, not {@code {}} — {@code Content-Length: 0} is what the SDKs + * expect for a void operation.
  • + *
+ */ +@ApplicationScoped +public class SwfJsonHandler { + + private final SwfService service; + private final ObjectMapper objectMapper; + private final RegionResolver regionResolver; + + @Inject + public SwfJsonHandler(SwfService service, ObjectMapper objectMapper, RegionResolver regionResolver) { + this.service = service; + this.objectMapper = objectMapper; + this.regionResolver = regionResolver; + } + + public Response handle(String action, JsonNode request, String region) { + return switch (action) { + case "RegisterDomain" -> registerDomain(request, region); + case "DescribeDomain" -> describeDomain(request, region); + case "ListDomains" -> listDomains(request, region); + case "DeprecateDomain" -> voidResponse(() -> service.deprecateDomain(region, text(request, "name"))); + case "UndeprecateDomain" -> voidResponse(() -> service.undeprecateDomain(region, text(request, "name"))); + + case "RegisterWorkflowType" -> registerWorkflowType(request, region); + case "DescribeWorkflowType" -> describeWorkflowType(request, region); + case "ListWorkflowTypes" -> listWorkflowTypes(request, region); + case "DeprecateWorkflowType" -> voidResponse(() -> service.deprecateWorkflowType(region, + text(request, "domain"), nested(request, "workflowType", "name"), + nested(request, "workflowType", "version"))); + case "UndeprecateWorkflowType" -> voidResponse(() -> service.undeprecateWorkflowType(region, + text(request, "domain"), nested(request, "workflowType", "name"), + nested(request, "workflowType", "version"))); + case "DeleteWorkflowType" -> voidResponse(() -> service.deleteWorkflowType(region, + text(request, "domain"), nested(request, "workflowType", "name"), + nested(request, "workflowType", "version"))); + + case "RegisterActivityType" -> registerActivityType(request, region); + case "DescribeActivityType" -> describeActivityType(request, region); + case "ListActivityTypes" -> listActivityTypes(request, region); + case "DeprecateActivityType" -> voidResponse(() -> service.deprecateActivityType(region, + text(request, "domain"), nested(request, "activityType", "name"), + nested(request, "activityType", "version"))); + case "UndeprecateActivityType" -> voidResponse(() -> service.undeprecateActivityType(region, + text(request, "domain"), nested(request, "activityType", "name"), + nested(request, "activityType", "version"))); + case "DeleteActivityType" -> voidResponse(() -> service.deleteActivityType(region, + text(request, "domain"), nested(request, "activityType", "name"), + nested(request, "activityType", "version"))); + + case "StartWorkflowExecution" -> startWorkflowExecution(request, region); + case "DescribeWorkflowExecution" -> describeWorkflowExecution(request, region); + case "GetWorkflowExecutionHistory" -> getWorkflowExecutionHistory(request, region); + case "ListOpenWorkflowExecutions" -> listExecutions(request, region, false); + case "ListClosedWorkflowExecutions" -> listExecutions(request, region, true); + case "CountOpenWorkflowExecutions" -> countExecutions(request, region, false); + case "CountClosedWorkflowExecutions" -> countExecutions(request, region, true); + case "CountPendingActivityTasks" -> count(service.countPendingActivityTasks(region, + text(request, "domain"), nested(request, "taskList", "name"))); + case "CountPendingDecisionTasks" -> count(service.countPendingDecisionTasks(region, + text(request, "domain"), nested(request, "taskList", "name"))); + + case "PollForDecisionTask" -> pollForDecisionTask(request, region); + case "RespondDecisionTaskCompleted" -> respondDecisionTaskCompleted(request); + case "PollForActivityTask" -> pollForActivityTask(request, region); + case "RecordActivityTaskHeartbeat" -> recordActivityTaskHeartbeat(request); + case "RespondActivityTaskCompleted" -> voidResponse(() -> service.respondActivityTaskCompleted( + text(request, "taskToken"), text(request, "result"))); + case "RespondActivityTaskFailed" -> voidResponse(() -> service.respondActivityTaskFailed( + text(request, "taskToken"), text(request, "reason"), text(request, "details"))); + case "RespondActivityTaskCanceled" -> voidResponse(() -> service.respondActivityTaskCanceled( + text(request, "taskToken"), text(request, "details"))); + + case "SignalWorkflowExecution" -> voidResponse(() -> service.signalWorkflowExecution(region, + text(request, "domain"), text(request, "workflowId"), text(request, "runId"), + text(request, "signalName"), text(request, "input"))); + case "RequestCancelWorkflowExecution" -> voidResponse(() -> service.requestCancelWorkflowExecution(region, + text(request, "domain"), text(request, "workflowId"), text(request, "runId"))); + case "TerminateWorkflowExecution" -> voidResponse(() -> service.terminateWorkflowExecution(region, + text(request, "domain"), text(request, "workflowId"), text(request, "runId"), + text(request, "reason"), text(request, "details"), text(request, "childPolicy"))); + + case "ListTagsForResource" -> listTagsForResource(request); + case "TagResource" -> voidResponse(() -> service.tagResource( + text(request, "resourceArn"), parseTags(request.path("tags")))); + case "UntagResource" -> voidResponse(() -> service.untagResource( + text(request, "resourceArn"), parseStringList(request.path("tagKeys")))); + + default -> null; + }; + } + + // ──────────────────────────────── Domains ──────────────────────────────── + + private Response registerDomain(JsonNode request, String region) { + service.registerDomain( + text(request, "name"), + text(request, "description"), + text(request, "workflowExecutionRetentionPeriodInDays"), + parseTags(request.path("tags")), + region); + return empty(); + } + + private Response describeDomain(JsonNode request, String region) { + SwfDomain domain = service.describeDomain(region, text(request, "name")); + ObjectNode response = objectMapper.createObjectNode(); + response.set("domainInfo", domainInfo(domain, region)); + response.putObject("configuration") + .put("workflowExecutionRetentionPeriodInDays", domain.getWorkflowExecutionRetentionPeriodInDays()); + return Response.ok(response).build(); + } + + private Response listDomains(JsonNode request, String region) { + List domains = service.listDomains(region, text(request, "registrationStatus")); + if (request.path("reverseOrder").asBoolean(false)) { + domains = new ArrayList<>(domains); + java.util.Collections.reverse(domains); + } + return pagedList(request, "domainInfos", domains, domain -> domainInfo(domain, region)); + } + + private ObjectNode domainInfo(SwfDomain domain, String region) { + ObjectNode info = objectMapper.createObjectNode(); + info.put("name", domain.getName()); + info.put("status", domain.getStatus()); + putIfPresent(info, "description", domain.getDescription()); + info.put("arn", service.domainArnFor(domain, region)); + return info; + } + + // ───────────────────────────── Workflow types ──────────────────────────── + + private Response registerWorkflowType(JsonNode request, String region) { + SwfWorkflowType type = new SwfWorkflowType(); + type.setName(text(request, "name")); + type.setVersion(text(request, "version")); + type.setDescription(text(request, "description")); + type.setDefaultTaskStartToCloseTimeout(text(request, "defaultTaskStartToCloseTimeout")); + type.setDefaultExecutionStartToCloseTimeout(text(request, "defaultExecutionStartToCloseTimeout")); + type.setDefaultTaskList(nested(request, "defaultTaskList", "name")); + type.setDefaultTaskPriority(text(request, "defaultTaskPriority")); + type.setDefaultChildPolicy(text(request, "defaultChildPolicy")); + type.setDefaultLambdaRole(text(request, "defaultLambdaRole")); + service.registerWorkflowType(region, text(request, "domain"), type); + return empty(); + } + + private Response describeWorkflowType(JsonNode request, String region) { + SwfWorkflowType type = service.describeWorkflowType(region, text(request, "domain"), + nested(request, "workflowType", "name"), nested(request, "workflowType", "version")); + ObjectNode response = objectMapper.createObjectNode(); + response.set("typeInfo", workflowTypeInfo(type)); + + ObjectNode configuration = response.putObject("configuration"); + putIfPresent(configuration, "defaultTaskStartToCloseTimeout", type.getDefaultTaskStartToCloseTimeout()); + putIfPresent(configuration, "defaultExecutionStartToCloseTimeout", + type.getDefaultExecutionStartToCloseTimeout()); + putTaskList(configuration, "defaultTaskList", type.getDefaultTaskList()); + putIfPresent(configuration, "defaultTaskPriority", type.getDefaultTaskPriority()); + putIfPresent(configuration, "defaultChildPolicy", type.getDefaultChildPolicy()); + putIfPresent(configuration, "defaultLambdaRole", type.getDefaultLambdaRole()); + return Response.ok(response).build(); + } + + private Response listWorkflowTypes(JsonNode request, String region) { + List types = service.listWorkflowTypes(region, text(request, "domain"), text(request, "name"), + text(request, "registrationStatus"), request.path("reverseOrder").asBoolean(false)); + return pagedList(request, "typeInfos", types, this::workflowTypeInfo); + } + + private ObjectNode workflowTypeInfo(SwfWorkflowType type) { + ObjectNode info = objectMapper.createObjectNode(); + info.set("workflowType", typeNode(type.getName(), type.getVersion())); + info.put("status", type.getStatus()); + putIfPresent(info, "description", type.getDescription()); + info.put("creationDate", type.getCreationDate()); + if (type.getDeprecationDate() != null) { + info.put("deprecationDate", type.getDeprecationDate()); + } + return info; + } + + // ───────────────────────────── Activity types ──────────────────────────── + + private Response registerActivityType(JsonNode request, String region) { + SwfActivityType type = new SwfActivityType(); + type.setName(text(request, "name")); + type.setVersion(text(request, "version")); + type.setDescription(text(request, "description")); + type.setDefaultTaskStartToCloseTimeout(text(request, "defaultTaskStartToCloseTimeout")); + type.setDefaultTaskHeartbeatTimeout(text(request, "defaultTaskHeartbeatTimeout")); + type.setDefaultTaskList(nested(request, "defaultTaskList", "name")); + type.setDefaultTaskPriority(text(request, "defaultTaskPriority")); + type.setDefaultTaskScheduleToStartTimeout(text(request, "defaultTaskScheduleToStartTimeout")); + type.setDefaultTaskScheduleToCloseTimeout(text(request, "defaultTaskScheduleToCloseTimeout")); + service.registerActivityType(region, text(request, "domain"), type); + return empty(); + } + + private Response describeActivityType(JsonNode request, String region) { + SwfActivityType type = service.describeActivityType(region, text(request, "domain"), + nested(request, "activityType", "name"), nested(request, "activityType", "version")); + ObjectNode response = objectMapper.createObjectNode(); + response.set("typeInfo", activityTypeInfo(type)); + + ObjectNode configuration = response.putObject("configuration"); + putIfPresent(configuration, "defaultTaskStartToCloseTimeout", type.getDefaultTaskStartToCloseTimeout()); + putIfPresent(configuration, "defaultTaskHeartbeatTimeout", type.getDefaultTaskHeartbeatTimeout()); + putTaskList(configuration, "defaultTaskList", type.getDefaultTaskList()); + putIfPresent(configuration, "defaultTaskPriority", type.getDefaultTaskPriority()); + putIfPresent(configuration, "defaultTaskScheduleToStartTimeout", + type.getDefaultTaskScheduleToStartTimeout()); + putIfPresent(configuration, "defaultTaskScheduleToCloseTimeout", + type.getDefaultTaskScheduleToCloseTimeout()); + return Response.ok(response).build(); + } + + private Response listActivityTypes(JsonNode request, String region) { + List types = service.listActivityTypes(region, text(request, "domain"), text(request, "name"), + text(request, "registrationStatus"), request.path("reverseOrder").asBoolean(false)); + return pagedList(request, "typeInfos", types, this::activityTypeInfo); + } + + private ObjectNode activityTypeInfo(SwfActivityType type) { + ObjectNode info = objectMapper.createObjectNode(); + info.set("activityType", typeNode(type.getName(), type.getVersion())); + info.put("status", type.getStatus()); + putIfPresent(info, "description", type.getDescription()); + info.put("creationDate", type.getCreationDate()); + if (type.getDeprecationDate() != null) { + info.put("deprecationDate", type.getDeprecationDate()); + } + return info; + } + + // ─────────────────────────────── Executions ────────────────────────────── + + private Response startWorkflowExecution(JsonNode request, String region) { + String runId = service.startWorkflowExecution(new StartWorkflowExecutionRequest( + region, + text(request, "domain"), + text(request, "workflowId"), + nested(request, "workflowType", "name"), + nested(request, "workflowType", "version"), + nested(request, "taskList", "name"), + text(request, "taskPriority"), + text(request, "input"), + text(request, "executionStartToCloseTimeout"), + text(request, "taskStartToCloseTimeout"), + text(request, "childPolicy"), + parseStringList(request.path("tagList")), + text(request, "lambdaRole"))); + ObjectNode response = objectMapper.createObjectNode(); + response.put("runId", runId); + return Response.ok(response).build(); + } + + private Response describeWorkflowExecution(JsonNode request, String region) { + SwfWorkflowExecution execution = service.describeWorkflowExecution(region, text(request, "domain"), + nested(request, "execution", "workflowId"), nested(request, "execution", "runId")); + + ObjectNode response = objectMapper.createObjectNode(); + response.set("executionInfo", executionInfo(execution)); + + ObjectNode configuration = response.putObject("executionConfiguration"); + configuration.put("taskStartToCloseTimeout", execution.getTaskStartToCloseTimeout()); + configuration.put("executionStartToCloseTimeout", execution.getExecutionStartToCloseTimeout()); + putTaskList(configuration, "taskList", execution.getTaskList()); + putIfPresent(configuration, "taskPriority", execution.getTaskPriority()); + configuration.put("childPolicy", execution.getChildPolicy()); + putIfPresent(configuration, "lambdaRole", execution.getLambdaRole()); + + ObjectNode openCounts = response.putObject("openCounts"); + openCounts.put("openActivityTasks", service.openActivityCount(execution)); + openCounts.put("openDecisionTasks", service.openDecisionTaskCount(execution)); + openCounts.put("openTimers", service.openTimerCount(execution)); + openCounts.put("openChildWorkflowExecutions", service.openChildCount(execution)); + openCounts.put("openLambdaFunctions", 0); + + if (execution.getLatestActivityTaskTimestamp() != null) { + response.put("latestActivityTaskTimestamp", execution.getLatestActivityTaskTimestamp()); + } + putIfPresent(response, "latestExecutionContext", execution.getLatestExecutionContext()); + return Response.ok(response).build(); + } + + /** + * Applies {@code maximumPageSize} and {@code nextPageToken} to an already-ordered list, + * appending each item on the page via {@code render} and setting {@code nextPageToken} + * only when more items remain. + * + *

Measured against the live service: the token is absent on the final page even when + * that page is exactly full; a {@code maximumPageSize} of 0 (or absent) means "no caller + * limit"; above 1000 is a ValidationException; and an unparseable token is rejected rather + * than silently restarting from the beginning. + */ + private Response pagedList(JsonNode request, String itemsField, List items, + Function render) { + int pageSize = service.pageSize(optionalInt(request, "maximumPageSize")); + int from = Math.min(decodePageToken(text(request, "nextPageToken")).offset(), items.size()); + int to = Math.min(from + pageSize, items.size()); + + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode array = response.putArray(itemsField); + for (T item : items.subList(from, to)) { + array.add(render.apply(item)); + } + if (to < items.size()) { + response.put("nextPageToken", encodePageToken(to, null)); + } + return Response.ok(response).build(); + } + + private Response getWorkflowExecutionHistory(JsonNode request, String region) { + boolean reverseOrder = request.path("reverseOrder").asBoolean(false); + List events = service.getWorkflowExecutionHistory(region, text(request, "domain"), + nested(request, "execution", "workflowId"), nested(request, "execution", "runId"), reverseOrder); + + return pagedList(request, "events", events, this::historyEvent); + } + + private Response listExecutions(JsonNode request, String region, boolean closed) { + List executions = service.listExecutions(region, text(request, "domain"), + buildFilter(request, closed), closed); + if (request.path("reverseOrder").asBoolean(false)) { + executions = new ArrayList<>(executions); + java.util.Collections.reverse(executions); + } + + return pagedList(request, "executionInfos", executions, this::executionInfo); + } + + private Response countExecutions(JsonNode request, String region, boolean closed) { + List executions = service.listExecutions(region, text(request, "domain"), + buildFilter(request, closed), closed); + return count(executions.size()); + } + + private Response count(int value) { + ObjectNode response = objectMapper.createObjectNode(); + response.put("count", value); + response.put("truncated", false); + return Response.ok(response).build(); + } + + private ObjectNode executionInfo(SwfWorkflowExecution execution) { + ObjectNode info = objectMapper.createObjectNode(); + info.set("execution", executionNode(execution.getWorkflowId(), execution.getRunId())); + info.set("workflowType", typeNode(execution.getWorkflowTypeName(), execution.getWorkflowTypeVersion())); + info.put("startTimestamp", execution.getStartTimestamp()); + if (execution.getCloseTimestamp() != null) { + info.put("closeTimestamp", execution.getCloseTimestamp()); + } + info.put("executionStatus", execution.getExecutionStatus()); + putIfPresent(info, "closeStatus", execution.getCloseStatus()); + if (execution.getParentWorkflowId() != null) { + info.set("parent", executionNode(execution.getParentWorkflowId(), execution.getParentRunId())); + } + if (!execution.getTagList().isEmpty()) { + ArrayNode tags = info.putArray("tagList"); + execution.getTagList().forEach(tags::add); + } + info.put("cancelRequested", execution.isCancelRequested()); + return info; + } + + /** + * Builds the filter from whichever of the mutually exclusive filter members is present. + * SWF applies at most one of executionFilter/typeFilter/tagFilter, plus the time filter + * that matches the list flavour (startTimeFilter for open, either for closed). + */ + private ExecutionFilter buildFilter(JsonNode request, boolean closed) { + ExecutionFilter filter = ExecutionFilter.all(); + + JsonNode executionFilter = request.path("executionFilter"); + if (executionFilter.hasNonNull("workflowId")) { + String workflowId = executionFilter.path("workflowId").asText(); + filter = filter.and(execution -> workflowId.equals(execution.getWorkflowId())); + } + + JsonNode typeFilter = request.path("typeFilter"); + if (typeFilter.hasNonNull("name")) { + String name = typeFilter.path("name").asText(); + String version = typeFilter.path("version").asText(null); + filter = filter.and(execution -> name.equals(execution.getWorkflowTypeName()) + && (version == null || version.isEmpty() || version.equals(execution.getWorkflowTypeVersion()))); + } + + JsonNode tagFilter = request.path("tagFilter"); + if (tagFilter.hasNonNull("tag")) { + String tag = tagFilter.path("tag").asText(); + filter = filter.and(execution -> execution.getTagList().contains(tag)); + } + + if (closed) { + JsonNode closeStatusFilter = request.path("closeStatusFilter"); + if (closeStatusFilter.hasNonNull("status")) { + String status = closeStatusFilter.path("status").asText(); + filter = filter.and(execution -> status.equals(execution.getCloseStatus())); + } + filter = filter.and(timeFilter(request.path("closeTimeFilter"), + execution -> execution.getCloseTimestamp() != null ? execution.getCloseTimestamp() : 0.0)); + } + return filter.and(timeFilter(request.path("startTimeFilter"), + SwfWorkflowExecution::getStartTimestamp)); + } + + private ExecutionFilter timeFilter(JsonNode filterNode, + java.util.function.ToDoubleFunction extractor) { + if (filterNode == null || filterNode.isMissingNode() || filterNode.isNull()) { + return ExecutionFilter.all(); + } + Double oldest = filterNode.hasNonNull("oldestDate") ? filterNode.path("oldestDate").asDouble() : null; + Double latest = filterNode.hasNonNull("latestDate") ? filterNode.path("latestDate").asDouble() : null; + if (oldest == null && latest == null) { + return ExecutionFilter.all(); + } + return execution -> { + double value = extractor.applyAsDouble(execution); + return (oldest == null || value >= oldest) && (latest == null || value <= latest); + }; + } + + // ─────────────────────────────── Task polling ──────────────────────────── + + /** + * {@code PollForDecisionTask}. + * + *

A request carrying {@code nextPageToken} continues an earlier poll rather than starting + * a new one — the live service documents that "calling PollForDecisionTask with a + * nextPageToken doesn't return a new decision task", and answers with the same task's next + * history page, same {@code startedEventId} and {@code workflowExecution}. The token + * therefore names the task it belongs to, and a continuation resolves that task instead of + * claiming another. + */ + private Response pollForDecisionTask(JsonNode request, String region) { + String pageToken = text(request, "nextPageToken"); + SwfDecisionTask task; + int offset; + if (pageToken != null && !pageToken.isEmpty()) { + Page page = decodePageToken(pageToken); + if (page.taskToken() == null) { + throw SwfFaults.invalidPageToken(); + } + task = service.decisionTaskForToken(page.taskToken()); + offset = page.offset(); + } else { + Optional maybeTask = service.pollForDecisionTask(region, + text(request, "domain"), nested(request, "taskList", "name"), + text(request, "identity")); + if (maybeTask.isEmpty()) { + return Response.ok(emptyPollResponse()).build(); + } + task = maybeTask.get(); + offset = 0; + } + + boolean reverseOrder = request.path("reverseOrder").asBoolean(false); + List events = service.getWorkflowExecutionHistory(region, task.getDomain(), + task.getWorkflowId(), task.getRunId(), reverseOrder); + + // startAtPreviousStartedEvent trims the history to what the decider has not seen, + // starting *at* previousStartedEventId — inclusive, measured against the live service. + long from = task.getPreviousStartedEventId(); + if (request.path("startAtPreviousStartedEvent").asBoolean(false) && from > 0) { + events = events.stream().filter(e -> e.getEventId() >= from).toList(); + } + + int pageSize = service.pageSize(optionalInt(request, "maximumPageSize")); + int end = Math.min(offset + pageSize, events.size()); + + ObjectNode response = objectMapper.createObjectNode(); + response.put("taskToken", task.getTaskToken()); + response.put("startedEventId", task.getStartedEventId()); + response.set("workflowExecution", executionNode(task.getWorkflowId(), task.getRunId())); + ArrayNode array = response.putArray("events"); + for (SwfHistoryEvent event : events.subList(Math.min(offset, events.size()), end)) { + array.add(historyEvent(event)); + } + response.put("previousStartedEventId", task.getPreviousStartedEventId()); + if (end < events.size()) { + response.put("nextPageToken", encodePageToken(end, task.getTaskToken())); + } + + SwfWorkflowExecution execution = service.describeWorkflowExecution(region, task.getDomain(), + task.getWorkflowId(), task.getRunId()); + response.set("workflowType", typeNode(execution.getWorkflowTypeName(), + execution.getWorkflowTypeVersion())); + return Response.ok(response).build(); + } + + /** + * An empty poll answers 200 with {@code taskToken: ""}. The SDKs treat the empty + * token as "no task"; omitting the member makes them raise on a missing required field. + */ + private ObjectNode emptyPollResponse() { + ObjectNode response = objectMapper.createObjectNode(); + response.put("taskToken", ""); + response.put("startedEventId", 0); + response.put("previousStartedEventId", 0); + return response; + } + + private Response pollForActivityTask(JsonNode request, String region) { + Optional maybeTask = service.pollForActivityTask(region, text(request, "domain"), + nested(request, "taskList", "name"), text(request, "identity")); + if (maybeTask.isEmpty()) { + ObjectNode response = objectMapper.createObjectNode(); + response.put("taskToken", ""); + response.put("activityId", ""); + response.put("startedEventId", 0); + return Response.ok(response).build(); + } + + SwfActivityTask task = maybeTask.get(); + ObjectNode response = objectMapper.createObjectNode(); + response.put("taskToken", task.getTaskToken()); + response.put("activityId", task.getActivityId()); + response.put("startedEventId", task.getStartedEventId()); + response.set("workflowExecution", executionNode(task.getWorkflowId(), task.getRunId())); + response.set("activityType", typeNode(task.getActivityTypeName(), task.getActivityTypeVersion())); + putIfPresent(response, "input", task.getInput()); + return Response.ok(response).build(); + } + + private Response recordActivityTaskHeartbeat(JsonNode request) { + boolean cancelRequested = service.recordActivityTaskHeartbeat(text(request, "taskToken"), + text(request, "details")); + ObjectNode response = objectMapper.createObjectNode(); + response.put("cancelRequested", cancelRequested); + return Response.ok(response).build(); + } + + private Response respondDecisionTaskCompleted(JsonNode request) { + service.respondDecisionTaskCompleted(text(request, "taskToken"), + parseDecisions(request.path("decisions")), text(request, "executionContext")); + return empty(); + } + + /** + * Unwraps each decision from its {@code DecisionAttributes} envelope. The + * attribute member name is the decision type with a lower-cased first letter, which is + * how the model names every one of the thirteen decision types. + */ + private List parseDecisions(JsonNode decisionsNode) { + List decisions = new ArrayList<>(); + if (!decisionsNode.isArray()) { + return decisions; + } + for (JsonNode node : decisionsNode) { + String type = node.path("decisionType").asText(null); + if (type == null || type.isEmpty()) { + throw SwfFaults.missingRequired("decisions.1.member.decisionType"); + } + String attributesField = Character.toLowerCase(type.charAt(0)) + type.substring(1) + + "DecisionAttributes"; + decisions.add(new Decision(type, toMap(node.path(attributesField)))); + } + return decisions; + } + + private Response listTagsForResource(JsonNode request) { + Map tags = service.listTagsForResource(text(request, "resourceArn")); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode array = response.putArray("tags"); + tags.forEach((key, value) -> { + ObjectNode entry = array.addObject(); + entry.put("key", key); + if (value != null) { + entry.put("value", value); + } + }); + return Response.ok(response).build(); + } + + // ──────────────────────────── Wire serialization ───────────────────────── + + private ObjectNode historyEvent(SwfHistoryEvent event) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("eventTimestamp", event.getEventTimestamp()); + node.put("eventType", event.getEventType()); + node.put("eventId", event.getEventId()); + if (!event.getAttributes().isEmpty()) { + node.set(event.attributesFieldName(), objectMapper.valueToTree(event.getAttributes())); + } + return node; + } + + private ObjectNode typeNode(String name, String version) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("name", name); + node.put("version", version); + return node; + } + + private ObjectNode executionNode(String workflowId, String runId) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("workflowId", workflowId); + node.put("runId", runId); + return node; + } + + private void putTaskList(ObjectNode parent, String field, String taskList) { + if (taskList != null && !taskList.isEmpty()) { + parent.putObject(field).put("name", taskList); + } + } + + private static void putIfPresent(ObjectNode node, String field, String value) { + if (value != null && !value.isEmpty()) { + node.put(field, value); + } + } + + /** + * Operations SWF models without an output shape answer 200 with no body. Returning + * {@code {}} instead makes strict SDK response handlers log a shape mismatch. + */ + private Response empty() { + return Response.ok().build(); + } + + private Response voidResponse(Runnable action) { + action.run(); + return empty(); + } + + private static String text(JsonNode request, String field) { + JsonNode node = request.get(field); + return node != null && !node.isNull() ? node.asText() : null; + } + + private static String nested(JsonNode request, String field, String key) { + JsonNode parent = request.get(field); + if (parent == null || parent.isNull()) { + return null; + } + JsonNode node = parent.get(key); + return node != null && !node.isNull() ? node.asText() : null; + } + + /** + * Reads an optional integer, rejecting wrong types rather than letting + * {@code asInt()} coerce a string or fraction to 0 and silently mean "use the default". + */ + private static Integer optionalInt(JsonNode request, String field) { + JsonNode node = request.get(field); + if (node == null || node.isNull()) { + return null; + } + if (!node.isIntegralNumber()) { + throw SwfFaults.validationConstraint(node.toString(), field, "Member must be an integer."); + } + return node.intValue(); + } + + private static Map parseTags(JsonNode tagsNode) { + Map tags = new LinkedHashMap<>(); + if (tagsNode != null && tagsNode.isArray()) { + for (JsonNode entry : tagsNode) { + String key = entry.path("key").asText(null); + if (key != null) { + tags.put(key, entry.path("value").asText("")); + } + } + } + return tags; + } + + private static List parseStringList(JsonNode arrayNode) { + if (arrayNode == null || !arrayNode.isArray()) { + return null; + } + List values = new ArrayList<>(); + for (JsonNode node : arrayNode) { + values.add(node.asText()); + } + return values; + } + + @SuppressWarnings("unchecked") + private Map toMap(JsonNode node) { + if (node == null || !node.isObject()) { + return Map.of(); + } + return objectMapper.convertValue(node, Map.class); + } + + /** + * A decoded continuation token: how far the caller has read, and — for + * {@code PollForDecisionTask} — which decision task the page belongs to. + * + *

SWF tokens are opaque blobs, so the encoding is ours to choose; a corrupt one is + * rejected with {@code ValidationException: Invalid token} rather than restarting at the + * first page, which would turn a caller's paging loop into an infinite one. + */ + private record Page(int offset, String taskToken) { + + static final Page FIRST = new Page(0, null); + } + + private static String encodePageToken(int offset, String taskToken) { + String body = "offset=" + offset + (taskToken == null ? "" : "\ntask=" + taskToken); + return java.util.Base64.getEncoder() + .encodeToString(body.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + private static Page decodePageToken(String token) { + if (token == null || token.isEmpty()) { + return Page.FIRST; + } + String decoded; + try { + decoded = new String(java.util.Base64.getDecoder().decode(token), + java.nio.charset.StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + throw SwfFaults.invalidPageToken(); + } + if (!decoded.startsWith("offset=")) { + throw SwfFaults.invalidPageToken(); + } + int split = decoded.indexOf("\ntask="); + String offsetPart = split < 0 ? decoded.substring("offset=".length()) + : decoded.substring("offset=".length(), split); + String taskToken = split < 0 ? null : decoded.substring(split + "\ntask=".length()); + try { + int offset = Integer.parseInt(offsetPart); + if (offset < 0 || (taskToken != null && taskToken.isEmpty())) { + throw SwfFaults.invalidPageToken(); + } + return new Page(offset, taskToken); + } catch (NumberFormatException e) { + throw SwfFaults.invalidPageToken(); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/SwfLambdaInvoker.java b/src/main/java/io/github/hectorvent/floci/services/swf/SwfLambdaInvoker.java new file mode 100644 index 0000000000..477a1f48e9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/SwfLambdaInvoker.java @@ -0,0 +1,39 @@ +package io.github.hectorvent.floci.services.swf; + +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.InvocationType; +import io.github.hectorvent.floci.services.lambda.model.InvokeResult; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.nio.charset.StandardCharsets; + +/** + * Runtime {@link LambdaInvoker}: runs the function through Floci's own Lambda service, which + * executes it in a container exactly as an {@code Invoke} API call would. + * + *

Uses {@link InvocationType#RequestResponse} because SWF needs the response body to record + * as the LambdaFunctionCompleted {@code result} — an {@code Event} invocation would return + * immediately with nothing to record, the same reason the EventBridge and Scheduler invokers + * pick {@code Event} for their fire-and-forget targets and this one does not. + */ +@ApplicationScoped +public class SwfLambdaInvoker implements LambdaInvoker { + + private final LambdaService lambdaService; + + @Inject + public SwfLambdaInvoker(LambdaService lambdaService) { + this.lambdaService = lambdaService; + } + + @Override + public LambdaInvocationResult invoke(String region, String functionName, byte[] payload) { + InvokeResult result = lambdaService.invoke(region, functionName, payload, + InvocationType.RequestResponse); + byte[] body = result.getPayload(); + return new LambdaInvocationResult( + body == null ? "" : new String(body, StandardCharsets.UTF_8), + result.getFunctionError()); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/SwfService.java b/src/main/java/io/github/hectorvent/floci/services/swf/SwfService.java new file mode 100644 index 0000000000..b7f5f12df6 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/SwfService.java @@ -0,0 +1,2155 @@ +package io.github.hectorvent.floci.services.swf; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.Resettable; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.swf.model.SwfActivityTask; +import io.github.hectorvent.floci.services.swf.model.SwfActivityType; +import io.github.hectorvent.floci.services.swf.model.SwfConstants; +import io.github.hectorvent.floci.services.swf.model.SwfDecisionTask; +import io.github.hectorvent.floci.services.swf.model.SwfDomain; +import io.github.hectorvent.floci.services.swf.model.SwfHistoryEvent; +import io.github.hectorvent.floci.services.swf.model.SwfTimer; +import io.github.hectorvent.floci.services.swf.model.SwfWorkflowExecution; +import io.github.hectorvent.floci.services.swf.model.SwfWorkflowType; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Predicate; + +/** + * Amazon SWF domain logic: registration, the workflow execution state machine, and + * the decision/activity task lifecycle. + * + *

Storage layout. Domains and types are keyed by ARN-like composite keys and live in + * {@link StorageBackend}s so they survive restarts under persistent storage modes. + * Executions are keyed {@code domain/workflowId/runId}. Task tokens are an in-memory + * index only: SWF tokens do not outlive a service restart, and a token that resolved + * after a restart would point at a decision the emulator can no longer honour. + * + *

Event ordering. Every state transition appends to the execution's history under the + * execution's monotonic {@code nextEventId}. All mutation is serialized per domain via + * {@link #domainLock(String, String)} because deciders and workers poll concurrently, and a + * torn history (two events sharing an id, or an activity closing twice) is + * indistinguishable from corruption to an SDK-driven decider. + * + *

The lock is per domain rather than per execution because several invariants span + * more than one execution: StartWorkflowExecution must see any concurrently inserted run + * of the same workflowId to reject it, and a closing execution mutates its parent + * (ChildWorkflowExecution* events) and its children (childPolicy). A parent and a child + * always live in the same domain, so one lock covers a whole family and never has to be + * nested — nesting would deadlock, since a closing child takes its parent while a closing + * parent takes its children. + * + *

Timeouts are enforced by {@link SwfTimeoutSweeper} calling {@link #sweep()}, not by + * per-task threads. + */ +@ApplicationScoped +public class SwfService implements Resettable { + + private static final Logger LOG = Logger.getLogger(SwfService.class); + + private static final int MAX_TAGS = 50; + /** SWF caps maximumPageSize at 1000 on every paginated operation. */ + private static final int MAX_PAGE_SIZE = 1000; + + private final StorageBackend domainStore; + private final StorageBackend workflowTypeStore; + private final StorageBackend activityTypeStore; + private final StorageBackend executionStore; + + private final Map decisionTokens = new ConcurrentHashMap<>(); + private final Map activityTokens = new ConcurrentHashMap<>(); + private final Map domainLocks = new ConcurrentHashMap<>(); + + private final RegionResolver regionResolver; + private final Clock clock; + private final LambdaInvoker lambdaInvoker; + + + @Inject + public SwfService(StorageFactory storageFactory, RegionResolver regionResolver, Clock clock, + LambdaInvoker lambdaInvoker) { + this.domainStore = storageFactory.create("swf", "swf-domains.json", + new TypeReference>() {}); + this.workflowTypeStore = storageFactory.create("swf", "swf-workflow-types.json", + new TypeReference>() {}); + this.activityTypeStore = storageFactory.create("swf", "swf-activity-types.json", + new TypeReference>() {}); + this.executionStore = storageFactory.create("swf", "swf-executions.json", + new TypeReference>() {}); + this.regionResolver = regionResolver; + this.clock = clock; + this.lambdaInvoker = lambdaInvoker; + } + + @Override + public void clear() { + decisionTokens.clear(); + activityTokens.clear(); + domainLocks.clear(); + } + + // ──────────────────────────────── Domains ──────────────────────────────── + + public void registerDomain(String name, String description, String retentionDays, + Map tags, String region) { + requireName(name, "name"); + if (retentionDays == null || retentionDays.isEmpty()) { + throw SwfFaults.missingRequired("workflowExecutionRetentionPeriodInDays"); + } + validateRetentionPeriod(retentionDays); + if (tags != null && tags.size() > MAX_TAGS) { + throw SwfFaults.fault(SwfConstants.TOO_MANY_TAGS, name); + } + if (domainStore.get(domainKey(region, name)).isPresent()) { + throw SwfFaults.domainAlreadyExists(name); + } + + SwfDomain domain = new SwfDomain(); + domain.setName(name); + domain.setDescription(description); + domain.setWorkflowExecutionRetentionPeriodInDays(retentionDays); + domain.setCreationDate(now()); + domain.setArn(domainArn(name, region)); + if (tags != null) { + domain.getTags().putAll(tags); + } + domainStore.put(domainKey(region, name), domain); + LOG.debugv("Registered SWF domain {0} in {1}", name, region); + } + + public SwfDomain describeDomain(String region, String name) { + requireName(name, "name"); + return domainStore.get(domainKey(region, name)).orElseThrow(() -> SwfFaults.unknownDomain(name)); + } + + /** + * Resolves a domain for operations that act on its contents. Deprecated domains stay + * readable — SWF only rejects registration and execution-starting operations on them — + * so the deprecation check lives at those call sites instead of here. + */ + private SwfDomain requireDomain(String region, String name) { + requireName(name, "domain"); + return domainStore.get(domainKey(region, name)).orElseThrow(() -> SwfFaults.unknownDomain(name)); + } + + public List listDomains(String region, String registrationStatus) { + String status = requireRegistrationStatus(registrationStatus); + String prefix = region + ":"; + List domains = domainStore.scan(k -> k.startsWith(prefix)); + domains.removeIf(d -> !status.equals(d.getStatus())); + domains.sort(Comparator.comparing(SwfDomain::getName)); + return domains; + } + + public void deprecateDomain(String region, String name) { + SwfDomain domain = requireDomain(region, name); + if (domain.isDeprecated()) { + throw SwfFaults.domainDeprecated(name); + } + domain.setStatus(SwfConstants.STATUS_DEPRECATED); + domain.setDeprecationDate(now()); + domainStore.put(domainKey(region, name), domain); + } + + public void undeprecateDomain(String region, String name) { + SwfDomain domain = requireDomain(region, name); + if (!domain.isDeprecated()) { + throw SwfFaults.domainAlreadyExists(name); + } + domain.setStatus(SwfConstants.STATUS_REGISTERED); + domain.setDeprecationDate(null); + domainStore.put(domainKey(region, name), domain); + } + + // ───────────────────────────── Workflow types ──────────────────────────── + + public void registerWorkflowType(String region, String domainName, SwfWorkflowType type) { + SwfDomain domain = requireDomain(region, domainName); + if (domain.isDeprecated()) { + throw SwfFaults.domainDeprecated(domainName); + } + requireName(type.getName(), "name"); + requireName(type.getVersion(), "version"); + + String key = typeKey(region, domainName, type.getName(), type.getVersion()); + if (workflowTypeStore.get(key).isPresent()) { + throw SwfFaults.workflowTypeAlreadyExists(type.getName(), type.getVersion()); + } + type.setDomain(domainName); + type.setCreationDate(now()); + workflowTypeStore.put(key, type); + } + + public SwfWorkflowType describeWorkflowType(String region, String domainName, String name, String version) { + requireDomain(region, domainName); + return findWorkflowType(region, domainName, name, version); + } + + private SwfWorkflowType findWorkflowType(String region, String domainName, String name, String version) { + requireName(name, "workflowType.name"); + requireName(version, "workflowType.version"); + return workflowTypeStore.get(typeKey(region, domainName, name, version)) + .orElseThrow(() -> SwfFaults.unknownWorkflowType(name, version)); + } + + public List listWorkflowTypes(String region, String domainName, String name, + String registrationStatus, boolean reverseOrder) { + requireDomain(region, domainName); + String status = requireRegistrationStatus(registrationStatus); + String prefix = region + ":" + domainName + "/"; + List types = workflowTypeStore.scan(k -> k.startsWith(prefix)); + types.removeIf(t -> !status.equals(t.getStatus())); + if (name != null && !name.isEmpty()) { + types.removeIf(t -> !name.equals(t.getName())); + } + types.sort(Comparator.comparing(SwfWorkflowType::getName).thenComparing(SwfWorkflowType::getVersion)); + if (reverseOrder) { + java.util.Collections.reverse(types); + } + return types; + } + + public void deprecateWorkflowType(String region, String domainName, String name, String version) { + requireDomain(region, domainName); + SwfWorkflowType type = findWorkflowType(region, domainName, name, version); + if (type.isDeprecated()) { + throw SwfFaults.workflowTypeDeprecated(name, version); + } + type.setStatus(SwfConstants.STATUS_DEPRECATED); + type.setDeprecationDate(now()); + workflowTypeStore.put(typeKey(region, domainName, name, version), type); + } + + public void undeprecateWorkflowType(String region, String domainName, String name, String version) { + requireDomain(region, domainName); + SwfWorkflowType type = findWorkflowType(region, domainName, name, version); + if (!type.isDeprecated()) { + throw SwfFaults.workflowTypeAlreadyExists(name, version); + } + type.setStatus(SwfConstants.STATUS_REGISTERED); + type.setDeprecationDate(null); + workflowTypeStore.put(typeKey(region, domainName, name, version), type); + } + + /** SWF only deletes a type that is already deprecated. */ + public void deleteWorkflowType(String region, String domainName, String name, String version) { + requireDomain(region, domainName); + SwfWorkflowType type = findWorkflowType(region, domainName, name, version); + if (!type.isDeprecated()) { + throw SwfFaults.typeNotDeprecated(); + } + workflowTypeStore.delete(typeKey(region, domainName, name, version)); + } + + // ───────────────────────────── Activity types ──────────────────────────── + + public void registerActivityType(String region, String domainName, SwfActivityType type) { + SwfDomain domain = requireDomain(region, domainName); + if (domain.isDeprecated()) { + throw SwfFaults.domainDeprecated(domainName); + } + requireName(type.getName(), "name"); + requireName(type.getVersion(), "version"); + + String key = typeKey(region, domainName, type.getName(), type.getVersion()); + if (activityTypeStore.get(key).isPresent()) { + throw SwfFaults.activityTypeAlreadyExists(type.getName(), type.getVersion()); + } + type.setDomain(domainName); + type.setCreationDate(now()); + activityTypeStore.put(key, type); + } + + public SwfActivityType describeActivityType(String region, String domainName, String name, String version) { + requireDomain(region, domainName); + return findActivityType(region, domainName, name, version); + } + + private SwfActivityType findActivityType(String region, String domainName, String name, String version) { + requireName(name, "activityType.name"); + requireName(version, "activityType.version"); + return activityTypeStore.get(typeKey(region, domainName, name, version)) + .orElseThrow(() -> SwfFaults.unknownActivityType(name, version)); + } + + public List listActivityTypes(String region, String domainName, String name, + String registrationStatus, boolean reverseOrder) { + requireDomain(region, domainName); + String status = requireRegistrationStatus(registrationStatus); + String prefix = region + ":" + domainName + "/"; + List types = activityTypeStore.scan(k -> k.startsWith(prefix)); + types.removeIf(t -> !status.equals(t.getStatus())); + if (name != null && !name.isEmpty()) { + types.removeIf(t -> !name.equals(t.getName())); + } + types.sort(Comparator.comparing(SwfActivityType::getName).thenComparing(SwfActivityType::getVersion)); + if (reverseOrder) { + java.util.Collections.reverse(types); + } + return types; + } + + public void deprecateActivityType(String region, String domainName, String name, String version) { + requireDomain(region, domainName); + SwfActivityType type = findActivityType(region, domainName, name, version); + if (type.isDeprecated()) { + throw SwfFaults.activityTypeDeprecated(name, version); + } + type.setStatus(SwfConstants.STATUS_DEPRECATED); + type.setDeprecationDate(now()); + activityTypeStore.put(typeKey(region, domainName, name, version), type); + } + + public void undeprecateActivityType(String region, String domainName, String name, String version) { + requireDomain(region, domainName); + SwfActivityType type = findActivityType(region, domainName, name, version); + if (!type.isDeprecated()) { + throw SwfFaults.activityTypeAlreadyExists(name, version); + } + type.setStatus(SwfConstants.STATUS_REGISTERED); + type.setDeprecationDate(null); + activityTypeStore.put(typeKey(region, domainName, name, version), type); + } + + public void deleteActivityType(String region, String domainName, String name, String version) { + requireDomain(region, domainName); + SwfActivityType type = findActivityType(region, domainName, name, version); + if (!type.isDeprecated()) { + throw SwfFaults.typeNotDeprecated(); + } + activityTypeStore.delete(typeKey(region, domainName, name, version)); + } + + // ─────────────────────────── Execution lifecycle ───────────────────────── + + public String startWorkflowExecution(StartWorkflowExecutionRequest request) { + SwfDomain domain = requireDomain(request.region(), request.domain()); + if (domain.isDeprecated()) { + throw SwfFaults.domainDeprecated(request.domain()); + } + requireName(request.workflowId(), "workflowId"); + + SwfWorkflowType type = findWorkflowType(request.region(), request.domain(), request.typeName(), request.typeVersion()); + if (type.isDeprecated()) { + throw SwfFaults.workflowTypeDeprecated(type.getName(), type.getVersion()); + } + + // The open-run check and the insert have to be one atomic step, or two concurrent + // starts for the same workflowId both scan clean and persist distinct run keys, + // leaving two open runs where SWF guarantees one. + synchronized (domainLock(request.region(), request.domain())) { + if (findOpenExecution(request.region(), request.domain(), request.workflowId()).isPresent()) { + throw SwfFaults.executionAlreadyStarted(); + } + + SwfWorkflowExecution execution = buildExecution(request, type); + appendWorkflowExecutionStarted(execution, request.input(), null); + scheduleDecisionTask(execution); + executionStore.put(executionKey(execution), execution); + LOG.debugv("Started SWF execution {0}/{1} run {2}", + execution.getDomain(), execution.getWorkflowId(), execution.getRunId()); + return execution.getRunId(); + } + } + + private SwfWorkflowExecution buildExecution(StartWorkflowExecutionRequest request, SwfWorkflowType type) { + SwfWorkflowExecution execution = new SwfWorkflowExecution(); + execution.setRegion(request.region()); + execution.setDomain(request.domain()); + execution.setWorkflowId(request.workflowId()); + execution.setRunId(newRunId()); + execution.setWorkflowTypeName(type.getName()); + execution.setWorkflowTypeVersion(type.getVersion()); + execution.setInput(request.input()); + execution.setStartTimestamp(now()); + if (request.tagList() != null) { + execution.setTagList(new ArrayList<>(request.tagList())); + } + + execution.setTaskList(resolveRequired(request.taskList(), type.getDefaultTaskList(), + "defaultTaskList")); + execution.setExecutionStartToCloseTimeout(resolveRequired(request.executionStartToCloseTimeout(), + type.getDefaultExecutionStartToCloseTimeout(), "defaultExecutionStartToCloseTimeout")); + execution.setTaskStartToCloseTimeout(resolveRequired(request.taskStartToCloseTimeout(), + type.getDefaultTaskStartToCloseTimeout(), "defaultTaskStartToCloseTimeout")); + execution.setChildPolicy(validateChildPolicy(resolveRequired(request.childPolicy(), + type.getDefaultChildPolicy(), "defaultChildPolicy"))); + execution.setTaskPriority(firstNonEmpty(request.taskPriority(), type.getDefaultTaskPriority())); + execution.setLambdaRole(firstNonEmpty(request.lambdaRole(), type.getDefaultLambdaRole())); + return execution; + } + + /** + * StartWorkflowExecution fields that fall back to the workflow type's registration + * default. When neither is set SWF rejects the call with DefaultUndefinedFault naming + * the missing type-level default rather than the request field. + */ + private String resolveRequired(String requested, String typeDefault, String defaultFieldName) { + String value = firstNonEmpty(requested, typeDefault); + if (value == null) { + throw SwfFaults.defaultUndefined(defaultFieldName); + } + return value; + } + + public SwfWorkflowExecution describeWorkflowExecution(String region, String domainName, String workflowId, String runId) { + requireDomain(region, domainName); + return requireExecution(region, domainName, workflowId, runId); + } + + private SwfWorkflowExecution requireExecution(String region, String domainName, String workflowId, String runId) { + requireName(workflowId, "execution.workflowId"); + if (runId == null || runId.isEmpty()) { + return findOpenExecution(region, domainName, workflowId) + .orElseThrow(() -> SwfFaults.unknownExecution(workflowId, "")); + } + return executionStore.get(executionKey(region, domainName, workflowId, runId)) + .orElseThrow(() -> SwfFaults.unknownExecution(workflowId, runId)); + } + + private Optional findOpenExecution(String region, String domainName, String workflowId) { + String prefix = region + ":" + domainName + "/" + workflowId + "/"; + return executionStore.scan(k -> k.startsWith(prefix)).stream() + .filter(SwfWorkflowExecution::isOpen) + .findFirst(); + } + + public List getWorkflowExecutionHistory(String region, String domainName, String workflowId, + String runId, boolean reverseOrder) { + requireDomain(region, domainName); + SwfWorkflowExecution execution = requireExecution(region, domainName, workflowId, runId); + List events = new ArrayList<>(execution.getEvents()); + if (reverseOrder) { + java.util.Collections.reverse(events); + } + return events; + } + + /** + * The page size for every paginated operation: the registration lists, the history, the + * execution listings, and PollForDecisionTask. + * + *

Measured against the live service on all four: an absent or zero + * {@code maximumPageSize} means "no caller limit" and returns everything up to the service + * maximum, above 1000 is rejected rather than clamped, and a negative value is rejected + * with its own constraint message. + */ + public int pageSize(Integer requested) { + if (requested == null || requested == 0) { + return MAX_PAGE_SIZE; + } + if (requested < 0) { + throw SwfFaults.validationConstraint(String.valueOf(requested), "maximumPageSize", + "Member must have value greater than or equal to 0"); + } + if (requested > MAX_PAGE_SIZE) { + throw SwfFaults.validationConstraint(String.valueOf(requested), "maximumPageSize", + "Member must have value less than or equal to " + MAX_PAGE_SIZE); + } + return requested; + } + + public List listExecutions(String region, String domainName, ExecutionFilter filter, boolean closed) { + requireDomain(region, domainName); + String prefix = region + ":" + domainName + "/"; + List executions = executionStore.scan(k -> k.startsWith(prefix)); + executions.removeIf(e -> closed == e.isOpen()); + executions.removeIf(filter.negate()); + executions.sort(Comparator.comparingDouble(SwfWorkflowExecution::getStartTimestamp).reversed()); + return executions; + } + + public int countPendingActivityTasks(String region, String domainName, String taskList) { + requireDomain(region, domainName); + requireName(taskList, "taskList.name"); + int count = 0; + for (SwfWorkflowExecution execution : executionsIn(region, domainName)) { + for (SwfActivityTask task : execution.getActivities().values()) { + if (SwfActivityTask.STATE_SCHEDULED.equals(task.getState()) && taskList.equals(task.getTaskList())) { + count++; + } + } + } + return count; + } + + public int countPendingDecisionTasks(String region, String domainName, String taskList) { + requireDomain(region, domainName); + requireName(taskList, "taskList.name"); + int count = 0; + for (SwfWorkflowExecution execution : executionsIn(region, domainName)) { + SwfDecisionTask task = execution.getDecisionTask(); + if (task != null && SwfDecisionTask.STATE_SCHEDULED.equals(task.getState()) + && taskList.equals(task.getTaskList())) { + count++; + } + } + return count; + } + + private List executionsIn(String region, String domainName) { + String prefix = region + ":" + domainName + "/"; + return executionStore.scan(k -> k.startsWith(prefix)); + } + + // ────────────────────────────── Decision tasks ─────────────────────────── + + /** + * Claims the oldest scheduled decision task on {@code taskList}, or returns empty when + * none is available. SWF long-polls for up to 60s; the emulator answers immediately and + * lets the caller decide whether to poll again, which keeps request threads free. + */ + public Optional pollForDecisionTask(String region, String domainName, String taskList, String identity) { + requireDomain(region, domainName); + requireName(taskList, "taskList.name"); + + List candidates = executionsIn(region, domainName); + candidates.sort(Comparator.comparingDouble(e -> { + SwfDecisionTask task = e.getDecisionTask(); + return task != null ? task.getScheduledTimestamp() : Double.MAX_VALUE; + })); + + for (SwfWorkflowExecution candidate : candidates) { + SwfDecisionTask claimed = tryClaimDecisionTask(candidate, taskList, identity); + if (claimed != null) { + return Optional.of(claimed); + } + } + return Optional.empty(); + } + + private SwfDecisionTask tryClaimDecisionTask(SwfWorkflowExecution candidate, String taskList, String identity) { + synchronized (domainLock(candidate)) { + SwfWorkflowExecution execution = executionStore.get(executionKey(candidate)).orElse(null); + if (execution == null || !execution.isOpen()) { + return null; + } + SwfDecisionTask task = execution.getDecisionTask(); + if (task == null || !SwfDecisionTask.STATE_SCHEDULED.equals(task.getState()) + || !taskList.equals(task.getTaskList())) { + return null; + } + + task.setState(SwfDecisionTask.STATE_STARTED); + task.setIdentity(identity); + task.setStartedTimestamp(now()); + SwfHistoryEvent started = appendEvent(execution, "DecisionTaskStarted"); + started.attr("identity", identity) + .attr("scheduledEventId", task.getScheduledEventId()) + .attr("startedOnPreviousTaskCompletion", Boolean.FALSE); + task.setStartedEventId(started.getEventId()); + + String token = newTaskToken(); + task.setTaskToken(token); + decisionTokens.put(token, executionKey(execution)); + executionStore.put(executionKey(execution), execution); + return task; + } + } + + public SwfWorkflowExecution executionForDecisionToken(String taskToken) { + if (taskToken == null || taskToken.isEmpty()) { + throw SwfFaults.missingRequired("taskToken"); + } + String key = decisionTokens.get(taskToken); + if (key == null) { + throw SwfFaults.unknownTaskToken(); + } + return executionStore.get(key).orElseThrow(SwfFaults::unknownTaskToken); + } + + /** + * Applies a decider's decisions in order. + * + *

A closing decision (Complete/Fail/Cancel/ContinueAsNew) must be last: the live + * service rejects the whole batch with {@code ValidationException} rather than applying + * the prefix, so this is validated before any state changes. + */ + public void respondDecisionTaskCompleted(String taskToken, List decisions, String executionContext) { + // Scoped to this call, not to the thread: a request that throws before the drain must + // not leave an invocation for whichever request reuses this pooled thread next. + List queued = new ArrayList<>(); + SwfWorkflowExecution located = executionForDecisionToken(taskToken); + synchronized (domainLock(located)) { + SwfWorkflowExecution execution = executionStore.get(executionKey(located)) + .orElseThrow(SwfFaults::unknownTaskToken); + SwfDecisionTask task = execution.getDecisionTask(); + if (task == null || !taskToken.equals(task.getTaskToken())) { + throw SwfFaults.unknownTaskToken(); + } + + // Rejected before anything is mutated: the live service answers 400 and leaves + // the task outstanding, so the decider can retry with a corrected batch. + requireValidBatch(decisions); + + SwfHistoryEvent completed = appendEvent(execution, "DecisionTaskCompleted"); + completed.attr("executionContext", executionContext) + .attr("scheduledEventId", task.getScheduledEventId()) + .attr("startedEventId", task.getStartedEventId()); + long decisionEventId = completed.getEventId(); + + decisionTokens.remove(taskToken); + execution.setDecisionTask(null); + execution.setDecisionTaskOutstanding(false); + if (executionContext != null) { + execution.setLatestExecutionContext(executionContext); + } + + applyDecisions(execution, decisions, queued, decisionEventId); + + if (execution.isOpen() && (execution.isDecisionNeeded() || hasNothingPending(execution))) { + execution.setDecisionNeeded(false); + scheduleDecisionTask(execution); + } + executionStore.put(executionKey(execution), execution); + } + // Only reached when the batch was applied and stored: anything thrown above leaves + // `queued` unreferenced, so a failed request cannot invoke a function. + queued.forEach(this::runPendingLambda); + } + + /** + * The decision task a token identifies, without claiming anything. + * + *

Used by {@code PollForDecisionTask} continuation paging: the live service returns the + * same task's next history page for a {@code nextPageToken} rather than handing out a new + * task, so a continuation resolves the original task instead of polling again. + */ + public SwfDecisionTask decisionTaskForToken(String taskToken) { + SwfWorkflowExecution execution = executionForDecisionToken(taskToken); + SwfDecisionTask task = execution.getDecisionTask(); + if (task == null || !taskToken.equals(task.getTaskToken())) { + throw SwfFaults.unknownTaskToken(); + } + return task; + } + + /** + * Validates a whole batch before any of it is applied. + * + *

The live service rejects an invalid batch with {@code ValidationException} and leaves + * the execution untouched: no {@code DecisionTaskCompleted}, no earlier decision applied, + * and the token still claimable for a corrected batch. Validating up front is what makes + * that possible — the mutations land on the in-memory execution and on + * {@code decisionTokens}, so there is nothing to roll back once they have happened. + * + *

Two rules, both measured against the live service: every {@code decisionType} must be + * one the service knows, and a closing decision may appear only last. + */ + private void requireValidBatch(List decisions) { + if (decisions == null || decisions.isEmpty()) { + return; + } + for (int i = 0; i < decisions.size(); i++) { + String type = decisions.get(i).type(); + if (!SwfConstants.DECISION_TYPES.contains(type)) { + // AWS names the offending member by its 1-based position in the list. + throw SwfFaults.validationConstraint(type, + "decisions." + (i + 1) + ".member.decisionType", + "Member must satisfy enum value set: " + SwfConstants.DECISION_TYPE_SET_MESSAGE); + } + if (i < decisions.size() - 1 && SwfConstants.CLOSING_DECISIONS.contains(type)) { + throw SwfFaults.validation("Close must be last decision in list"); + } + } + } + + private void applyDecisions(SwfWorkflowExecution execution, List decisions, + List queued, long decisionEventId) { + if (decisions == null) { + return; + } + for (Decision decision : decisions) { + if (!execution.isOpen()) { + LOG.debugv("Dropping {0} decision: execution {1} already closed", + decision.type(), execution.getRunId()); + return; + } + applyDecision(execution, decision, queued, decisionEventId); + } + } + + private void applyDecision(SwfWorkflowExecution execution, Decision decision, + List queued, long decisionEventId) { + switch (decision.type()) { + case "ScheduleActivityTask" -> scheduleActivityTask(execution, decision, decisionEventId); + case "RequestCancelActivityTask" -> requestCancelActivityTask(execution, decision, decisionEventId); + case "CompleteWorkflowExecution" -> completeWorkflowExecution(execution, decision, decisionEventId); + case "FailWorkflowExecution" -> failWorkflowExecution(execution, decision, decisionEventId); + case "CancelWorkflowExecution" -> cancelWorkflowExecution(execution, decision, decisionEventId); + case "ContinueAsNewWorkflowExecution" -> continueAsNew(execution, decision, decisionEventId); + case "RecordMarker" -> recordMarker(execution, decision, decisionEventId); + case "StartTimer" -> startTimer(execution, decision, decisionEventId); + case "CancelTimer" -> cancelTimer(execution, decision, decisionEventId); + case "SignalExternalWorkflowExecution" -> signalExternal(execution, decision, decisionEventId); + case "RequestCancelExternalWorkflowExecution" -> cancelExternal(execution, decision, decisionEventId); + case "StartChildWorkflowExecution" -> startChild(execution, decision, decisionEventId); + case "ScheduleLambdaFunction" -> scheduleLambdaFunction(execution, decision, queued, decisionEventId); + // requireValidBatch has already rejected anything outside DECISION_TYPES. + default -> throw new IllegalStateException("unvalidated decision type " + decision.type()); + } + } + + private void scheduleActivityTask(SwfWorkflowExecution execution, Decision decision, long decisionEventId) { + String activityId = decision.string("activityId"); + String typeName = decision.nested("activityType", "name"); + String typeVersion = decision.nested("activityType", "version"); + + SwfActivityType type = activityTypeStore.get(typeKey(execution.getRegion(), execution.getDomain(), typeName, typeVersion)) + .orElse(null); + if (type == null) { + appendScheduleActivityTaskFailed(execution, decision, decisionEventId, "ACTIVITY_TYPE_DOES_NOT_EXIST"); + return; + } + if (type.isDeprecated()) { + appendScheduleActivityTaskFailed(execution, decision, decisionEventId, "ACTIVITY_TYPE_DEPRECATED"); + return; + } + SwfActivityTask existing = execution.getActivities().get(activityId); + if (existing != null && existing.isOpen()) { + appendScheduleActivityTaskFailed(execution, decision, decisionEventId, "ACTIVITY_ID_ALREADY_IN_USE"); + return; + } + + String taskList = firstNonEmpty(decision.nested("taskList", "name"), type.getDefaultTaskList()); + if (taskList == null) { + appendScheduleActivityTaskFailed(execution, decision, decisionEventId, "DEFAULT_TASK_LIST_UNDEFINED"); + return; + } + String scheduleToStart = firstNonEmpty(decision.string("scheduleToStartTimeout"), + type.getDefaultTaskScheduleToStartTimeout()); + String scheduleToClose = firstNonEmpty(decision.string("scheduleToCloseTimeout"), + type.getDefaultTaskScheduleToCloseTimeout()); + String startToClose = firstNonEmpty(decision.string("startToCloseTimeout"), + type.getDefaultTaskStartToCloseTimeout()); + String heartbeat = firstNonEmpty(decision.string("heartbeatTimeout"), + type.getDefaultTaskHeartbeatTimeout()); + if (scheduleToStart == null) { + appendScheduleActivityTaskFailed(execution, decision, decisionEventId, + "DEFAULT_SCHEDULE_TO_START_TIMEOUT_UNDEFINED"); + return; + } + if (startToClose == null) { + appendScheduleActivityTaskFailed(execution, decision, decisionEventId, + "DEFAULT_START_TO_CLOSE_TIMEOUT_UNDEFINED"); + return; + } + + SwfHistoryEvent scheduled = appendEvent(execution, "ActivityTaskScheduled"); + scheduled.attr("activityType", Map.of("name", typeName, "version", typeVersion)) + .attr("activityId", activityId) + .attr("input", decision.string("input")) + .attr("control", decision.string("control")) + .attr("scheduleToStartTimeout", scheduleToStart) + .attr("scheduleToCloseTimeout", scheduleToClose) + .attr("startToCloseTimeout", startToClose) + .attr("heartbeatTimeout", heartbeat) + .attr("taskList", Map.of("name", taskList)) + .attr("taskPriority", firstNonEmpty(decision.string("taskPriority"), type.getDefaultTaskPriority())) + .attr("decisionTaskCompletedEventId", decisionEventId) + .attr("immediatelyStart", Boolean.FALSE); + + SwfActivityTask task = new SwfActivityTask(); + task.setDomain(execution.getDomain()); + task.setWorkflowId(execution.getWorkflowId()); + task.setRunId(execution.getRunId()); + task.setActivityId(activityId); + task.setActivityTypeName(typeName); + task.setActivityTypeVersion(typeVersion); + task.setTaskList(taskList); + task.setTaskPriority(firstNonEmpty(decision.string("taskPriority"), type.getDefaultTaskPriority())); + task.setInput(decision.string("input")); + task.setControl(decision.string("control")); + task.setScheduleToStartTimeout(scheduleToStart); + task.setScheduleToCloseTimeout(scheduleToClose); + task.setStartToCloseTimeout(startToClose); + task.setHeartbeatTimeout(heartbeat); + task.setScheduledEventId(scheduled.getEventId()); + task.setDecisionTaskCompletedEventId(decisionEventId); + task.setScheduledTimestamp(scheduled.getEventTimestamp()); + execution.getActivities().put(activityId, task); + } + + private void appendScheduleActivityTaskFailed(SwfWorkflowExecution execution, Decision decision, + long decisionEventId, String cause) { + appendEvent(execution, "ScheduleActivityTaskFailed") + .attr("activityType", Map.of( + "name", nullToEmpty(decision.nested("activityType", "name")), + "version", nullToEmpty(decision.nested("activityType", "version")))) + .attr("activityId", nullToEmpty(decision.string("activityId"))) + .attr("cause", cause) + .attr("decisionTaskCompletedEventId", decisionEventId); + execution.setDecisionNeeded(true); + } + + private void requestCancelActivityTask(SwfWorkflowExecution execution, Decision decision, long decisionEventId) { + String activityId = decision.string("activityId"); + SwfActivityTask task = execution.getActivities().get(activityId); + if (task == null || !task.isOpen()) { + appendEvent(execution, "RequestCancelActivityTaskFailed") + .attr("activityId", nullToEmpty(activityId)) + .attr("cause", "ACTIVITY_ID_UNKNOWN") + .attr("decisionTaskCompletedEventId", decisionEventId); + execution.setDecisionNeeded(true); + return; + } + + SwfHistoryEvent requested = appendEvent(execution, "ActivityTaskCancelRequested"); + requested.attr("decisionTaskCompletedEventId", decisionEventId).attr("activityId", activityId); + task.setCancelRequested(true); + task.setLatestCancelRequestedEventId(requested.getEventId()); + + // A scheduled-but-unstarted activity has no worker to observe the cancellation, + // so SWF cancels it immediately rather than waiting for a heartbeat. + if (SwfActivityTask.STATE_SCHEDULED.equals(task.getState())) { + appendEvent(execution, "ActivityTaskCanceled") + .attr("scheduledEventId", task.getScheduledEventId()) + .attr("startedEventId", 0L) + .attr("latestCancelRequestedEventId", requested.getEventId()); + task.setState(SwfActivityTask.STATE_CLOSED); + execution.setDecisionNeeded(true); + } + } + + private void completeWorkflowExecution(SwfWorkflowExecution execution, Decision decision, long decisionEventId) { + if (hasOpenWork(execution)) { + appendEvent(execution, "CompleteWorkflowExecutionFailed") + .attr("cause", "UNHANDLED_DECISION") + .attr("decisionTaskCompletedEventId", decisionEventId); + execution.setDecisionNeeded(true); + return; + } + appendEvent(execution, "WorkflowExecutionCompleted") + .attr("result", decision.string("result")) + .attr("decisionTaskCompletedEventId", decisionEventId); + closeExecution(execution, SwfConstants.CLOSE_STATUS_COMPLETED); + } + + private void failWorkflowExecution(SwfWorkflowExecution execution, Decision decision, long decisionEventId) { + if (hasOpenWork(execution)) { + appendEvent(execution, "FailWorkflowExecutionFailed") + .attr("cause", "UNHANDLED_DECISION") + .attr("decisionTaskCompletedEventId", decisionEventId); + execution.setDecisionNeeded(true); + return; + } + appendEvent(execution, "WorkflowExecutionFailed") + .attr("reason", decision.string("reason")) + .attr("details", decision.string("details")) + .attr("decisionTaskCompletedEventId", decisionEventId); + closeExecution(execution, SwfConstants.CLOSE_STATUS_FAILED); + } + + private void cancelWorkflowExecution(SwfWorkflowExecution execution, Decision decision, long decisionEventId) { + if (hasOpenWork(execution)) { + appendEvent(execution, "CancelWorkflowExecutionFailed") + .attr("cause", "UNHANDLED_DECISION") + .attr("decisionTaskCompletedEventId", decisionEventId); + execution.setDecisionNeeded(true); + return; + } + appendEvent(execution, "WorkflowExecutionCanceled") + .attr("details", decision.string("details")) + .attr("decisionTaskCompletedEventId", decisionEventId); + closeExecution(execution, SwfConstants.CLOSE_STATUS_CANCELED); + } + + /** + * Moves a parent relationship from a run onto its continue-as-new successor. + * + *

Continuing as new closes one run and opens another, and the live service keeps the + * parent link across that boundary: the successor reports the same + * {@code parentWorkflowExecution} and {@code parentInitiatedEventId}. The parent's own child + * entry has to move too, otherwise it keeps pointing at the closed run and would never see + * the successor's outcome or have child policy applied to it. + */ + private void carryParentTo(SwfWorkflowExecution closing, SwfWorkflowExecution successor) { + if (closing.getParentWorkflowId() == null) { + return; + } + successor.setParentWorkflowId(closing.getParentWorkflowId()); + successor.setParentRunId(closing.getParentRunId()); + successor.setParentInitiatedEventId(closing.getParentInitiatedEventId()); + successor.setParentStartedEventId(closing.getParentStartedEventId()); + + // The parent shares this run's domain, so the domain lock is already held. + String parentKey = executionKey(closing.getRegion(), closing.getDomain(), + closing.getParentWorkflowId(), closing.getParentRunId()); + executionStore.get(parentKey).ifPresent(parent -> { + parent.getChildExecutions().put(successor.getWorkflowId(), successor.getRunId()); + executionStore.put(parentKey, parent); + }); + } + + private void continueAsNew(SwfWorkflowExecution execution, Decision decision, long decisionEventId) { + String version = firstNonEmpty(decision.string("workflowTypeVersion"), execution.getWorkflowTypeVersion()); + SwfWorkflowType type = workflowTypeStore + .get(typeKey(execution.getRegion(), execution.getDomain(), execution.getWorkflowTypeName(), version)).orElse(null); + if (type == null) { + appendEvent(execution, "ContinueAsNewWorkflowExecutionFailed") + .attr("cause", "WORKFLOW_TYPE_DOES_NOT_EXIST") + .attr("decisionTaskCompletedEventId", decisionEventId); + execution.setDecisionNeeded(true); + return; + } + if (type.isDeprecated()) { + appendEvent(execution, "ContinueAsNewWorkflowExecutionFailed") + .attr("cause", "WORKFLOW_TYPE_DEPRECATED") + .attr("decisionTaskCompletedEventId", decisionEventId); + execution.setDecisionNeeded(true); + return; + } + + StartWorkflowExecutionRequest request = new StartWorkflowExecutionRequest( + execution.getRegion(), execution.getDomain(), execution.getWorkflowId(), type.getName(), version, + decision.nested("taskList", "name"), decision.string("taskPriority"), + decision.string("input"), decision.string("executionStartToCloseTimeout"), + decision.string("taskStartToCloseTimeout"), decision.string("childPolicy"), + decision.stringList("tagList"), decision.string("lambdaRole")); + + SwfWorkflowExecution next = buildExecution(request, type); + next.setContinuedExecutionRunId(execution.getRunId()); + carryParentTo(execution, next); + + appendEvent(execution, "WorkflowExecutionContinuedAsNew") + .attr("input", decision.string("input")) + .attr("decisionTaskCompletedEventId", decisionEventId) + .attr("newExecutionRunId", next.getRunId()) + .attr("executionStartToCloseTimeout", next.getExecutionStartToCloseTimeout()) + .attr("taskList", Map.of("name", next.getTaskList())) + .attr("taskPriority", next.getTaskPriority()) + .attr("taskStartToCloseTimeout", next.getTaskStartToCloseTimeout()) + .attr("childPolicy", next.getChildPolicy()) + .attr("tagList", next.getTagList().isEmpty() ? null : new ArrayList<>(next.getTagList())) + .attr("workflowType", Map.of("name", type.getName(), "version", version)) + .attr("lambdaRole", next.getLambdaRole()); + closeExecution(execution, SwfConstants.CLOSE_STATUS_CONTINUED_AS_NEW); + + appendWorkflowExecutionStarted(next, decision.string("input"), execution.getRunId()); + scheduleDecisionTask(next); + executionStore.put(executionKey(next), next); + } + + private void recordMarker(SwfWorkflowExecution execution, Decision decision, long decisionEventId) { + appendEvent(execution, "MarkerRecorded") + .attr("markerName", decision.string("markerName")) + .attr("details", decision.string("details")) + .attr("decisionTaskCompletedEventId", decisionEventId); + } + + private void startTimer(SwfWorkflowExecution execution, Decision decision, long decisionEventId) { + String timerId = decision.string("timerId"); + SwfTimer existing = execution.getTimers().get(timerId); + if (existing != null && !existing.isCanceled()) { + appendEvent(execution, "StartTimerFailed") + .attr("timerId", nullToEmpty(timerId)) + .attr("cause", "TIMER_ID_ALREADY_IN_USE") + .attr("decisionTaskCompletedEventId", decisionEventId); + execution.setDecisionNeeded(true); + return; + } + + String startToFire = decision.string("startToFireTimeout"); + SwfHistoryEvent started = appendEvent(execution, "TimerStarted"); + started.attr("timerId", timerId) + .attr("control", decision.string("control")) + .attr("startToFireTimeout", startToFire) + .attr("decisionTaskCompletedEventId", decisionEventId); + + SwfTimer timer = new SwfTimer(); + timer.setTimerId(timerId); + timer.setControl(decision.string("control")); + timer.setStartToFireTimeout(startToFire); + timer.setStartedEventId(started.getEventId()); + timer.setDecisionTaskCompletedEventId(decisionEventId); + timer.setStartedTimestamp(started.getEventTimestamp()); + timer.setFireTimestamp(started.getEventTimestamp() + parseSeconds(startToFire, 0)); + execution.getTimers().put(timerId, timer); + } + + private void cancelTimer(SwfWorkflowExecution execution, Decision decision, long decisionEventId) { + String timerId = decision.string("timerId"); + SwfTimer timer = execution.getTimers().get(timerId); + if (timer == null || timer.isCanceled()) { + appendEvent(execution, "CancelTimerFailed") + .attr("timerId", nullToEmpty(timerId)) + .attr("cause", "TIMER_ID_UNKNOWN") + .attr("decisionTaskCompletedEventId", decisionEventId); + execution.setDecisionNeeded(true); + return; + } + appendEvent(execution, "TimerCanceled") + .attr("timerId", timerId) + .attr("startedEventId", timer.getStartedEventId()) + .attr("decisionTaskCompletedEventId", decisionEventId); + timer.setCanceled(true); + execution.getTimers().remove(timerId); + } + + private void signalExternal(SwfWorkflowExecution execution, Decision decision, long decisionEventId) { + String targetWorkflowId = decision.string("workflowId"); + String targetRunId = decision.string("runId"); + String signalName = decision.string("signalName"); + + SwfHistoryEvent initiated = appendEvent(execution, "SignalExternalWorkflowExecutionInitiated"); + initiated.attr("workflowId", targetWorkflowId) + .attr("runId", targetRunId) + .attr("signalName", signalName) + .attr("input", decision.string("input")) + .attr("decisionTaskCompletedEventId", decisionEventId) + .attr("control", decision.string("control")); + + SwfWorkflowExecution target = resolveTarget(execution.getRegion(), execution.getDomain(), targetWorkflowId, targetRunId); + if (target == null || !target.isOpen()) { + appendEvent(execution, "SignalExternalWorkflowExecutionFailed") + .attr("workflowId", nullToEmpty(targetWorkflowId)) + .attr("runId", targetRunId) + .attr("cause", "UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION") + .attr("initiatedEventId", initiated.getEventId()) + .attr("decisionTaskCompletedEventId", decisionEventId) + .attr("control", decision.string("control")); + execution.setDecisionNeeded(true); + return; + } + + deliverSignal(target, signalName, decision.string("input"), + Map.of("workflowId", execution.getWorkflowId(), "runId", execution.getRunId()), + initiated.getEventId()); + appendEvent(execution, "ExternalWorkflowExecutionSignaled") + .attr("workflowExecution", Map.of("workflowId", target.getWorkflowId(), + "runId", target.getRunId())) + .attr("initiatedEventId", initiated.getEventId()); + } + + private void cancelExternal(SwfWorkflowExecution execution, Decision decision, long decisionEventId) { + String targetWorkflowId = decision.string("workflowId"); + String targetRunId = decision.string("runId"); + + SwfHistoryEvent initiated = appendEvent(execution, "RequestCancelExternalWorkflowExecutionInitiated"); + initiated.attr("workflowId", targetWorkflowId) + .attr("runId", targetRunId) + .attr("decisionTaskCompletedEventId", decisionEventId) + .attr("control", decision.string("control")); + + SwfWorkflowExecution target = resolveTarget(execution.getRegion(), execution.getDomain(), targetWorkflowId, targetRunId); + if (target == null || !target.isOpen()) { + appendEvent(execution, "RequestCancelExternalWorkflowExecutionFailed") + .attr("workflowId", nullToEmpty(targetWorkflowId)) + .attr("runId", targetRunId) + .attr("cause", "UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION") + .attr("initiatedEventId", initiated.getEventId()) + .attr("decisionTaskCompletedEventId", decisionEventId) + .attr("control", decision.string("control")); + execution.setDecisionNeeded(true); + return; + } + + deliverCancelRequest(target, Map.of("workflowId", execution.getWorkflowId(), + "runId", execution.getRunId()), initiated.getEventId(), null); + appendEvent(execution, "ExternalWorkflowExecutionCancelRequested") + .attr("workflowExecution", Map.of("workflowId", target.getWorkflowId(), + "runId", target.getRunId())) + .attr("initiatedEventId", initiated.getEventId()); + } + + private void startChild(SwfWorkflowExecution execution, Decision decision, long decisionEventId) { + String childWorkflowId = decision.string("workflowId"); + String typeName = decision.nested("workflowType", "name"); + String typeVersion = decision.nested("workflowType", "version"); + + SwfWorkflowType type = workflowTypeStore.get(typeKey(execution.getRegion(), execution.getDomain(), typeName, typeVersion)) + .orElse(null); + if (type == null || type.isDeprecated()) { + appendStartChildFailed(execution, decision, decisionEventId, + type == null ? "WORKFLOW_TYPE_DOES_NOT_EXIST" : "WORKFLOW_TYPE_DEPRECATED", 0L); + return; + } + if (findOpenExecution(execution.getRegion(), execution.getDomain(), childWorkflowId).isPresent()) { + appendStartChildFailed(execution, decision, decisionEventId, "WORKFLOW_ALREADY_RUNNING", 0L); + return; + } + + SwfHistoryEvent initiated = appendEvent(execution, "StartChildWorkflowExecutionInitiated"); + String childPolicy = firstNonEmpty(decision.string("childPolicy"), type.getDefaultChildPolicy()); + String taskList = firstNonEmpty(decision.nested("taskList", "name"), type.getDefaultTaskList()); + initiated.attr("workflowId", childWorkflowId) + .attr("workflowType", Map.of("name", typeName, "version", typeVersion)) + .attr("control", decision.string("control")) + .attr("input", decision.string("input")) + .attr("executionStartToCloseTimeout", firstNonEmpty( + decision.string("executionStartToCloseTimeout"), + type.getDefaultExecutionStartToCloseTimeout())) + .attr("taskList", taskList != null ? Map.of("name", taskList) : null) + .attr("taskPriority", firstNonEmpty(decision.string("taskPriority"), type.getDefaultTaskPriority())) + .attr("decisionTaskCompletedEventId", decisionEventId) + .attr("childPolicy", childPolicy) + .attr("taskStartToCloseTimeout", firstNonEmpty(decision.string("taskStartToCloseTimeout"), + type.getDefaultTaskStartToCloseTimeout())) + .attr("tagList", decision.stringList("tagList")) + .attr("lambdaRole", firstNonEmpty(decision.string("lambdaRole"), type.getDefaultLambdaRole())); + + StartWorkflowExecutionRequest request = new StartWorkflowExecutionRequest( + execution.getRegion(), execution.getDomain(), childWorkflowId, typeName, typeVersion, + decision.nested("taskList", "name"), decision.string("taskPriority"), + decision.string("input"), decision.string("executionStartToCloseTimeout"), + decision.string("taskStartToCloseTimeout"), decision.string("childPolicy"), + decision.stringList("tagList"), decision.string("lambdaRole")); + + SwfWorkflowExecution child; + try { + child = buildExecution(request, type); + } catch (AwsException e) { + LOG.debugv("Child workflow {0} rejected: {1}", childWorkflowId, e.getMessage()); + appendStartChildFailed(execution, decision, decisionEventId, + causeForDefaultUndefined(e.getMessage()), initiated.getEventId()); + return; + } + child.setParentWorkflowId(execution.getWorkflowId()); + child.setParentRunId(execution.getRunId()); + child.setParentInitiatedEventId(initiated.getEventId()); + + appendWorkflowExecutionStarted(child, decision.string("input"), null); + scheduleDecisionTask(child); + execution.getChildExecutions().put(childWorkflowId, child.getRunId()); + + SwfHistoryEvent childStarted = appendEvent(execution, "ChildWorkflowExecutionStarted"); + childStarted.attr("workflowExecution", Map.of("workflowId", child.getWorkflowId(), + "runId", child.getRunId())) + .attr("workflowType", Map.of("name", typeName, "version", typeVersion)) + .attr("initiatedEventId", initiated.getEventId()); + + // The child reports this id back on startedEventId of every + // ChildWorkflowExecution* event, so it has to be stored before the child is saved. + child.setParentStartedEventId(childStarted.getEventId()); + executionStore.put(executionKey(child), child); + } + + /** Maps a DefaultUndefinedFault message onto the matching child-start failure cause. */ + private String causeForDefaultUndefined(String message) { + if (message == null) { + return "OPERATION_NOT_PERMITTED"; + } + return switch (message) { + case "defaultExecutionStartToCloseTimeout" -> "DEFAULT_EXECUTION_START_TO_CLOSE_TIMEOUT_UNDEFINED"; + case "defaultTaskStartToCloseTimeout" -> "DEFAULT_TASK_START_TO_CLOSE_TIMEOUT_UNDEFINED"; + case "defaultTaskList" -> "DEFAULT_TASK_LIST_UNDEFINED"; + case "defaultChildPolicy" -> "DEFAULT_CHILD_POLICY_UNDEFINED"; + default -> "OPERATION_NOT_PERMITTED"; + }; + } + + private void appendStartChildFailed(SwfWorkflowExecution execution, Decision decision, + long decisionEventId, String cause, long initiatedEventId) { + appendEvent(execution, "StartChildWorkflowExecutionFailed") + .attr("workflowType", Map.of( + "name", nullToEmpty(decision.nested("workflowType", "name")), + "version", nullToEmpty(decision.nested("workflowType", "version")))) + .attr("cause", cause) + .attr("workflowId", nullToEmpty(decision.string("workflowId"))) + .attr("initiatedEventId", initiatedEventId) + .attr("decisionTaskCompletedEventId", decisionEventId) + .attr("control", decision.string("control")); + execution.setDecisionNeeded(true); + } + + /** + * Invokes the Lambda function the decider asked for, through Floci's own Lambda service, + * and records the outcome as the live service does. + * + *

Verified against the live service: a successful call appends Scheduled, Started, then + * Completed with the function's response as {@code result}; a function that cannot be + * resolved still gets Scheduled and Started, then Failed with the SDK's error code as + * {@code reason}; and an execution with no {@code lambdaRole} never reaches Started at all, + * appending StartLambdaFunctionFailed with cause ASSUME_ROLE_FAILED instead. Reusing an + * {@code id} is accepted — SWF does not report ID_ALREADY_IN_USE for Lambda invocations the + * way it does for activity ids. + * + *

The invocation is synchronous here rather than dispatched to the sweeper: floci's + * Lambda service runs the function in a container it manages and returns the payload, so + * the natural place to record Completed/Failed is the same decision that scheduled it. + */ + private void scheduleLambdaFunction(SwfWorkflowExecution execution, Decision decision, + List queued, long decisionEventId) { + String id = nullToEmpty(decision.string("id")); + String name = decision.string("name"); + + SwfHistoryEvent scheduled = appendEvent(execution, "LambdaFunctionScheduled"); + scheduled.attr("id", id) + .attr("name", nullToEmpty(name)) + .attr("control", decision.string("control")) + .attr("input", decision.string("input")) + .attr("startToCloseTimeout", decision.string("startToCloseTimeout")) + .attr("decisionTaskCompletedEventId", decisionEventId); + + // No role means SWF cannot assume anything to invoke with, so the function is never + // started. This is the one path that skips LambdaFunctionStarted entirely. + if (execution.getLambdaRole() == null || execution.getLambdaRole().isEmpty()) { + appendEvent(execution, "StartLambdaFunctionFailed") + .attr("scheduledEventId", scheduled.getEventId()) + .attr("cause", "ASSUME_ROLE_FAILED") + .attr("message", "No IAM role is attached to the current workflow execution."); + execution.setDecisionNeeded(true); + return; + } + + SwfHistoryEvent started = appendEvent(execution, "LambdaFunctionStarted"); + started.attr("scheduledEventId", scheduled.getEventId()); + + // An empty input is delivered to the handler as {}, matching the live service. + String input = decision.string("input"); + byte[] payload = (input == null || input.isEmpty() ? "{}" : input) + .getBytes(StandardCharsets.UTF_8); + + // The invocation runs once the domain lock is released: a cold start takes seconds and + // this lock deliberately covers every execution in the domain. + queued.add(new PendingLambda(executionKey(execution), id, name, payload, + scheduled.getEventId(), started.getEventId())); + } + + /** A Lambda invocation a decision queued, to run once the domain lock is released. */ + private record PendingLambda(String executionKey, String id, String name, byte[] payload, + long scheduledEventId, long startedEventId) { + } + + /** + * Invokes a queued function with no lock held, then re-takes the domain lock to record the + * outcome as one atomic transition. + */ + private void runPendingLambda(PendingLambda pending) { + String eventType; + String reason = null; + String details = null; + String result = null; + try { + LambdaInvocationResult invoked = lambdaInvoker.invoke( + regionOf(pending.executionKey()), pending.name(), pending.payload()); + if (invoked.functionError() != null && !invoked.functionError().isEmpty()) { + eventType = "LambdaFunctionFailed"; + reason = invoked.functionError(); + details = invoked.payload(); + } else { + eventType = "LambdaFunctionCompleted"; + result = invoked.payload(); + } + } catch (AwsException e) { + // The live service surfaces the Lambda SDK's own error code and message here, so a + // decider sees ResourceNotFoundException for a function that does not exist. + eventType = "LambdaFunctionFailed"; + reason = e.getErrorCode(); + details = e.getMessage(); + } catch (RuntimeException e) { + LOG.warnv("SWF Lambda invocation {0} ({1}) failed: {2}", + pending.id(), pending.name(), e.getMessage()); + eventType = "LambdaFunctionFailed"; + reason = e.getClass().getSimpleName(); + details = nullToEmpty(e.getMessage()); + } + + synchronized (domainLockForKey(pending.executionKey())) { + SwfWorkflowExecution execution = executionStore.get(pending.executionKey()).orElse(null); + if (execution == null || !execution.isOpen()) { + return; + } + appendEvent(execution, eventType) + .attr("scheduledEventId", pending.scheduledEventId()) + .attr("startedEventId", pending.startedEventId()) + .attr("reason", reason) + .attr("details", details) + .attr("result", result); + if (hasNothingPending(execution)) { + scheduleDecisionTask(execution); + } else { + execution.setDecisionNeeded(true); + } + executionStore.put(pending.executionKey(), execution); + } + } + + /** The region segment of a {@code :/...} storage key. */ + private static String regionOf(String executionKey) { + int colon = executionKey.indexOf(':'); + return colon < 0 ? executionKey : executionKey.substring(0, colon); + } + + // ────────────────────────────── Activity tasks ─────────────────────────── + + public Optional pollForActivityTask(String region, String domainName, String taskList, String identity) { + requireDomain(region, domainName); + requireName(taskList, "taskList.name"); + + List candidates = executionsIn(region, domainName); + candidates.sort(Comparator.comparingDouble(SwfWorkflowExecution::getStartTimestamp)); + for (SwfWorkflowExecution candidate : candidates) { + SwfActivityTask claimed = tryClaimActivityTask(candidate, taskList, identity); + if (claimed != null) { + return Optional.of(claimed); + } + } + return Optional.empty(); + } + + private SwfActivityTask tryClaimActivityTask(SwfWorkflowExecution candidate, String taskList, String identity) { + synchronized (domainLock(candidate)) { + SwfWorkflowExecution execution = executionStore.get(executionKey(candidate)).orElse(null); + if (execution == null || !execution.isOpen()) { + return null; + } + SwfActivityTask task = execution.getActivities().values().stream() + .filter(t -> SwfActivityTask.STATE_SCHEDULED.equals(t.getState())) + .filter(t -> taskList.equals(t.getTaskList())) + .min(Comparator.comparingDouble(SwfActivityTask::getScheduledTimestamp)) + .orElse(null); + if (task == null) { + return null; + } + + task.setState(SwfActivityTask.STATE_STARTED); + task.setIdentity(identity); + double startedAt = now(); + task.setStartedTimestamp(startedAt); + task.setLastHeartbeatTimestamp(startedAt); + SwfHistoryEvent started = appendEvent(execution, "ActivityTaskStarted"); + started.attr("identity", identity).attr("scheduledEventId", task.getScheduledEventId()); + task.setStartedEventId(started.getEventId()); + execution.setLatestActivityTaskTimestamp(started.getEventTimestamp()); + + String token = newTaskToken(); + task.setTaskToken(token); + activityTokens.put(token, executionKey(execution) + "|" + task.getActivityId()); + executionStore.put(executionKey(execution), execution); + return task; + } + } + + /** True when the worker holding {@code taskToken} should abandon the activity. */ + public boolean recordActivityTaskHeartbeat(String taskToken, String details) { + return withActivityToken(taskToken, (execution, task) -> { + task.setLastHeartbeatTimestamp(now()); + if (details != null) { + task.setControl(details); + } + executionStore.put(executionKey(execution), execution); + return task.isCancelRequested(); + }); + } + + public void respondActivityTaskCompleted(String taskToken, String result) { + withActivityToken(taskToken, (execution, task) -> { + appendEvent(execution, "ActivityTaskCompleted") + .attr("result", result) + .attr("scheduledEventId", task.getScheduledEventId()) + .attr("startedEventId", task.getStartedEventId()); + closeActivity(execution, task); + return null; + }); + } + + public void respondActivityTaskFailed(String taskToken, String reason, String details) { + withActivityToken(taskToken, (execution, task) -> { + appendEvent(execution, "ActivityTaskFailed") + .attr("reason", reason) + .attr("details", details) + .attr("scheduledEventId", task.getScheduledEventId()) + .attr("startedEventId", task.getStartedEventId()); + closeActivity(execution, task); + return null; + }); + } + + public void respondActivityTaskCanceled(String taskToken, String details) { + withActivityToken(taskToken, (execution, task) -> { + appendEvent(execution, "ActivityTaskCanceled") + .attr("details", details) + .attr("scheduledEventId", task.getScheduledEventId()) + .attr("startedEventId", task.getStartedEventId()) + .attr("latestCancelRequestedEventId", task.getLatestCancelRequestedEventId()); + closeActivity(execution, task); + return null; + }); + } + + private void closeActivity(SwfWorkflowExecution execution, SwfActivityTask task) { + task.setState(SwfActivityTask.STATE_CLOSED); + // The token mapping is deliberately retained: withActivityToken needs it to tell a + // genuine token whose task has closed (Unknown activity, scheduledEventId = N) from + // a token that never existed. Reuse is still refused by the isOpen() check there. + scheduleDecisionTaskIfIdle(execution); + executionStore.put(executionKey(execution), execution); + } + + private T withActivityToken(String taskToken, ActivityTokenAction action) { + if (taskToken == null || taskToken.isEmpty()) { + throw SwfFaults.missingRequired("taskToken"); + } + String pointer = activityTokens.get(taskToken); + if (pointer == null) { + throw SwfFaults.unknownTaskToken(); + } + int separator = pointer.lastIndexOf('|'); + String executionKey = pointer.substring(0, separator); + String activityId = pointer.substring(separator + 1); + + synchronized (domainLockForKey(executionKey)) { + SwfWorkflowExecution execution = executionStore.get(executionKey) + .orElseThrow(SwfFaults::unknownTaskToken); + SwfActivityTask task = execution.getActivities().get(activityId); + if (task == null || !taskToken.equals(task.getTaskToken())) { + throw SwfFaults.unknownTaskToken(); + } + if (!task.isOpen()) { + // The token is genuine but the task already closed, so the live service + // names the scheduled event instead of calling the token unknown. + throw SwfFaults.unknownActivity(task.getScheduledEventId()); + } + return action.apply(execution, task); + } + } + + private interface ActivityTokenAction { + T apply(SwfWorkflowExecution execution, SwfActivityTask task); + } + + // ───────────────────────── External execution control ──────────────────── + + public void signalWorkflowExecution(String region, String domainName, String workflowId, String runId, + String signalName, String input) { + requireDomain(region, domainName); + requireName(signalName, "signalName"); + SwfWorkflowExecution located = requireExecution(region, domainName, workflowId, runId); + synchronized (domainLock(located)) { + SwfWorkflowExecution execution = executionStore.get(executionKey(located)) + .orElseThrow(() -> SwfFaults.unknownExecution(workflowId, runId)); + if (!execution.isOpen()) { + throw SwfFaults.unknownExecution(workflowId, nullToEmpty(runId)); + } + deliverSignal(execution, signalName, input, null, null); + } + } + + private void deliverSignal(SwfWorkflowExecution execution, String signalName, String input, + Map externalExecution, Long externalInitiatedEventId) { + appendEvent(execution, "WorkflowExecutionSignaled") + .attr("signalName", signalName) + .attr("input", input) + .attr("externalWorkflowExecution", externalExecution) + .attr("externalInitiatedEventId", externalInitiatedEventId); + scheduleDecisionTaskIfIdle(execution); + executionStore.put(executionKey(execution), execution); + } + + public void requestCancelWorkflowExecution(String region, String domainName, String workflowId, String runId) { + requireDomain(region, domainName); + SwfWorkflowExecution located = requireExecution(region, domainName, workflowId, runId); + synchronized (domainLock(located)) { + SwfWorkflowExecution execution = executionStore.get(executionKey(located)) + .orElseThrow(() -> SwfFaults.unknownExecution(workflowId, runId)); + if (!execution.isOpen()) { + throw SwfFaults.unknownExecution(workflowId, nullToEmpty(runId)); + } + deliverCancelRequest(execution, null, null, null); + } + } + + private void deliverCancelRequest(SwfWorkflowExecution execution, Map externalExecution, + Long externalInitiatedEventId, String cause) { + appendEvent(execution, "WorkflowExecutionCancelRequested") + .attr("externalWorkflowExecution", externalExecution) + .attr("externalInitiatedEventId", externalInitiatedEventId) + .attr("cause", cause); + execution.setCancelRequested(true); + scheduleDecisionTaskIfIdle(execution); + executionStore.put(executionKey(execution), execution); + } + + public void terminateWorkflowExecution(String region, String domainName, String workflowId, String runId, + String reason, String details, String childPolicy) { + requireDomain(region, domainName); + SwfWorkflowExecution located = requireExecution(region, domainName, workflowId, runId); + synchronized (domainLock(located)) { + SwfWorkflowExecution execution = executionStore.get(executionKey(located)) + .orElseThrow(() -> SwfFaults.unknownExecution(workflowId, runId)); + if (!execution.isOpen()) { + throw SwfFaults.unknownExecution(workflowId, nullToEmpty(runId)); + } + String policy = validateChildPolicy(firstNonEmpty(childPolicy, execution.getChildPolicy())); + terminate(execution, reason, details, policy, null); + } + } + + private void terminate(SwfWorkflowExecution execution, String reason, String details, + String childPolicy, String cause) { + appendEvent(execution, "WorkflowExecutionTerminated") + .attr("reason", reason) + .attr("details", details) + .attr("childPolicy", childPolicy) + .attr("cause", cause); + closeExecution(execution, SwfConstants.CLOSE_STATUS_TERMINATED); + executionStore.put(executionKey(execution), execution); + } + + // ──────────────────────────────── Tagging ──────────────────────────────── + + public Map listTagsForResource(String resourceArn) { + return domainForArn(resourceArn).getTags(); + } + + public void tagResource(String resourceArn, Map tags) { + SwfDomain domain = domainForArn(resourceArn); + if (tags != null) { + if (domain.getTags().size() + tags.size() > MAX_TAGS) { + throw SwfFaults.fault(SwfConstants.TOO_MANY_TAGS, domain.getName()); + } + domain.getTags().putAll(tags); + } + domainStore.put(domain.getName(), domain); + } + + public void untagResource(String resourceArn, List tagKeys) { + SwfDomain domain = domainForArn(resourceArn); + if (tagKeys != null) { + tagKeys.forEach(domain.getTags()::remove); + } + domainStore.put(domain.getName(), domain); + } + + /** + * SWF tagging targets a domain by ARN. The domain name is the segment after + * {@code /domain/}; anything else is not a taggable SWF resource. + * + *

The region is read out of the ARN rather than the request: an ARN already names its + * region, and tagging a domain in another region must not resolve to the caller's. + */ + private SwfDomain domainForArn(String resourceArn) { + if (resourceArn == null || resourceArn.isEmpty()) { + throw SwfFaults.missingRequired("resourceArn"); + } + int marker = resourceArn.indexOf("/domain/"); + if (marker < 0) { + throw SwfFaults.unknownDomain(resourceArn); + } + String name = resourceArn.substring(marker + "/domain/".length()); + // arn:aws:swf:::/domain/ + String[] parts = resourceArn.split(":", 5); + String arnRegion = parts.length >= 4 ? parts[3] : regionResolver.getDefaultRegion(); + return domainStore.get(domainKey(arnRegion, name)) + .orElseThrow(() -> SwfFaults.unknownDomain(name)); + } + + // ──────────────────────────────── Timeouts ─────────────────────────────── + + /** + * Applies every timeout that has come due: activity schedule-to-start, + * start-to-close, schedule-to-close and heartbeat; decision task start-to-close; + * workflow execution start-to-close; and pending timers. + * + *

Called on a fixed interval by {@link SwfTimeoutSweeper} rather than from a + * per-task timer, so a restart cannot leave orphaned timeout threads behind. + */ + public void sweep() { + double nowSeconds = now(); + for (String key : executionStore.keys()) { + synchronized (domainLockForKey(key)) { + SwfWorkflowExecution execution = executionStore.get(key).orElse(null); + if (execution == null || !execution.isOpen()) { + continue; + } + boolean changed = fireTimers(execution, nowSeconds) + | timeOutActivities(execution, nowSeconds) + | timeOutDecisionTask(execution, nowSeconds); + if (timeOutExecution(execution, nowSeconds)) { + changed = true; + } else if (changed && execution.isOpen()) { + scheduleDecisionTaskIfIdle(execution); + } + if (changed) { + executionStore.put(key, execution); + } + } + } + } + + private boolean fireTimers(SwfWorkflowExecution execution, double nowSeconds) { + List due = execution.getTimers().values().stream() + .filter(t -> !t.isCanceled() && t.getFireTimestamp() <= nowSeconds) + .sorted(Comparator.comparingDouble(SwfTimer::getFireTimestamp)) + .toList(); + for (SwfTimer timer : due) { + appendEvent(execution, "TimerFired") + .attr("timerId", timer.getTimerId()) + .attr("startedEventId", timer.getStartedEventId()); + execution.getTimers().remove(timer.getTimerId()); + } + return !due.isEmpty(); + } + + private boolean timeOutActivities(SwfWorkflowExecution execution, double nowSeconds) { + boolean changed = false; + for (SwfActivityTask task : new ArrayList<>(execution.getActivities().values())) { + if (!task.isOpen()) { + continue; + } + String timeoutType = dueActivityTimeout(task, nowSeconds); + if (timeoutType == null) { + continue; + } + appendEvent(execution, "ActivityTaskTimedOut") + .attr("timeoutType", timeoutType) + .attr("scheduledEventId", task.getScheduledEventId()) + .attr("startedEventId", task.getStartedEventId() != null ? task.getStartedEventId() : 0L); + task.setState(SwfActivityTask.STATE_CLOSED); + if (task.getTaskToken() != null) { + activityTokens.remove(task.getTaskToken()); + } + changed = true; + } + return changed; + } + + /** + * The first activity timeout that has elapsed, or null. SCHEDULE_TO_CLOSE is checked + * first because it bounds the others; HEARTBEAT only applies once the task is started + * and a heartbeat timeout was configured. + */ + private String dueActivityTimeout(SwfActivityTask task, double nowSeconds) { + Double scheduleToClose = timeoutSeconds(task.getScheduleToCloseTimeout()); + if (scheduleToClose != null && nowSeconds - task.getScheduledTimestamp() >= scheduleToClose) { + return "SCHEDULE_TO_CLOSE"; + } + if (SwfActivityTask.STATE_SCHEDULED.equals(task.getState())) { + Double scheduleToStart = timeoutSeconds(task.getScheduleToStartTimeout()); + if (scheduleToStart != null && nowSeconds - task.getScheduledTimestamp() >= scheduleToStart) { + return "SCHEDULE_TO_START"; + } + return null; + } + Double startToClose = timeoutSeconds(task.getStartToCloseTimeout()); + if (startToClose != null && task.getStartedTimestamp() != null + && nowSeconds - task.getStartedTimestamp() >= startToClose) { + return "START_TO_CLOSE"; + } + Double heartbeat = timeoutSeconds(task.getHeartbeatTimeout()); + if (heartbeat != null && task.getLastHeartbeatTimestamp() != null + && nowSeconds - task.getLastHeartbeatTimestamp() >= heartbeat) { + return "HEARTBEAT"; + } + return null; + } + + private boolean timeOutDecisionTask(SwfWorkflowExecution execution, double nowSeconds) { + SwfDecisionTask task = execution.getDecisionTask(); + if (task == null || !SwfDecisionTask.STATE_STARTED.equals(task.getState())) { + return false; + } + Double startToClose = timeoutSeconds(task.getStartToCloseTimeout()); + if (startToClose == null || task.getStartedTimestamp() == null + || nowSeconds - task.getStartedTimestamp() < startToClose) { + return false; + } + appendEvent(execution, "DecisionTaskTimedOut") + .attr("timeoutType", "START_TO_CLOSE") + .attr("scheduledEventId", task.getScheduledEventId()) + .attr("startedEventId", task.getStartedEventId()); + if (task.getTaskToken() != null) { + decisionTokens.remove(task.getTaskToken()); + } + execution.setDecisionTask(null); + execution.setDecisionTaskOutstanding(false); + scheduleDecisionTask(execution); + return true; + } + + private boolean timeOutExecution(SwfWorkflowExecution execution, double nowSeconds) { + Double startToClose = timeoutSeconds(execution.getExecutionStartToCloseTimeout()); + if (startToClose == null || nowSeconds - execution.getStartTimestamp() < startToClose) { + return false; + } + appendEvent(execution, "WorkflowExecutionTimedOut") + .attr("timeoutType", "START_TO_CLOSE") + .attr("childPolicy", execution.getChildPolicy()); + closeExecution(execution, SwfConstants.CLOSE_STATUS_TIMED_OUT); + return true; + } + + // ─────────────────────────── History and lifecycle ─────────────────────── + + private void appendWorkflowExecutionStarted(SwfWorkflowExecution execution, String input, + String continuedFromRunId) { + SwfHistoryEvent event = appendEvent(execution, "WorkflowExecutionStarted"); + event.attr("input", input) + .attr("executionStartToCloseTimeout", execution.getExecutionStartToCloseTimeout()) + .attr("taskStartToCloseTimeout", execution.getTaskStartToCloseTimeout()) + .attr("childPolicy", execution.getChildPolicy()) + .attr("taskList", Map.of("name", execution.getTaskList())) + .attr("taskPriority", execution.getTaskPriority()) + .attr("workflowType", Map.of("name", execution.getWorkflowTypeName(), + "version", execution.getWorkflowTypeVersion())) + .attr("tagList", execution.getTagList().isEmpty() ? null + : new ArrayList<>(execution.getTagList())) + .attr("continuedExecutionRunId", continuedFromRunId) + .attr("lambdaRole", execution.getLambdaRole()); + if (execution.getParentWorkflowId() != null) { + event.attr("parentWorkflowExecution", Map.of("workflowId", execution.getParentWorkflowId(), + "runId", execution.getParentRunId())) + .attr("parentInitiatedEventId", execution.getParentInitiatedEventId()); + } else { + // The live service reports 0 rather than omitting the member on root executions. + event.attr("parentInitiatedEventId", 0L); + } + } + + private void scheduleDecisionTask(SwfWorkflowExecution execution) { + SwfHistoryEvent scheduled = appendEvent(execution, "DecisionTaskScheduled"); + scheduled.attr("taskList", Map.of("name", execution.getTaskList())) + .attr("taskPriority", execution.getTaskPriority()) + .attr("startToCloseTimeout", execution.getTaskStartToCloseTimeout()) + .attr("scheduleToStartTimeout", SwfConstants.TIMEOUT_NONE); + + SwfDecisionTask task = new SwfDecisionTask(); + task.setDomain(execution.getDomain()); + task.setWorkflowId(execution.getWorkflowId()); + task.setRunId(execution.getRunId()); + task.setTaskList(execution.getTaskList()); + task.setTaskPriority(execution.getTaskPriority()); + task.setStartToCloseTimeout(execution.getTaskStartToCloseTimeout()); + task.setScheduledEventId(scheduled.getEventId()); + task.setScheduledTimestamp(scheduled.getEventTimestamp()); + task.setPreviousStartedEventId(lastStartedDecisionEventId(execution)); + execution.setDecisionTask(task); + execution.setDecisionTaskOutstanding(true); + } + + /** + * Schedules a decision task unless one is already outstanding. SWF permits only one + * decision task per execution at a time; while one is outstanding the need is recorded + * and satisfied when that task completes. + */ + private void scheduleDecisionTaskIfIdle(SwfWorkflowExecution execution) { + if (!execution.isOpen()) { + return; + } + if (execution.isDecisionTaskOutstanding()) { + execution.setDecisionNeeded(true); + return; + } + scheduleDecisionTask(execution); + } + + private long lastStartedDecisionEventId(SwfWorkflowExecution execution) { + long last = 0; + for (SwfHistoryEvent event : execution.getEvents()) { + if ("DecisionTaskStarted".equals(event.getEventType())) { + last = event.getEventId(); + } + } + return last; + } + + private SwfHistoryEvent appendEvent(SwfWorkflowExecution execution, String eventType) { + SwfHistoryEvent event = new SwfHistoryEvent(execution.allocateEventId(), now(), eventType); + execution.getEvents().add(event); + return event; + } + + private void closeExecution(SwfWorkflowExecution execution, String closeStatus) { + execution.setExecutionStatus(SwfConstants.EXECUTION_STATUS_CLOSED); + execution.setCloseStatus(closeStatus); + execution.setCloseTimestamp(now()); + + SwfDecisionTask task = execution.getDecisionTask(); + if (task != null && task.getTaskToken() != null) { + decisionTokens.remove(task.getTaskToken()); + } + execution.setDecisionTask(null); + execution.setDecisionTaskOutstanding(false); + for (SwfActivityTask activity : execution.getActivities().values()) { + if (activity.getTaskToken() != null) { + activityTokens.remove(activity.getTaskToken()); + } + activity.setState(SwfActivityTask.STATE_CLOSED); + } + execution.getTimers().clear(); + + notifyParent(execution); + applyChildPolicy(execution); + } + + /** + * Reports a child's outcome to its parent so the parent's decider observes the + * matching ChildWorkflowExecution* event. CONTINUED_AS_NEW is deliberately silent: + * the continuation run carries the parent link and reports for itself. + */ + private void notifyParent(SwfWorkflowExecution execution) { + if (execution.getParentWorkflowId() == null || execution.getParentRunId() == null) { + return; + } + if (SwfConstants.CLOSE_STATUS_CONTINUED_AS_NEW.equals(execution.getCloseStatus())) { + return; + } + String parentKey = executionKey(execution.getRegion(), execution.getDomain(), + execution.getParentWorkflowId(), execution.getParentRunId()); + SwfWorkflowExecution parent = executionStore.get(parentKey).orElse(null); + if (parent == null || !parent.isOpen()) { + return; + } + + String eventType = switch (execution.getCloseStatus()) { + case SwfConstants.CLOSE_STATUS_COMPLETED -> "ChildWorkflowExecutionCompleted"; + case SwfConstants.CLOSE_STATUS_FAILED -> "ChildWorkflowExecutionFailed"; + case SwfConstants.CLOSE_STATUS_CANCELED -> "ChildWorkflowExecutionCanceled"; + case SwfConstants.CLOSE_STATUS_TERMINATED -> "ChildWorkflowExecutionTerminated"; + case SwfConstants.CLOSE_STATUS_TIMED_OUT -> "ChildWorkflowExecutionTimedOut"; + default -> null; + }; + if (eventType == null) { + return; + } + + SwfHistoryEvent event = appendEvent(parent, eventType); + event.attr("workflowExecution", Map.of("workflowId", execution.getWorkflowId(), + "runId", execution.getRunId())) + .attr("workflowType", Map.of("name", execution.getWorkflowTypeName(), + "version", execution.getWorkflowTypeVersion())) + .attr("initiatedEventId", execution.getParentInitiatedEventId()) + .attr("startedEventId", execution.getParentStartedEventId() != null + ? execution.getParentStartedEventId() + : execution.getParentInitiatedEventId()); + if (SwfConstants.CLOSE_STATUS_COMPLETED.equals(execution.getCloseStatus())) { + event.attr("result", lastEventAttribute(execution, "WorkflowExecutionCompleted", "result")); + } else if (SwfConstants.CLOSE_STATUS_FAILED.equals(execution.getCloseStatus())) { + event.attr("reason", lastEventAttribute(execution, "WorkflowExecutionFailed", "reason")); + event.attr("details", lastEventAttribute(execution, "WorkflowExecutionFailed", "details")); + } else if (SwfConstants.CLOSE_STATUS_TIMED_OUT.equals(execution.getCloseStatus())) { + event.attr("timeoutType", "START_TO_CLOSE"); + } + + scheduleDecisionTaskIfIdle(parent); + executionStore.put(parentKey, parent); + } + + private Object lastEventAttribute(SwfWorkflowExecution execution, String eventType, String attribute) { + for (int i = execution.getEvents().size() - 1; i >= 0; i--) { + SwfHistoryEvent event = execution.getEvents().get(i); + if (eventType.equals(event.getEventType())) { + return event.getAttributes().get(attribute); + } + } + return null; + } + + /** + * Applies the closing execution's childPolicy to its still-open children: + * TERMINATE ends them, REQUEST_CANCEL asks their deciders to wind down, and + * ABANDON leaves them running. + */ + private void applyChildPolicy(SwfWorkflowExecution execution) { + if (execution.getChildExecutions().isEmpty() + || SwfConstants.CHILD_POLICY_ABANDON.equals(execution.getChildPolicy())) { + return; + } + for (Map.Entry entry : execution.getChildExecutions().entrySet()) { + String childKey = executionKey(execution.getRegion(), execution.getDomain(), entry.getKey(), entry.getValue()); + SwfWorkflowExecution child = executionStore.get(childKey).orElse(null); + if (child == null || !child.isOpen()) { + continue; + } + if (SwfConstants.CHILD_POLICY_TERMINATE.equals(execution.getChildPolicy())) { + terminate(child, null, null, child.getChildPolicy(), "CHILD_POLICY_APPLIED"); + } else { + deliverCancelRequest(child, null, null, "CHILD_POLICY_APPLIED"); + } + } + } + + /** + * True when the execution still has activities, timers, or children the decider must + * resolve before it may close the execution. SWF rejects a closing decision in that + * state with UNHANDLED_DECISION. + */ + private boolean hasOpenWork(SwfWorkflowExecution execution) { + if (execution.getActivities().values().stream().anyMatch(SwfActivityTask::isOpen)) { + return true; + } + if (!execution.getTimers().isEmpty()) { + return true; + } + return execution.getChildExecutions().entrySet().stream().anyMatch(entry -> executionStore + .get(executionKey(execution.getRegion(), execution.getDomain(), entry.getKey(), entry.getValue())) + .filter(SwfWorkflowExecution::isOpen) + .isPresent()); + } + + /** + * True when nothing is pending, so the decider gets another decision task rather than + * an execution stalled with no outstanding work and no scheduled decision. + */ + private boolean hasNothingPending(SwfWorkflowExecution execution) { + return !hasOpenWork(execution); + } + + public int openActivityCount(SwfWorkflowExecution execution) { + return (int) execution.getActivities().values().stream().filter(SwfActivityTask::isOpen).count(); + } + + public int openTimerCount(SwfWorkflowExecution execution) { + return execution.getTimers().size(); + } + + public int openDecisionTaskCount(SwfWorkflowExecution execution) { + return execution.getDecisionTask() != null ? 1 : 0; + } + + public int openChildCount(SwfWorkflowExecution execution) { + return (int) execution.getChildExecutions().entrySet().stream() + .filter(entry -> executionStore + .get(executionKey(execution.getRegion(), execution.getDomain(), entry.getKey(), entry.getValue())) + .filter(SwfWorkflowExecution::isOpen) + .isPresent()) + .count(); + } + + // ──────────────────────────────── Helpers ─────────────────────────────── + + private SwfWorkflowExecution resolveTarget(String region, String domainName, String workflowId, String runId) { + if (workflowId == null || workflowId.isEmpty()) { + return null; + } + if (runId != null && !runId.isEmpty()) { + return executionStore.get(executionKey(region, domainName, workflowId, runId)).orElse(null); + } + return findOpenExecution(region, domainName, workflowId).orElse(null); + } + + /** + * One lock per region-qualified domain. See the class Javadoc: parent/child and multi-run + * invariants span executions, so the lock has to cover the whole family to stay + * non-nested. The region is part of the lock identity because the same domain name in two + * regions is two independent domains — and because it must agree with + * {@link #domainLockForKey(String)}, which derives the same scope from a storage key. + */ + private Object domainLock(String region, String domain) { + return domainLocks.computeIfAbsent(region + ":" + domain, k -> new Object()); + } + + /** Locks the region-qualified domain an execution already knows it belongs to. */ + private Object domainLock(SwfWorkflowExecution execution) { + return domainLock(execution.getRegion(), execution.getDomain()); + } + + /** + * Locks the domain of an execution identified only by its storage key. The key is + * {@code ://}, so the segment before the first + * {@code /} is the region-qualified domain — which is the right lock scope now that the + * same domain name can exist in more than one region. + */ + private Object domainLockForKey(String executionKey) { + int separator = executionKey.indexOf('/'); + String qualifiedDomain = separator < 0 ? executionKey : executionKey.substring(0, separator); + return domainLocks.computeIfAbsent(qualifiedDomain, k -> new Object()); + } + + private double now() { + return clock.millis() / 1000.0; + } + + /** SWF task tokens are opaque; a random base64 blob matches how SDKs treat them. */ + private String newTaskToken() { + byte[] raw = (UUID.randomUUID() + ":" + UUID.randomUUID()).getBytes(StandardCharsets.UTF_8); + return Base64.getEncoder().encodeToString(raw); + } + + /** SWF runIds are base64-ish opaque strings ending in '='. */ + private String newRunId() { + String raw = Base64.getEncoder().withoutPadding() + .encodeToString(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8)); + return raw.substring(0, Math.min(raw.length(), 48)) + "="; + } + + private String domainArn(String name, String region) { + return "arn:aws:swf:" + region + ":" + regionResolver.getAccountId() + ":/domain/" + name; + } + + public String domainArnFor(SwfDomain domain, String region) { + return domain.getArn() != null ? domain.getArn() : domainArn(domain.getName(), region); + } + + /** + * Storage keys are region-scoped: SWF names are unique per region, so the same domain + * (and its types and executions) can exist independently in two regions. + */ + private static String domainKey(String region, String domain) { + return region + ":" + domain; + } + + private static String typeKey(String region, String domain, String name, String version) { + return region + ":" + domain + "/" + name + "/" + version; + } + + private static String executionKey(SwfWorkflowExecution execution) { + return executionKey(execution.getRegion(), execution.getDomain(), + execution.getWorkflowId(), execution.getRunId()); + } + + private static String executionKey(String region, String domain, String workflowId, String runId) { + return region + ":" + domain + "/" + workflowId + "/" + runId; + } + + private static void requireName(String value, String field) { + if (value == null || value.isEmpty()) { + throw SwfFaults.missingRequired(field); + } + } + + private static String requireRegistrationStatus(String status) { + if (status == null || status.isEmpty()) { + throw SwfFaults.missingRequired("registrationStatus"); + } + if (!SwfConstants.STATUS_REGISTERED.equals(status) && !SwfConstants.STATUS_DEPRECATED.equals(status)) { + throw SwfFaults.validationConstraint(status, "registrationStatus", + "Member must satisfy enum value set: [REGISTERED, DEPRECATED]"); + } + return status; + } + + private static String validateChildPolicy(String childPolicy) { + if (childPolicy == null) { + return null; + } + if (!SwfConstants.CHILD_POLICY_TERMINATE.equals(childPolicy) + && !SwfConstants.CHILD_POLICY_REQUEST_CANCEL.equals(childPolicy) + && !SwfConstants.CHILD_POLICY_ABANDON.equals(childPolicy)) { + throw SwfFaults.validationConstraint(childPolicy, "childPolicy", + "Member must satisfy enum value set: [TERMINATE, REQUEST_CANCEL, ABANDON]"); + } + return childPolicy; + } + + private static void validateRetentionPeriod(String retentionDays) { + if (SwfConstants.TIMEOUT_NONE.equals(retentionDays)) { + return; + } + try { + long days = Long.parseLong(retentionDays); + if (days < 0 || days > 90) { + throw SwfFaults.validationConstraint(retentionDays, + "workflowExecutionRetentionPeriodInDays", + "Member must be between 0 and 90 days, or NONE"); + } + } catch (NumberFormatException e) { + throw SwfFaults.validationConstraint(retentionDays, "workflowExecutionRetentionPeriodInDays", + "Member must be a number of days or NONE"); + } + } + + /** + * Timeout fields are strings holding seconds, or the literal "NONE" for no timeout. + * Returns null when no timeout applies. + */ + private static Double timeoutSeconds(String value) { + if (value == null || value.isEmpty() || SwfConstants.TIMEOUT_NONE.equals(value)) { + return null; + } + try { + return Double.parseDouble(value); + } catch (NumberFormatException e) { + LOG.debugv("Ignoring unparseable SWF timeout value {0}", value); + return null; + } + } + + private static double parseSeconds(String value, double fallback) { + Double parsed = timeoutSeconds(value); + return parsed != null ? parsed : fallback; + } + + private static String firstNonEmpty(String preferred, String fallback) { + if (preferred != null && !preferred.isEmpty()) { + return preferred; + } + return fallback != null && !fallback.isEmpty() ? fallback : null; + } + + private static String nullToEmpty(String value) { + return value != null ? value : ""; + } + + /** Fields StartWorkflowExecution accepts, before type defaults are resolved. */ + public record StartWorkflowExecutionRequest( + String region, + String domain, + String workflowId, + String typeName, + String typeVersion, + String taskList, + String taskPriority, + String input, + String executionStartToCloseTimeout, + String taskStartToCloseTimeout, + String childPolicy, + List tagList, + String lambdaRole) { + } + + /** + * One decision from RespondDecisionTaskCompleted, already unwrapped from its + * {@code DecisionAttributes} envelope so the service reads plain fields. + */ + public record Decision(String type, Map attributes) { + + public String string(String field) { + Object value = attributes.get(field); + return value instanceof String s && !s.isEmpty() ? s : null; + } + + @SuppressWarnings("unchecked") + public String nested(String field, String key) { + Object value = attributes.get(field); + if (value instanceof Map map) { + Object nested = ((Map) map).get(key); + return nested instanceof String s && !s.isEmpty() ? s : null; + } + return null; + } + + @SuppressWarnings("unchecked") + public List stringList(String field) { + Object value = attributes.get(field); + if (value instanceof List list && !list.isEmpty()) { + return new ArrayList<>((List) list); + } + return null; + } + } + + /** Composable predicate over executions, built from the API's filter members. */ + public interface ExecutionFilter extends Predicate { + + static ExecutionFilter all() { + return execution -> true; + } + + default ExecutionFilter and(ExecutionFilter other) { + return execution -> test(execution) && other.test(execution); + } + + @Override + default Predicate negate() { + return execution -> !test(execution); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/SwfTimeoutSweeper.java b/src/main/java/io/github/hectorvent/floci/services/swf/SwfTimeoutSweeper.java new file mode 100644 index 0000000000..e54cddc267 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/SwfTimeoutSweeper.java @@ -0,0 +1,85 @@ +package io.github.hectorvent.floci.services.swf; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.quarkus.runtime.ShutdownEvent; +import io.quarkus.runtime.StartupEvent; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * Drives SWF timeout expiry from one background thread. + * + *

SWF timeouts are observable state changes — an activity that misses its + * start-to-close timeout must produce an ActivityTaskTimedOut event and a fresh + * decision task whether or not anyone is polling. A single sweep over open + * executions on a fixed interval delivers that without one timer per task, and + * leaves nothing to reconcile after a restart. + */ +@ApplicationScoped +public class SwfTimeoutSweeper { + + private static final Logger LOG = Logger.getLogger(SwfTimeoutSweeper.class); + + /** Used when the configured interval is not a positive number of seconds. */ + static final long DEFAULT_TICK_INTERVAL_SECONDS = 1L; + + private final SwfService swfService; + private final boolean enabled; + private final long tickIntervalSeconds; + private final ScheduledExecutorService executor; + + @Inject + public SwfTimeoutSweeper(SwfService swfService, EmulatorConfig config) { + this.swfService = swfService; + this.enabled = config.services().swf().enabled() + && config.services().swf().timeoutSweepEnabled(); + this.tickIntervalSeconds = resolveInterval(config.services().swf().timeoutSweepIntervalSeconds()); + this.executor = Executors.newSingleThreadScheduledExecutor(runnable -> { + Thread thread = new Thread(runnable, "swf-timeout-sweeper"); + thread.setDaemon(true); + return thread; + }); + } + + /** + * A zero or negative interval would make {@code scheduleWithFixedDelay} throw from the + * startup observer and stop the whole emulator becoming ready. A misconfigured value is + * not worth failing every other service for, so it falls back with a warning. + */ + private static long resolveInterval(long configured) { + if (configured > 0) { + return configured; + } + LOG.warnv("Ignoring SWF timeout-sweep interval {0}s: must be a positive number of " + + "seconds, falling back to {1}s", configured, DEFAULT_TICK_INTERVAL_SECONDS); + return DEFAULT_TICK_INTERVAL_SECONDS; + } + + void onStart(@Observes StartupEvent event) { + if (!enabled) { + LOG.debug("SWF timeout sweeper disabled"); + return; + } + executor.scheduleWithFixedDelay(this::tick, tickIntervalSeconds, tickIntervalSeconds, TimeUnit.SECONDS); + LOG.debugv("SWF timeout sweeper started, interval {0}s", tickIntervalSeconds); + } + + void onStop(@Observes ShutdownEvent event) { + executor.shutdownNow(); + } + + private void tick() { + try { + swfService.sweep(); + } catch (RuntimeException e) { + // A sweep failure must not kill the scheduled task; the next tick retries. + LOG.error("SWF timeout sweep failed", e); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfActivityTask.java b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfActivityTask.java new file mode 100644 index 0000000000..9b9998ff2e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfActivityTask.java @@ -0,0 +1,253 @@ +package io.github.hectorvent.floci.services.swf.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * An activity task from the moment it is scheduled by a decision until it closes. + * + *

Timeouts are stored as the resolved effective values (activity type defaults + * already applied) so the timeout sweep does not have to re-resolve them. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class SwfActivityTask { + + public static final String STATE_SCHEDULED = "SCHEDULED"; + public static final String STATE_STARTED = "STARTED"; + public static final String STATE_CLOSED = "CLOSED"; + + private String taskToken; + private String domain; + private String workflowId; + private String runId; + private String activityId; + private String activityTypeName; + private String activityTypeVersion; + private String taskList; + private String taskPriority; + private String input; + private String control; + + private String scheduleToStartTimeout; + private String scheduleToCloseTimeout; + private String startToCloseTimeout; + private String heartbeatTimeout; + + private long scheduledEventId; + private Long startedEventId; + private long decisionTaskCompletedEventId; + + private double scheduledTimestamp; + private Double startedTimestamp; + private Double lastHeartbeatTimestamp; + + private String state = STATE_SCHEDULED; + private boolean cancelRequested; + private Long latestCancelRequestedEventId; + private String identity; + + public String getTaskToken() { + return taskToken; + } + + public void setTaskToken(String taskToken) { + this.taskToken = taskToken; + } + + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + public String getWorkflowId() { + return workflowId; + } + + public void setWorkflowId(String workflowId) { + this.workflowId = workflowId; + } + + public String getRunId() { + return runId; + } + + public void setRunId(String runId) { + this.runId = runId; + } + + public String getActivityId() { + return activityId; + } + + public void setActivityId(String activityId) { + this.activityId = activityId; + } + + public String getActivityTypeName() { + return activityTypeName; + } + + public void setActivityTypeName(String activityTypeName) { + this.activityTypeName = activityTypeName; + } + + public String getActivityTypeVersion() { + return activityTypeVersion; + } + + public void setActivityTypeVersion(String activityTypeVersion) { + this.activityTypeVersion = activityTypeVersion; + } + + public String getTaskList() { + return taskList; + } + + public void setTaskList(String taskList) { + this.taskList = taskList; + } + + public String getTaskPriority() { + return taskPriority; + } + + public void setTaskPriority(String taskPriority) { + this.taskPriority = taskPriority; + } + + public String getInput() { + return input; + } + + public void setInput(String input) { + this.input = input; + } + + public String getControl() { + return control; + } + + public void setControl(String control) { + this.control = control; + } + + public String getScheduleToStartTimeout() { + return scheduleToStartTimeout; + } + + public void setScheduleToStartTimeout(String scheduleToStartTimeout) { + this.scheduleToStartTimeout = scheduleToStartTimeout; + } + + public String getScheduleToCloseTimeout() { + return scheduleToCloseTimeout; + } + + public void setScheduleToCloseTimeout(String scheduleToCloseTimeout) { + this.scheduleToCloseTimeout = scheduleToCloseTimeout; + } + + public String getStartToCloseTimeout() { + return startToCloseTimeout; + } + + public void setStartToCloseTimeout(String startToCloseTimeout) { + this.startToCloseTimeout = startToCloseTimeout; + } + + public String getHeartbeatTimeout() { + return heartbeatTimeout; + } + + public void setHeartbeatTimeout(String heartbeatTimeout) { + this.heartbeatTimeout = heartbeatTimeout; + } + + public long getScheduledEventId() { + return scheduledEventId; + } + + public void setScheduledEventId(long scheduledEventId) { + this.scheduledEventId = scheduledEventId; + } + + public Long getStartedEventId() { + return startedEventId; + } + + public void setStartedEventId(Long startedEventId) { + this.startedEventId = startedEventId; + } + + public long getDecisionTaskCompletedEventId() { + return decisionTaskCompletedEventId; + } + + public void setDecisionTaskCompletedEventId(long decisionTaskCompletedEventId) { + this.decisionTaskCompletedEventId = decisionTaskCompletedEventId; + } + + public double getScheduledTimestamp() { + return scheduledTimestamp; + } + + public void setScheduledTimestamp(double scheduledTimestamp) { + this.scheduledTimestamp = scheduledTimestamp; + } + + public Double getStartedTimestamp() { + return startedTimestamp; + } + + public void setStartedTimestamp(Double startedTimestamp) { + this.startedTimestamp = startedTimestamp; + } + + public Double getLastHeartbeatTimestamp() { + return lastHeartbeatTimestamp; + } + + public void setLastHeartbeatTimestamp(Double lastHeartbeatTimestamp) { + this.lastHeartbeatTimestamp = lastHeartbeatTimestamp; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public boolean isCancelRequested() { + return cancelRequested; + } + + public void setCancelRequested(boolean cancelRequested) { + this.cancelRequested = cancelRequested; + } + + public Long getLatestCancelRequestedEventId() { + return latestCancelRequestedEventId; + } + + public void setLatestCancelRequestedEventId(Long latestCancelRequestedEventId) { + this.latestCancelRequestedEventId = latestCancelRequestedEventId; + } + + public String getIdentity() { + return identity; + } + + public void setIdentity(String identity) { + this.identity = identity; + } + + public boolean isOpen() { + return !STATE_CLOSED.equals(state); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfActivityType.java b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfActivityType.java new file mode 100644 index 0000000000..145dd10b12 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfActivityType.java @@ -0,0 +1,139 @@ +package io.github.hectorvent.floci.services.swf.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * A registered activity type and its registration-time defaults. + * + *

Each {@code default*} timeout supplies the fallback for the matching field + * a ScheduleActivityTask decision omits; when neither is present the decision + * fails with the corresponding {@code DEFAULT_*_UNDEFINED} cause. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class SwfActivityType { + + private String domain; + private String name; + private String version; + private String description; + private String status = SwfConstants.STATUS_REGISTERED; + private double creationDate; + private Double deprecationDate; + + private String defaultTaskStartToCloseTimeout; + private String defaultTaskHeartbeatTimeout; + private String defaultTaskList; + private String defaultTaskPriority; + private String defaultTaskScheduleToStartTimeout; + private String defaultTaskScheduleToCloseTimeout; + + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public double getCreationDate() { + return creationDate; + } + + public void setCreationDate(double creationDate) { + this.creationDate = creationDate; + } + + public Double getDeprecationDate() { + return deprecationDate; + } + + public void setDeprecationDate(Double deprecationDate) { + this.deprecationDate = deprecationDate; + } + + public String getDefaultTaskStartToCloseTimeout() { + return defaultTaskStartToCloseTimeout; + } + + public void setDefaultTaskStartToCloseTimeout(String defaultTaskStartToCloseTimeout) { + this.defaultTaskStartToCloseTimeout = defaultTaskStartToCloseTimeout; + } + + public String getDefaultTaskHeartbeatTimeout() { + return defaultTaskHeartbeatTimeout; + } + + public void setDefaultTaskHeartbeatTimeout(String defaultTaskHeartbeatTimeout) { + this.defaultTaskHeartbeatTimeout = defaultTaskHeartbeatTimeout; + } + + public String getDefaultTaskList() { + return defaultTaskList; + } + + public void setDefaultTaskList(String defaultTaskList) { + this.defaultTaskList = defaultTaskList; + } + + public String getDefaultTaskPriority() { + return defaultTaskPriority; + } + + public void setDefaultTaskPriority(String defaultTaskPriority) { + this.defaultTaskPriority = defaultTaskPriority; + } + + public String getDefaultTaskScheduleToStartTimeout() { + return defaultTaskScheduleToStartTimeout; + } + + public void setDefaultTaskScheduleToStartTimeout(String defaultTaskScheduleToStartTimeout) { + this.defaultTaskScheduleToStartTimeout = defaultTaskScheduleToStartTimeout; + } + + public String getDefaultTaskScheduleToCloseTimeout() { + return defaultTaskScheduleToCloseTimeout; + } + + public void setDefaultTaskScheduleToCloseTimeout(String defaultTaskScheduleToCloseTimeout) { + this.defaultTaskScheduleToCloseTimeout = defaultTaskScheduleToCloseTimeout; + } + + public boolean isDeprecated() { + return SwfConstants.STATUS_DEPRECATED.equals(status); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfConstants.java b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfConstants.java new file mode 100644 index 0000000000..cf83911889 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfConstants.java @@ -0,0 +1,95 @@ +package io.github.hectorvent.floci.services.swf.model; + +import java.util.Set; + +/** + * Wire-level constants shared by the SWF service and handler. + * + *

SWF reports faults with a namespaced {@code __type} of + * {@code com.amazonaws.swf.base.model#} and HTTP 400, verified against + * the live service. The AWS SDKs match on the suffix after {@code #}, so the + * namespace has to be present for a fault to deserialize as its typed + * exception rather than a generic {@code SwfException}. + */ +public final class SwfConstants { + + public static final String FAULT_NAMESPACE = "com.amazonaws.swf.base.model#"; + public static final String VALIDATION_NAMESPACE = "com.amazon.coral.validate#"; + + /** + * Decision types that close the execution. SWF requires one of these to be the last + * decision in a batch and rejects the batch outright otherwise. + */ + public static final Set CLOSING_DECISIONS = Set.of( + "CompleteWorkflowExecution", + "FailWorkflowExecution", + "CancelWorkflowExecution", + "ContinueAsNewWorkflowExecution"); + + /** + * Every decision type the service accepts. A batch containing anything else is rejected + * before any of it is applied, so this is the single source of truth for both the check + * and the enum list the fault message quotes. + */ + public static final Set DECISION_TYPES = Set.of( + "ScheduleActivityTask", + "RequestCancelActivityTask", + "CompleteWorkflowExecution", + "FailWorkflowExecution", + "CancelWorkflowExecution", + "ContinueAsNewWorkflowExecution", + "RecordMarker", + "StartTimer", + "CancelTimer", + "SignalExternalWorkflowExecution", + "RequestCancelExternalWorkflowExecution", + "StartChildWorkflowExecution", + "ScheduleLambdaFunction"); + + /** + * The enum list exactly as the live service renders it in a ValidationException. + * + *

This order is the service's, not the API model's — the two differ, and the service's + * was stable across repeated calls, so it is what a byte-comparing client sees. + */ + public static final String DECISION_TYPE_SET_MESSAGE = + "[CompleteWorkflowExecution, StartTimer, RequestCancelExternalWorkflowExecution, " + + "SignalExternalWorkflowExecution, CancelTimer, RecordMarker, ScheduleActivityTask, " + + "ContinueAsNewWorkflowExecution, ScheduleLambdaFunction, FailWorkflowExecution, " + + "RequestCancelActivityTask, StartChildWorkflowExecution, CancelWorkflowExecution]"; + + public static final String UNKNOWN_RESOURCE = "UnknownResourceFault"; + public static final String DOMAIN_ALREADY_EXISTS = "DomainAlreadyExistsFault"; + public static final String DOMAIN_DEPRECATED = "DomainDeprecatedFault"; + public static final String TYPE_ALREADY_EXISTS = "TypeAlreadyExistsFault"; + public static final String TYPE_DEPRECATED = "TypeDeprecatedFault"; + public static final String TYPE_NOT_DEPRECATED = "TypeNotDeprecatedFault"; + public static final String WORKFLOW_EXECUTION_ALREADY_STARTED = "WorkflowExecutionAlreadyStartedFault"; + public static final String DEFAULT_UNDEFINED = "DefaultUndefinedFault"; + public static final String LIMIT_EXCEEDED = "LimitExceededFault"; + public static final String OPERATION_NOT_PERMITTED = "OperationNotPermittedFault"; + public static final String TOO_MANY_TAGS = "TooManyTagsFault"; + public static final String VALIDATION = "ValidationException"; + + public static final String STATUS_REGISTERED = "REGISTERED"; + public static final String STATUS_DEPRECATED = "DEPRECATED"; + + public static final String EXECUTION_STATUS_OPEN = "OPEN"; + public static final String EXECUTION_STATUS_CLOSED = "CLOSED"; + + public static final String CLOSE_STATUS_COMPLETED = "COMPLETED"; + public static final String CLOSE_STATUS_FAILED = "FAILED"; + public static final String CLOSE_STATUS_CANCELED = "CANCELED"; + public static final String CLOSE_STATUS_TERMINATED = "TERMINATED"; + public static final String CLOSE_STATUS_CONTINUED_AS_NEW = "CONTINUED_AS_NEW"; + public static final String CLOSE_STATUS_TIMED_OUT = "TIMED_OUT"; + + public static final String CHILD_POLICY_TERMINATE = "TERMINATE"; + public static final String CHILD_POLICY_REQUEST_CANCEL = "REQUEST_CANCEL"; + public static final String CHILD_POLICY_ABANDON = "ABANDON"; + + public static final String TIMEOUT_NONE = "NONE"; + + private SwfConstants() { + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfDecisionTask.java b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfDecisionTask.java new file mode 100644 index 0000000000..2509403c31 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfDecisionTask.java @@ -0,0 +1,146 @@ +package io.github.hectorvent.floci.services.swf.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * A decision task. Scheduled whenever the execution needs a decision and + * consumed by PollForDecisionTask; only one may be outstanding per execution. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class SwfDecisionTask { + + public static final String STATE_SCHEDULED = "SCHEDULED"; + public static final String STATE_STARTED = "STARTED"; + + private String taskToken; + private String domain; + private String workflowId; + private String runId; + private String taskList; + private String taskPriority; + private String startToCloseTimeout; + + private long scheduledEventId; + private Long startedEventId; + private long previousStartedEventId; + + private double scheduledTimestamp; + private Double startedTimestamp; + + private String state = STATE_SCHEDULED; + private String identity; + + public String getTaskToken() { + return taskToken; + } + + public void setTaskToken(String taskToken) { + this.taskToken = taskToken; + } + + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + public String getWorkflowId() { + return workflowId; + } + + public void setWorkflowId(String workflowId) { + this.workflowId = workflowId; + } + + public String getRunId() { + return runId; + } + + public void setRunId(String runId) { + this.runId = runId; + } + + public String getTaskList() { + return taskList; + } + + public void setTaskList(String taskList) { + this.taskList = taskList; + } + + public String getTaskPriority() { + return taskPriority; + } + + public void setTaskPriority(String taskPriority) { + this.taskPriority = taskPriority; + } + + public String getStartToCloseTimeout() { + return startToCloseTimeout; + } + + public void setStartToCloseTimeout(String startToCloseTimeout) { + this.startToCloseTimeout = startToCloseTimeout; + } + + public long getScheduledEventId() { + return scheduledEventId; + } + + public void setScheduledEventId(long scheduledEventId) { + this.scheduledEventId = scheduledEventId; + } + + public Long getStartedEventId() { + return startedEventId; + } + + public void setStartedEventId(Long startedEventId) { + this.startedEventId = startedEventId; + } + + public long getPreviousStartedEventId() { + return previousStartedEventId; + } + + public void setPreviousStartedEventId(long previousStartedEventId) { + this.previousStartedEventId = previousStartedEventId; + } + + public double getScheduledTimestamp() { + return scheduledTimestamp; + } + + public void setScheduledTimestamp(double scheduledTimestamp) { + this.scheduledTimestamp = scheduledTimestamp; + } + + public Double getStartedTimestamp() { + return startedTimestamp; + } + + public void setStartedTimestamp(Double startedTimestamp) { + this.startedTimestamp = startedTimestamp; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getIdentity() { + return identity; + } + + public void setIdentity(String identity) { + this.identity = identity; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfDomain.java b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfDomain.java new file mode 100644 index 0000000000..09cfd752f9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfDomain.java @@ -0,0 +1,89 @@ +package io.github.hectorvent.floci.services.swf.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.LinkedHashMap; +import java.util.Map; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class SwfDomain { + + private String name; + private String arn; + private String description; + private String status = SwfConstants.STATUS_REGISTERED; + private String workflowExecutionRetentionPeriodInDays; + private double creationDate; + private Double deprecationDate; + private Map tags = new LinkedHashMap<>(); + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getArn() { + return arn; + } + + public void setArn(String arn) { + this.arn = arn; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getWorkflowExecutionRetentionPeriodInDays() { + return workflowExecutionRetentionPeriodInDays; + } + + public void setWorkflowExecutionRetentionPeriodInDays(String workflowExecutionRetentionPeriodInDays) { + this.workflowExecutionRetentionPeriodInDays = workflowExecutionRetentionPeriodInDays; + } + + public double getCreationDate() { + return creationDate; + } + + public void setCreationDate(double creationDate) { + this.creationDate = creationDate; + } + + public Double getDeprecationDate() { + return deprecationDate; + } + + public void setDeprecationDate(Double deprecationDate) { + this.deprecationDate = deprecationDate; + } + + public Map getTags() { + return tags; + } + + public void setTags(Map tags) { + this.tags = tags != null ? tags : new LinkedHashMap<>(); + } + + public boolean isDeprecated() { + return SwfConstants.STATUS_DEPRECATED.equals(status); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfHistoryEvent.java b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfHistoryEvent.java new file mode 100644 index 0000000000..912805d4ae --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfHistoryEvent.java @@ -0,0 +1,82 @@ +package io.github.hectorvent.floci.services.swf.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * One entry in a workflow execution's history. + * + *

On the wire an event carries exactly one {@code EventAttributes} + * member alongside {@code eventId}/{@code eventType}/{@code eventTimestamp}. The attribute + * bag is kept generic here and serialized under the name derived from the event type, so + * adding an event type does not require a new field on this class. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class SwfHistoryEvent { + + private long eventId; + private double eventTimestamp; + private String eventType; + private Map attributes = new LinkedHashMap<>(); + + public SwfHistoryEvent() { + } + + public SwfHistoryEvent(long eventId, double eventTimestamp, String eventType) { + this.eventId = eventId; + this.eventTimestamp = eventTimestamp; + this.eventType = eventType; + } + + public long getEventId() { + return eventId; + } + + public void setEventId(long eventId) { + this.eventId = eventId; + } + + public double getEventTimestamp() { + return eventTimestamp; + } + + public void setEventTimestamp(double eventTimestamp) { + this.eventTimestamp = eventTimestamp; + } + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public Map getAttributes() { + return attributes; + } + + public void setAttributes(Map attributes) { + this.attributes = attributes != null ? attributes : new LinkedHashMap<>(); + } + + public SwfHistoryEvent attr(String key, Object value) { + if (value != null) { + attributes.put(key, value); + } + return this; + } + + /** + * The wire name of this event's attribute member: the event type with a lower-cased + * first letter plus {@code EventAttributes} (WorkflowExecutionStarted becomes + * workflowExecutionStartedEventAttributes). + */ + public String attributesFieldName() { + return Character.toLowerCase(eventType.charAt(0)) + eventType.substring(1) + "EventAttributes"; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfTimer.java b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfTimer.java new file mode 100644 index 0000000000..54dd4788dd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfTimer.java @@ -0,0 +1,83 @@ +package io.github.hectorvent.floci.services.swf.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** A timer started by a StartTimer decision, pending until its fire time passes. */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class SwfTimer { + + private String timerId; + private String control; + private String startToFireTimeout; + private long startedEventId; + private long decisionTaskCompletedEventId; + private double startedTimestamp; + private double fireTimestamp; + private boolean canceled; + + public String getTimerId() { + return timerId; + } + + public void setTimerId(String timerId) { + this.timerId = timerId; + } + + public String getControl() { + return control; + } + + public void setControl(String control) { + this.control = control; + } + + public String getStartToFireTimeout() { + return startToFireTimeout; + } + + public void setStartToFireTimeout(String startToFireTimeout) { + this.startToFireTimeout = startToFireTimeout; + } + + public long getStartedEventId() { + return startedEventId; + } + + public void setStartedEventId(long startedEventId) { + this.startedEventId = startedEventId; + } + + public long getDecisionTaskCompletedEventId() { + return decisionTaskCompletedEventId; + } + + public void setDecisionTaskCompletedEventId(long decisionTaskCompletedEventId) { + this.decisionTaskCompletedEventId = decisionTaskCompletedEventId; + } + + public double getStartedTimestamp() { + return startedTimestamp; + } + + public void setStartedTimestamp(double startedTimestamp) { + this.startedTimestamp = startedTimestamp; + } + + public double getFireTimestamp() { + return fireTimestamp; + } + + public void setFireTimestamp(double fireTimestamp) { + this.fireTimestamp = fireTimestamp; + } + + public boolean isCanceled() { + return canceled; + } + + public void setCanceled(boolean canceled) { + this.canceled = canceled; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfWorkflowExecution.java b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfWorkflowExecution.java new file mode 100644 index 0000000000..290dbfffe3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfWorkflowExecution.java @@ -0,0 +1,355 @@ +package io.github.hectorvent.floci.services.swf.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * A workflow execution: its effective configuration, history, and the in-flight + * activities, timers, and child executions the decider can still act on. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class SwfWorkflowExecution { + + /** + * The region this execution lives in. SWF names are unique per region, so the region is + * part of the execution's identity — it is what lets the same domain and workflowId exist + * independently in two regions, and it is how Lambda invocations reach the right region. + */ + private String region; + private String domain; + private String workflowId; + private String runId; + private String workflowTypeName; + private String workflowTypeVersion; + + private String taskList; + private String taskPriority; + private String executionStartToCloseTimeout; + private String taskStartToCloseTimeout; + private String childPolicy; + private String lambdaRole; + private String input; + private List tagList = new ArrayList<>(); + + private String executionStatus = SwfConstants.EXECUTION_STATUS_OPEN; + private String closeStatus; + private double startTimestamp; + private Double closeTimestamp; + private boolean cancelRequested; + + private String parentWorkflowId; + private String parentRunId; + private Long parentInitiatedEventId; + /** + * The parent's ChildWorkflowExecutionStarted event id. Distinct from + * {@link #parentInitiatedEventId}: the live service reports the initiated id on + * {@code initiatedEventId} and this one on {@code startedEventId} of every + * ChildWorkflowExecution* event, and deciders correlate on both. + */ + private Long parentStartedEventId; + private String continuedExecutionRunId; + + private long nextEventId = 1; + private List events = new ArrayList<>(); + + /** Latest decision task, if one is scheduled or started. */ + private SwfDecisionTask decisionTask; + /** True while a decision task is scheduled or started; SWF allows only one at a time. */ + private boolean decisionTaskOutstanding; + /** Set when an event arrives while a decision task is already outstanding. */ + private boolean decisionNeeded; + + private Map activities = new LinkedHashMap<>(); + private Map timers = new LinkedHashMap<>(); + /** Child workflow runIds keyed by the initiating decision's workflowId. */ + private Map childExecutions = new LinkedHashMap<>(); + + private Double latestActivityTaskTimestamp; + private String latestExecutionContext; + + public String getRegion() { + return region; + } + + public void setRegion(String region) { + this.region = region; + } + + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + public String getWorkflowId() { + return workflowId; + } + + public void setWorkflowId(String workflowId) { + this.workflowId = workflowId; + } + + public String getRunId() { + return runId; + } + + public void setRunId(String runId) { + this.runId = runId; + } + + public String getWorkflowTypeName() { + return workflowTypeName; + } + + public void setWorkflowTypeName(String workflowTypeName) { + this.workflowTypeName = workflowTypeName; + } + + public String getWorkflowTypeVersion() { + return workflowTypeVersion; + } + + public void setWorkflowTypeVersion(String workflowTypeVersion) { + this.workflowTypeVersion = workflowTypeVersion; + } + + public String getTaskList() { + return taskList; + } + + public void setTaskList(String taskList) { + this.taskList = taskList; + } + + public String getTaskPriority() { + return taskPriority; + } + + public void setTaskPriority(String taskPriority) { + this.taskPriority = taskPriority; + } + + public String getExecutionStartToCloseTimeout() { + return executionStartToCloseTimeout; + } + + public void setExecutionStartToCloseTimeout(String executionStartToCloseTimeout) { + this.executionStartToCloseTimeout = executionStartToCloseTimeout; + } + + public String getTaskStartToCloseTimeout() { + return taskStartToCloseTimeout; + } + + public void setTaskStartToCloseTimeout(String taskStartToCloseTimeout) { + this.taskStartToCloseTimeout = taskStartToCloseTimeout; + } + + public String getChildPolicy() { + return childPolicy; + } + + public void setChildPolicy(String childPolicy) { + this.childPolicy = childPolicy; + } + + public String getLambdaRole() { + return lambdaRole; + } + + public void setLambdaRole(String lambdaRole) { + this.lambdaRole = lambdaRole; + } + + public String getInput() { + return input; + } + + public void setInput(String input) { + this.input = input; + } + + public List getTagList() { + return tagList; + } + + public void setTagList(List tagList) { + this.tagList = tagList != null ? tagList : new ArrayList<>(); + } + + public String getExecutionStatus() { + return executionStatus; + } + + public void setExecutionStatus(String executionStatus) { + this.executionStatus = executionStatus; + } + + public String getCloseStatus() { + return closeStatus; + } + + public void setCloseStatus(String closeStatus) { + this.closeStatus = closeStatus; + } + + public double getStartTimestamp() { + return startTimestamp; + } + + public void setStartTimestamp(double startTimestamp) { + this.startTimestamp = startTimestamp; + } + + public Double getCloseTimestamp() { + return closeTimestamp; + } + + public void setCloseTimestamp(Double closeTimestamp) { + this.closeTimestamp = closeTimestamp; + } + + public boolean isCancelRequested() { + return cancelRequested; + } + + public void setCancelRequested(boolean cancelRequested) { + this.cancelRequested = cancelRequested; + } + + public String getParentWorkflowId() { + return parentWorkflowId; + } + + public void setParentWorkflowId(String parentWorkflowId) { + this.parentWorkflowId = parentWorkflowId; + } + + public String getParentRunId() { + return parentRunId; + } + + public void setParentRunId(String parentRunId) { + this.parentRunId = parentRunId; + } + + public Long getParentInitiatedEventId() { + return parentInitiatedEventId; + } + + public void setParentInitiatedEventId(Long parentInitiatedEventId) { + this.parentInitiatedEventId = parentInitiatedEventId; + } + + public Long getParentStartedEventId() { + return parentStartedEventId; + } + + public void setParentStartedEventId(Long parentStartedEventId) { + this.parentStartedEventId = parentStartedEventId; + } + + public String getContinuedExecutionRunId() { + return continuedExecutionRunId; + } + + public void setContinuedExecutionRunId(String continuedExecutionRunId) { + this.continuedExecutionRunId = continuedExecutionRunId; + } + + public long getNextEventId() { + return nextEventId; + } + + public void setNextEventId(long nextEventId) { + this.nextEventId = nextEventId; + } + + public List getEvents() { + return events; + } + + public void setEvents(List events) { + this.events = events != null ? events : new ArrayList<>(); + } + + public SwfDecisionTask getDecisionTask() { + return decisionTask; + } + + public void setDecisionTask(SwfDecisionTask decisionTask) { + this.decisionTask = decisionTask; + } + + public boolean isDecisionTaskOutstanding() { + return decisionTaskOutstanding; + } + + public void setDecisionTaskOutstanding(boolean decisionTaskOutstanding) { + this.decisionTaskOutstanding = decisionTaskOutstanding; + } + + public boolean isDecisionNeeded() { + return decisionNeeded; + } + + public void setDecisionNeeded(boolean decisionNeeded) { + this.decisionNeeded = decisionNeeded; + } + + public Map getActivities() { + return activities; + } + + public void setActivities(Map activities) { + this.activities = activities != null ? activities : new LinkedHashMap<>(); + } + + public Map getTimers() { + return timers; + } + + public void setTimers(Map timers) { + this.timers = timers != null ? timers : new LinkedHashMap<>(); + } + + public Map getChildExecutions() { + return childExecutions; + } + + public void setChildExecutions(Map childExecutions) { + this.childExecutions = childExecutions != null ? childExecutions : new LinkedHashMap<>(); + } + + public Double getLatestActivityTaskTimestamp() { + return latestActivityTaskTimestamp; + } + + public void setLatestActivityTaskTimestamp(Double latestActivityTaskTimestamp) { + this.latestActivityTaskTimestamp = latestActivityTaskTimestamp; + } + + public String getLatestExecutionContext() { + return latestExecutionContext; + } + + public void setLatestExecutionContext(String latestExecutionContext) { + this.latestExecutionContext = latestExecutionContext; + } + + public boolean isOpen() { + return SwfConstants.EXECUTION_STATUS_OPEN.equals(executionStatus); + } + + public long allocateEventId() { + return nextEventId++; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfWorkflowType.java b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfWorkflowType.java new file mode 100644 index 0000000000..2d68a2d6c5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/swf/model/SwfWorkflowType.java @@ -0,0 +1,139 @@ +package io.github.hectorvent.floci.services.swf.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * A registered workflow type and its registration-time defaults. + * + *

The {@code default*} fields are echoed back verbatim by + * DescribeWorkflowType and supply the fallback for any field a + * StartWorkflowExecution call omits. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class SwfWorkflowType { + + private String domain; + private String name; + private String version; + private String description; + private String status = SwfConstants.STATUS_REGISTERED; + private double creationDate; + private Double deprecationDate; + + private String defaultTaskStartToCloseTimeout; + private String defaultExecutionStartToCloseTimeout; + private String defaultTaskList; + private String defaultTaskPriority; + private String defaultChildPolicy; + private String defaultLambdaRole; + + public String getDomain() { + return domain; + } + + public void setDomain(String domain) { + this.domain = domain; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public double getCreationDate() { + return creationDate; + } + + public void setCreationDate(double creationDate) { + this.creationDate = creationDate; + } + + public Double getDeprecationDate() { + return deprecationDate; + } + + public void setDeprecationDate(Double deprecationDate) { + this.deprecationDate = deprecationDate; + } + + public String getDefaultTaskStartToCloseTimeout() { + return defaultTaskStartToCloseTimeout; + } + + public void setDefaultTaskStartToCloseTimeout(String defaultTaskStartToCloseTimeout) { + this.defaultTaskStartToCloseTimeout = defaultTaskStartToCloseTimeout; + } + + public String getDefaultExecutionStartToCloseTimeout() { + return defaultExecutionStartToCloseTimeout; + } + + public void setDefaultExecutionStartToCloseTimeout(String defaultExecutionStartToCloseTimeout) { + this.defaultExecutionStartToCloseTimeout = defaultExecutionStartToCloseTimeout; + } + + public String getDefaultTaskList() { + return defaultTaskList; + } + + public void setDefaultTaskList(String defaultTaskList) { + this.defaultTaskList = defaultTaskList; + } + + public String getDefaultTaskPriority() { + return defaultTaskPriority; + } + + public void setDefaultTaskPriority(String defaultTaskPriority) { + this.defaultTaskPriority = defaultTaskPriority; + } + + public String getDefaultChildPolicy() { + return defaultChildPolicy; + } + + public void setDefaultChildPolicy(String defaultChildPolicy) { + this.defaultChildPolicy = defaultChildPolicy; + } + + public String getDefaultLambdaRole() { + return defaultLambdaRole; + } + + public void setDefaultLambdaRole(String defaultLambdaRole) { + this.defaultLambdaRole = defaultLambdaRole; + } + + public boolean isDeprecated() { + return SwfConstants.STATUS_DEPRECATED.equals(status); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 76db9313a6..76ac54db97 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -313,6 +313,10 @@ floci: stepfunctions: enabled: true allow-plaintext-http: false + swf: + enabled: true + timeout-sweep-enabled: true + timeout-sweep-interval-seconds: 1 cloudformation: enabled: true acm: diff --git a/src/test/java/io/github/hectorvent/floci/services/swf/SwfIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/swf/SwfIntegrationTest.java new file mode 100644 index 0000000000..0c20799455 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/swf/SwfIntegrationTest.java @@ -0,0 +1,1810 @@ +package io.github.hectorvent.floci.services.swf; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * End-to-end coverage of the SWF wire protocol: registration, the decider/worker + * handshake, and the resulting history. + * + *

Expected shapes and error strings here were captured from the live service, so a + * change that breaks SDK compatibility fails these tests rather than surfacing later as + * a decider that silently stalls. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.MethodName.class) +class SwfIntegrationTest { + + private static final String SWF_CONTENT_TYPE = "application/x-amz-json-1.0"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + // ──────────────────────────────── Domains ──────────────────────────────── + + @Test + void registerDomain_thenDescribe_returnsDomainInfoAndConfiguration() { + String domain = uniqueName("describe-domain"); + registerDomain(domain); + + call("DescribeDomain", """ + {"name": "%s"} + """.formatted(domain)) + .then() + .statusCode(200) + .body("domainInfo.name", equalTo(domain)) + .body("domainInfo.status", equalTo("REGISTERED")) + .body("domainInfo.description", equalTo("floci test domain")) + .body("domainInfo.arn", startsWith("arn:aws:swf:us-east-1:")) + .body("domainInfo.arn", org.hamcrest.Matchers.endsWith(":/domain/" + domain)) + .body("configuration.workflowExecutionRetentionPeriodInDays", equalTo("7")); + } + + @Test + void registerDomain_duplicate_returnsDomainAlreadyExistsFaultNamedByDomain() { + String domain = uniqueName("dup-domain"); + registerDomain(domain); + + // The live service reports the bare domain name as the message, not a sentence. + call("RegisterDomain", """ + {"name": "%s", "workflowExecutionRetentionPeriodInDays": "7"} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#DomainAlreadyExistsFault")) + .body("message", equalTo(domain)); + } + + @Test + void describeDomain_unknown_returnsUnknownResourceFaultWithUnknownDomainMessage() { + call("DescribeDomain", """ + {"name": "no-such-domain-floci"} + """) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#UnknownResourceFault")) + .body("message", equalTo("Unknown domain: no-such-domain-floci")); + } + + @Test + void listDomains_badRegistrationStatus_returnsCoralValidationException() { + call("ListDomains", """ + {"registrationStatus": "BOGUS"} + """) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazon.coral.validate#ValidationException")) + .body("message", org.hamcrest.Matchers.containsString( + "Member must satisfy enum value set: [REGISTERED, DEPRECATED]")); + } + + @Test + void deprecateDomain_thenListDeprecated_movesDomainBetweenStatuses() { + String domain = uniqueName("deprecate-domain"); + registerDomain(domain); + + call("DeprecateDomain", """ + {"name": "%s"} + """.formatted(domain)).then().statusCode(200); + + call("ListDomains", """ + {"registrationStatus": "DEPRECATED"} + """) + .then() + .statusCode(200) + .body("domainInfos.name", hasItem(domain)); + + call("ListDomains", """ + {"registrationStatus": "REGISTERED"} + """) + .then() + .statusCode(200) + .body("domainInfos.name", org.hamcrest.Matchers.not(hasItem(domain))); + + // Deprecating twice is an error; undeprecating restores REGISTERED. + call("DeprecateDomain", """ + {"name": "%s"} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#DomainDeprecatedFault")); + + call("UndeprecateDomain", """ + {"name": "%s"} + """.formatted(domain)).then().statusCode(200); + + call("DescribeDomain", """ + {"name": "%s"} + """.formatted(domain)) + .then() + .body("domainInfo.status", equalTo("REGISTERED")); + } + + // ────────────────────────────────- Types ───────────────────────────────── + + @Test + void registerWorkflowType_thenDescribe_echoesRegistrationDefaults() { + String domain = uniqueName("wf-type"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + + call("DescribeWorkflowType", """ + {"domain": "%s", "workflowType": {"name": "TestWf", "version": "1.0"}} + """.formatted(domain)) + .then() + .statusCode(200) + .body("typeInfo.workflowType.name", equalTo("TestWf")) + .body("typeInfo.workflowType.version", equalTo("1.0")) + .body("typeInfo.status", equalTo("REGISTERED")) + // creationDate is an epoch-second number, never an ISO string. + .body("typeInfo.creationDate", greaterThan(1.0e9f)) + .body("configuration.defaultTaskStartToCloseTimeout", equalTo("60")) + .body("configuration.defaultExecutionStartToCloseTimeout", equalTo("3600")) + .body("configuration.defaultTaskList.name", equalTo("floci-tl")) + .body("configuration.defaultChildPolicy", equalTo("TERMINATE")); + } + + @Test + void registerWorkflowType_duplicate_returnsTypeAlreadyExistsFaultWithTypeDescriptor() { + String domain = uniqueName("wf-type-dup"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + + call("RegisterWorkflowType", """ + {"domain": "%s", "name": "TestWf", "version": "1.0"} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#TypeAlreadyExistsFault")) + .body("message", equalTo("WorkflowType=[name=TestWf, version=1.0]")); + } + + @Test + void describeWorkflowType_unknown_namesTheTypeInTheMessage() { + String domain = uniqueName("wf-type-unknown"); + registerDomain(domain); + + call("DescribeWorkflowType", """ + {"domain": "%s", "workflowType": {"name": "NoSuchWf", "version": "1"}} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#UnknownResourceFault")) + .body("message", equalTo("Unknown type: WorkflowType=[name=NoSuchWf, version=1]")); + } + + @Test + void registerActivityType_thenListAndDescribe_returnsTimeoutConfiguration() { + String domain = uniqueName("act-type"); + registerDomain(domain); + registerActivityType(domain, "TestAct", "1.0"); + + call("DescribeActivityType", """ + {"domain": "%s", "activityType": {"name": "TestAct", "version": "1.0"}} + """.formatted(domain)) + .then() + .statusCode(200) + .body("typeInfo.activityType.name", equalTo("TestAct")) + .body("typeInfo.status", equalTo("REGISTERED")) + .body("configuration.defaultTaskStartToCloseTimeout", equalTo("60")) + .body("configuration.defaultTaskScheduleToStartTimeout", equalTo("60")) + .body("configuration.defaultTaskList.name", equalTo("floci-tl")); + + call("ListActivityTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED"} + """.formatted(domain)) + .then() + .statusCode(200) + .body("typeInfos.activityType.name", hasItem("TestAct")); + } + + @Test + void deleteWorkflowType_beforeDeprecation_returnsTypeNotDeprecatedFault() { + String domain = uniqueName("wf-delete"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + + call("DeleteWorkflowType", """ + {"domain": "%s", "workflowType": {"name": "TestWf", "version": "1.0"}} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#TypeNotDeprecatedFault")); + + call("DeprecateWorkflowType", """ + {"domain": "%s", "workflowType": {"name": "TestWf", "version": "1.0"}} + """.formatted(domain)).then().statusCode(200); + + call("DeleteWorkflowType", """ + {"domain": "%s", "workflowType": {"name": "TestWf", "version": "1.0"}} + """.formatted(domain)).then().statusCode(200); + + call("DescribeWorkflowType", """ + {"domain": "%s", "workflowType": {"name": "TestWf", "version": "1.0"}} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#UnknownResourceFault")); + } + + // ───────────────────────────── Execution start ─────────────────────────── + + @Test + void startWorkflowExecution_seedsHistoryWithStartedAndDecisionTaskScheduled() { + String domain = uniqueName("start-exec"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + String runId = startExecution(domain, "wf-1", "{\"hello\":\"world\"}"); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-1", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .statusCode(200) + .body("events", hasSize(2)) + .body("events[0].eventId", equalTo(1)) + .body("events[0].eventType", equalTo("WorkflowExecutionStarted")) + .body("events[0].eventTimestamp", greaterThan(1.0e9f)) + .body("events[0].workflowExecutionStartedEventAttributes.input", + equalTo("{\"hello\":\"world\"}")) + .body("events[0].workflowExecutionStartedEventAttributes.childPolicy", + equalTo("TERMINATE")) + .body("events[0].workflowExecutionStartedEventAttributes.taskList.name", + equalTo("floci-tl")) + .body("events[0].workflowExecutionStartedEventAttributes.workflowType.name", + equalTo("TestWf")) + // Root executions report 0 rather than omitting the member. + .body("events[0].workflowExecutionStartedEventAttributes.parentInitiatedEventId", + equalTo(0)) + .body("events[1].eventId", equalTo(2)) + .body("events[1].eventType", equalTo("DecisionTaskScheduled")) + .body("events[1].decisionTaskScheduledEventAttributes.startToCloseTimeout", + equalTo("60")) + .body("events[1].decisionTaskScheduledEventAttributes.scheduleToStartTimeout", + equalTo("NONE")); + } + + @Test + void startWorkflowExecution_whileOneIsOpen_returnsAlreadyStartedFaultWithEmptyMessage() { + String domain = uniqueName("start-dup"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + startExecution(domain, "wf-dup", null); + + call("StartWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-dup", + "workflowType": {"name": "TestWf", "version": "1.0"}} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#WorkflowExecutionAlreadyStartedFault")) + .body("message", equalTo("")); + } + + @Test + void startWorkflowExecution_withoutTypeDefault_returnsDefaultUndefinedFault() { + String domain = uniqueName("start-nodefault"); + registerDomain(domain); + // Registered with no defaults at all, so every required field must come from the request. + call("RegisterWorkflowType", """ + {"domain": "%s", "name": "Bare", "version": "1.0"} + """.formatted(domain)).then().statusCode(200); + + call("StartWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-bare", + "workflowType": {"name": "Bare", "version": "1.0"}} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#DefaultUndefinedFault")); + } + + @Test + void startWorkflowExecution_onDeprecatedType_returnsTypeDeprecatedFault() { + String domain = uniqueName("start-deprecated"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + call("DeprecateWorkflowType", """ + {"domain": "%s", "workflowType": {"name": "TestWf", "version": "1.0"}} + """.formatted(domain)).then().statusCode(200); + + call("StartWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-dep", + "workflowType": {"name": "TestWf", "version": "1.0"}} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#TypeDeprecatedFault")); + } + + // ──────────────────────── Decider and worker handshake ─────────────────── + + @Test + void fullActivityLifecycle_producesTheExpectedHistoryAndClosesTheExecution() { + String domain = uniqueName("lifecycle"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + registerActivityType(domain, "TestAct", "1.0"); + String runId = startExecution(domain, "wf-life", "{\"n\":1}"); + + // 1. Decider claims the task and sees the two seeded events. + Response decisionTask = call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "floci-tl"}, "identity": "decider-1"} + """.formatted(domain)); + decisionTask.then() + .statusCode(200) + .body("taskToken", notNullValue()) + .body("workflowExecution.workflowId", equalTo("wf-life")) + .body("workflowExecution.runId", equalTo(runId)) + .body("workflowType.name", equalTo("TestWf")) + .body("events.eventType", hasItem("DecisionTaskStarted")) + .body("previousStartedEventId", equalTo(0)); + String decisionToken = decisionTask.path("taskToken"); + + // 2. Decider schedules an activity. + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "executionContext": "step-1", + "decisions": [{ + "decisionType": "ScheduleActivityTask", + "scheduleActivityTaskDecisionAttributes": { + "activityId": "act-1", + "activityType": {"name": "TestAct", "version": "1.0"}, + "input": "{\\"work\\":true}" + }}]} + """.formatted(decisionToken)).then().statusCode(200); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-life", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("events.eventType", hasItem("DecisionTaskCompleted")) + .body("events.eventType", hasItem("ActivityTaskScheduled")) + .body("events.find { it.eventType == 'ActivityTaskScheduled' }" + + ".activityTaskScheduledEventAttributes.activityId", equalTo("act-1")) + .body("events.find { it.eventType == 'ActivityTaskScheduled' }" + + ".activityTaskScheduledEventAttributes.taskList.name", equalTo("floci-tl")) + // Timeouts resolve from the activity type's registration defaults. + .body("events.find { it.eventType == 'ActivityTaskScheduled' }" + + ".activityTaskScheduledEventAttributes.startToCloseTimeout", equalTo("60")); + + // 3. Worker claims the activity, heartbeats, and completes it. + Response activityTask = call("PollForActivityTask", """ + {"domain": "%s", "taskList": {"name": "floci-tl"}, "identity": "worker-1"} + """.formatted(domain)); + activityTask.then() + .statusCode(200) + .body("taskToken", notNullValue()) + .body("activityId", equalTo("act-1")) + .body("activityType.name", equalTo("TestAct")) + .body("input", equalTo("{\"work\":true}")) + .body("workflowExecution.runId", equalTo(runId)); + String activityToken = activityTask.path("taskToken"); + + call("RecordActivityTaskHeartbeat", """ + {"taskToken": "%s", "details": "50%%"} + """.formatted(activityToken)) + .then() + .statusCode(200) + .body("cancelRequested", is(false)); + + call("RespondActivityTaskCompleted", """ + {"taskToken": "%s", "result": "{\\"done\\":true}"} + """.formatted(activityToken)).then().statusCode(200); + + // 4. Activity completion schedules a fresh decision task. + Response secondDecision = call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "floci-tl"}, "identity": "decider-1"} + """.formatted(domain)); + secondDecision.then() + .statusCode(200) + .body("taskToken", notNullValue()) + .body("events.eventType", hasItem("ActivityTaskCompleted")) + .body("previousStartedEventId", greaterThan(0)); + + // 5. Decider closes the execution. + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [{ + "decisionType": "CompleteWorkflowExecution", + "completeWorkflowExecutionDecisionAttributes": {"result": "{\\"ok\\":true}"} + }]} + """.formatted(secondDecision.path("taskToken").toString())).then().statusCode(200); + + call("DescribeWorkflowExecution", """ + {"domain": "%s", "execution": {"workflowId": "wf-life", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .statusCode(200) + .body("executionInfo.executionStatus", equalTo("CLOSED")) + .body("executionInfo.closeStatus", equalTo("COMPLETED")) + .body("executionInfo.closeTimestamp", notNullValue()) + .body("openCounts.openActivityTasks", equalTo(0)) + .body("openCounts.openDecisionTasks", equalTo(0)) + .body("latestExecutionContext", equalTo("step-1")); + + call("ListClosedWorkflowExecutions", """ + {"domain": "%s", "startTimeFilter": {"oldestDate": 1}} + """.formatted(domain)) + .then() + .statusCode(200) + .body("executionInfos.execution.workflowId", hasItem("wf-life")) + .body("executionInfos.find { it.execution.workflowId == 'wf-life' }.closeStatus", + equalTo("COMPLETED")); + } + + @Test + void pollForDecisionTask_withNoWork_returnsEmptyTaskTokenRatherThanOmittingIt() { + String domain = uniqueName("empty-poll"); + registerDomain(domain); + + // An empty token is how the SDKs recognise "no task"; omitting the member makes + // them fail on a missing required field. + call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "idle-tl"}, "identity": "decider-1"} + """.formatted(domain)) + .then() + .statusCode(200) + .body("taskToken", equalTo("")) + .body("startedEventId", equalTo(0)); + + call("PollForActivityTask", """ + {"domain": "%s", "taskList": {"name": "idle-tl"}, "identity": "worker-1"} + """.formatted(domain)) + .then() + .statusCode(200) + .body("taskToken", equalTo("")); + } + + @Test + void onlyOneDecisionTaskIsOutstandingAtATime() { + String domain = uniqueName("single-decision"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + startExecution(domain, "wf-single", null); + + Response first = call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "floci-tl"}, "identity": "d1"} + """.formatted(domain)); + first.then().statusCode(200).body("taskToken", notNullValue()); + + // A second poll while the first is outstanding must not hand out another task. + call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "floci-tl"}, "identity": "d2"} + """.formatted(domain)) + .then() + .statusCode(200) + .body("taskToken", equalTo("")); + + // A signal arriving mid-decision is recorded but does not create a second task. + call("SignalWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-single", "signalName": "poke"} + """.formatted(domain)).then().statusCode(200); + + call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "floci-tl"}, "identity": "d3"} + """.formatted(domain)) + .then() + .statusCode(200) + .body("taskToken", equalTo("")); + + // Completing the outstanding task releases the deferred one. + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": []} + """.formatted(first.path("taskToken").toString())).then().statusCode(200); + + call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "floci-tl"}, "identity": "d4"} + """.formatted(domain)) + .then() + .statusCode(200) + .body("taskToken", org.hamcrest.Matchers.not(equalTo(""))) + .body("events.eventType", hasItem("WorkflowExecutionSignaled")); + } + + @Test + void respondDecisionTaskCompleted_withStaleToken_returnsUnknownResourceFault() { + call("RespondDecisionTaskCompleted", """ + {"taskToken": "bogus-token", "decisions": []} + """) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#UnknownResourceFault")); + } + + @Test + void respondDecisionTaskCompleted_closeNotLast_returnsCoralValidationException() { + String domain = uniqueName("close-order"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + registerActivityType(domain, "TestAct", "1.0"); + String runId = startExecution(domain, "wf-close-order", null); + String token = pollDecisionToken(domain); + + // The live service rejects the batch outright instead of applying the prefix, and + // this fault is namespaced com.amazon.coral.validate, not com.amazonaws.swf.base.model. + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [ + {"decisionType": "CompleteWorkflowExecution", + "completeWorkflowExecutionDecisionAttributes": {"result": "early"}}, + {"decisionType": "ScheduleActivityTask", + "scheduleActivityTaskDecisionAttributes": { + "activityId": "after-close", + "activityType": {"name": "TestAct", "version": "1.0"} + }}]} + """.formatted(token)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazon.coral.validate#ValidationException")) + .body("message", equalTo("Close must be last decision in list")); + + // The execution is untouched and the same token still works for a valid batch. + call("DescribeWorkflowExecution", """ + {"domain": "%s", "execution": {"workflowId": "wf-close-order"}} + """.formatted(domain)) + .then() + .body("executionInfo.executionStatus", equalTo("OPEN")); + + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [ + {"decisionType": "CompleteWorkflowExecution", + "completeWorkflowExecutionDecisionAttributes": {"result": "ok"}}]} + """.formatted(token)) + .then().statusCode(200); + + call("DescribeWorkflowExecution", """ + {"domain": "%s", "execution": {"workflowId": "wf-close-order", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("executionInfo.closeStatus", equalTo("COMPLETED")); + } + + @Test + void closingDecisionWithOpenActivity_failsWithUnhandledDecision() { + String domain = uniqueName("unhandled"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + registerActivityType(domain, "TestAct", "1.0"); + String runId = startExecution(domain, "wf-unhandled", null); + + String token = pollDecisionToken(domain); + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [{ + "decisionType": "ScheduleActivityTask", + "scheduleActivityTaskDecisionAttributes": { + "activityId": "act-open", + "activityType": {"name": "TestAct", "version": "1.0"} + }}]} + """.formatted(token)).then().statusCode(200); + + // A successful ScheduleActivityTask does not itself schedule another decision task — + // the decider waits for the activity to close. A signal is what gets it a task while + // the activity is still open. + call("SignalWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-unhandled", "signalName": "poke"} + """.formatted(domain)).then().statusCode(200); + + // The scheduled activity is still open, so completing the execution is rejected. + String second = pollDecisionToken(domain); + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [{ + "decisionType": "CompleteWorkflowExecution", + "completeWorkflowExecutionDecisionAttributes": {} + }]} + """.formatted(second)).then().statusCode(200); + + call("DescribeWorkflowExecution", """ + {"domain": "%s", "execution": {"workflowId": "wf-unhandled", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("executionInfo.executionStatus", equalTo("OPEN")); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-unhandled", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("events.eventType", hasItem("CompleteWorkflowExecutionFailed")) + .body("events.find { it.eventType == 'CompleteWorkflowExecutionFailed' }" + + ".completeWorkflowExecutionFailedEventAttributes.cause", + equalTo("UNHANDLED_DECISION")); + } + + @Test + void scheduleActivityTask_withUnknownType_recordsScheduleActivityTaskFailed() { + String domain = uniqueName("bad-activity"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + String runId = startExecution(domain, "wf-bad-act", null); + + String token = pollDecisionToken(domain); + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [{ + "decisionType": "ScheduleActivityTask", + "scheduleActivityTaskDecisionAttributes": { + "activityId": "nope", + "activityType": {"name": "NoSuchAct", "version": "9.9"} + }}]} + """.formatted(token)).then().statusCode(200); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-bad-act", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("events.eventType", hasItem("ScheduleActivityTaskFailed")) + .body("events.find { it.eventType == 'ScheduleActivityTaskFailed' }" + + ".scheduleActivityTaskFailedEventAttributes.cause", + equalTo("ACTIVITY_TYPE_DOES_NOT_EXIST")) + .body("events.find { it.eventType == 'ScheduleActivityTaskFailed' }" + + ".scheduleActivityTaskFailedEventAttributes.activityId", equalTo("nope")); + } + + @Test + void markerAndTimerDecisions_appendTheirOwnEvents() { + String domain = uniqueName("marker-timer"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + String runId = startExecution(domain, "wf-marker", null); + + String token = pollDecisionToken(domain); + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [ + {"decisionType": "RecordMarker", + "recordMarkerDecisionAttributes": {"markerName": "checkpoint", "details": "n=1"}}, + {"decisionType": "StartTimer", + "startTimerDecisionAttributes": {"timerId": "t-1", "startToFireTimeout": "3600"}} + ]} + """.formatted(token)).then().statusCode(200); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-marker", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("events.eventType", hasItem("MarkerRecorded")) + .body("events.find { it.eventType == 'MarkerRecorded' }" + + ".markerRecordedEventAttributes.markerName", equalTo("checkpoint")) + .body("events.eventType", hasItem("TimerStarted")) + .body("events.find { it.eventType == 'TimerStarted' }" + + ".timerStartedEventAttributes.startToFireTimeout", equalTo("3600")); + + call("DescribeWorkflowExecution", """ + {"domain": "%s", "execution": {"workflowId": "wf-marker", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("openCounts.openTimers", equalTo(1)); + + // The timer is still pending, so no decision task is scheduled on its own; a signal + // is what brings the decider back while the timer runs. + call("SignalWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-marker", "signalName": "poke"} + """.formatted(domain)).then().statusCode(200); + + // Cancelling an unknown timer is reported in history rather than faulting. + String second = pollDecisionToken(domain); + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [{ + "decisionType": "CancelTimer", + "cancelTimerDecisionAttributes": {"timerId": "no-such-timer"}}]} + """.formatted(second)).then().statusCode(200); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-marker", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("events.find { it.eventType == 'CancelTimerFailed' }" + + ".cancelTimerFailedEventAttributes.cause", equalTo("TIMER_ID_UNKNOWN")); + } + + // ─────────────────────────── External control ──────────────────────────── + + @Test + void signalWorkflowExecution_appendsSignalAndSchedulesADecision() { + String domain = uniqueName("signal"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + String runId = startExecution(domain, "wf-signal", null); + + // Drain the initial decision task so the signal's own task is observable. + String token = pollDecisionToken(domain); + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": []} + """.formatted(token)).then().statusCode(200); + drainDecisionTasks(domain); + + call("SignalWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-signal", "runId": "%s", + "signalName": "resume", "input": "{\\"go\\":1}"} + """.formatted(domain, runId)).then().statusCode(200); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-signal", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("events.eventType", hasItem("WorkflowExecutionSignaled")) + .body("events.find { it.eventType == 'WorkflowExecutionSignaled' }" + + ".workflowExecutionSignaledEventAttributes.signalName", equalTo("resume")) + .body("events.find { it.eventType == 'WorkflowExecutionSignaled' }" + + ".workflowExecutionSignaledEventAttributes.input", equalTo("{\"go\":1}")); + + call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "floci-tl"}, "identity": "d"} + """.formatted(domain)) + .then() + .body("taskToken", org.hamcrest.Matchers.not(equalTo(""))); + } + + @Test + void requestCancelWorkflowExecution_setsCancelRequestedAndRecordsTheEvent() { + String domain = uniqueName("cancel-request"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + String runId = startExecution(domain, "wf-cancel", null); + + call("RequestCancelWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-cancel", "runId": "%s"} + """.formatted(domain, runId)).then().statusCode(200); + + call("DescribeWorkflowExecution", """ + {"domain": "%s", "execution": {"workflowId": "wf-cancel", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("executionInfo.cancelRequested", is(true)) + .body("executionInfo.executionStatus", equalTo("OPEN")); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-cancel", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("events.eventType", hasItem("WorkflowExecutionCancelRequested")); + } + + @Test + void terminateWorkflowExecution_closesWithTerminatedStatus() { + String domain = uniqueName("terminate"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + String runId = startExecution(domain, "wf-terminate", null); + + call("TerminateWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-terminate", "runId": "%s", + "reason": "operator", "details": "manual stop"} + """.formatted(domain, runId)).then().statusCode(200); + + call("DescribeWorkflowExecution", """ + {"domain": "%s", "execution": {"workflowId": "wf-terminate", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("executionInfo.executionStatus", equalTo("CLOSED")) + .body("executionInfo.closeStatus", equalTo("TERMINATED")); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-terminate", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("events.find { it.eventType == 'WorkflowExecutionTerminated' }" + + ".workflowExecutionTerminatedEventAttributes.reason", equalTo("operator")) + .body("events.find { it.eventType == 'WorkflowExecutionTerminated' }" + + ".workflowExecutionTerminatedEventAttributes.childPolicy", equalTo("TERMINATE")); + + // A closed execution no longer accepts control operations. + call("SignalWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-terminate", "runId": "%s", "signalName": "x"} + """.formatted(domain, runId)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#UnknownResourceFault")); + } + + @Test + void continueAsNew_closesTheRunAndStartsASuccessor() { + String domain = uniqueName("continue-as-new"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + String runId = startExecution(domain, "wf-can", null); + + String token = pollDecisionToken(domain); + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [{ + "decisionType": "ContinueAsNewWorkflowExecution", + "continueAsNewWorkflowExecutionDecisionAttributes": {"input": "{\\"gen\\":2}"} + }]} + """.formatted(token)).then().statusCode(200); + + call("DescribeWorkflowExecution", """ + {"domain": "%s", "execution": {"workflowId": "wf-can", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("executionInfo.executionStatus", equalTo("CLOSED")) + .body("executionInfo.closeStatus", equalTo("CONTINUED_AS_NEW")); + + Response history = call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-can", "runId": "%s"}} + """.formatted(domain, runId)); + history.then() + .body("events.eventType", hasItem("WorkflowExecutionContinuedAsNew")) + .body("events.find { it.eventType == 'WorkflowExecutionContinuedAsNew' }" + + ".workflowExecutionContinuedAsNewEventAttributes.newExecutionRunId", + notNullValue()); + + String newRunId = history.path( + "events.find { it.eventType == 'WorkflowExecutionContinuedAsNew' }" + + ".workflowExecutionContinuedAsNewEventAttributes.newExecutionRunId"); + + // The successor is open, carries the new input, and links back to the prior run. + call("DescribeWorkflowExecution", """ + {"domain": "%s", "execution": {"workflowId": "wf-can", "runId": "%s"}} + """.formatted(domain, newRunId)) + .then() + .body("executionInfo.executionStatus", equalTo("OPEN")); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-can", "runId": "%s"}} + """.formatted(domain, newRunId)) + .then() + .body("events[0].workflowExecutionStartedEventAttributes.input", equalTo("{\"gen\":2}")) + .body("events[0].workflowExecutionStartedEventAttributes.continuedExecutionRunId", + equalTo(runId)); + } + + @Test + void startChildWorkflowExecution_linksParentAndReportsCompletionToTheParent() { + String domain = uniqueName("child-wf"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + String parentRunId = startExecution(domain, "wf-parent", null); + + String token = pollDecisionToken(domain); + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [{ + "decisionType": "StartChildWorkflowExecution", + "startChildWorkflowExecutionDecisionAttributes": { + "workflowId": "wf-child", + "workflowType": {"name": "TestWf", "version": "1.0"}, + "input": "{\\"child\\":true}" + }}]} + """.formatted(token)).then().statusCode(200); + + Response parentHistory = call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-parent", "runId": "%s"}} + """.formatted(domain, parentRunId)); + parentHistory.then() + .body("events.eventType", hasItem("StartChildWorkflowExecutionInitiated")) + .body("events.eventType", hasItem("ChildWorkflowExecutionStarted")); + + int initiatedEventId = parentHistory.path( + "events.find { it.eventType == 'StartChildWorkflowExecutionInitiated' }.eventId"); + int childStartedEventId = parentHistory.path( + "events.find { it.eventType == 'ChildWorkflowExecutionStarted' }.eventId"); + + // The child carries the parent link in its own start event. + Response childHistory = call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-child"}} + """.formatted(domain)); + childHistory.then() + .statusCode(200) + .body("events[0].workflowExecutionStartedEventAttributes.parentWorkflowExecution.workflowId", + equalTo("wf-parent")) + .body("events[0].workflowExecutionStartedEventAttributes.parentWorkflowExecution.runId", + equalTo(parentRunId)) + // The child's parentInitiatedEventId is the parent's + // StartChildWorkflowExecutionInitiated id, not its ChildWorkflowExecutionStarted id. + .body("events[0].workflowExecutionStartedEventAttributes.parentInitiatedEventId", + equalTo(initiatedEventId)); + + call("DescribeWorkflowExecution", """ + {"domain": "%s", "execution": {"workflowId": "wf-parent", "runId": "%s"}} + """.formatted(domain, parentRunId)) + .then() + .body("openCounts.openChildWorkflowExecutions", equalTo(1)); + + // Completing the child reports ChildWorkflowExecutionCompleted to the parent. + String childToken = pollDecisionTokenFor(domain, "wf-child"); + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [{ + "decisionType": "CompleteWorkflowExecution", + "completeWorkflowExecutionDecisionAttributes": {"result": "child-done"} + }]} + """.formatted(childToken)).then().statusCode(200); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-parent", "runId": "%s"}} + """.formatted(domain, parentRunId)) + .then() + .body("events.eventType", hasItem("ChildWorkflowExecutionCompleted")) + .body("events.find { it.eventType == 'ChildWorkflowExecutionCompleted' }" + + ".childWorkflowExecutionCompletedEventAttributes.result", equalTo("child-done")) + // initiatedEventId points at StartChildWorkflowExecutionInitiated and + // startedEventId at ChildWorkflowExecutionStarted — two different events. + // Reporting the initiated id for both mismatches any decider correlating + // on startedEventId. + .body("events.find { it.eventType == 'ChildWorkflowExecutionCompleted' }" + + ".childWorkflowExecutionCompletedEventAttributes.initiatedEventId", + equalTo(initiatedEventId)) + .body("events.find { it.eventType == 'ChildWorkflowExecutionCompleted' }" + + ".childWorkflowExecutionCompletedEventAttributes.startedEventId", + equalTo(childStartedEventId)); + } + + @Test + void activityTypeDeprecationLifecycle_blocksSchedulingAndGatesDeletion() { + String domain = uniqueName("act-lifecycle"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + registerActivityType(domain, "TestAct", "1.0"); + + call("DeprecateActivityType", """ + {"domain": "%s", "activityType": {"name": "TestAct", "version": "1.0"}} + """.formatted(domain)).then().statusCode(200); + + // Deprecating twice reports the type descriptor, not prose. + call("DeprecateActivityType", """ + {"domain": "%s", "activityType": {"name": "TestAct", "version": "1.0"}} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#TypeDeprecatedFault")) + .body("message", equalTo("ActivityType=[name=TestAct, version=1.0]")); + + // A deprecated type stays describable and is listed under DEPRECATED. + call("DescribeActivityType", """ + {"domain": "%s", "activityType": {"name": "TestAct", "version": "1.0"}} + """.formatted(domain)) + .then() + .statusCode(200) + .body("typeInfo.status", equalTo("DEPRECATED")) + .body("typeInfo.deprecationDate", notNullValue()); + + call("ListActivityTypes", """ + {"domain": "%s", "registrationStatus": "DEPRECATED"} + """.formatted(domain)) + .then() + .statusCode(200) + .body("typeInfos.activityType.name", hasItem("TestAct")); + + // Scheduling a deprecated type fails the decision rather than the request. + startExecution(domain, "wf-dep-act", null); + String token = pollDecisionToken(domain); + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [ + {"decisionType": "ScheduleActivityTask", + "scheduleActivityTaskDecisionAttributes": { + "activityId": "a1", + "activityType": {"name": "TestAct", "version": "1.0"} + }}]} + """.formatted(token)).then().statusCode(200); + + call("DescribeWorkflowExecution", """ + {"domain": "%s", "execution": {"workflowId": "wf-dep-act"}} + """.formatted(domain)) + .then() + .body("executionInfo.executionStatus", equalTo("OPEN")); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-dep-act"}} + """.formatted(domain)) + .then() + .body("events.find { it.eventType == 'ScheduleActivityTaskFailed' }" + + ".scheduleActivityTaskFailedEventAttributes.cause", + equalTo("ACTIVITY_TYPE_DEPRECATED")); + + // Delete is gated on deprecation, and reports prose rather than the descriptor. + call("UndeprecateActivityType", """ + {"domain": "%s", "activityType": {"name": "TestAct", "version": "1.0"}} + """.formatted(domain)).then().statusCode(200); + + call("UndeprecateActivityType", """ + {"domain": "%s", "activityType": {"name": "TestAct", "version": "1.0"}} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#TypeAlreadyExistsFault")); + + call("DeleteActivityType", """ + {"domain": "%s", "activityType": {"name": "TestAct", "version": "1.0"}} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#TypeNotDeprecatedFault")) + .body("message", + equalTo("The type is currently registered and cannot be deleted in its current state")); + + call("DeprecateActivityType", """ + {"domain": "%s", "activityType": {"name": "TestAct", "version": "1.0"}} + """.formatted(domain)).then().statusCode(200); + call("DeleteActivityType", """ + {"domain": "%s", "activityType": {"name": "TestAct", "version": "1.0"}} + """.formatted(domain)).then().statusCode(200); + + call("DescribeActivityType", """ + {"domain": "%s", "activityType": {"name": "TestAct", "version": "1.0"}} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#UnknownResourceFault")) + .body("message", equalTo("Unknown type: ActivityType=[name=TestAct, version=1.0]")); + } + + @Test + void deleteWorkflowType_isGatedOnDeprecationAndReportsProse() { + String domain = uniqueName("wf-delete"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + + call("DeleteWorkflowType", """ + {"domain": "%s", "workflowType": {"name": "TestWf", "version": "1.0"}} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#TypeNotDeprecatedFault")) + .body("message", + equalTo("The type is currently registered and cannot be deleted in its current state")); + + call("DeprecateWorkflowType", """ + {"domain": "%s", "workflowType": {"name": "TestWf", "version": "1.0"}} + """.formatted(domain)).then().statusCode(200); + call("DeleteWorkflowType", """ + {"domain": "%s", "workflowType": {"name": "TestWf", "version": "1.0"}} + """.formatted(domain)).then().statusCode(200); + + call("DeleteWorkflowType", """ + {"domain": "%s", "workflowType": {"name": "TestWf", "version": "1.0"}} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#UnknownResourceFault")) + .body("message", equalTo("Unknown type: WorkflowType=[name=TestWf, version=1.0]")); + } + + @Test + void listWorkflowTypes_filtersByRegistrationStatusAndName() { + String domain = uniqueName("wf-list"); + registerDomain(domain); + registerWorkflowType(domain, "Alpha", "1.0"); + registerWorkflowType(domain, "Beta", "1.0"); + + call("ListWorkflowTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED"} + """.formatted(domain)) + .then() + .statusCode(200) + .body("typeInfos.workflowType.name", hasItem("Alpha")) + .body("typeInfos.workflowType.name", hasItem("Beta")) + .body("typeInfos[0].status", equalTo("REGISTERED")) + .body("typeInfos[0].creationDate", notNullValue()); + + call("ListWorkflowTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED", "name": "Alpha"} + """.formatted(domain)) + .then() + .body("typeInfos.size()", equalTo(1)) + .body("typeInfos[0].workflowType.name", equalTo("Alpha")); + + call("DeprecateWorkflowType", """ + {"domain": "%s", "workflowType": {"name": "Alpha", "version": "1.0"}} + """.formatted(domain)).then().statusCode(200); + + call("ListWorkflowTypes", """ + {"domain": "%s", "registrationStatus": "DEPRECATED"} + """.formatted(domain)) + .then() + .body("typeInfos.size()", equalTo(1)) + .body("typeInfos[0].workflowType.name", equalTo("Alpha")); + + call("ListWorkflowTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED"} + """.formatted(domain)) + .then() + .body("typeInfos.workflowType.name", not(hasItem("Alpha"))) + .body("typeInfos.workflowType.name", hasItem("Beta")); + } + + @Test + void respondActivityTaskFailed_recordsReasonAndDetailsThenClosesTheToken() { + String domain = uniqueName("act-fail"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + registerActivityType(domain, "TestAct", "1.0"); + String runId = startExecution(domain, "wf-act-fail", null); + + String token = pollDecisionToken(domain); + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [ + {"decisionType": "ScheduleActivityTask", + "scheduleActivityTaskDecisionAttributes": { + "activityId": "a-fail", + "activityType": {"name": "TestAct", "version": "1.0"} + }}]} + """.formatted(token)).then().statusCode(200); + + String activityToken = call("PollForActivityTask", """ + {"domain": "%s", "taskList": {"name": "floci-tl"}, "identity": "w"} + """.formatted(domain)) + .then().statusCode(200) + .extract().path("taskToken"); + + call("RespondActivityTaskFailed", """ + {"taskToken": "%s", "reason": "boom", "details": "stack trace here"} + """.formatted(activityToken)).then().statusCode(200); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-act-fail", "runId": "%s"}} + """.formatted(domain, runId)) + .then() + .body("events.eventType", hasItem("ActivityTaskFailed")) + .body("events.find { it.eventType == 'ActivityTaskFailed' }" + + ".activityTaskFailedEventAttributes.reason", equalTo("boom")) + .body("events.find { it.eventType == 'ActivityTaskFailed' }" + + ".activityTaskFailedEventAttributes.details", equalTo("stack trace here")) + // A failed activity schedules a decision task so the decider can retry or fail. + .body("events[-1].eventType", equalTo("DecisionTaskScheduled")); + + // The token is genuine but its task has closed, so the fault names the scheduled event. + call("RespondActivityTaskFailed", """ + {"taskToken": "%s", "reason": "boom", "details": "again"} + """.formatted(activityToken)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#UnknownResourceFault")) + .body("message", equalTo("Unknown activity, scheduledEventId = 5")); + } + + @Test + void listWorkflowTypes_appliesMaximumPageSizeAndNextPageToken() { + String domain = uniqueName("wf-paging"); + registerDomain(domain); + for (int i = 0; i < 5; i++) { + registerWorkflowType(domain, "Paged" + i, "1.0"); + } + + Response first = call("ListWorkflowTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED", "maximumPageSize": 2} + """.formatted(domain)); + first.then() + .statusCode(200) + .body("typeInfos.size()", equalTo(2)) + .body("nextPageToken", notNullValue()); + + String token = first.path("nextPageToken"); + Response second = call("ListWorkflowTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED", "maximumPageSize": 2, + "nextPageToken": "%s"} + """.formatted(domain, token)); + second.then() + .statusCode(200) + .body("typeInfos.size()", equalTo(2)) + .body("nextPageToken", notNullValue()); + + // Page 2 must not repeat page 1. + List firstNames = first.path("typeInfos.workflowType.name"); + List secondNames = second.path("typeInfos.workflowType.name"); + assertTrue(java.util.Collections.disjoint(firstNames, secondNames), + "page 2 repeated page 1: " + firstNames + " / " + secondNames); + + // The final page carries no token, even when it is exactly full. + Response third = call("ListWorkflowTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED", "maximumPageSize": 2, + "nextPageToken": "%s"} + """.formatted(domain, second.path("nextPageToken").toString())); + third.then() + .statusCode(200) + .body("typeInfos.size()", equalTo(1)) + .body("nextPageToken", nullValue()); + + // An absent maximumPageSize returns everything. + call("ListWorkflowTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED"} + """.formatted(domain)) + .then() + .body("typeInfos.size()", equalTo(5)) + .body("nextPageToken", nullValue()); + } + + @Test + void listActivityTypesAndListDomains_paginateTheSameWay() { + String domain = uniqueName("act-paging"); + registerDomain(domain); + for (int i = 0; i < 3; i++) { + registerActivityType(domain, "PagedAct" + i, "1.0"); + } + + Response page = call("ListActivityTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED", "maximumPageSize": 2} + """.formatted(domain)); + page.then() + .statusCode(200) + .body("typeInfos.size()", equalTo(2)) + .body("nextPageToken", notNullValue()); + + call("ListActivityTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED", "maximumPageSize": 2, + "nextPageToken": "%s"} + """.formatted(domain, page.path("nextPageToken").toString())) + .then() + .body("typeInfos.size()", equalTo(1)) + .body("nextPageToken", nullValue()); + + // At least the domain just registered exists, so page size 1 must cap the listing. + call("ListDomains", """ + {"registrationStatus": "REGISTERED", "maximumPageSize": 1} + """) + .then() + .statusCode(200) + .body("domainInfos.size()", equalTo(1)); + } + + @Test + void listOperations_rejectAnOversizedPageSizeAndACorruptToken() { + String domain = uniqueName("paging-validation"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + + call("ListWorkflowTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED", "maximumPageSize": 1001} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazon.coral.validate#ValidationException")) + .body("message", containsString("less than or equal to 1000")); + + call("ListWorkflowTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED", "nextPageToken": "garbage"} + """.formatted(domain)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazon.coral.validate#ValidationException")) + .body("message", equalTo("Invalid token")); + } + + @Test + void listWorkflowTypes_appliesReverseOrderBeforePaging() { + String domain = uniqueName("wf-revpaging"); + registerDomain(domain); + for (int i = 0; i < 5; i++) { + registerWorkflowType(domain, "Paged" + i, "1.0"); + } + + // The live service reverses the whole result set and then pages it, so the first + // reversed page is the tail of the ascending order rather than a reversed first page. + Response first = call("ListWorkflowTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED", "maximumPageSize": 3, + "reverseOrder": true} + """.formatted(domain)); + first.then() + .statusCode(200) + .body("typeInfos.workflowType.name", equalTo(List.of("Paged4", "Paged3", "Paged2"))) + .body("nextPageToken", notNullValue()); + + call("ListWorkflowTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED", "maximumPageSize": 3, + "reverseOrder": true, "nextPageToken": "%s"} + """.formatted(domain, first.path("nextPageToken").toString())) + .then() + .statusCode(200) + .body("typeInfos.workflowType.name", equalTo(List.of("Paged1", "Paged0"))) + .body("nextPageToken", nullValue()); + } + + @Test + void domainsAreScopedByTheRegionInTheSigV4CredentialScope() { + String domain = uniqueName("wire-region"); + + // The region is read from the credential scope of the Authorization header, so the + // same name must register once per region rather than colliding. + callInRegion("RegisterDomain", """ + {"name": "%s", "description": "east", + "workflowExecutionRetentionPeriodInDays": "1"} + """.formatted(domain), "us-east-1") + .then().statusCode(200); + callInRegion("RegisterDomain", """ + {"name": "%s", "description": "west", + "workflowExecutionRetentionPeriodInDays": "2"} + """.formatted(domain), "eu-west-1") + .then().statusCode(200); + + // Each region keeps its own description, retention, and ARN. + callInRegion("DescribeDomain", """ + {"name": "%s"} + """.formatted(domain), "us-east-1") + .then() + .body("domainInfo.description", equalTo("east")) + .body("domainInfo.arn", containsString(":us-east-1:")) + .body("configuration.workflowExecutionRetentionPeriodInDays", equalTo("1")); + callInRegion("DescribeDomain", """ + {"name": "%s"} + """.formatted(domain), "eu-west-1") + .then() + .body("domainInfo.description", equalTo("west")) + .body("domainInfo.arn", containsString(":eu-west-1:")) + .body("configuration.workflowExecutionRetentionPeriodInDays", equalTo("2")); + + // A type registered in one region is unknown in the other. + callInRegion("RegisterWorkflowType", """ + {"domain": "%s", "name": "EastOnly", "version": "1.0", + "defaultTaskList": {"name": "tl"}, + "defaultTaskStartToCloseTimeout": "60", + "defaultExecutionStartToCloseTimeout": "600", + "defaultChildPolicy": "TERMINATE"} + """.formatted(domain), "us-east-1") + .then().statusCode(200); + callInRegion("ListWorkflowTypes", """ + {"domain": "%s", "registrationStatus": "REGISTERED"} + """.formatted(domain), "eu-west-1") + .then().body("typeInfos", hasSize(0)); + callInRegion("DescribeWorkflowType", """ + {"domain": "%s", "workflowType": {"name": "EastOnly", "version": "1.0"}} + """.formatted(domain), "eu-west-1") + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#UnknownResourceFault")); + + // Re-registering within one region is still a duplicate. + callInRegion("RegisterDomain", """ + {"name": "%s", "workflowExecutionRetentionPeriodInDays": "1"} + """.formatted(domain), "us-east-1") + .then() + .statusCode(400) + .body("__type", equalTo("com.amazonaws.swf.base.model#DomainAlreadyExistsFault")); + } + + @Test + void pollForDecisionTask_continuationReturnsTheSameTasksNextPage() { + String domain = uniqueName("poll-paging"); + registerDomain(domain); + registerWorkflowType(domain, "W", "1.0"); + call("StartWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-paged", + "workflowType": {"name": "W", "version": "1.0"}, + "taskList": {"name": "tl"}} + """.formatted(domain)).then().statusCode(200); + + // Page 1 claims the task; the history is 3 events, so a page size of 2 leaves a token. + Response first = call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "tl"}, "maximumPageSize": 2} + """.formatted(domain)); + first.then() + .statusCode(200) + .body("events.size()", equalTo(2)) + .body("nextPageToken", notNullValue()); + String taskToken = first.path("taskToken"); + int startedEventId = first.path("startedEventId"); + + // The continuation must be the SAME task's next page, not a new claim: AWS documents + // that "calling PollForDecisionTask with a nextPageToken doesn't return a new decision + // task". Previously this re-polled and answered with an empty task. + Response second = call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "tl"}, "maximumPageSize": 2, + "nextPageToken": "%s"} + """.formatted(domain, first.path("nextPageToken").toString())); + second.then() + .statusCode(200) + .body("taskToken", equalTo(taskToken)) + .body("startedEventId", equalTo(startedEventId)) + .body("workflowExecution.workflowId", equalTo("wf-paged")) + .body("events.size()", equalTo(1)) + .body("nextPageToken", nullValue()); + + // The pages are contiguous and do not repeat. + List firstIds = first.path("events.eventId"); + List secondIds = second.path("events.eventId"); + assertEquals(List.of(1, 2), firstIds); + assertEquals(List.of(3), secondIds); + } + + @Test + void pollForDecisionTask_startAtPreviousStartedEventTrimsSeenHistory() { + String domain = uniqueName("poll-sap"); + registerDomain(domain); + registerWorkflowType(domain, "W", "1.0"); + call("StartWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-sap", + "workflowType": {"name": "W", "version": "1.0"}, + "taskList": {"name": "tl"}} + """.formatted(domain)).then().statusCode(200); + + // Complete one decision task so previousStartedEventId becomes non-zero, then signal to + // get a second task. + Response initial = call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "tl"}} + """.formatted(domain)); + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [ + {"decisionType": "RecordMarker", + "recordMarkerDecisionAttributes": {"markerName": "m0"}}]} + """.formatted(initial.path("taskToken").toString())).then().statusCode(200); + call("SignalWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-sap", "signalName": "go"} + """.formatted(domain)).then().statusCode(200); + + Response full = call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "tl"}} + """.formatted(domain)); + List allIds = full.path("events.eventId"); + int previousStarted = full.path("previousStartedEventId"); + assertTrue(previousStarted > 0, "need a completed decision task for this case"); + assertTrue(allIds.contains(1), "the default poll returns the whole history"); + + // Same outstanding task, but asking only for what the decider has not seen. The live + // service starts *at* previousStartedEventId, inclusive. + Response trimmed = call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "tl"}, "startAtPreviousStartedEvent": true, + "nextPageToken": "%s"} + """.formatted(domain, encodedFirstPage(full.path("taskToken")))); + List trimmedIds = trimmed.path("events.eventId"); + assertFalse(trimmedIds.contains(1), + "startAtPreviousStartedEvent must drop already-seen events: " + trimmedIds); + assertEquals(previousStarted, trimmedIds.get(0).intValue(), + "the window starts at previousStartedEventId inclusive"); + } + + /** A page-1 continuation token for a task, so a poll resolves that task without claiming. */ + private static String encodedFirstPage(String taskToken) { + return java.util.Base64.getEncoder().encodeToString( + ("offset=0\ntask=" + taskToken).getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + + @Test + void everyPaginatedOperation_rejectsAnOversizedPageSize() { + String domain = uniqueName("pagesize"); + registerDomain(domain); + registerWorkflowType(domain, "W", "1.0"); + Response started = call("StartWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-ps", + "workflowType": {"name": "W", "version": "1.0"}, + "taskList": {"name": "tl"}} + """.formatted(domain)); + String runId = started.path("runId"); + + // The live service applies the same 1000 cap to the history and the execution listings, + // not only to the registration lists — the history used to clamp instead of rejecting. + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-ps", "runId": "%s"}, + "maximumPageSize": 1001} + """.formatted(domain, runId)) + .then() + .statusCode(400) + .body("__type", equalTo("com.amazon.coral.validate#ValidationException")) + .body("message", containsString("less than or equal to 1000")); + + call("ListOpenWorkflowExecutions", """ + {"domain": "%s", "startTimeFilter": {"oldestDate": 0}, "maximumPageSize": 1001} + """.formatted(domain)) + .then() + .statusCode(400) + .body("message", containsString("less than or equal to 1000")); + + // A negative page size has its own constraint message. + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-ps", "runId": "%s"}, + "maximumPageSize": -1} + """.formatted(domain, runId)) + .then() + .statusCode(400) + .body("message", containsString("greater than or equal to 0")); + } + + // ───────────────────────────── Counting and tags ───────────────────────── + + @Test + void countOperations_reportCountAndTruncatedFlag() { + String domain = uniqueName("counts"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + startExecution(domain, "wf-count", null); + + call("CountOpenWorkflowExecutions", """ + {"domain": "%s", "startTimeFilter": {"oldestDate": 1}} + """.formatted(domain)) + .then() + .statusCode(200) + .body("count", equalTo(1)) + .body("truncated", is(false)); + + call("CountClosedWorkflowExecutions", """ + {"domain": "%s", "startTimeFilter": {"oldestDate": 1}} + """.formatted(domain)) + .then() + .statusCode(200) + .body("count", equalTo(0)); + + call("CountPendingDecisionTasks", """ + {"domain": "%s", "taskList": {"name": "floci-tl"}} + """.formatted(domain)) + .then() + .statusCode(200) + .body("count", equalTo(1)) + .body("truncated", is(false)); + + call("CountPendingActivityTasks", """ + {"domain": "%s", "taskList": {"name": "floci-tl"}} + """.formatted(domain)) + .then() + .statusCode(200) + .body("count", equalTo(0)); + } + + @Test + void listOpenWorkflowExecutions_appliesTagAndTypeFilters() { + String domain = uniqueName("filters"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + registerWorkflowType(domain, "OtherWf", "2.0"); + + call("StartWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-tagged", + "workflowType": {"name": "TestWf", "version": "1.0"}, + "tagList": ["alpha", "beta"]} + """.formatted(domain)).then().statusCode(200); + call("StartWorkflowExecution", """ + {"domain": "%s", "workflowId": "wf-untagged", + "workflowType": {"name": "OtherWf", "version": "2.0"}} + """.formatted(domain)).then().statusCode(200); + + call("ListOpenWorkflowExecutions", """ + {"domain": "%s", "startTimeFilter": {"oldestDate": 1}, + "tagFilter": {"tag": "alpha"}} + """.formatted(domain)) + .then() + .statusCode(200) + .body("executionInfos", hasSize(1)) + .body("executionInfos[0].execution.workflowId", equalTo("wf-tagged")) + .body("executionInfos[0].tagList", hasItem("beta")); + + call("ListOpenWorkflowExecutions", """ + {"domain": "%s", "startTimeFilter": {"oldestDate": 1}, + "typeFilter": {"name": "OtherWf"}} + """.formatted(domain)) + .then() + .statusCode(200) + .body("executionInfos", hasSize(1)) + .body("executionInfos[0].execution.workflowId", equalTo("wf-untagged")); + + call("ListOpenWorkflowExecutions", """ + {"domain": "%s", "startTimeFilter": {"oldestDate": 1}, + "executionFilter": {"workflowId": "wf-tagged"}} + """.formatted(domain)) + .then() + .statusCode(200) + .body("executionInfos", hasSize(1)) + .body("executionInfos[0].execution.workflowId", equalTo("wf-tagged")); + } + + @Test + void tagResource_thenListAndUntag_roundTripsDomainTags() { + String domain = uniqueName("tags"); + registerDomain(domain); + String arn = call("DescribeDomain", """ + {"name": "%s"} + """.formatted(domain)).path("domainInfo.arn"); + + call("TagResource", """ + {"resourceArn": "%s", "tags": [{"key": "env", "value": "test"}, + {"key": "team", "value": "floci"}]} + """.formatted(arn)).then().statusCode(200); + + call("ListTagsForResource", """ + {"resourceArn": "%s"} + """.formatted(arn)) + .then() + .statusCode(200) + .body("tags.key", hasItem("env")) + .body("tags.find { it.key == 'env' }.value", equalTo("test")); + + call("UntagResource", """ + {"resourceArn": "%s", "tagKeys": ["env"]} + """.formatted(arn)).then().statusCode(200); + + call("ListTagsForResource", """ + {"resourceArn": "%s"} + """.formatted(arn)) + .then() + .statusCode(200) + .body("tags.key", org.hamcrest.Matchers.not(hasItem("env"))) + .body("tags.key", hasItem("team")); + } + + @Test + void getWorkflowExecutionHistory_paginatesWithAnOpaqueToken() { + String domain = uniqueName("history-page"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + String runId = startExecution(domain, "wf-page", null); + + Response firstPage = call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-page", "runId": "%s"}, + "maximumPageSize": 1} + """.formatted(domain, runId)); + firstPage.then() + .statusCode(200) + .body("events", hasSize(1)) + .body("events[0].eventId", equalTo(1)) + .body("nextPageToken", notNullValue()); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-page", "runId": "%s"}, + "maximumPageSize": 1, "nextPageToken": "%s"} + """.formatted(domain, runId, firstPage.path("nextPageToken").toString())) + .then() + .statusCode(200) + .body("events", hasSize(1)) + .body("events[0].eventId", equalTo(2)) + .body("nextPageToken", nullValue()); + } + + @Test + void getWorkflowExecutionHistory_reverseOrder_returnsNewestFirst() { + String domain = uniqueName("history-reverse"); + registerDomain(domain); + registerWorkflowType(domain, "TestWf", "1.0"); + String runId = startExecution(domain, "wf-reverse", null); + + call("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-reverse", "runId": "%s"}, + "reverseOrder": true} + """.formatted(domain, runId)) + .then() + .statusCode(200) + .body("events[0].eventType", equalTo("DecisionTaskScheduled")) + .body("events[1].eventType", equalTo("WorkflowExecutionStarted")); + } + + @Test + void unknownOperation_underSwfTargetPrefix_isRejected() { + given() + .header("X-Amz-Target", "SimpleWorkflowService.NotARealOperation") + .contentType(SWF_CONTENT_TYPE) + .body("{}") + .when() + .post("/") + .then() + .statusCode(404) + .body("__type", equalTo("UnknownOperationException")); + } + + // ───────────────────────────────- helpers ──────────────────────────────── + + private static String uniqueName(String prefix) { + return "floci-" + prefix + "-" + System.nanoTime(); + } + + private static Response call(String action, String body) { + return given() + .header("X-Amz-Target", "SimpleWorkflowService." + action) + .contentType(SWF_CONTENT_TYPE) + .body(body) + .when() + .post("/"); + } + + /** + * Sends a request whose SigV4 credential scope names {@code region}, which is how the + * emulator decides which region's state a call addresses. Only the scope is used, so the + * signature itself does not have to be valid. + */ + private static Response callInRegion(String action, String body, String region) { + return given() + .header("X-Amz-Target", "SimpleWorkflowService." + action) + .header("Authorization", "AWS4-HMAC-SHA256 " + + "Credential=test/20260101/" + region + "/swf/aws4_request, " + + "SignedHeaders=host;x-amz-target, Signature=not-verified") + .contentType(SWF_CONTENT_TYPE) + .body(body) + .when() + .post("/"); + } + + private static void registerDomain(String domain) { + call("RegisterDomain", """ + {"name": "%s", "description": "floci test domain", + "workflowExecutionRetentionPeriodInDays": "7"} + """.formatted(domain)).then().statusCode(200); + } + + private static void registerWorkflowType(String domain, String name, String version) { + call("RegisterWorkflowType", """ + {"domain": "%s", "name": "%s", "version": "%s", + "defaultTaskStartToCloseTimeout": "60", + "defaultExecutionStartToCloseTimeout": "3600", + "defaultTaskList": {"name": "floci-tl"}, + "defaultChildPolicy": "TERMINATE"} + """.formatted(domain, name, version)).then().statusCode(200); + } + + private static void registerActivityType(String domain, String name, String version) { + call("RegisterActivityType", """ + {"domain": "%s", "name": "%s", "version": "%s", + "defaultTaskStartToCloseTimeout": "60", + "defaultTaskScheduleToStartTimeout": "60", + "defaultTaskScheduleToCloseTimeout": "120", + "defaultTaskHeartbeatTimeout": "NONE", + "defaultTaskList": {"name": "floci-tl"}} + """.formatted(domain, name, version)).then().statusCode(200); + } + + private static String startExecution(String domain, String workflowId, String input) { + String body = input == null + ? """ + {"domain": "%s", "workflowId": "%s", + "workflowType": {"name": "TestWf", "version": "1.0"}} + """.formatted(domain, workflowId) + : """ + {"domain": "%s", "workflowId": "%s", + "workflowType": {"name": "TestWf", "version": "1.0"}, + "input": "%s"} + """.formatted(domain, workflowId, input.replace("\"", "\\\"")); + Response response = call("StartWorkflowExecution", body); + response.then().statusCode(200).body("runId", notNullValue()); + return response.path("runId"); + } + + private static String pollDecisionToken(String domain) { + Response response = call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "floci-tl"}, "identity": "decider"} + """.formatted(domain)); + response.then().statusCode(200); + String token = response.path("taskToken"); + org.junit.jupiter.api.Assertions.assertNotNull(token, "expected a decision task"); + org.junit.jupiter.api.Assertions.assertFalse(token.isEmpty(), "expected a decision task"); + return token; + } + + /** + * Claims decision tasks until one belongs to {@code workflowId}. Several executions in + * one domain share a task list, so a plain poll may hand back a sibling's task. + */ + private static String pollDecisionTokenFor(String domain, String workflowId) { + for (int attempt = 0; attempt < 10; attempt++) { + Response response = call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "floci-tl"}, "identity": "decider"} + """.formatted(domain)); + response.then().statusCode(200); + String token = response.path("taskToken"); + if (token == null || token.isEmpty()) { + continue; + } + if (workflowId.equals(response.path("workflowExecution.workflowId"))) { + return token; + } + // Release the sibling's task with an empty decision list so it does not block. + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": []} + """.formatted(token)).then().statusCode(200); + } + return org.junit.jupiter.api.Assertions.fail("no decision task for " + workflowId); + } + + private static void drainDecisionTasks(String domain) { + for (int attempt = 0; attempt < 5; attempt++) { + Response response = call("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "floci-tl"}, "identity": "drain"} + """.formatted(domain)); + String token = response.path("taskToken"); + if (token == null || token.isEmpty()) { + return; + } + call("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": []} + """.formatted(token)).then().statusCode(200); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/swf/SwfLambdaIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/swf/SwfLambdaIntegrationTest.java new file mode 100644 index 0000000000..329856f722 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/swf/SwfLambdaIntegrationTest.java @@ -0,0 +1,245 @@ +package io.github.hectorvent.floci.services.swf; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.util.Base64; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Drives {@code ScheduleLambdaFunction} against a real Lambda function — deployed + * through Floci's own Lambda API and executed in the container Floci starts for it — rather + * than a stub, so the whole path is exercised: decision to Lambda service to container to + * history event. + * + *

Separate from {@link SwfIntegrationTest} because these cases are the only SWF tests that + * need a Docker daemon; keeping them apart means a Docker-less run loses exactly this class + * instead of the whole SWF wire suite. + * + *

The expected event sequence and field shapes were captured from the live service: + * LambdaFunctionScheduled, LambdaFunctionStarted, then Completed carrying the function's + * response as {@code result}, followed by a fresh DecisionTaskScheduled. + */ +@QuarkusTest +class SwfLambdaIntegrationTest { + + private static final String LAMBDA_PATH = "/2015-03-31/functions"; + private static final String ROLE = "arn:aws:iam::000000000000:role/swf-lambda-role"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + private static Response swf(String action, String body) { + return given() + .header("X-Amz-Target", "SimpleWorkflowService." + action) + .contentType("application/x-amz-json-1.0") + .body(body) + .when().post("/"); + } + + /** A python handler that echoes its event, so the response proves the input reached it. */ + private static String echoFunctionZip() throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ZipOutputStream zip = new ZipOutputStream(baos)) { + zip.putNextEntry(new ZipEntry("handler.py")); + zip.write(("import json\n" + + "def handler(event, context):\n" + + " return {'echoed': event, 'ok': True}\n").getBytes()); + zip.closeEntry(); + } + return Base64.getEncoder().encodeToString(baos.toByteArray()); + } + + private static void createEchoFunction(String name) throws Exception { + given().contentType("application/json") + .body(""" + { + "FunctionName": "%s", + "Runtime": "python3.12", + "Role": "%s", + "Handler": "handler.handler", + "Timeout": 30, + "Code": {"ZipFile": "%s"} + } + """.formatted(name, ROLE, echoFunctionZip())) + .when().post(LAMBDA_PATH) + .then().statusCode(201) + .body("State", equalTo("Active")); + } + + /** Registers a domain plus a workflow type carrying {@code defaultLambdaRole}. */ + private static void setUpDomain(String domain, String taskList, String lambdaRole) { + swf("RegisterDomain", """ + {"name": "%s", "workflowExecutionRetentionPeriodInDays": "1"} + """.formatted(domain)).then().statusCode(200); + + String role = lambdaRole == null ? "" : "\"defaultLambdaRole\": \"%s\",".formatted(lambdaRole); + swf("RegisterWorkflowType", """ + {"domain": "%s", "name": "LambdaWf", "version": "1.0", + %s + "defaultTaskList": {"name": "%s"}, + "defaultTaskStartToCloseTimeout": "300", + "defaultExecutionStartToCloseTimeout": "900", + "defaultChildPolicy": "TERMINATE"} + """.formatted(domain, role, taskList)).then().statusCode(200); + } + + private static String startAndPoll(String domain, String workflowId, String taskList) { + swf("StartWorkflowExecution", """ + {"domain": "%s", "workflowId": "%s", + "workflowType": {"name": "LambdaWf", "version": "1.0"}} + """.formatted(domain, workflowId)).then().statusCode(200); + + return swf("PollForDecisionTask", """ + {"domain": "%s", "taskList": {"name": "%s"}, "identity": "decider"} + """.formatted(domain, taskList)) + .then().statusCode(200) + .extract().path("taskToken"); + } + + @Test + void scheduleLambdaFunction_runsTheRealFunctionAndRecordsItsResponse() throws Exception { + String suffix = String.valueOf(System.nanoTime()); + String fn = "swf-echo-" + suffix; + String domain = "swf-lambda-" + suffix; + String taskList = "lam-tl-" + suffix; + + createEchoFunction(fn); + setUpDomain(domain, taskList, ROLE); + String token = startAndPoll(domain, "wf-lambda", taskList); + + swf("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [ + {"decisionType": "ScheduleLambdaFunction", + "scheduleLambdaFunctionDecisionAttributes": { + "id": "lam-1", + "name": "%s", + "control": "ctl-1", + "input": "{\\"hello\\": \\"swf\\"}", + "startToCloseTimeout": "30" + }}]} + """.formatted(token, fn)).then().statusCode(200); + + Response history = swf("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-lambda"}} + """.formatted(domain)); + + history.then() + .statusCode(200) + .body("events.eventType", org.hamcrest.Matchers.hasItems( + "LambdaFunctionScheduled", "LambdaFunctionStarted", "LambdaFunctionCompleted")) + .body("events.find { it.eventType == 'LambdaFunctionScheduled' }" + + ".lambdaFunctionScheduledEventAttributes.id", equalTo("lam-1")) + .body("events.find { it.eventType == 'LambdaFunctionScheduled' }" + + ".lambdaFunctionScheduledEventAttributes.name", equalTo(fn)) + .body("events.find { it.eventType == 'LambdaFunctionScheduled' }" + + ".lambdaFunctionScheduledEventAttributes.control", equalTo("ctl-1")) + .body("events.find { it.eventType == 'LambdaFunctionScheduled' }" + + ".lambdaFunctionScheduledEventAttributes.startToCloseTimeout", equalTo("30")) + .body("events[-1].eventType", equalTo("DecisionTaskScheduled")); + + // The recorded result must be the function's actual output, which proves the container + // ran and received the decider's input rather than the event being synthesised. + String result = history.path( + "events.find { it.eventType == 'LambdaFunctionCompleted' }" + + ".lambdaFunctionCompletedEventAttributes.result"); + assertTrue(result != null && result.contains("\"ok\""), + "expected the echo handler's response, got: " + result); + assertTrue(result.contains("swf"), + "expected the decider's input echoed back, got: " + result); + + // initiated/started correlation ids must name the events they refer to. + int scheduledId = history.path( + "events.find { it.eventType == 'LambdaFunctionScheduled' }.eventId"); + int startedId = history.path( + "events.find { it.eventType == 'LambdaFunctionStarted' }.eventId"); + assertEquals(scheduledId, (int) history.path( + "events.find { it.eventType == 'LambdaFunctionStarted' }" + + ".lambdaFunctionStartedEventAttributes.scheduledEventId")); + assertEquals(scheduledId, (int) history.path( + "events.find { it.eventType == 'LambdaFunctionCompleted' }" + + ".lambdaFunctionCompletedEventAttributes.scheduledEventId")); + assertEquals(startedId, (int) history.path( + "events.find { it.eventType == 'LambdaFunctionCompleted' }" + + ".lambdaFunctionCompletedEventAttributes.startedEventId")); + } + + @Test + void scheduleLambdaFunction_forAMissingFunction_recordsFailedWithTheAwsErrorCode() { + String suffix = String.valueOf(System.nanoTime()); + String domain = "swf-lambda-missing-" + suffix; + String taskList = "lam-tl-" + suffix; + + setUpDomain(domain, taskList, ROLE); + String token = startAndPoll(domain, "wf-missing", taskList); + + swf("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [ + {"decisionType": "ScheduleLambdaFunction", + "scheduleLambdaFunctionDecisionAttributes": { + "id": "lam-missing", "name": "swf-no-such-function-%s" + }}]} + """.formatted(token, suffix)).then().statusCode(200); + + // The live service still records Started before Failed for an unresolvable function, + // and surfaces Lambda's own error code as the reason. + swf("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-missing"}} + """.formatted(domain)) + .then() + .statusCode(200) + .body("events.eventType", org.hamcrest.Matchers.hasItems( + "LambdaFunctionScheduled", "LambdaFunctionStarted", "LambdaFunctionFailed")) + .body("events.find { it.eventType == 'LambdaFunctionFailed' }" + + ".lambdaFunctionFailedEventAttributes.reason", + equalTo("ResourceNotFoundException")) + .body("events.find { it.eventType == 'LambdaFunctionFailed' }" + + ".lambdaFunctionFailedEventAttributes.details", notNullValue()) + .body("events[-1].eventType", equalTo("DecisionTaskScheduled")); + } + + @Test + void scheduleLambdaFunction_withNoLambdaRole_reportsAssumeRoleFailedAndNeverStarts() { + String suffix = String.valueOf(System.nanoTime()); + String domain = "swf-lambda-norole-" + suffix; + String taskList = "lam-tl-" + suffix; + + setUpDomain(domain, taskList, null); + String token = startAndPoll(domain, "wf-norole", taskList); + + swf("RespondDecisionTaskCompleted", """ + {"taskToken": "%s", "decisions": [ + {"decisionType": "ScheduleLambdaFunction", + "scheduleLambdaFunctionDecisionAttributes": {"id": "x", "name": "whatever"}}]} + """.formatted(token)).then().statusCode(200); + + swf("GetWorkflowExecutionHistory", """ + {"domain": "%s", "execution": {"workflowId": "wf-norole"}} + """.formatted(domain)) + .then() + .statusCode(200) + .body("events.eventType", org.hamcrest.Matchers.hasItem("StartLambdaFunctionFailed")) + // This is the one Lambda path that never reaches Started. + .body("events.eventType", + org.hamcrest.Matchers.not(org.hamcrest.Matchers.hasItem("LambdaFunctionStarted"))) + .body("events.find { it.eventType == 'StartLambdaFunctionFailed' }" + + ".startLambdaFunctionFailedEventAttributes.cause", equalTo("ASSUME_ROLE_FAILED")) + .body("events.find { it.eventType == 'StartLambdaFunctionFailed' }" + + ".startLambdaFunctionFailedEventAttributes.message", + equalTo("No IAM role is attached to the current workflow execution.")) + .body("events[-1].eventType", equalTo("DecisionTaskScheduled")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/swf/SwfServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/swf/SwfServiceTest.java new file mode 100644 index 0000000000..d2670b25be --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/swf/SwfServiceTest.java @@ -0,0 +1,1311 @@ +package io.github.hectorvent.floci.services.swf; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.swf.SwfService.Decision; +import io.github.hectorvent.floci.services.swf.SwfService.ExecutionFilter; +import io.github.hectorvent.floci.services.swf.SwfService.StartWorkflowExecutionRequest; +import io.github.hectorvent.floci.services.swf.model.SwfActivityTask; +import io.github.hectorvent.floci.services.swf.model.SwfActivityType; +import io.github.hectorvent.floci.services.swf.model.SwfDecisionTask; +import io.github.hectorvent.floci.services.swf.model.SwfDomain; +import io.github.hectorvent.floci.services.swf.model.SwfHistoryEvent; +import io.github.hectorvent.floci.services.swf.model.SwfWorkflowExecution; +import io.github.hectorvent.floci.services.swf.model.SwfWorkflowType; +import io.github.hectorvent.floci.testing.MutableClock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit coverage for the parts of the SWF state machine that are awkward to reach over + * HTTP: timeout expiry (driven here by a controllable clock rather than wall time) and + * the decision-task-outstanding invariant. + */ +class SwfServiceTest { + + private static final String REGION = "us-east-1"; + private static final String DOMAIN = "unit-domain"; + + private MutableClock clock; + private SwfService service; + private List lambdaInvocations; + private LambdaInvocationResult lambdaResponse; + private RuntimeException lambdaFailure; + private LambdaGate lambdaGate; + + @BeforeEach + void setUp() { + clock = new MutableClock(); + lambdaInvocations = new ArrayList<>(); + lambdaResponse = new LambdaInvocationResult("{\"ok\":true}", null); + lambdaFailure = null; + lambdaGate = null; + service = new SwfService(new InMemoryStorageFactory(), + new RegionResolver("us-east-1", "000000000000"), clock, recordingLambdaInvoker()); + + service.registerDomain(DOMAIN, "unit test domain", "7", Map.of(), REGION); + service.registerWorkflowType(REGION, DOMAIN, workflowType("W", "1")); + service.registerActivityType(REGION, DOMAIN, activityType("A", "1")); + } + + /** + * Stands in for the real Lambda service so these tests need no Docker daemon: records the + * region and function it was asked for, then returns {@link #lambdaResponse} or throws + * {@link #lambdaFailure}. + */ + private LambdaInvoker recordingLambdaInvoker() { + return (region, functionName, payload) -> { + lambdaInvocations.add(region + "|" + functionName + "|" + + new String(payload, StandardCharsets.UTF_8)); + LambdaGate gate = lambdaGate; + if (gate != null) { + // Let the test observe that the invocation is in flight, then block in it. + gate.started().countDown(); + try { + gate.release().await(15, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + if (lambdaFailure != null) { + throw lambdaFailure; + } + return lambdaResponse; + }; + } + + @Test + void startWorkflowExecution_seedsStartedAndDecisionTaskScheduledEvents() { + String runId = start("wf-1"); + + List events = service.getWorkflowExecutionHistory(REGION, DOMAIN, "wf-1", runId, false); + assertEquals(2, events.size()); + assertEquals(1, events.get(0).getEventId()); + assertEquals("WorkflowExecutionStarted", events.get(0).getEventType()); + assertEquals(2, events.get(1).getEventId()); + assertEquals("DecisionTaskScheduled", events.get(1).getEventType()); + } + + @Test + void startWorkflowExecution_resolvesUnsetFieldsFromTheWorkflowTypeDefaults() { + String runId = start("wf-defaults"); + SwfWorkflowExecution execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-defaults", runId); + + assertEquals("tl", execution.getTaskList()); + assertEquals("300", execution.getExecutionStartToCloseTimeout()); + assertEquals("10", execution.getTaskStartToCloseTimeout()); + assertEquals("TERMINATE", execution.getChildPolicy()); + } + + @Test + void startWorkflowExecution_withoutAnyDefault_throwsDefaultUndefinedFault() { + SwfWorkflowType bare = new SwfWorkflowType(); + bare.setName("Bare"); + bare.setVersion("1"); + service.registerWorkflowType(REGION, DOMAIN, bare); + + AwsException thrown = assertThrows(AwsException.class, () -> service.startWorkflowExecution( + new StartWorkflowExecutionRequest(REGION, DOMAIN, "wf-bare", "Bare", "1", + null, null, null, null, null, null, null, null))); + assertEquals("DefaultUndefinedFault", thrown.getErrorCode()); + assertEquals("com.amazonaws.swf.base.model#DefaultUndefinedFault", thrown.jsonType()); + } + + @Test + void faults_reportBareErrorCodeAndNamespacedJsonType() { + AwsException thrown = assertThrows(AwsException.class, () -> service.describeDomain(REGION, "no-such")); + + // botocore prefers the header (error code) over the body's __type, so the bare name + // has to stay on the code for the CLI to print UnknownResourceFault. + assertEquals("UnknownResourceFault", thrown.getErrorCode()); + assertEquals("com.amazonaws.swf.base.model#UnknownResourceFault", thrown.jsonType()); + assertEquals("Unknown domain: no-such", thrown.getMessage()); + assertEquals(400, thrown.getHttpStatus()); + } + + @Test + void pollForDecisionTask_handsOutOnlyOneTaskPerExecutionAtATime() { + start("wf-single"); + + assertTrue(service.pollForDecisionTask(REGION, DOMAIN, "tl", "d1").isPresent()); + assertTrue(service.pollForDecisionTask(REGION, DOMAIN, "tl", "d2").isEmpty(), + "a second decider must not receive the same execution's task"); + } + + @Test + void signalWhileDecisionOutstanding_defersTheNextTaskUntilTheCurrentOneCompletes() { + String runId = start("wf-defer"); + SwfDecisionTask first = service.pollForDecisionTask(REGION, DOMAIN, "tl", "d1").orElseThrow(); + + service.signalWorkflowExecution(REGION, DOMAIN, "wf-defer", runId, "poke", null); + assertTrue(service.pollForDecisionTask(REGION, DOMAIN, "tl", "d2").isEmpty(), + "the signal must not create a concurrent decision task"); + + service.respondDecisionTaskCompleted(first.getTaskToken(), List.of(), null); + assertTrue(service.pollForDecisionTask(REGION, DOMAIN, "tl", "d3").isPresent(), + "completing the outstanding task must release the deferred one"); + } + + @Test + void respondDecisionTaskCompleted_withStaleToken_throwsUnknownResourceFault() { + AwsException thrown = assertThrows(AwsException.class, + () -> service.respondDecisionTaskCompleted("not-a-token", List.of(), null)); + assertEquals("UnknownResourceFault", thrown.getErrorCode()); + } + + @Test + void respondDecisionTaskCompleted_rejectsABatchWhoseClosingDecisionIsNotLast() { + String runId = start("wf-after-close"); + SwfDecisionTask task = service.pollForDecisionTask(REGION, DOMAIN, "tl", "d").orElseThrow(); + + // The live service rejects the whole batch rather than applying the prefix. + AwsException thrown = assertThrows(AwsException.class, + () -> service.respondDecisionTaskCompleted(task.getTaskToken(), List.of( + new Decision("CompleteWorkflowExecution", Map.of("result", "done")), + new Decision("ScheduleActivityTask", Map.of( + "activityId", "too-late", + "activityType", Map.of("name", "A", "version", "1")))), null)); + assertEquals("ValidationException", thrown.getErrorCode()); + assertEquals("Close must be last decision in list", thrown.getMessage()); + assertEquals("com.amazon.coral.validate#ValidationException", thrown.jsonType()); + + // Nothing was applied and the task is still outstanding, so the decider can retry. + SwfWorkflowExecution execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-after-close", runId); + assertEquals("OPEN", execution.getExecutionStatus()); + assertTrue(execution.getActivities().isEmpty()); + assertNull(lastAttribute(execution, "DecisionTaskCompleted", "scheduledEventId"), + "a rejected batch must not append DecisionTaskCompleted"); + + service.respondDecisionTaskCompleted(task.getTaskToken(), List.of( + new Decision("CompleteWorkflowExecution", Map.of("result", "done"))), null); + assertEquals("COMPLETED", + service.describeWorkflowExecution(REGION, DOMAIN, "wf-after-close", runId).getCloseStatus()); + } + + @Test + void respondDecisionTaskCompleted_acceptsAClosingDecisionInFinalPosition() { + String runId = start("wf-close-last"); + SwfDecisionTask task = service.pollForDecisionTask(REGION, DOMAIN, "tl", "d").orElseThrow(); + + service.respondDecisionTaskCompleted(task.getTaskToken(), List.of( + new Decision("RecordMarker", Map.of("markerName", "m-1")), + new Decision("CompleteWorkflowExecution", Map.of("result", "done"))), null); + + SwfWorkflowExecution execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-close-last", runId); + assertEquals("m-1", lastAttribute(execution, "MarkerRecorded", "markerName")); + assertEquals("COMPLETED", execution.getCloseStatus()); + } + + @Test + void closingDecisionWithAnOpenActivity_recordsUnhandledDecisionAndKeepsTheExecutionOpen() { + String runId = start("wf-unhandled"); + scheduleActivity("wf-unhandled", "act-1"); + + SwfDecisionTask task = pokeForDecision("wf-unhandled"); + service.respondDecisionTaskCompleted(task.getTaskToken(), + List.of(new Decision("CompleteWorkflowExecution", Map.of())), null); + + SwfWorkflowExecution execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-unhandled", runId); + assertEquals("OPEN", execution.getExecutionStatus()); + assertEquals("UNHANDLED_DECISION", + lastAttribute(execution, "CompleteWorkflowExecutionFailed", "cause")); + } + + @Test + void activityScheduleToStartTimeout_expiresTheTaskAndSchedulesANewDecision() { + String runId = start("wf-s2s"); + scheduleActivity("wf-s2s", "act-s2s"); + + clock.advance(Duration.ofSeconds(31)); + service.sweep(); + + SwfWorkflowExecution execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-s2s", runId); + assertEquals("SCHEDULE_TO_START", lastAttribute(execution, "ActivityTaskTimedOut", "timeoutType")); + // Never started, so the live service reports startedEventId 0 rather than omitting it. + assertEquals(0L, lastAttribute(execution, "ActivityTaskTimedOut", "startedEventId")); + assertEquals(0, service.openActivityCount(execution)); + assertTrue(service.pollForDecisionTask(REGION, DOMAIN, "tl", "d").isPresent(), + "the timeout must schedule a decision task"); + } + + @Test + void activityStartToCloseTimeout_expiresAStartedTask() { + start("wf-s2c"); + scheduleActivity("wf-s2c", "act-s2c"); + SwfActivityTask task = service.pollForActivityTask(REGION, DOMAIN, "act-tl", "w").orElseThrow(); + assertEquals("act-s2c", task.getActivityId()); + + clock.advance(Duration.ofSeconds(61)); + service.sweep(); + + SwfWorkflowExecution execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-s2c", null); + assertEquals("START_TO_CLOSE", lastAttribute(execution, "ActivityTaskTimedOut", "timeoutType")); + assertThrows(AwsException.class, + () -> service.respondActivityTaskCompleted(task.getTaskToken(), "too late"), + "the token must stop resolving once the task has timed out"); + } + + @Test + void activityHeartbeatTimeout_expiresATaskThatStopsHeartbeating() { + SwfActivityType heartbeating = activityType("HB", "1"); + heartbeating.setDefaultTaskHeartbeatTimeout("10"); + heartbeating.setDefaultTaskStartToCloseTimeout("600"); + service.registerActivityType(REGION, DOMAIN, heartbeating); + + start("wf-hb"); + SwfDecisionTask decision = service.pollForDecisionTask(REGION, DOMAIN, "tl", "d").orElseThrow(); + service.respondDecisionTaskCompleted(decision.getTaskToken(), List.of( + new Decision("ScheduleActivityTask", Map.of( + "activityId", "act-hb", + "activityType", Map.of("name", "HB", "version", "1")))), null); + SwfActivityTask task = service.pollForActivityTask(REGION, DOMAIN, "act-tl", "w").orElseThrow(); + + // A heartbeat resets the window, so the task survives the first advance. + clock.advance(Duration.ofSeconds(8)); + assertFalse(service.recordActivityTaskHeartbeat(task.getTaskToken(), "alive")); + clock.advance(Duration.ofSeconds(8)); + service.sweep(); + SwfWorkflowExecution execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-hb", null); + assertNull(lastAttribute(execution, "ActivityTaskTimedOut", "timeoutType"), + "a heartbeat within the window must keep the task alive"); + + clock.advance(Duration.ofSeconds(11)); + service.sweep(); + execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-hb", null); + assertEquals("HEARTBEAT", lastAttribute(execution, "ActivityTaskTimedOut", "timeoutType")); + } + + @Test + void decisionTaskStartToCloseTimeout_reschedulesTheTaskForAnotherDecider() { + String runId = start("wf-dt-timeout"); + SwfDecisionTask abandoned = service.pollForDecisionTask(REGION, DOMAIN, "tl", "dead").orElseThrow(); + + clock.advance(Duration.ofSeconds(11)); + service.sweep(); + + SwfWorkflowExecution execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-dt-timeout", runId); + assertEquals("START_TO_CLOSE", lastAttribute(execution, "DecisionTaskTimedOut", "timeoutType")); + assertThrows(AwsException.class, + () -> service.respondDecisionTaskCompleted(abandoned.getTaskToken(), List.of(), null)); + + SwfDecisionTask replacement = service.pollForDecisionTask(REGION, DOMAIN, "tl", "fresh").orElseThrow(); + assertEquals(abandoned.getStartedEventId(), replacement.getPreviousStartedEventId()); + } + + @Test + void workflowExecutionStartToCloseTimeout_closesTheExecutionAsTimedOut() { + String runId = start("wf-exec-timeout"); + + clock.advance(Duration.ofSeconds(301)); + service.sweep(); + + SwfWorkflowExecution execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-exec-timeout", runId); + assertEquals("CLOSED", execution.getExecutionStatus()); + assertEquals("TIMED_OUT", execution.getCloseStatus()); + assertEquals("START_TO_CLOSE", lastAttribute(execution, "WorkflowExecutionTimedOut", "timeoutType")); + } + + @Test + void timerFires_onceItsStartToFireTimeoutElapses() { + String runId = start("wf-timer"); + SwfDecisionTask decision = service.pollForDecisionTask(REGION, DOMAIN, "tl", "d").orElseThrow(); + service.respondDecisionTaskCompleted(decision.getTaskToken(), List.of( + new Decision("StartTimer", Map.of("timerId", "t-1", "startToFireTimeout", "30"))), null); + + service.sweep(); + assertEquals(1, service.openTimerCount( + service.describeWorkflowExecution(REGION, DOMAIN, "wf-timer", runId))); + + clock.advance(Duration.ofSeconds(31)); + service.sweep(); + + SwfWorkflowExecution execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-timer", runId); + assertEquals("t-1", lastAttribute(execution, "TimerFired", "timerId")); + assertEquals(0, service.openTimerCount(execution)); + } + + @Test + void timeoutSweep_neverTouchesClosedExecutions() { + String runId = start("wf-closed"); + SwfDecisionTask decision = service.pollForDecisionTask(REGION, DOMAIN, "tl", "d").orElseThrow(); + service.respondDecisionTaskCompleted(decision.getTaskToken(), + List.of(new Decision("CompleteWorkflowExecution", Map.of("result", "ok"))), null); + int eventCount = service.getWorkflowExecutionHistory(REGION, DOMAIN, "wf-closed", runId, false).size(); + + clock.advance(Duration.ofHours(2)); + service.sweep(); + + assertEquals(eventCount, + service.getWorkflowExecutionHistory(REGION, DOMAIN, "wf-closed", runId, false).size(), + "a closed execution must not accrue timeout events"); + } + + @Test + void concurrentStartsOfTheSameWorkflowId_produceExactlyOneOpenRun() throws Exception { + int threads = 8; + ExecutorService pool = Executors.newFixedThreadPool(threads); + CountDownLatch releaseAll = new CountDownLatch(1); + List> attempts = new ArrayList<>(); + try { + for (int i = 0; i < threads; i++) { + attempts.add(pool.submit(() -> { + releaseAll.await(); + return service.startWorkflowExecution(new StartWorkflowExecutionRequest( + REGION, DOMAIN, "wf-race", "W", "1", null, null, null, null, null, null, null, null)); + })); + } + releaseAll.countDown(); + + int started = 0; + int rejected = 0; + for (Future attempt : attempts) { + try { + assertNotNull(attempt.get(10, TimeUnit.SECONDS)); + started++; + } catch (ExecutionException e) { + assertInstanceOf(AwsException.class, e.getCause()); + assertEquals("WorkflowExecutionAlreadyStartedFault", + ((AwsException) e.getCause()).getErrorCode()); + rejected++; + } + } + + // SWF admits one open run per workflowId; the losers must see the fault rather + // than each persisting their own run key. + assertEquals(1, started, "exactly one start may succeed"); + assertEquals(threads - 1, rejected); + assertEquals(1, service.listExecutions(REGION, DOMAIN, ExecutionFilter.all(), false).stream() + .filter(e -> "wf-race".equals(e.getWorkflowId())) + .count()); + } finally { + pool.shutdownNow(); + } + } + + @Test + void closingAChildWhileTheParentIsMutated_keepsBothHistoriesIntact() throws Exception { + String parentRunId = start("wf-cc-parent"); + SwfDecisionTask decision = pollFor("wf-cc-parent"); + List children = new ArrayList<>(); + for (int i = 0; i < 6; i++) { + children.add(new Decision("StartChildWorkflowExecution", Map.of( + "workflowId", "wf-cc-child-" + i, + "workflowType", Map.of("name", "W", "version", "1")))); + } + service.respondDecisionTaskCompleted(decision.getTaskToken(), children, null); + + // Children closing concurrently all append ChildWorkflowExecutionCompleted to the + // same parent. Unsynchronized event-id allocation loses or duplicates events. + ExecutorService pool = Executors.newFixedThreadPool(6); + CountDownLatch releaseAll = new CountDownLatch(1); + List> closes = new ArrayList<>(); + try { + for (int i = 0; i < 6; i++) { + String childId = "wf-cc-child-" + i; + closes.add(pool.submit(() -> { + releaseAll.await(); + SwfDecisionTask childTask = pollFor(childId); + service.respondDecisionTaskCompleted(childTask.getTaskToken(), + List.of(new Decision("CompleteWorkflowExecution", + Map.of("result", childId))), null); + return null; + })); + } + releaseAll.countDown(); + for (Future close : closes) { + close.get(20, TimeUnit.SECONDS); + } + } finally { + pool.shutdownNow(); + } + + SwfWorkflowExecution parent = service.describeWorkflowExecution(REGION, DOMAIN, "wf-cc-parent", parentRunId); + List events = parent.getEvents(); + + // Event ids must stay a contiguous 1..n with no duplicates. + Set ids = new LinkedHashSet<>(); + for (SwfHistoryEvent event : events) { + assertTrue(ids.add(event.getEventId()), "duplicate eventId " + event.getEventId()); + } + for (int i = 0; i < events.size(); i++) { + assertEquals(i + 1L, events.get(i).getEventId(), "eventIds must be contiguous"); + } + + // Every child must be reported exactly once. + Map reported = events.stream() + .filter(e -> "ChildWorkflowExecutionCompleted".equals(e.getEventType())) + .collect(Collectors.groupingBy( + e -> (String) ((Map) e.getAttributes().get("workflowExecution")).get("workflowId"), + Collectors.counting())); + assertEquals(6, reported.size(), "each child reports to the parent"); + reported.forEach((childId, count) -> + assertEquals(1L, count, childId + " reported " + count + " times")); + } + + @Test + void scheduleLambdaFunction_invokesTheFunctionAndRecordsCompletion() { + // A lambdaRole is required for SWF to invoke at all. + service.registerWorkflowType(REGION, DOMAIN, lambdaWorkflowType("LW", "1", + "arn:aws:iam::000000000000:role/swf-lambda")); + String runId = startLambdaWf("wf-lam", "LW"); + + SwfDecisionTask task = service.pollForDecisionTask(REGION, DOMAIN, "tl", "d").orElseThrow(); + lambdaResponse = new LambdaInvocationResult("{\"echoed\":{\"hello\":\"swf\"}}", null); + service.respondDecisionTaskCompleted(task.getTaskToken(), List.of( + scheduleLambda("lam-1", "my-fn", "{\"hello\":\"swf\"}", "ctl", "30")), null); + + assertEquals(1, lambdaInvocations.size(), "the function must actually be invoked"); + assertEquals("us-east-1|my-fn|{\"hello\":\"swf\"}", lambdaInvocations.get(0)); + + List events = service.getWorkflowExecutionHistory(REGION, DOMAIN, "wf-lam", runId, false); + SwfHistoryEvent scheduled = eventOfType(events, "LambdaFunctionScheduled"); + SwfHistoryEvent started = eventOfType(events, "LambdaFunctionStarted"); + SwfHistoryEvent completed = eventOfType(events, "LambdaFunctionCompleted"); + + assertEquals("lam-1", scheduled.getAttributes().get("id")); + assertEquals("my-fn", scheduled.getAttributes().get("name")); + assertEquals("ctl", scheduled.getAttributes().get("control")); + assertEquals("30", scheduled.getAttributes().get("startToCloseTimeout")); + assertEquals(scheduled.getEventId(), started.getAttributes().get("scheduledEventId")); + assertEquals(scheduled.getEventId(), completed.getAttributes().get("scheduledEventId")); + assertEquals(started.getEventId(), completed.getAttributes().get("startedEventId")); + assertEquals("{\"echoed\":{\"hello\":\"swf\"}}", completed.getAttributes().get("result")); + + // The outcome gives the decider a fresh task to react to. + assertEquals("DecisionTaskScheduled", events.get(events.size() - 1).getEventType()); + } + + @Test + void scheduleLambdaFunction_withNoInput_passesAnEmptyJsonObject() { + service.registerWorkflowType(REGION, DOMAIN, lambdaWorkflowType("LW", "1", + "arn:aws:iam::000000000000:role/swf-lambda")); + startLambdaWf("wf-lam-empty", "LW"); + SwfDecisionTask task = service.pollForDecisionTask(REGION, DOMAIN, "tl", "d").orElseThrow(); + + service.respondDecisionTaskCompleted(task.getTaskToken(), List.of( + scheduleLambda("lam-1", "my-fn", null, null, null)), null); + + assertEquals("us-east-1|my-fn|{}", lambdaInvocations.get(0)); + } + + @Test + void scheduleLambdaFunction_whenTheFunctionIsMissing_recordsFailedWithTheAwsErrorCode() { + service.registerWorkflowType(REGION, DOMAIN, lambdaWorkflowType("LW", "1", + "arn:aws:iam::000000000000:role/swf-lambda")); + String runId = startLambdaWf("wf-lam-missing", "LW"); + SwfDecisionTask task = service.pollForDecisionTask(REGION, DOMAIN, "tl", "d").orElseThrow(); + + lambdaFailure = new AwsException("ResourceNotFoundException", + "Function not found: arn:aws:lambda:us-east-1:000000000000:function:gone", 404); + service.respondDecisionTaskCompleted(task.getTaskToken(), List.of( + scheduleLambda("lam-1", "gone", null, null, null)), null); + + List events = service.getWorkflowExecutionHistory(REGION, DOMAIN, "wf-lam-missing", runId, false); + // The live service still reports Started before Failed for an unresolvable function. + SwfHistoryEvent started = eventOfType(events, "LambdaFunctionStarted"); + SwfHistoryEvent failed = eventOfType(events, "LambdaFunctionFailed"); + assertEquals("ResourceNotFoundException", failed.getAttributes().get("reason")); + assertEquals(started.getEventId(), failed.getAttributes().get("startedEventId")); + assertEquals("DecisionTaskScheduled", events.get(events.size() - 1).getEventType()); + } + + @Test + void scheduleLambdaFunction_whenTheHandlerErrors_recordsFailedWithTheFunctionError() { + service.registerWorkflowType(REGION, DOMAIN, lambdaWorkflowType("LW", "1", + "arn:aws:iam::000000000000:role/swf-lambda")); + String runId = startLambdaWf("wf-lam-err", "LW"); + SwfDecisionTask task = service.pollForDecisionTask(REGION, DOMAIN, "tl", "d").orElseThrow(); + + lambdaResponse = new LambdaInvocationResult("{\"errorMessage\":\"boom\"}", "Unhandled"); + service.respondDecisionTaskCompleted(task.getTaskToken(), List.of( + scheduleLambda("lam-1", "my-fn", null, null, null)), null); + + SwfHistoryEvent failed = eventOfType( + service.getWorkflowExecutionHistory(REGION, DOMAIN, "wf-lam-err", runId, false), "LambdaFunctionFailed"); + assertEquals("Unhandled", failed.getAttributes().get("reason")); + assertEquals("{\"errorMessage\":\"boom\"}", failed.getAttributes().get("details")); + } + + @Test + void scheduleLambdaFunction_withoutALambdaRole_neverStartsAndReportsAssumeRoleFailed() { + // The workflow type registered in setUp() has no defaultLambdaRole. + String runId = start("wf-lam-norole"); + SwfDecisionTask task = service.pollForDecisionTask(REGION, DOMAIN, "tl", "d").orElseThrow(); + + service.respondDecisionTaskCompleted(task.getTaskToken(), List.of( + scheduleLambda("lam-1", "my-fn", null, null, null)), null); + + assertTrue(lambdaInvocations.isEmpty(), "no role means the function is never invoked"); + + List events = service.getWorkflowExecutionHistory(REGION, DOMAIN, "wf-lam-norole", runId, false); + SwfHistoryEvent scheduled = eventOfType(events, "LambdaFunctionScheduled"); + SwfHistoryEvent failed = eventOfType(events, "StartLambdaFunctionFailed"); + assertEquals("ASSUME_ROLE_FAILED", failed.getAttributes().get("cause")); + assertEquals("No IAM role is attached to the current workflow execution.", + failed.getAttributes().get("message")); + assertEquals(scheduled.getEventId(), failed.getAttributes().get("scheduledEventId")); + // This is the one Lambda path that skips Started entirely. + assertTrue(events.stream().noneMatch(e -> "LambdaFunctionStarted".equals(e.getEventType()))); + } + + @Test + void startWorkflowExecution_resolvesLambdaRoleFromTheTypeDefaultAndAcceptsAnOverride() { + service.registerWorkflowType(REGION, DOMAIN, lambdaWorkflowType("LW", "1", + "arn:aws:iam::000000000000:role/type-default")); + + String inherited = startLambdaWf("wf-inherit", "LW"); + assertEquals("arn:aws:iam::000000000000:role/type-default", + service.describeWorkflowExecution(REGION, DOMAIN, "wf-inherit", inherited).getLambdaRole()); + + String overridden = service.startWorkflowExecution(new StartWorkflowExecutionRequest( + REGION, DOMAIN, "wf-override", "LW", "1", null, null, null, null, null, null, null, + "arn:aws:iam::000000000000:role/per-execution")); + assertEquals("arn:aws:iam::000000000000:role/per-execution", + service.describeWorkflowExecution(REGION, DOMAIN, "wf-override", overridden).getLambdaRole()); + } + + @Test + void domainsAreScopedByRegion_soTheSameNameCanExistInTwoRegions() { + // us-east-1 already has DOMAIN from setUp(); registering it in eu-west-1 must succeed + // rather than reporting DomainAlreadyExistsFault, because SWF names are per-region. + service.registerDomain(DOMAIN, "west copy", "3", Map.of(), "eu-west-1"); + + assertEquals("unit test domain", service.describeDomain(REGION, DOMAIN).getDescription()); + assertEquals("west copy", service.describeDomain("eu-west-1", DOMAIN).getDescription()); + assertEquals("7", service.describeDomain(REGION, DOMAIN) + .getWorkflowExecutionRetentionPeriodInDays()); + assertEquals("3", service.describeDomain("eu-west-1", DOMAIN) + .getWorkflowExecutionRetentionPeriodInDays()); + + // Each domain's ARN names its own region. + assertTrue(service.describeDomain(REGION, DOMAIN).getArn().contains(":" + REGION + ":"), + service.describeDomain(REGION, DOMAIN).getArn()); + assertTrue(service.describeDomain("eu-west-1", DOMAIN).getArn().contains(":eu-west-1:"), + service.describeDomain("eu-west-1", DOMAIN).getArn()); + + // Re-registering in a region that already has it is still a duplicate. + AwsException duplicate = assertThrows(AwsException.class, + () -> service.registerDomain(DOMAIN, "again", "1", Map.of(), REGION)); + assertEquals("DomainAlreadyExistsFault", duplicate.getErrorCode()); + + // ListDomains only reports the caller's region. + assertEquals(List.of(DOMAIN), service.listDomains("eu-west-1", "REGISTERED").stream() + .map(SwfDomain::getName).toList()); + } + + @Test + void typesAndExecutionsAreScopedByRegion() { + service.registerDomain(DOMAIN, "west copy", "3", Map.of(), "eu-west-1"); + + // A type registered only in us-east-1 must be invisible from eu-west-1. + assertEquals(List.of("W"), service.listWorkflowTypes(REGION, DOMAIN, null, "REGISTERED", false) + .stream().map(SwfWorkflowType::getName).toList()); + assertEquals(List.of(), service.listWorkflowTypes("eu-west-1", DOMAIN, null, "REGISTERED", false)); + AwsException unknownType = assertThrows(AwsException.class, + () -> service.describeWorkflowType("eu-west-1", DOMAIN, "W", "1")); + assertEquals("UnknownResourceFault", unknownType.getErrorCode()); + + // The same workflowId can run independently in each region. + service.registerWorkflowType("eu-west-1", DOMAIN, workflowType("W", "1")); + String eastRun = start("wf-shared"); + String westRun = service.startWorkflowExecution(new StartWorkflowExecutionRequest( + "eu-west-1", DOMAIN, "wf-shared", "W", "1", + null, null, null, null, null, null, null, null)); + assertNotEquals(eastRun, westRun); + + assertEquals(eastRun, service.describeWorkflowExecution(REGION, DOMAIN, "wf-shared", null).getRunId()); + assertEquals(westRun, service.describeWorkflowExecution("eu-west-1", DOMAIN, "wf-shared", null).getRunId()); + + // A runId from one region must not resolve in the other. + AwsException crossRegion = assertThrows(AwsException.class, + () -> service.describeWorkflowExecution("eu-west-1", DOMAIN, "wf-shared", eastRun)); + assertEquals("UnknownResourceFault", crossRegion.getErrorCode()); + + // Each region hands out only its own decision tasks. + SwfDecisionTask east = service.pollForDecisionTask(REGION, DOMAIN, "tl", "d").orElseThrow(); + assertEquals(eastRun, east.getRunId()); + SwfDecisionTask west = service.pollForDecisionTask("eu-west-1", DOMAIN, "tl", "d").orElseThrow(); + assertEquals(westRun, west.getRunId()); + } + + @Test + void pageSize_matchesTheLiveServiceLimits() { + // Absent or zero means "no caller limit"; above the 1000 cap is rejected, not clamped. + assertEquals(1000, service.pageSize(null)); + assertEquals(1000, service.pageSize(0)); + assertEquals(25, service.pageSize(25)); + assertEquals(1000, service.pageSize(1000)); + + AwsException tooBig = assertThrows(AwsException.class, () -> service.pageSize(1001)); + assertEquals("ValidationException", tooBig.getErrorCode()); + assertTrue(tooBig.getMessage().contains("less than or equal to 1000"), tooBig.getMessage()); + assertThrows(AwsException.class, () -> service.pageSize(-1)); + } + + @Test + void anInvalidDecisionAnywhereInABatch_leavesTheExecutionUntouched() { + String runId = start("wf-batch"); + SwfDecisionTask task = pollFor("wf-batch"); + int before = service.getWorkflowExecutionHistory(REGION, DOMAIN, "wf-batch", runId, false).size(); + + // A valid decision followed by an unknown type: the live service rejects the batch and + // persists none of it, so the marker must not appear and the token must stay claimable. + AwsException thrown = assertThrows(AwsException.class, () -> service.respondDecisionTaskCompleted( + task.getTaskToken(), + List.of(new Decision("RecordMarker", Map.of("markerName", "should-not-persist")), + new Decision("NotARealDecision", Map.of())), + null)); + assertEquals("ValidationException", thrown.getErrorCode()); + + // Assert the state damage first: on the previous implementation the batch was rejected + // too, but only after DecisionTaskCompleted and MarkerRecorded had already been appended + // and the token consumed. That — not the message wording — is what this guards. + List after = + service.getWorkflowExecutionHistory(REGION, DOMAIN, "wf-batch", runId, false); + assertEquals(before, after.size(), "a rejected batch must not grow the history"); + assertTrue(after.stream().noneMatch(e -> "DecisionTaskCompleted".equals(e.getEventType())), + "DecisionTaskCompleted must not be appended for a rejected batch"); + assertTrue(after.stream().noneMatch(e -> "MarkerRecorded".equals(e.getEventType())), + "an earlier decision in a rejected batch must not be applied"); + + // The same token still works, so the decider has a recovery path. + service.respondDecisionTaskCompleted(task.getTaskToken(), + List.of(new Decision("RecordMarker", Map.of("markerName", "retry-after-reject"))), null); + assertTrue(service.getWorkflowExecutionHistory(REGION, DOMAIN, "wf-batch", runId, false).stream() + .anyMatch(e -> "MarkerRecorded".equals(e.getEventType())), + "the rejected token must remain claimable for a corrected batch"); + + // AWS names the offending member by its 1-based position in the list, and renders the + // enum set in the service's own order — which is not the API model's order. + assertEquals("1 validation error detected: Value 'NotARealDecision' at " + + "'decisions.2.member.decisionType' failed to satisfy constraint: " + + "Member must satisfy enum value set: " + + "[CompleteWorkflowExecution, StartTimer, RequestCancelExternalWorkflowExecution, " + + "SignalExternalWorkflowExecution, CancelTimer, RecordMarker, ScheduleActivityTask, " + + "ContinueAsNewWorkflowExecution, ScheduleLambdaFunction, FailWorkflowExecution, " + + "RequestCancelActivityTask, StartChildWorkflowExecution, CancelWorkflowExecution]", + thrown.getMessage()); + } + + @Test + void aChildThatContinuesAsNew_keepsItsParentAndRepointsTheParentsChildEntry() { + String parentRun = start("wf-cn-parent"); + SwfDecisionTask parentTask = pollFor("wf-cn-parent"); + service.respondDecisionTaskCompleted(parentTask.getTaskToken(), + List.of(new Decision("StartChildWorkflowExecution", Map.of( + "workflowId", "wf-cn-child", + "workflowType", Map.of("name", "W", "version", "1"), + "taskList", Map.of("name", "tl"), + "childPolicy", "TERMINATE"))), + null); + + SwfWorkflowExecution child = service.describeWorkflowExecution(REGION, DOMAIN, "wf-cn-child", null); + String originalChildRun = child.getRunId(); + assertEquals("wf-cn-parent", child.getParentWorkflowId()); + + SwfDecisionTask childTask = pollFor("wf-cn-child"); + service.respondDecisionTaskCompleted(childTask.getTaskToken(), + List.of(new Decision("ContinueAsNewWorkflowExecution", Map.of( + "taskList", Map.of("name", "tl"), "childPolicy", "TERMINATE"))), + null); + + SwfWorkflowExecution successor = service.describeWorkflowExecution(REGION, DOMAIN, "wf-cn-child", null); + assertNotEquals(originalChildRun, successor.getRunId(), "continue-as-new must open a new run"); + assertEquals(originalChildRun, successor.getContinuedExecutionRunId()); + + // The successor keeps the parent link the live service reports on it. + assertEquals("wf-cn-parent", successor.getParentWorkflowId(), + "the successor of a child must keep its parent"); + assertEquals(parentRun, successor.getParentRunId()); + assertEquals(child.getParentInitiatedEventId(), successor.getParentInitiatedEventId()); + + // ...and the parent now tracks the successor, not the closed original run. + SwfWorkflowExecution parent = + service.describeWorkflowExecution(REGION, DOMAIN, "wf-cn-parent", parentRun); + assertEquals(successor.getRunId(), parent.getChildExecutions().get("wf-cn-child"), + "the parent must track the successor run, not the closed one"); + + // The successor's started event carries the parent, as the live service does. + SwfHistoryEvent startedEvent = service + .getWorkflowExecutionHistory(REGION, DOMAIN, "wf-cn-child", successor.getRunId(), false) + .get(0); + assertEquals("WorkflowExecutionStarted", startedEvent.getEventType()); + assertNotNull(startedEvent.getAttributes().get("parentWorkflowExecution"), + "the successor's WorkflowExecutionStarted must name the parent"); + } + + @Test + void aBlockingLambdaDoesNotStallOtherExecutionsInTheDomain() throws Exception { + // A decision that schedules a Lambda must not hold the domain lock for the duration of + // the invocation: the lock deliberately covers the whole domain, so a cold start would + // otherwise stall every unrelated execution in it. + CountDownLatch invocationStarted = new CountDownLatch(1); + CountDownLatch releaseInvocation = new CountDownLatch(1); + lambdaGate = new LambdaGate(invocationStarted, releaseInvocation); + + service.registerWorkflowType(REGION, DOMAIN, lambdaWorkflowType("LW", "1", + "arn:aws:iam::000000000000:role/swf-lambda")); + String lambdaRun = service.startWorkflowExecution(new StartWorkflowExecutionRequest( + REGION, DOMAIN, "wf-lambda", "LW", "1", + null, null, null, null, null, null, null, + "arn:aws:iam::000000000000:role/swf-lambda")); + SwfDecisionTask lambdaTask = pollFor("wf-lambda"); + + // A second, unrelated execution in the same domain. + String otherRun = start("wf-other"); + + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + Future scheduling = pool.submit(() -> service.respondDecisionTaskCompleted( + lambdaTask.getTaskToken(), + List.of(new Decision("ScheduleLambdaFunction", + Map.of("id", "lam-1", "name", "blocking-fn"))), + null)); + + assertTrue(invocationStarted.await(5, TimeUnit.SECONDS), + "the Lambda invocation should have been reached"); + + // While the invocation is blocked, an unrelated execution must still progress. + Future signalling = pool.submit(() -> service.signalWorkflowExecution( + REGION, DOMAIN, "wf-other", otherRun, "ping", null)); + try { + signalling.get(5, TimeUnit.SECONDS); + } catch (TimeoutException e) { + releaseInvocation.countDown(); + throw new AssertionError( + "signalling an unrelated execution blocked on the Lambda invocation", e); + } + + releaseInvocation.countDown(); + scheduling.get(10, TimeUnit.SECONDS); + } finally { + releaseInvocation.countDown(); + pool.shutdownNow(); + } + + // The outcome is still recorded on the execution that scheduled it. + assertTrue(service.getWorkflowExecutionHistory(REGION, DOMAIN, "wf-lambda", lambdaRun, false) + .stream().anyMatch(e -> "LambdaFunctionCompleted".equals(e.getEventType())), + "the invocation's result must still be recorded after the lock is released"); + } + + /** Blocks inside invoke() until released, so the test can observe lock behaviour. */ + private record LambdaGate(CountDownLatch started, CountDownLatch release) { + } + + @Test + void aFailedBatchLeavesNoLambdaWorkForTheNextRequestOnTheSameThread() throws Exception { + // The queue of deferred invocations must be scoped to the request, not the thread. To + // reach the window, the store is made to fail *after* a Lambda has been queued and the + // history mutated — the point past which a ThreadLocal queue would survive the throw. + AtomicBoolean failNextPut = new AtomicBoolean(false); + SwfService failing = new SwfService(new FailOnDemandStorageFactory(failNextPut), + new RegionResolver("us-east-1", "000000000000"), clock, recordingLambdaInvoker()); + failing.registerDomain(DOMAIN, "leak test", "7", Map.of(), REGION); + failing.registerWorkflowType(REGION, DOMAIN, workflowType("W", "1")); + failing.registerWorkflowType(REGION, DOMAIN, lambdaWorkflowType("LW", "1", + "arn:aws:iam::000000000000:role/swf-lambda")); + + failing.startWorkflowExecution(new StartWorkflowExecutionRequest( + REGION, DOMAIN, "wf-leak", "LW", "1", null, null, null, null, null, null, null, + "arn:aws:iam::000000000000:role/swf-lambda")); + SwfDecisionTask leaky = failing.pollForDecisionTask(REGION, DOMAIN, "tl", "d") + .orElseThrow(); + + String plainRun = failing.startWorkflowExecution(new StartWorkflowExecutionRequest( + REGION, DOMAIN, "wf-plain", "W", "1", null, null, null, null, null, null, null, null)); + SwfDecisionTask plain = failing.pollForDecisionTask(REGION, DOMAIN, "tl", "d") + .orElseThrow(); + + // Queue a Lambda, then fail while persisting the batch. + failNextPut.set(true); + assertThrows(RuntimeException.class, () -> failing.respondDecisionTaskCompleted( + leaky.getTaskToken(), + List.of(new Decision("ScheduleLambdaFunction", + Map.of("id", "leak-1", "name", "leaked-fn"))), + null)); + failNextPut.set(false); + assertTrue(lambdaInvocations.isEmpty(), + "a request that failed before the drain must not invoke anything: " + lambdaInvocations); + + // A later request on the SAME thread must not inherit that queued invocation. + failing.respondDecisionTaskCompleted(plain.getTaskToken(), + List.of(new Decision("RecordMarker", Map.of("markerName", "m"))), null); + + assertTrue(lambdaInvocations.isEmpty(), + "a later request must not run a failed request's queued Lambda: " + lambdaInvocations); + assertTrue(failing.getWorkflowExecutionHistory(REGION, DOMAIN, "wf-plain", plainRun, false) + .stream().noneMatch(e -> e.getEventType().startsWith("LambdaFunction")), + "no Lambda event may appear on the unrelated execution"); + } + + /** Storage whose put() throws once on demand, to fail a request mid-flight. */ + private static final class FailOnDemandStorageFactory extends StorageFactory { + + private final AtomicBoolean failNextPut; + + private FailOnDemandStorageFactory(AtomicBoolean failNextPut) { + super(null, null); + this.failNextPut = failNextPut; + } + + @Override + public AccountAwareStorageBackend create(String serviceName, String fileName, + TypeReference> typeReference) { + StorageBackend inner = new InMemoryStorage<>(); + if (!"swf-executions.json".equals(fileName)) { + return new AccountAwareStorageBackend<>(inner, null, "000000000000"); + } + StorageBackend failing = new StorageBackend<>() { + @Override + public void put(String key, V value) { + if (failNextPut.get()) { + throw new IllegalStateException("simulated store failure"); + } + inner.put(key, value); + } + + @Override + public Optional get(String key) { + return inner.get(key); + } + + @Override + public void delete(String key) { + inner.delete(key); + } + + @Override + public Set keys() { + return inner.keys(); + } + + @Override + public List scan(java.util.function.Predicate keyFilter) { + return inner.scan(keyFilter); + } + + @Override + public void flush() { + inner.flush(); + } + + @Override + public void load() { + inner.load(); + } + + @Override + public void clear() { + inner.clear(); + } + }; + return new AccountAwareStorageBackend<>(failing, null, "000000000000"); + } + } + + @Test + void listExecutions_separatesOpenFromClosed() { + start("wf-open"); + String closedRunId = start("wf-done"); + SwfDecisionTask decision = pollFor("wf-done"); + service.respondDecisionTaskCompleted(decision.getTaskToken(), + List.of(new Decision("CompleteWorkflowExecution", Map.of())), null); + + List open = service.listExecutions(REGION, DOMAIN, ExecutionFilter.all(), false); + List closed = service.listExecutions(REGION, DOMAIN, ExecutionFilter.all(), true); + + assertTrue(open.stream().anyMatch(e -> "wf-open".equals(e.getWorkflowId()))); + assertFalse(open.stream().anyMatch(e -> "wf-done".equals(e.getWorkflowId()))); + assertTrue(closed.stream() + .anyMatch(e -> "wf-done".equals(e.getWorkflowId()) && closedRunId.equals(e.getRunId()))); + } + + @Test + void deprecatedType_cannotStartAnExecutionButRemainsDescribable() { + service.deprecateWorkflowType(REGION, DOMAIN, "W", "1"); + + AwsException thrown = assertThrows(AwsException.class, () -> start("wf-dep")); + assertEquals("TypeDeprecatedFault", thrown.getErrorCode()); + assertNotNull(service.describeWorkflowType(REGION, DOMAIN, "W", "1")); + + service.undeprecateWorkflowType(REGION, DOMAIN, "W", "1"); + assertNotNull(start("wf-dep")); + } + + @Test + void deleteWorkflowType_requiresPriorDeprecation() { + AwsException thrown = assertThrows(AwsException.class, + () -> service.deleteWorkflowType(REGION, DOMAIN, "W", "1")); + assertEquals("TypeNotDeprecatedFault", thrown.getErrorCode()); + + service.deprecateWorkflowType(REGION, DOMAIN, "W", "1"); + service.deleteWorkflowType(REGION, DOMAIN, "W", "1"); + assertThrows(AwsException.class, () -> service.describeWorkflowType(REGION, DOMAIN, "W", "1")); + } + + @Test + void terminatingAParentAppliesTerminateChildPolicyToItsOpenChildren() { + String parentRunId = start("wf-parent"); + SwfDecisionTask decision = pollFor("wf-parent"); + service.respondDecisionTaskCompleted(decision.getTaskToken(), List.of( + new Decision("StartChildWorkflowExecution", Map.of( + "workflowId", "wf-child", + "workflowType", Map.of("name", "W", "version", "1")))), null); + + SwfWorkflowExecution child = service.describeWorkflowExecution(REGION, DOMAIN, "wf-child", null); + assertEquals("OPEN", child.getExecutionStatus()); + assertEquals("wf-parent", child.getParentWorkflowId()); + + service.terminateWorkflowExecution(REGION, DOMAIN, "wf-parent", parentRunId, "stop", null, null); + + child = service.describeWorkflowExecution(REGION, DOMAIN, "wf-child", child.getRunId()); + assertEquals("CLOSED", child.getExecutionStatus()); + assertEquals("TERMINATED", child.getCloseStatus()); + assertEquals("CHILD_POLICY_APPLIED", lastAttribute(child, "WorkflowExecutionTerminated", "cause")); + } + + @Test + void abandonChildPolicy_leavesChildrenRunning() { + SwfWorkflowType abandoning = workflowType("Abandon", "1"); + abandoning.setDefaultChildPolicy("ABANDON"); + service.registerWorkflowType(REGION, DOMAIN, abandoning); + + String parentRunId = service.startWorkflowExecution(new StartWorkflowExecutionRequest( + REGION, DOMAIN, "wf-abandon", "Abandon", "1", null, null, null, null, null, null, null, null)); + SwfDecisionTask decision = pollFor("wf-abandon"); + service.respondDecisionTaskCompleted(decision.getTaskToken(), List.of( + new Decision("StartChildWorkflowExecution", Map.of( + "workflowId", "wf-abandoned-child", + "workflowType", Map.of("name", "W", "version", "1")))), null); + + service.terminateWorkflowExecution(REGION, DOMAIN, "wf-abandon", parentRunId, null, null, null); + + assertEquals("OPEN", service.describeWorkflowExecution(REGION, DOMAIN, "wf-abandoned-child", null) + .getExecutionStatus()); + } + + @Test + void requestCancelActivityTask_cancelsAScheduledTaskImmediately() { + String runId = start("wf-cancel-act"); + scheduleActivity("wf-cancel-act", "act-cancel"); + + SwfDecisionTask decision = pokeForDecision("wf-cancel-act"); + service.respondDecisionTaskCompleted(decision.getTaskToken(), List.of( + new Decision("RequestCancelActivityTask", Map.of("activityId", "act-cancel"))), null); + + SwfWorkflowExecution execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-cancel-act", runId); + assertNotNull(lastAttribute(execution, "ActivityTaskCancelRequested", "activityId")); + // No worker holds the task, so there is nothing to observe the request: SWF cancels it. + assertNotNull(lastAttribute(execution, "ActivityTaskCanceled", "scheduledEventId")); + assertEquals(0, service.openActivityCount(execution)); + } + + @Test + void activityTokenOnAClosedTask_reportsUnknownActivityWithItsScheduledEventId() { + start("wf-stale-activity"); + scheduleActivity("wf-stale-activity", "act-stale"); + SwfActivityTask task = service.pollForActivityTask(REGION, DOMAIN, "act-tl", "w").orElseThrow(); + service.respondActivityTaskCompleted(task.getTaskToken(), "done"); + + // The token is genuine, so the live service names the scheduled event rather than + // calling the token unknown — a worker that heartbeats after closing sees this. + AwsException thrown = assertThrows(AwsException.class, + () -> service.recordActivityTaskHeartbeat(task.getTaskToken(), "late")); + assertEquals("UnknownResourceFault", thrown.getErrorCode()); + assertEquals("Unknown activity, scheduledEventId = " + task.getScheduledEventId(), + thrown.getMessage()); + + // A token that never existed still reports the bad token instead. + assertEquals("Unknown or expired task token", + assertThrows(AwsException.class, + () -> service.recordActivityTaskHeartbeat("bogus", null)).getMessage()); + } + + @Test + void heartbeatReportsCancelRequested_afterTheDeciderAsksToCancelAStartedTask() { + start("wf-cancel-started"); + scheduleActivity("wf-cancel-started", "act-running"); + SwfActivityTask task = service.pollForActivityTask(REGION, DOMAIN, "act-tl", "w").orElseThrow(); + + SwfDecisionTask decision = pokeForDecision("wf-cancel-started"); + service.respondDecisionTaskCompleted(decision.getTaskToken(), List.of( + new Decision("RequestCancelActivityTask", Map.of("activityId", "act-running"))), null); + + assertTrue(service.recordActivityTaskHeartbeat(task.getTaskToken(), null), + "the worker learns about the cancellation through its heartbeat"); + service.respondActivityTaskCanceled(task.getTaskToken(), "stopped"); + + SwfWorkflowExecution execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-cancel-started", null); + assertEquals("stopped", lastAttribute(execution, "ActivityTaskCanceled", "details")); + } + + @Test + void scheduleActivityTask_withUnknownType_recordsFailureAndKeepsTheExecutionOpen() { + String runId = start("wf-bad-type"); + SwfDecisionTask decision = service.pollForDecisionTask(REGION, DOMAIN, "tl", "d").orElseThrow(); + + service.respondDecisionTaskCompleted(decision.getTaskToken(), List.of( + new Decision("ScheduleActivityTask", Map.of( + "activityId", "nope", + "activityType", Map.of("name", "Missing", "version", "9")))), null); + + SwfWorkflowExecution execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-bad-type", runId); + assertEquals("ACTIVITY_TYPE_DOES_NOT_EXIST", + lastAttribute(execution, "ScheduleActivityTaskFailed", "cause")); + assertEquals("OPEN", execution.getExecutionStatus()); + assertTrue(service.pollForDecisionTask(REGION, DOMAIN, "tl", "d2").isPresent(), + "a failed decision must give the decider another chance"); + } + + @Test + void continueAsNew_closesTheRunAndLinksTheSuccessor() { + String firstRunId = start("wf-can"); + SwfDecisionTask decision = pollFor("wf-can"); + service.respondDecisionTaskCompleted(decision.getTaskToken(), List.of( + new Decision("ContinueAsNewWorkflowExecution", Map.of("input", "gen-2"))), null); + + SwfWorkflowExecution closed = service.describeWorkflowExecution(REGION, DOMAIN, "wf-can", firstRunId); + assertEquals("CONTINUED_AS_NEW", closed.getCloseStatus()); + + String newRunId = (String) lastAttribute(closed, "WorkflowExecutionContinuedAsNew", "newExecutionRunId"); + assertNotNull(newRunId); + SwfWorkflowExecution successor = service.describeWorkflowExecution(REGION, DOMAIN, "wf-can", newRunId); + assertEquals("OPEN", successor.getExecutionStatus()); + assertEquals(firstRunId, successor.getContinuedExecutionRunId()); + assertEquals("gen-2", successor.getInput()); + } + + @Test + void signalExternalWorkflowExecution_deliversToTheTargetAndConfirmsToTheSender() { + start("wf-sender"); + start("wf-receiver"); + + SwfDecisionTask decision = pollFor("wf-sender"); + service.respondDecisionTaskCompleted(decision.getTaskToken(), List.of( + new Decision("SignalExternalWorkflowExecution", Map.of( + "workflowId", "wf-receiver", "signalName", "ping", "input", "hello"))), null); + + SwfWorkflowExecution receiver = service.describeWorkflowExecution(REGION, DOMAIN, "wf-receiver", null); + assertEquals("ping", lastAttribute(receiver, "WorkflowExecutionSignaled", "signalName")); + assertEquals("hello", lastAttribute(receiver, "WorkflowExecutionSignaled", "input")); + + SwfWorkflowExecution sender = service.describeWorkflowExecution(REGION, DOMAIN, "wf-sender", null); + assertNotNull(lastAttribute(sender, "ExternalWorkflowExecutionSignaled", "initiatedEventId")); + } + + @Test + void signalUnknownExternalExecution_recordsFailureRatherThanThrowing() { + start("wf-lonely"); + SwfDecisionTask decision = pollFor("wf-lonely"); + + service.respondDecisionTaskCompleted(decision.getTaskToken(), List.of( + new Decision("SignalExternalWorkflowExecution", Map.of( + "workflowId", "not-there", "signalName", "ping"))), null); + + SwfWorkflowExecution execution = service.describeWorkflowExecution(REGION, DOMAIN, "wf-lonely", null); + assertEquals("UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION", + lastAttribute(execution, "SignalExternalWorkflowExecutionFailed", "cause")); + } + + @Test + void registerDomain_rejectsARetentionPeriodOutsideTheAllowedRange() { + AwsException thrown = assertThrows(AwsException.class, + () -> service.registerDomain("bad-retention", null, "500", Map.of(), "us-east-1")); + assertEquals("ValidationException", thrown.getErrorCode()); + + // NONE is the documented sentinel for "keep forever" and must be accepted. + service.registerDomain("no-retention", null, "NONE", Map.of(), REGION); + assertEquals("NONE", service.describeDomain(REGION, "no-retention") + .getWorkflowExecutionRetentionPeriodInDays()); + } + + @Test + void tagResource_roundTripsThroughTheDomainArn() { + String arn = service.domainArnFor(service.describeDomain(REGION, DOMAIN), "us-east-1"); + assertEquals("arn:aws:swf:us-east-1:000000000000:/domain/" + DOMAIN, arn); + + service.tagResource(arn, Map.of("env", "unit")); + assertEquals("unit", service.listTagsForResource(arn).get("env")); + + service.untagResource(arn, List.of("env")); + assertTrue(service.listTagsForResource(arn).isEmpty()); + } + + // ── helpers ───────────────────────────────────────────────────────────── + + private String start(String workflowId) { + return service.startWorkflowExecution(new StartWorkflowExecutionRequest( + REGION, DOMAIN, workflowId, "W", "1", null, null, null, null, null, null, null, null)); + } + + /** + * Schedules {@code activityId} onto the {@code act-tl} list via a decision. + * + *

A successful ScheduleActivityTask does not schedule a further decision task — the + * decider waits for the activity to close — so callers that need another decision task + * while the activity is open should use {@link #pokeForDecision(String)}. + */ + private void scheduleActivity(String workflowId, String activityId) { + SwfDecisionTask decision = pollFor(workflowId); + service.respondDecisionTaskCompleted(decision.getTaskToken(), List.of( + new Decision("ScheduleActivityTask", Map.of( + "activityId", activityId, + "activityType", Map.of("name", "A", "version", "1")))), null); + } + + /** Signals the execution so a decision task is scheduled, then claims it. */ + private SwfDecisionTask pokeForDecision(String workflowId) { + service.signalWorkflowExecution(REGION, DOMAIN, workflowId, null, "poke", null); + return pollFor(workflowId); + } + + /** + * Claims decision tasks until one belongs to {@code workflowId}; sibling executions in + * the same domain share the {@code tl} task list. + * + *

Tolerates a transient empty poll so the concurrency tests can call this from + * several threads: another thread may hold the task this caller wants at that instant. + */ + private SwfDecisionTask pollFor(String workflowId) { + for (int attempt = 0; attempt < 200; attempt++) { + Optional claimed = service.pollForDecisionTask(REGION, DOMAIN, "tl", "d"); + if (claimed.isPresent()) { + SwfDecisionTask task = claimed.get(); + if (workflowId.equals(task.getWorkflowId())) { + return task; + } + // Release a sibling's task so its own poller can claim it. + service.respondDecisionTaskCompleted(task.getTaskToken(), List.of(), null); + continue; + } + try { + Thread.sleep(5); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } + throw new AssertionError("no decision task for " + workflowId); + } + + private Object lastAttribute(SwfWorkflowExecution execution, String eventType, String attribute) { + List events = execution.getEvents(); + for (int i = events.size() - 1; i >= 0; i--) { + if (eventType.equals(events.get(i).getEventType())) { + return events.get(i).getAttributes().get(attribute); + } + } + return null; + } + + private static SwfWorkflowType workflowType(String name, String version) { + SwfWorkflowType type = new SwfWorkflowType(); + type.setName(name); + type.setVersion(version); + type.setDefaultTaskList("tl"); + type.setDefaultExecutionStartToCloseTimeout("300"); + type.setDefaultTaskStartToCloseTimeout("10"); + type.setDefaultChildPolicy("TERMINATE"); + return type; + } + + private static SwfActivityType activityType(String name, String version) { + SwfActivityType type = new SwfActivityType(); + type.setName(name); + type.setVersion(version); + type.setDefaultTaskList("act-tl"); + type.setDefaultTaskScheduleToStartTimeout("30"); + type.setDefaultTaskStartToCloseTimeout("60"); + type.setDefaultTaskScheduleToCloseTimeout("NONE"); + type.setDefaultTaskHeartbeatTimeout("NONE"); + return type; + } + + /** A workflow type carrying a {@code defaultLambdaRole}, which SWF requires to invoke Lambda. */ + private static SwfWorkflowType lambdaWorkflowType(String name, String version, String role) { + SwfWorkflowType type = workflowType(name, version); + type.setDefaultLambdaRole(role); + return type; + } + + private String startLambdaWf(String workflowId, String typeName) { + return service.startWorkflowExecution(new StartWorkflowExecutionRequest( + REGION, DOMAIN, workflowId, typeName, "1", null, null, null, null, null, null, null, null)); + } + + private static Decision scheduleLambda(String id, String name, String input, + String control, String startToCloseTimeout) { + Map attrs = new LinkedHashMap<>(); + attrs.put("id", id); + attrs.put("name", name); + if (input != null) { + attrs.put("input", input); + } + if (control != null) { + attrs.put("control", control); + } + if (startToCloseTimeout != null) { + attrs.put("startToCloseTimeout", startToCloseTimeout); + } + return new Decision("ScheduleLambdaFunction", attrs); + } + + private static SwfHistoryEvent eventOfType(List events, String eventType) { + return events.stream() + .filter(e -> eventType.equals(e.getEventType())) + .findFirst() + .orElseThrow(() -> new AssertionError("no " + eventType + " in " + + events.stream().map(SwfHistoryEvent::getEventType).toList())); + } + + /** + * Minimal in-memory {@link StorageFactory} so the service under test needs no Quarkus + * container. Only {@link StorageFactory#create} is exercised by SwfService. + */ + private static final class InMemoryStorageFactory extends StorageFactory { + + InMemoryStorageFactory() { + super(null, null); + } + + @Override + public synchronized AccountAwareStorageBackend create( + String serviceName, String fileName, TypeReference> typeReference) { + return AccountAwareStorageBackend.inMemory("000000000000"); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/swf/SwfTimeoutSweeperTest.java b/src/test/java/io/github/hectorvent/floci/services/swf/SwfTimeoutSweeperTest.java new file mode 100644 index 0000000000..92c0daf8f9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/swf/SwfTimeoutSweeperTest.java @@ -0,0 +1,64 @@ +package io.github.hectorvent.floci.services.swf; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.quarkus.runtime.StartupEvent; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +/** + * The sweep interval reaches {@code scheduleWithFixedDelay}, which rejects a non-positive + * delay. Because the schedule happens in a {@link StartupEvent} observer, an + * IllegalArgumentException there stops the whole emulator from becoming ready — so a + * misconfigured interval must not be passed through unchecked. + */ +class SwfTimeoutSweeperTest { + + @Test + void nonPositiveConfiguredInterval_doesNotPreventStartup() { + for (long interval : new long[] {0L, -1L, Long.MIN_VALUE}) { + SwfTimeoutSweeper sweeper = new SwfTimeoutSweeper(null, configWithInterval(interval)); + assertDoesNotThrow(() -> sweeper.onStart(new StartupEvent()), + "interval " + interval + " must not abort startup"); + sweeper.onStop(new io.quarkus.runtime.ShutdownEvent()); + } + } + + @Test + void positiveConfiguredInterval_startsNormally() { + SwfTimeoutSweeper sweeper = new SwfTimeoutSweeper(null, configWithInterval(30L)); + assertDoesNotThrow(() -> sweeper.onStart(new StartupEvent())); + sweeper.onStop(new io.quarkus.runtime.ShutdownEvent()); + } + + /** + * Minimal {@link EmulatorConfig} view: the sweeper reads only the three SWF settings, so + * a proxy answering those avoids standing up the Quarkus config container. + */ + private static EmulatorConfig configWithInterval(long intervalSeconds) { + Map answers = Map.of( + "enabled", Boolean.TRUE, + "timeoutSweepEnabled", Boolean.TRUE, + "timeoutSweepIntervalSeconds", intervalSeconds); + + InvocationHandler handler = new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) { + Object answer = answers.get(method.getName()); + if (answer != null) { + return answer; + } + // services() and swf() return further config views; proxy those too. + return Proxy.newProxyInstance(method.getReturnType().getClassLoader(), + new Class[] {method.getReturnType()}, this); + } + }; + return (EmulatorConfig) Proxy.newProxyInstance(EmulatorConfig.class.getClassLoader(), + new Class[] {EmulatorConfig.class}, handler); + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 3b3021508a..4bed797ec7 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -182,6 +182,10 @@ floci: stepfunctions: enabled: true allow-plaintext-http: true + swf: + enabled: true + timeout-sweep-enabled: true + timeout-sweep-interval-seconds: 1 cloudformation: enabled: true acm: diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index 3054bdcae5..b4c3b0f54a 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -88,6 +88,10 @@ services: doc: docs/services/step-functions.md sources: - { path: src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsJsonHandler.java, mode: switch } + - service: swf + doc: docs/services/swf.md + sources: + - { path: src/main/java/io/github/hectorvent/floci/services/swf/SwfJsonHandler.java, mode: switch } - service: wafv2 doc: docs/services/wafv2.md sources: