mirror of
https://github.com/floci-io/floci.git
synced 2026-11-30 17:05:21 -05:00
feat(swf): add Simple Workflow Service emulation
Implements all 39 SWF operations over the JSON 1.0 protocol
(X-Amz-Target: SimpleWorkflowService.*): domain and type registration,
the workflow execution state machine, and the decider/worker task
lifecycle.
Behaviour was derived from botocore's swf-2012-01-25 model and verified
against the live service, which drove several details that are easy to
get wrong from the model alone:
- Faults carry a namespaced __type (com.amazonaws.swf.base.model#Fault)
in the body but the bare fault name in x-amzn-query-error. botocore
prefers the header, so a namespaced value there makes the CLI print
"com.amazonaws.swf.base.model#UnknownResourceFault" where SWF prints
"UnknownResourceFault". SwfException keeps the two spellings apart.
- Timestamps are epoch-second numbers, not ISO strings.
- Void operations answer 200 with an empty body rather than {}.
- An idle poll returns taskToken "" rather than omitting the member;
the SDKs read the empty token as "no task".
- ActivityTaskTimedOut reports startedEventId 0 for a task that never
started, and WorkflowExecutionStarted reports parentInitiatedEventId 0
on root executions, rather than omitting either member.
State machine:
- One decision task outstanding per execution. Events arriving while one
is outstanding set a pending flag that is satisfied when it completes,
so a signal cannot produce two concurrent decision tasks.
- Decisions apply in order; a decision after a closing decision is
dropped. A decision that cannot be applied appends its *Failed event
with the AWS cause and gives the decider a fresh task instead of
failing the request.
- Closing with open activities, timers, or children appends
UNHANDLED_DECISION and leaves the execution open.
- Timeouts (activity schedule-to-start, start-to-close,
schedule-to-close, heartbeat; decision start-to-close; execution
start-to-close; timers) expire from one background sweep rather than a
timer per task, so a restart leaves nothing to reconcile.
- Child executions link to their parent and report their outcome back;
the closing parent's childPolicy is applied to open children.
Tests: 29 unit tests drive timeout expiry through a controllable clock,
32 integration tests assert the wire shapes and fault strings captured
from the live service, and a compatibility suite exercises the same
flows through the AWS SDK v2 client so responses must deserialize into
the generated model and faults into typed exceptions.
Long polling, ScheduleLambdaFunction invocation, and retention-based
pruning are not implemented; docs/services/swf.md records each.
Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
28 files changed
+6572
-2
No files matched your search
@@ -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 |
|
||||
| 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 |
|
||||
|
||||
@@ -132,6 +132,10 @@
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>sfn</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>swf</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>iam</artifactId>
|
||||
|
||||
@@ -33,6 +33,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;
|
||||
@@ -580,6 +581,14 @@ public final class TestFixtures {
|
||||
.build();
|
||||
}
|
||||
|
||||
public static SwfClient swfClient() {
|
||||
return SwfClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
.region(REGION)
|
||||
.credentialsProvider(CREDENTIALS)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static SesClient sesClient() {
|
||||
return SesClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<HistoryEvent> 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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
# 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
|
||||
|
||||
<!-- floci:actions:start -->
|
||||
| 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 |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
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` | Recorded as `ScheduleLambdaFunctionFailed` with cause `LAMBDA_SERVICE_NOT_AVAILABLE_IN_REGION` (see [Limitations](#limitations)) |
|
||||
|
||||
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. Decisions that follow a closing decision are dropped.
|
||||
|
||||
## 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.
|
||||
|
||||
## 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=<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 |
|
||||
| `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 or a value outside an enum |
|
||||
|
||||
## 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.
|
||||
- **`ScheduleLambdaFunction`.** Lambda-backed activities are recorded as
|
||||
`ScheduleLambdaFunctionFailed` rather than invoking a function, so a decider that uses
|
||||
them keeps making progress instead of waiting for an event that never arrives.
|
||||
- **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; tokens are opaque
|
||||
offsets and are not interchangeable with real SWF tokens.
|
||||
@@ -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
|
||||
|
||||
@@ -550,6 +550,7 @@ public interface EmulatorConfig {
|
||||
KmsServiceConfig kms();
|
||||
CognitoServiceConfig cognito();
|
||||
StepFunctionsServiceConfig stepfunctions();
|
||||
SwfServiceConfig swf();
|
||||
CloudFormationServiceConfig cloudformation();
|
||||
AcmServiceConfig acm();
|
||||
AthenaServiceConfig athena();
|
||||
@@ -1076,6 +1077,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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -201,6 +201,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),
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
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.
|
||||
*
|
||||
* <p>SWF answers every modeled fault with HTTP 400 and a namespaced {@code __type}
|
||||
* of {@code com.amazonaws.swf.base.model#<Fault>} (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");
|
||||
}
|
||||
|
||||
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 + "]");
|
||||
}
|
||||
|
||||
static AwsException workflowTypeNotDeprecated(String name, String version) {
|
||||
return fault(SwfConstants.TYPE_NOT_DEPRECATED,
|
||||
"WorkflowType=[name=" + name + ", version=" + version + "]");
|
||||
}
|
||||
|
||||
static AwsException activityTypeNotDeprecated(String name, String version) {
|
||||
return fault(SwfConstants.TYPE_NOT_DEPRECATED,
|
||||
"ActivityType=[name=" + name + ", version=" + version + "]");
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,730 @@
|
||||
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.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Translates the SWF JSON 1.0 wire protocol to and from {@link SwfService}.
|
||||
*
|
||||
* <p>Two wire details this class is responsible for:
|
||||
* <ul>
|
||||
* <li>Timestamps are epoch-second numbers, not ISO strings — the AWS SDKs parse
|
||||
* {@code 1.786560427599E9} and reject a formatted date.</li>
|
||||
* <li>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.</li>
|
||||
* </ul>
|
||||
*/
|
||||
@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(text(request, "name")));
|
||||
case "UndeprecateDomain" -> voidResponse(() -> service.undeprecateDomain(text(request, "name")));
|
||||
|
||||
case "RegisterWorkflowType" -> registerWorkflowType(request);
|
||||
case "DescribeWorkflowType" -> describeWorkflowType(request);
|
||||
case "ListWorkflowTypes" -> listWorkflowTypes(request);
|
||||
case "DeprecateWorkflowType" -> voidResponse(() -> service.deprecateWorkflowType(
|
||||
text(request, "domain"), nested(request, "workflowType", "name"),
|
||||
nested(request, "workflowType", "version")));
|
||||
case "UndeprecateWorkflowType" -> voidResponse(() -> service.undeprecateWorkflowType(
|
||||
text(request, "domain"), nested(request, "workflowType", "name"),
|
||||
nested(request, "workflowType", "version")));
|
||||
case "DeleteWorkflowType" -> voidResponse(() -> service.deleteWorkflowType(
|
||||
text(request, "domain"), nested(request, "workflowType", "name"),
|
||||
nested(request, "workflowType", "version")));
|
||||
|
||||
case "RegisterActivityType" -> registerActivityType(request);
|
||||
case "DescribeActivityType" -> describeActivityType(request);
|
||||
case "ListActivityTypes" -> listActivityTypes(request);
|
||||
case "DeprecateActivityType" -> voidResponse(() -> service.deprecateActivityType(
|
||||
text(request, "domain"), nested(request, "activityType", "name"),
|
||||
nested(request, "activityType", "version")));
|
||||
case "UndeprecateActivityType" -> voidResponse(() -> service.undeprecateActivityType(
|
||||
text(request, "domain"), nested(request, "activityType", "name"),
|
||||
nested(request, "activityType", "version")));
|
||||
case "DeleteActivityType" -> voidResponse(() -> service.deleteActivityType(
|
||||
text(request, "domain"), nested(request, "activityType", "name"),
|
||||
nested(request, "activityType", "version")));
|
||||
|
||||
case "StartWorkflowExecution" -> startWorkflowExecution(request);
|
||||
case "DescribeWorkflowExecution" -> describeWorkflowExecution(request);
|
||||
case "GetWorkflowExecutionHistory" -> getWorkflowExecutionHistory(request);
|
||||
case "ListOpenWorkflowExecutions" -> listExecutions(request, false);
|
||||
case "ListClosedWorkflowExecutions" -> listExecutions(request, true);
|
||||
case "CountOpenWorkflowExecutions" -> countExecutions(request, false);
|
||||
case "CountClosedWorkflowExecutions" -> countExecutions(request, true);
|
||||
case "CountPendingActivityTasks" -> count(service.countPendingActivityTasks(
|
||||
text(request, "domain"), nested(request, "taskList", "name")));
|
||||
case "CountPendingDecisionTasks" -> count(service.countPendingDecisionTasks(
|
||||
text(request, "domain"), nested(request, "taskList", "name")));
|
||||
|
||||
case "PollForDecisionTask" -> pollForDecisionTask(request);
|
||||
case "RespondDecisionTaskCompleted" -> respondDecisionTaskCompleted(request);
|
||||
case "PollForActivityTask" -> pollForActivityTask(request);
|
||||
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(
|
||||
text(request, "domain"), text(request, "workflowId"), text(request, "runId"),
|
||||
text(request, "signalName"), text(request, "input")));
|
||||
case "RequestCancelWorkflowExecution" -> voidResponse(() -> service.requestCancelWorkflowExecution(
|
||||
text(request, "domain"), text(request, "workflowId"), text(request, "runId")));
|
||||
case "TerminateWorkflowExecution" -> voidResponse(() -> service.terminateWorkflowExecution(
|
||||
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(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<SwfDomain> domains = service.listDomains(text(request, "registrationStatus"));
|
||||
if (request.path("reverseOrder").asBoolean(false)) {
|
||||
domains = new ArrayList<>(domains);
|
||||
java.util.Collections.reverse(domains);
|
||||
}
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode infos = response.putArray("domainInfos");
|
||||
for (SwfDomain domain : domains) {
|
||||
infos.add(domainInfo(domain, region));
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
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) {
|
||||
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(text(request, "domain"), type);
|
||||
return empty();
|
||||
}
|
||||
|
||||
private Response describeWorkflowType(JsonNode request) {
|
||||
SwfWorkflowType type = service.describeWorkflowType(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) {
|
||||
List<SwfWorkflowType> types = service.listWorkflowTypes(text(request, "domain"), text(request, "name"),
|
||||
text(request, "registrationStatus"), request.path("reverseOrder").asBoolean(false));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode infos = response.putArray("typeInfos");
|
||||
for (SwfWorkflowType type : types) {
|
||||
infos.add(workflowTypeInfo(type));
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
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) {
|
||||
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(text(request, "domain"), type);
|
||||
return empty();
|
||||
}
|
||||
|
||||
private Response describeActivityType(JsonNode request) {
|
||||
SwfActivityType type = service.describeActivityType(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) {
|
||||
List<SwfActivityType> types = service.listActivityTypes(text(request, "domain"), text(request, "name"),
|
||||
text(request, "registrationStatus"), request.path("reverseOrder").asBoolean(false));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode infos = response.putArray("typeInfos");
|
||||
for (SwfActivityType type : types) {
|
||||
infos.add(activityTypeInfo(type));
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
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 runId = service.startWorkflowExecution(new StartWorkflowExecutionRequest(
|
||||
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) {
|
||||
SwfWorkflowExecution execution = service.describeWorkflowExecution(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();
|
||||
}
|
||||
|
||||
private Response getWorkflowExecutionHistory(JsonNode request) {
|
||||
boolean reverseOrder = request.path("reverseOrder").asBoolean(false);
|
||||
List<SwfHistoryEvent> events = service.getWorkflowExecutionHistory(text(request, "domain"),
|
||||
nested(request, "execution", "workflowId"), nested(request, "execution", "runId"), reverseOrder);
|
||||
|
||||
int pageSize = service.historyPageSize(optionalInt(request, "maximumPageSize"));
|
||||
int offset = decodePageToken(text(request, "nextPageToken"));
|
||||
int end = Math.min(offset + pageSize, events.size());
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode array = response.putArray("events");
|
||||
for (SwfHistoryEvent event : events.subList(Math.min(offset, events.size()), end)) {
|
||||
array.add(historyEvent(event));
|
||||
}
|
||||
if (end < events.size()) {
|
||||
response.put("nextPageToken", encodePageToken(end));
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response listExecutions(JsonNode request, boolean closed) {
|
||||
List<SwfWorkflowExecution> executions = service.listExecutions(text(request, "domain"),
|
||||
buildFilter(request, closed), closed);
|
||||
if (request.path("reverseOrder").asBoolean(false)) {
|
||||
executions = new ArrayList<>(executions);
|
||||
java.util.Collections.reverse(executions);
|
||||
}
|
||||
|
||||
int pageSize = service.historyPageSize(optionalInt(request, "maximumPageSize"));
|
||||
int offset = decodePageToken(text(request, "nextPageToken"));
|
||||
int end = Math.min(offset + pageSize, executions.size());
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode array = response.putArray("executionInfos");
|
||||
for (SwfWorkflowExecution execution : executions.subList(Math.min(offset, executions.size()), end)) {
|
||||
array.add(executionInfo(execution));
|
||||
}
|
||||
if (end < executions.size()) {
|
||||
response.put("nextPageToken", encodePageToken(end));
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response countExecutions(JsonNode request, boolean closed) {
|
||||
List<SwfWorkflowExecution> executions = service.listExecutions(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<SwfWorkflowExecution> 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 ────────────────────────────
|
||||
|
||||
private Response pollForDecisionTask(JsonNode request) {
|
||||
Optional<SwfDecisionTask> maybeTask = service.pollForDecisionTask(text(request, "domain"),
|
||||
nested(request, "taskList", "name"), text(request, "identity"));
|
||||
if (maybeTask.isEmpty()) {
|
||||
return Response.ok(emptyPollResponse()).build();
|
||||
}
|
||||
|
||||
SwfDecisionTask task = maybeTask.get();
|
||||
boolean reverseOrder = request.path("reverseOrder").asBoolean(false);
|
||||
List<SwfHistoryEvent> events = service.getWorkflowExecutionHistory(task.getDomain(),
|
||||
task.getWorkflowId(), task.getRunId(), reverseOrder);
|
||||
|
||||
int pageSize = service.historyPageSize(optionalInt(request, "maximumPageSize"));
|
||||
int offset = decodePageToken(text(request, "nextPageToken"));
|
||||
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));
|
||||
}
|
||||
|
||||
SwfWorkflowExecution execution = service.describeWorkflowExecution(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) {
|
||||
Optional<SwfActivityTask> maybeTask = service.pollForActivityTask(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 <type>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<Decision> parseDecisions(JsonNode decisionsNode) {
|
||||
List<Decision> 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<String, String> 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<String, String> parseTags(JsonNode tagsNode) {
|
||||
Map<String, String> 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<String> parseStringList(JsonNode arrayNode) {
|
||||
if (arrayNode == null || !arrayNode.isArray()) {
|
||||
return null;
|
||||
}
|
||||
List<String> values = new ArrayList<>();
|
||||
for (JsonNode node : arrayNode) {
|
||||
values.add(node.asText());
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Map<String, Object> toMap(JsonNode node) {
|
||||
if (node == null || !node.isObject()) {
|
||||
return Map.of();
|
||||
}
|
||||
return objectMapper.convertValue(node, Map.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Page tokens are an opaque offset. SWF's own tokens are opaque blobs, so callers must
|
||||
* not parse them; a malformed token restarts from the beginning rather than faulting,
|
||||
* which is what the live service does with a stale token.
|
||||
*/
|
||||
private static String encodePageToken(int offset) {
|
||||
return java.util.Base64.getEncoder()
|
||||
.encodeToString(("offset=" + offset).getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static int decodePageToken(String token) {
|
||||
if (token == null || token.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
String decoded = new String(java.util.Base64.getDecoder().decode(token),
|
||||
java.nio.charset.StandardCharsets.UTF_8);
|
||||
return Integer.parseInt(decoded.substring("offset=".length()));
|
||||
} catch (IllegalArgumentException | IndexOutOfBoundsException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,68 @@
|
||||
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.
|
||||
*
|
||||
* <p>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);
|
||||
|
||||
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 = config.services().swf().timeoutSweepIntervalSeconds();
|
||||
this.executor = Executors.newSingleThreadScheduledExecutor(runnable -> {
|
||||
Thread thread = new Thread(runnable, "swf-timeout-sweeper");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package io.github.hectorvent.floci.services.swf.model;
|
||||
|
||||
/**
|
||||
* Wire-level constants shared by the SWF service and handler.
|
||||
*
|
||||
* <p>SWF reports faults with a namespaced {@code __type} of
|
||||
* {@code com.amazonaws.swf.base.model#<Fault>} 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#";
|
||||
|
||||
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() {
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<String, String> 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<String, String> getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public void setTags(Map<String, String> tags) {
|
||||
this.tags = tags != null ? tags : new LinkedHashMap<>();
|
||||
}
|
||||
|
||||
public boolean isDeprecated() {
|
||||
return SwfConstants.STATUS_DEPRECATED.equals(status);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>On the wire an event carries exactly one {@code <camelCaseEventType>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<String, Object> 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<String, Object> getAttributes() {
|
||||
return attributes;
|
||||
}
|
||||
|
||||
public void setAttributes(Map<String, Object> 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";
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+326
@@ -0,0 +1,326 @@
|
||||
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 {
|
||||
|
||||
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<String> 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;
|
||||
private String continuedExecutionRunId;
|
||||
|
||||
private long nextEventId = 1;
|
||||
private List<SwfHistoryEvent> 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<String, SwfActivityTask> activities = new LinkedHashMap<>();
|
||||
private Map<String, SwfTimer> timers = new LinkedHashMap<>();
|
||||
/** Child workflow runIds keyed by the initiating decision's workflowId. */
|
||||
private Map<String, String> childExecutions = new LinkedHashMap<>();
|
||||
|
||||
private Double latestActivityTaskTimestamp;
|
||||
private String latestExecutionContext;
|
||||
|
||||
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<String> getTagList() {
|
||||
return tagList;
|
||||
}
|
||||
|
||||
public void setTagList(List<String> 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 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<SwfHistoryEvent> getEvents() {
|
||||
return events;
|
||||
}
|
||||
|
||||
public void setEvents(List<SwfHistoryEvent> 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<String, SwfActivityTask> getActivities() {
|
||||
return activities;
|
||||
}
|
||||
|
||||
public void setActivities(Map<String, SwfActivityTask> activities) {
|
||||
this.activities = activities != null ? activities : new LinkedHashMap<>();
|
||||
}
|
||||
|
||||
public Map<String, SwfTimer> getTimers() {
|
||||
return timers;
|
||||
}
|
||||
|
||||
public void setTimers(Map<String, SwfTimer> timers) {
|
||||
this.timers = timers != null ? timers : new LinkedHashMap<>();
|
||||
}
|
||||
|
||||
public Map<String, String> getChildExecutions() {
|
||||
return childExecutions;
|
||||
}
|
||||
|
||||
public void setChildExecutions(Map<String, String> 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++;
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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);
|
||||
}
|
||||
}
|
||||
@@ -309,6 +309,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:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,600 @@
|
||||
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.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.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
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 DOMAIN = "unit-domain";
|
||||
|
||||
private MutableClock clock;
|
||||
private SwfService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
clock = new MutableClock();
|
||||
service = new SwfService(new InMemoryStorageFactory(),
|
||||
new RegionResolver("us-east-1", "000000000000"), clock);
|
||||
|
||||
service.registerDomain(DOMAIN, "unit test domain", "7", Map.of(), "us-east-1");
|
||||
service.registerWorkflowType(DOMAIN, workflowType("W", "1"));
|
||||
service.registerActivityType(DOMAIN, activityType("A", "1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void startWorkflowExecution_seedsStartedAndDecisionTaskScheduledEvents() {
|
||||
String runId = start("wf-1");
|
||||
|
||||
List<SwfHistoryEvent> events = service.getWorkflowExecutionHistory(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(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(DOMAIN, bare);
|
||||
|
||||
AwsException thrown = assertThrows(AwsException.class, () -> service.startWorkflowExecution(
|
||||
new StartWorkflowExecutionRequest(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("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(DOMAIN, "tl", "d1").isPresent());
|
||||
assertTrue(service.pollForDecisionTask(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(DOMAIN, "tl", "d1").orElseThrow();
|
||||
|
||||
service.signalWorkflowExecution(DOMAIN, "wf-defer", runId, "poke", null);
|
||||
assertTrue(service.pollForDecisionTask(DOMAIN, "tl", "d2").isEmpty(),
|
||||
"the signal must not create a concurrent decision task");
|
||||
|
||||
service.respondDecisionTaskCompleted(first.getTaskToken(), List.of(), null);
|
||||
assertTrue(service.pollForDecisionTask(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_dropsDecisionsAfterAClosingDecision() {
|
||||
String runId = start("wf-after-close");
|
||||
SwfDecisionTask task = service.pollForDecisionTask(DOMAIN, "tl", "d").orElseThrow();
|
||||
|
||||
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);
|
||||
|
||||
SwfWorkflowExecution execution = service.describeWorkflowExecution(DOMAIN, "wf-after-close", runId);
|
||||
assertEquals("CLOSED", execution.getExecutionStatus());
|
||||
assertEquals("COMPLETED", execution.getCloseStatus());
|
||||
assertTrue(execution.getActivities().isEmpty(),
|
||||
"a decision after the closing decision must be dropped");
|
||||
}
|
||||
|
||||
@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(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(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(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(DOMAIN, "act-tl", "w").orElseThrow();
|
||||
assertEquals("act-s2c", task.getActivityId());
|
||||
|
||||
clock.advance(Duration.ofSeconds(61));
|
||||
service.sweep();
|
||||
|
||||
SwfWorkflowExecution execution = service.describeWorkflowExecution(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(DOMAIN, heartbeating);
|
||||
|
||||
start("wf-hb");
|
||||
SwfDecisionTask decision = service.pollForDecisionTask(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(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(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(DOMAIN, "wf-hb", null);
|
||||
assertEquals("HEARTBEAT", lastAttribute(execution, "ActivityTaskTimedOut", "timeoutType"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void decisionTaskStartToCloseTimeout_reschedulesTheTaskForAnotherDecider() {
|
||||
String runId = start("wf-dt-timeout");
|
||||
SwfDecisionTask abandoned = service.pollForDecisionTask(DOMAIN, "tl", "dead").orElseThrow();
|
||||
|
||||
clock.advance(Duration.ofSeconds(11));
|
||||
service.sweep();
|
||||
|
||||
SwfWorkflowExecution execution = service.describeWorkflowExecution(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(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(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(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(DOMAIN, "wf-timer", runId)));
|
||||
|
||||
clock.advance(Duration.ofSeconds(31));
|
||||
service.sweep();
|
||||
|
||||
SwfWorkflowExecution execution = service.describeWorkflowExecution(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(DOMAIN, "tl", "d").orElseThrow();
|
||||
service.respondDecisionTaskCompleted(decision.getTaskToken(),
|
||||
List.of(new Decision("CompleteWorkflowExecution", Map.of("result", "ok"))), null);
|
||||
int eventCount = service.getWorkflowExecutionHistory(DOMAIN, "wf-closed", runId, false).size();
|
||||
|
||||
clock.advance(Duration.ofHours(2));
|
||||
service.sweep();
|
||||
|
||||
assertEquals(eventCount,
|
||||
service.getWorkflowExecutionHistory(DOMAIN, "wf-closed", runId, false).size(),
|
||||
"a closed execution must not accrue timeout events");
|
||||
}
|
||||
|
||||
@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<SwfWorkflowExecution> open = service.listExecutions(DOMAIN, ExecutionFilter.all(), false);
|
||||
List<SwfWorkflowExecution> closed = service.listExecutions(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(DOMAIN, "W", "1");
|
||||
|
||||
AwsException thrown = assertThrows(AwsException.class, () -> start("wf-dep"));
|
||||
assertEquals("TypeDeprecatedFault", thrown.getErrorCode());
|
||||
assertNotNull(service.describeWorkflowType(DOMAIN, "W", "1"));
|
||||
|
||||
service.undeprecateWorkflowType(DOMAIN, "W", "1");
|
||||
assertNotNull(start("wf-dep"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteWorkflowType_requiresPriorDeprecation() {
|
||||
AwsException thrown = assertThrows(AwsException.class,
|
||||
() -> service.deleteWorkflowType(DOMAIN, "W", "1"));
|
||||
assertEquals("TypeNotDeprecatedFault", thrown.getErrorCode());
|
||||
|
||||
service.deprecateWorkflowType(DOMAIN, "W", "1");
|
||||
service.deleteWorkflowType(DOMAIN, "W", "1");
|
||||
assertThrows(AwsException.class, () -> service.describeWorkflowType(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(DOMAIN, "wf-child", null);
|
||||
assertEquals("OPEN", child.getExecutionStatus());
|
||||
assertEquals("wf-parent", child.getParentWorkflowId());
|
||||
|
||||
service.terminateWorkflowExecution(DOMAIN, "wf-parent", parentRunId, "stop", null, null);
|
||||
|
||||
child = service.describeWorkflowExecution(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(DOMAIN, abandoning);
|
||||
|
||||
String parentRunId = service.startWorkflowExecution(new StartWorkflowExecutionRequest(
|
||||
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(DOMAIN, "wf-abandon", parentRunId, null, null, null);
|
||||
|
||||
assertEquals("OPEN", service.describeWorkflowExecution(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(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 heartbeatReportsCancelRequested_afterTheDeciderAsksToCancelAStartedTask() {
|
||||
start("wf-cancel-started");
|
||||
scheduleActivity("wf-cancel-started", "act-running");
|
||||
SwfActivityTask task = service.pollForActivityTask(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(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(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(DOMAIN, "wf-bad-type", runId);
|
||||
assertEquals("ACTIVITY_TYPE_DOES_NOT_EXIST",
|
||||
lastAttribute(execution, "ScheduleActivityTaskFailed", "cause"));
|
||||
assertEquals("OPEN", execution.getExecutionStatus());
|
||||
assertTrue(service.pollForDecisionTask(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(DOMAIN, "wf-can", firstRunId);
|
||||
assertEquals("CONTINUED_AS_NEW", closed.getCloseStatus());
|
||||
|
||||
String newRunId = (String) lastAttribute(closed, "WorkflowExecutionContinuedAsNew", "newExecutionRunId");
|
||||
assertNotNull(newRunId);
|
||||
SwfWorkflowExecution successor = service.describeWorkflowExecution(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(DOMAIN, "wf-receiver", null);
|
||||
assertEquals("ping", lastAttribute(receiver, "WorkflowExecutionSignaled", "signalName"));
|
||||
assertEquals("hello", lastAttribute(receiver, "WorkflowExecutionSignaled", "input"));
|
||||
|
||||
SwfWorkflowExecution sender = service.describeWorkflowExecution(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(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(), "us-east-1");
|
||||
assertEquals("NONE", service.describeDomain("no-retention")
|
||||
.getWorkflowExecutionRetentionPeriodInDays());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagResource_roundTripsThroughTheDomainArn() {
|
||||
String arn = service.domainArnFor(service.describeDomain(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(
|
||||
DOMAIN, workflowId, "W", "1", null, null, null, null, null, null, null, null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules {@code activityId} onto the {@code act-tl} list via a decision.
|
||||
*
|
||||
* <p>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(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.
|
||||
*/
|
||||
private SwfDecisionTask pollFor(String workflowId) {
|
||||
for (int attempt = 0; attempt < 20; attempt++) {
|
||||
Optional<SwfDecisionTask> claimed = service.pollForDecisionTask(DOMAIN, "tl", "d");
|
||||
if (claimed.isEmpty()) {
|
||||
break;
|
||||
}
|
||||
SwfDecisionTask task = claimed.get();
|
||||
if (workflowId.equals(task.getWorkflowId())) {
|
||||
return task;
|
||||
}
|
||||
service.respondDecisionTaskCompleted(task.getTaskToken(), List.of(), null);
|
||||
}
|
||||
throw new AssertionError("no decision task for " + workflowId);
|
||||
}
|
||||
|
||||
private Object lastAttribute(SwfWorkflowExecution execution, String eventType, String attribute) {
|
||||
List<SwfHistoryEvent> 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 <V> AccountAwareStorageBackend<V> create(
|
||||
String serviceName, String fileName, TypeReference<Map<String, V>> typeReference) {
|
||||
return AccountAwareStorageBackend.inMemory("000000000000");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -185,6 +185,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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user