software.amazon.awssdk
iam
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index 0eea320471..81c816eb1b 100644
--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
@@ -34,6 +34,7 @@ import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.ses.SesClient;
import software.amazon.awssdk.services.sesv2.SesV2Client;
import software.amazon.awssdk.services.sfn.SfnClient;
+import software.amazon.awssdk.services.swf.SwfClient;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.ssm.SsmClient;
@@ -589,6 +590,22 @@ public final class TestFixtures {
.build();
}
+ public static SwfClient swfClient() {
+ return swfClient(REGION);
+ }
+
+ /**
+ * SWF names are unique per region, so cross-region tests need two clients pointed at the
+ * same emulator with different regions.
+ */
+ public static SwfClient swfClient(Region region) {
+ return SwfClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(region)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
public static SesClient sesClient() {
return SesClient.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfLambdaTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfLambdaTest.java
new file mode 100644
index 0000000000..3398e81135
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfLambdaTest.java
@@ -0,0 +1,199 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.services.lambda.LambdaClient;
+import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest;
+import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest;
+import software.amazon.awssdk.services.lambda.model.FunctionCode;
+import software.amazon.awssdk.services.lambda.model.Runtime;
+import software.amazon.awssdk.services.swf.SwfClient;
+import software.amazon.awssdk.services.swf.model.ChildPolicy;
+import software.amazon.awssdk.services.swf.model.Decision;
+import software.amazon.awssdk.services.swf.model.DecisionType;
+import software.amazon.awssdk.services.swf.model.EventType;
+import software.amazon.awssdk.services.swf.model.GetWorkflowExecutionHistoryRequest;
+import software.amazon.awssdk.services.swf.model.HistoryEvent;
+import software.amazon.awssdk.services.swf.model.LambdaFunctionCompletedEventAttributes;
+import software.amazon.awssdk.services.swf.model.LambdaFunctionScheduledEventAttributes;
+import software.amazon.awssdk.services.swf.model.PollForDecisionTaskRequest;
+import software.amazon.awssdk.services.swf.model.PollForDecisionTaskResponse;
+import software.amazon.awssdk.services.swf.model.RegisterDomainRequest;
+import software.amazon.awssdk.services.swf.model.RegisterWorkflowTypeRequest;
+import software.amazon.awssdk.services.swf.model.RespondDecisionTaskCompletedRequest;
+import software.amazon.awssdk.services.swf.model.ScheduleLambdaFunctionDecisionAttributes;
+import software.amazon.awssdk.services.swf.model.StartWorkflowExecutionRequest;
+import software.amazon.awssdk.services.swf.model.TaskList;
+import software.amazon.awssdk.services.swf.model.WorkflowExecution;
+import software.amazon.awssdk.services.swf.model.WorkflowType;
+
+import java.io.ByteArrayOutputStream;
+import java.util.List;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Drives SWF's ScheduleLambdaFunction decision through the AWS SDK against a real Lambda
+ * function that Floci runs in a container.
+ *
+ * The point of doing this at the SDK layer is that the generated model has to accept what
+ * the emulator returns: the Lambda history events must deserialize into
+ * {@code LambdaFunctionScheduled/Started/Completed} with their typed
+ * {@code *EventAttributes} members populated, which a hand-rolled HTTP assertion cannot
+ * verify.
+ */
+@DisplayName("SWF Lambda decisions via the AWS SDK")
+class SwfLambdaTest {
+
+ private static final String SUFFIX = String.valueOf(System.nanoTime());
+ private static final String DOMAIN = "sdk-swf-lambda-" + SUFFIX;
+ private static final String FUNCTION = "sdk-swf-fn-" + SUFFIX;
+ private static final String TASK_LIST = "sdk-lam-tl-" + SUFFIX;
+ private static final String ROLE = "arn:aws:iam::000000000000:role/swf-lambda-role";
+
+ private static SwfClient swf;
+ private static LambdaClient lambda;
+
+ @BeforeAll
+ static void setUp() throws Exception {
+ swf = TestFixtures.swfClient();
+ lambda = TestFixtures.lambdaClient();
+
+ lambda.createFunction(CreateFunctionRequest.builder()
+ .functionName(FUNCTION)
+ .runtime(Runtime.PYTHON3_12)
+ .role(ROLE)
+ .handler("handler.handler")
+ .timeout(30)
+ .code(FunctionCode.builder().zipFile(SdkBytes.fromByteArray(handlerZip())).build())
+ .build());
+
+ swf.registerDomain(RegisterDomainRequest.builder()
+ .name(DOMAIN)
+ .workflowExecutionRetentionPeriodInDays("1")
+ .build());
+
+ swf.registerWorkflowType(RegisterWorkflowTypeRequest.builder()
+ .domain(DOMAIN)
+ .name("LambdaWf")
+ .version("1.0")
+ .defaultTaskList(TaskList.builder().name(TASK_LIST).build())
+ .defaultTaskStartToCloseTimeout("300")
+ .defaultExecutionStartToCloseTimeout("900")
+ .defaultChildPolicy(ChildPolicy.TERMINATE)
+ // SWF needs a role to invoke Lambda with; without one the invocation never starts.
+ .defaultLambdaRole(ROLE)
+ .build());
+ }
+
+ @AfterAll
+ static void tearDown() {
+ try {
+ lambda.deleteFunction(DeleteFunctionRequest.builder().functionName(FUNCTION).build());
+ } catch (RuntimeException ignored) {
+ // Best effort: leaving the function behind must not fail the suite.
+ }
+ }
+
+ private static byte[] handlerZip() throws Exception {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ try (ZipOutputStream zip = new ZipOutputStream(baos)) {
+ zip.putNextEntry(new ZipEntry("handler.py"));
+ zip.write(("def handler(event, context):\n"
+ + " return {'doubled': [n * 2 for n in event.get('numbers', [])]}\n").getBytes());
+ zip.closeEntry();
+ }
+ return baos.toByteArray();
+ }
+
+ @Test
+ @DisplayName("ScheduleLambdaFunction runs the function and the SDK reads back its result")
+ void scheduleLambdaFunction() {
+ String runId = swf.startWorkflowExecution(StartWorkflowExecutionRequest.builder()
+ .domain(DOMAIN)
+ .workflowId("sdk-wf-lambda")
+ .workflowType(WorkflowType.builder().name("LambdaWf").version("1.0").build())
+ .build())
+ .runId();
+ assertNotNull(runId);
+
+ PollForDecisionTaskResponse task = null;
+ for (int attempt = 0; attempt < 20 && task == null; attempt++) {
+ PollForDecisionTaskResponse candidate = swf.pollForDecisionTask(
+ PollForDecisionTaskRequest.builder()
+ .domain(DOMAIN)
+ .taskList(TaskList.builder().name(TASK_LIST).build())
+ .identity("sdk-decider")
+ .build());
+ if (candidate.taskToken() != null && !candidate.taskToken().isEmpty()) {
+ task = candidate;
+ }
+ }
+ assertNotNull(task, "no decision task became available");
+
+ swf.respondDecisionTaskCompleted(RespondDecisionTaskCompletedRequest.builder()
+ .taskToken(task.taskToken())
+ .decisions(Decision.builder()
+ .decisionType(DecisionType.SCHEDULE_LAMBDA_FUNCTION)
+ .scheduleLambdaFunctionDecisionAttributes(
+ ScheduleLambdaFunctionDecisionAttributes.builder()
+ .id("sdk-lam-1")
+ .name(FUNCTION)
+ .control("sdk-ctl")
+ .input("{\"numbers\": [1, 2, 3]}")
+ .startToCloseTimeout("30")
+ .build())
+ .build())
+ .build());
+
+ List events = swf.getWorkflowExecutionHistory(
+ GetWorkflowExecutionHistoryRequest.builder()
+ .domain(DOMAIN)
+ .execution(WorkflowExecution.builder()
+ .workflowId("sdk-wf-lambda").runId(runId).build())
+ .build())
+ .events();
+
+ HistoryEvent scheduled = eventOf(events, EventType.LAMBDA_FUNCTION_SCHEDULED);
+ HistoryEvent started = eventOf(events, EventType.LAMBDA_FUNCTION_STARTED);
+ HistoryEvent completed = eventOf(events, EventType.LAMBDA_FUNCTION_COMPLETED);
+
+ // The generated model must populate the typed attribute members.
+ LambdaFunctionScheduledEventAttributes scheduledAttrs =
+ scheduled.lambdaFunctionScheduledEventAttributes();
+ assertEquals("sdk-lam-1", scheduledAttrs.id());
+ assertEquals(FUNCTION, scheduledAttrs.name());
+ assertEquals("sdk-ctl", scheduledAttrs.control());
+ assertEquals("30", scheduledAttrs.startToCloseTimeout());
+ assertEquals(scheduled.eventId(),
+ started.lambdaFunctionStartedEventAttributes().scheduledEventId());
+
+ LambdaFunctionCompletedEventAttributes completedAttrs =
+ completed.lambdaFunctionCompletedEventAttributes();
+ assertEquals(scheduled.eventId(), completedAttrs.scheduledEventId());
+ assertEquals(started.eventId(), completedAttrs.startedEventId());
+
+ // Proof the container actually executed: the handler doubled the decider's input.
+ assertTrue(completedAttrs.result().contains("2")
+ && completedAttrs.result().contains("4")
+ && completedAttrs.result().contains("6"),
+ "expected the handler to double [1,2,3], got: " + completedAttrs.result());
+
+ assertEquals(EventType.DECISION_TASK_SCHEDULED, events.get(events.size() - 1).eventType());
+ }
+
+ private static HistoryEvent eventOf(List events, EventType type) {
+ return events.stream()
+ .filter(e -> type.equals(e.eventType()))
+ .findFirst()
+ .orElseThrow(() -> new AssertionError("no " + type + " in "
+ + events.stream().map(HistoryEvent::eventType).toList()));
+ }
+}
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfRegionPaginationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfRegionPaginationTest.java
new file mode 100644
index 0000000000..d5b4d9d5c6
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfRegionPaginationTest.java
@@ -0,0 +1,270 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.swf.SwfClient;
+import software.amazon.awssdk.services.swf.model.ActivityType;
+import software.amazon.awssdk.services.swf.model.ChildPolicy;
+import software.amazon.awssdk.services.swf.model.DescribeDomainRequest;
+import software.amazon.awssdk.services.swf.model.DescribeWorkflowExecutionRequest;
+import software.amazon.awssdk.services.swf.model.DescribeWorkflowTypeRequest;
+import software.amazon.awssdk.services.swf.model.DomainAlreadyExistsException;
+import software.amazon.awssdk.services.swf.model.ExecutionTimeFilter;
+import software.amazon.awssdk.services.swf.model.ListActivityTypesRequest;
+import software.amazon.awssdk.services.swf.model.ListActivityTypesResponse;
+import software.amazon.awssdk.services.swf.model.ListDomainsRequest;
+import software.amazon.awssdk.services.swf.model.ListDomainsResponse;
+import software.amazon.awssdk.services.swf.model.ListOpenWorkflowExecutionsRequest;
+import software.amazon.awssdk.services.swf.model.ListWorkflowTypesRequest;
+import software.amazon.awssdk.services.swf.model.ListWorkflowTypesResponse;
+import software.amazon.awssdk.services.swf.model.RegisterActivityTypeRequest;
+import software.amazon.awssdk.services.swf.model.RegisterDomainRequest;
+import software.amazon.awssdk.services.swf.model.RegisterWorkflowTypeRequest;
+import software.amazon.awssdk.services.swf.model.RegistrationStatus;
+import software.amazon.awssdk.services.swf.model.StartWorkflowExecutionRequest;
+import software.amazon.awssdk.services.swf.model.SwfException;
+import software.amazon.awssdk.services.swf.model.TaskList;
+import software.amazon.awssdk.services.swf.model.UnknownResourceException;
+import software.amazon.awssdk.services.swf.model.WorkflowExecution;
+import software.amazon.awssdk.services.swf.model.WorkflowType;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Regression coverage for two AWS behaviours a single-region client cannot exercise:
+ * SWF names are unique per region, and the registration lists are paginated.
+ *
+ * Both were measured against the live service before being asserted here. Region isolation
+ * needs two clients pointed at the same emulator with different {@code Region} values, which
+ * is exactly what an SDK-level test can express and a raw-HTTP test cannot do naturally.
+ */
+@DisplayName("SWF cross-region isolation and registration pagination via the AWS SDK")
+class SwfRegionPaginationTest {
+
+ private static final String SUFFIX = String.valueOf(System.nanoTime());
+ private static final String DOMAIN = "sdk-region-" + SUFFIX;
+
+ /** A fresh domain per test, registered in both regions, so tests never collide. */
+ private static String freshDomain(String label) {
+ String name = "sdk-" + label + "-" + System.nanoTime();
+ east.registerDomain(RegisterDomainRequest.builder()
+ .name(name).workflowExecutionRetentionPeriodInDays("1").build());
+ return name;
+ }
+ private static final String TASK_LIST = "sdk-region-tl-" + SUFFIX;
+
+ private static SwfClient east;
+ private static SwfClient west;
+
+ @BeforeAll
+ static void setUp() {
+ east = TestFixtures.swfClient(Region.US_EAST_1);
+ west = TestFixtures.swfClient(Region.EU_WEST_1);
+ }
+
+ private static void registerWorkflowType(SwfClient swf, String domain, String name) {
+ swf.registerWorkflowType(RegisterWorkflowTypeRequest.builder()
+ .domain(domain).name(name).version("1.0")
+ .defaultTaskList(TaskList.builder().name(TASK_LIST).build())
+ .defaultTaskStartToCloseTimeout("300")
+ .defaultExecutionStartToCloseTimeout("900")
+ .defaultChildPolicy(ChildPolicy.TERMINATE)
+ .build());
+ }
+
+ @Test
+ @DisplayName("the same domain name registers independently in two regions")
+ void domainNamesAreUniquePerRegion() {
+ east.registerDomain(RegisterDomainRequest.builder()
+ .name(DOMAIN).description("east").workflowExecutionRetentionPeriodInDays("1").build());
+
+ // The maintainer's first report: this used to fail as a duplicate.
+ west.registerDomain(RegisterDomainRequest.builder()
+ .name(DOMAIN).description("west").workflowExecutionRetentionPeriodInDays("2").build());
+
+ var eastDomain = east.describeDomain(DescribeDomainRequest.builder().name(DOMAIN).build());
+ var westDomain = west.describeDomain(DescribeDomainRequest.builder().name(DOMAIN).build());
+
+ assertEquals("east", eastDomain.domainInfo().description());
+ assertEquals("west", westDomain.domainInfo().description());
+ assertEquals("1", eastDomain.configuration().workflowExecutionRetentionPeriodInDays());
+ assertEquals("2", westDomain.configuration().workflowExecutionRetentionPeriodInDays());
+
+ // Each ARN names its own region rather than leaking the first registration's.
+ assertTrue(eastDomain.domainInfo().arn().contains(":us-east-1:"),
+ eastDomain.domainInfo().arn());
+ assertTrue(westDomain.domainInfo().arn().contains(":eu-west-1:"),
+ westDomain.domainInfo().arn());
+
+ // Re-registering within one region is still a duplicate.
+ assertThrows(DomainAlreadyExistsException.class, () ->
+ east.registerDomain(RegisterDomainRequest.builder()
+ .name(DOMAIN).workflowExecutionRetentionPeriodInDays("1").build()));
+ }
+
+ @Test
+ @DisplayName("types and executions do not leak across regions")
+ void typesAndExecutionsAreIsolatedPerRegion() {
+ String domain = "sdk-isolate-" + System.nanoTime();
+ east.registerDomain(RegisterDomainRequest.builder()
+ .name(domain).workflowExecutionRetentionPeriodInDays("1").build());
+ west.registerDomain(RegisterDomainRequest.builder()
+ .name(domain).workflowExecutionRetentionPeriodInDays("1").build());
+
+ registerWorkflowType(east, domain, "EastOnly");
+
+ // Visible in its own region only.
+ assertTrue(typeNames(east.listWorkflowTypes(ListWorkflowTypesRequest.builder()
+ .domain(domain).registrationStatus(RegistrationStatus.REGISTERED).build()))
+ .contains("EastOnly"));
+ assertFalse(typeNames(west.listWorkflowTypes(ListWorkflowTypesRequest.builder()
+ .domain(domain).registrationStatus(RegistrationStatus.REGISTERED).build()))
+ .contains("EastOnly"));
+ assertThrows(UnknownResourceException.class, () ->
+ west.describeWorkflowType(DescribeWorkflowTypeRequest.builder()
+ .domain(domain)
+ .workflowType(WorkflowType.builder().name("EastOnly").version("1.0").build())
+ .build()));
+
+ // The same workflowId runs independently in each region.
+ registerWorkflowType(west, domain, "EastOnly");
+ String eastRun = east.startWorkflowExecution(StartWorkflowExecutionRequest.builder()
+ .domain(domain).workflowId("wf-shared")
+ .workflowType(WorkflowType.builder().name("EastOnly").version("1.0").build())
+ .build())
+ .runId();
+ String westRun = west.startWorkflowExecution(StartWorkflowExecutionRequest.builder()
+ .domain(domain).workflowId("wf-shared")
+ .workflowType(WorkflowType.builder().name("EastOnly").version("1.0").build())
+ .build())
+ .runId();
+ assertNotEquals(eastRun, westRun);
+
+ List eastOpen = east.listOpenWorkflowExecutions(ListOpenWorkflowExecutionsRequest.builder()
+ .domain(domain)
+ .startTimeFilter(ExecutionTimeFilter.builder()
+ .oldestDate(Instant.EPOCH).build())
+ .build())
+ .executionInfos().stream().map(i -> i.execution().runId()).toList();
+ assertTrue(eastOpen.contains(eastRun));
+ assertFalse(eastOpen.contains(westRun), "a west run must not appear in an east listing");
+
+ // A runId from the other region must not resolve.
+ assertThrows(UnknownResourceException.class, () ->
+ west.describeWorkflowExecution(DescribeWorkflowExecutionRequest.builder()
+ .domain(domain)
+ .execution(WorkflowExecution.builder()
+ .workflowId("wf-shared").runId(eastRun).build())
+ .build()));
+ }
+
+ @Test
+ @DisplayName("ListWorkflowTypes honours maximumPageSize and nextPageToken")
+ void listWorkflowTypesPaginates() {
+ String domain = freshDomain("pagewf");
+ for (int i = 0; i < 5; i++) {
+ registerWorkflowType(east, domain, "PageWf" + i);
+ }
+
+ List seen = new ArrayList<>();
+ String token = null;
+ int pages = 0;
+ do {
+ ListWorkflowTypesResponse page = east.listWorkflowTypes(ListWorkflowTypesRequest.builder()
+ .domain(domain)
+ .registrationStatus(RegistrationStatus.REGISTERED)
+ .maximumPageSize(2)
+ .nextPageToken(token)
+ .build());
+ assertTrue(page.typeInfos().size() <= 2,
+ "maximumPageSize must cap the page: " + page.typeInfos().size());
+ seen.addAll(typeNames(page));
+ token = page.nextPageToken();
+ pages++;
+ } while (token != null && !token.isEmpty() && pages < 10);
+
+ assertTrue(pages > 1, "5 types at page size 2 must span several pages, got " + pages);
+ assertNull(emptyToNull(token), "the final page must not carry a continuation token");
+ for (int i = 0; i < 5; i++) {
+ assertTrue(seen.contains("PageWf" + i), "paging lost PageWf" + i + ": " + seen);
+ }
+ assertEquals(seen.size(), seen.stream().distinct().count(), "paging repeated an item: " + seen);
+ }
+
+ @Test
+ @DisplayName("ListActivityTypes and ListDomains paginate the same way")
+ void listActivityTypesAndDomainsPaginate() {
+ String domain = freshDomain("pageact");
+ for (int i = 0; i < 4; i++) {
+ east.registerActivityType(RegisterActivityTypeRequest.builder()
+ .domain(domain).name("PageAct" + i).version("1.0")
+ .defaultTaskList(TaskList.builder().name(TASK_LIST).build())
+ .defaultTaskScheduleToStartTimeout("60")
+ .defaultTaskStartToCloseTimeout("60")
+ .defaultTaskScheduleToCloseTimeout("NONE")
+ .defaultTaskHeartbeatTimeout("NONE")
+ .build());
+ }
+
+ ListActivityTypesResponse firstActivities = east.listActivityTypes(ListActivityTypesRequest.builder()
+ .domain(domain).registrationStatus(RegistrationStatus.REGISTERED)
+ .maximumPageSize(3).build());
+ assertEquals(3, firstActivities.typeInfos().size());
+ assertTrue(firstActivities.nextPageToken() != null && !firstActivities.nextPageToken().isEmpty(),
+ "a partial listing must offer a continuation token");
+
+ ListActivityTypesResponse secondActivities = east.listActivityTypes(ListActivityTypesRequest.builder()
+ .domain(domain).registrationStatus(RegistrationStatus.REGISTERED)
+ .maximumPageSize(3).nextPageToken(firstActivities.nextPageToken()).build());
+ List firstNames = firstActivities.typeInfos().stream()
+ .map(i -> i.activityType().name()).toList();
+ for (var info : secondActivities.typeInfos()) {
+ assertFalse(firstNames.contains(info.activityType().name()),
+ "page 2 repeated " + info.activityType().name());
+ }
+
+ // ListDomains pages too; at least this domain exists, so page size 1 must cap it.
+ ListDomainsResponse domains = east.listDomains(ListDomainsRequest.builder()
+ .registrationStatus(RegistrationStatus.REGISTERED).maximumPageSize(1).build());
+ assertEquals(1, domains.domainInfos().size());
+ }
+
+ @Test
+ @DisplayName("an oversized page size and a corrupt token are rejected")
+ void paginationInputsAreValidated() {
+ String domain = freshDomain("pagevalid");
+
+ // The live service caps maximumPageSize at 1000 rather than clamping silently.
+ SwfException tooBig = assertThrows(SwfException.class, () ->
+ east.listWorkflowTypes(ListWorkflowTypesRequest.builder()
+ .domain(domain).registrationStatus(RegistrationStatus.REGISTERED)
+ .maximumPageSize(1001).build()));
+ assertEquals("ValidationException", tooBig.awsErrorDetails().errorCode());
+
+ SwfException badToken = assertThrows(SwfException.class, () ->
+ east.listWorkflowTypes(ListWorkflowTypesRequest.builder()
+ .domain(domain).registrationStatus(RegistrationStatus.REGISTERED)
+ .nextPageToken("not-a-real-token").build()));
+ assertEquals("ValidationException", badToken.awsErrorDetails().errorCode());
+ assertEquals("Invalid token", badToken.awsErrorDetails().errorMessage());
+ }
+
+ private static List typeNames(ListWorkflowTypesResponse response) {
+ return response.typeInfos().stream().map(i -> i.workflowType().name()).toList();
+ }
+
+ private static String emptyToNull(String value) {
+ return value == null || value.isEmpty() ? null : value;
+ }
+}
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfTest.java
new file mode 100644
index 0000000000..c6a3730d3a
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SwfTest.java
@@ -0,0 +1,403 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import software.amazon.awssdk.services.swf.SwfClient;
+import software.amazon.awssdk.services.swf.model.ActivityTaskCompletedEventAttributes;
+import software.amazon.awssdk.services.swf.model.ActivityType;
+import software.amazon.awssdk.services.swf.model.ChildPolicy;
+import software.amazon.awssdk.services.swf.model.CloseStatus;
+import software.amazon.awssdk.services.swf.model.Decision;
+import software.amazon.awssdk.services.swf.model.DecisionType;
+import software.amazon.awssdk.services.swf.model.DescribeDomainRequest;
+import software.amazon.awssdk.services.swf.model.DescribeDomainResponse;
+import software.amazon.awssdk.services.swf.model.DescribeWorkflowExecutionRequest;
+import software.amazon.awssdk.services.swf.model.DescribeWorkflowExecutionResponse;
+import software.amazon.awssdk.services.swf.model.DescribeWorkflowTypeRequest;
+import software.amazon.awssdk.services.swf.model.DescribeWorkflowTypeResponse;
+import software.amazon.awssdk.services.swf.model.DomainAlreadyExistsException;
+import software.amazon.awssdk.services.swf.model.EventType;
+import software.amazon.awssdk.services.swf.model.ExecutionStatus;
+import software.amazon.awssdk.services.swf.model.GetWorkflowExecutionHistoryRequest;
+import software.amazon.awssdk.services.swf.model.GetWorkflowExecutionHistoryResponse;
+import software.amazon.awssdk.services.swf.model.PollForActivityTaskResponse;
+import software.amazon.awssdk.services.swf.model.PollForDecisionTaskResponse;
+import software.amazon.awssdk.services.swf.model.HistoryEvent;
+import software.amazon.awssdk.services.swf.model.ListDomainsRequest;
+import software.amazon.awssdk.services.swf.model.PollForActivityTaskRequest;
+import software.amazon.awssdk.services.swf.model.PollForDecisionTaskRequest;
+import software.amazon.awssdk.services.swf.model.RegisterActivityTypeRequest;
+import software.amazon.awssdk.services.swf.model.RegisterDomainRequest;
+import software.amazon.awssdk.services.swf.model.RegisterWorkflowTypeRequest;
+import software.amazon.awssdk.services.swf.model.RegistrationStatus;
+import software.amazon.awssdk.services.swf.model.RespondActivityTaskCompletedRequest;
+import software.amazon.awssdk.services.swf.model.RespondDecisionTaskCompletedRequest;
+import software.amazon.awssdk.services.swf.model.ScheduleActivityTaskDecisionAttributes;
+import software.amazon.awssdk.services.swf.model.SignalWorkflowExecutionRequest;
+import software.amazon.awssdk.services.swf.model.StartWorkflowExecutionRequest;
+import software.amazon.awssdk.services.swf.model.TaskList;
+import software.amazon.awssdk.services.swf.model.TerminateWorkflowExecutionRequest;
+import software.amazon.awssdk.services.swf.model.TypeAlreadyExistsException;
+import software.amazon.awssdk.services.swf.model.UnknownResourceException;
+import software.amazon.awssdk.services.swf.model.WorkflowExecution;
+import software.amazon.awssdk.services.swf.model.WorkflowExecutionAlreadyStartedException;
+import software.amazon.awssdk.services.swf.model.WorkflowType;
+
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * Drives the SWF emulation with the real AWS SDK v2 client.
+ *
+ * This is the check the raw-HTTP tests cannot make: the SDK must deserialize every
+ * response into its generated model (epoch-second timestamps into {@code Instant},
+ * event attributes into the right {@code *EventAttributes} member) and map each fault
+ * onto its typed exception class. A response that is merely "valid JSON" fails here.
+ */
+@DisplayName("SWF workflow lifecycle")
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class SwfTest {
+
+ private static final String DOMAIN = "sdk-swf-" + System.currentTimeMillis();
+ private static final String TASK_LIST = "sdk-swf-tl";
+ private static final WorkflowType WORKFLOW_TYPE =
+ WorkflowType.builder().name("SdkWorkflow").version("1.0").build();
+ private static final ActivityType ACTIVITY_TYPE =
+ ActivityType.builder().name("SdkActivity").version("1.0").build();
+
+ private static SwfClient swf;
+ private static String runId;
+
+ @BeforeAll
+ static void setup() {
+ swf = TestFixtures.swfClient();
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (swf != null) {
+ swf.close();
+ }
+ }
+
+ @Test
+ @Order(1)
+ @DisplayName("Register domain and describe it")
+ void registerDomain() {
+ swf.registerDomain(RegisterDomainRequest.builder()
+ .name(DOMAIN)
+ .description("sdk compatibility domain")
+ .workflowExecutionRetentionPeriodInDays("7")
+ .build());
+
+ DescribeDomainResponse described = swf.describeDomain(
+ DescribeDomainRequest.builder().name(DOMAIN).build());
+
+ assertThat(described.domainInfo().name()).isEqualTo(DOMAIN);
+ assertThat(described.domainInfo().status()).isEqualTo(RegistrationStatus.REGISTERED);
+ assertThat(described.domainInfo().arn()).contains(":/domain/" + DOMAIN);
+ assertThat(described.configuration().workflowExecutionRetentionPeriodInDays()).isEqualTo("7");
+
+ assertThat(swf.listDomains(ListDomainsRequest.builder()
+ .registrationStatus(RegistrationStatus.REGISTERED).build())
+ .domainInfos())
+ .anyMatch(info -> DOMAIN.equals(info.name()));
+ }
+
+ @Test
+ @Order(2)
+ @DisplayName("Duplicate domain raises DomainAlreadyExistsException")
+ void duplicateDomainIsTyped() {
+ // The fault must arrive with the namespaced __type SWF uses, or the SDK falls back
+ // to a generic SwfException and this assertion fails.
+ assertThatThrownBy(() -> swf.registerDomain(RegisterDomainRequest.builder()
+ .name(DOMAIN)
+ .workflowExecutionRetentionPeriodInDays("7")
+ .build()))
+ .isInstanceOf(DomainAlreadyExistsException.class);
+ }
+
+ @Test
+ @Order(3)
+ @DisplayName("Unknown domain raises UnknownResourceException")
+ void unknownDomainIsTyped() {
+ assertThatThrownBy(() -> swf.describeDomain(
+ DescribeDomainRequest.builder().name("sdk-swf-missing").build()))
+ .isInstanceOf(UnknownResourceException.class)
+ .hasMessageContaining("Unknown domain: sdk-swf-missing");
+ }
+
+ @Test
+ @Order(4)
+ @DisplayName("Register workflow and activity types with defaults")
+ void registerTypes() {
+ swf.registerWorkflowType(RegisterWorkflowTypeRequest.builder()
+ .domain(DOMAIN)
+ .name(WORKFLOW_TYPE.name())
+ .version(WORKFLOW_TYPE.version())
+ .defaultTaskList(TaskList.builder().name(TASK_LIST).build())
+ .defaultTaskStartToCloseTimeout("60")
+ .defaultExecutionStartToCloseTimeout("3600")
+ .defaultChildPolicy(ChildPolicy.TERMINATE)
+ .build());
+
+ swf.registerActivityType(RegisterActivityTypeRequest.builder()
+ .domain(DOMAIN)
+ .name(ACTIVITY_TYPE.name())
+ .version(ACTIVITY_TYPE.version())
+ .defaultTaskList(TaskList.builder().name(TASK_LIST).build())
+ .defaultTaskScheduleToStartTimeout("60")
+ .defaultTaskStartToCloseTimeout("300")
+ .build());
+
+ DescribeWorkflowTypeResponse described = swf.describeWorkflowType(
+ DescribeWorkflowTypeRequest.builder().domain(DOMAIN).workflowType(WORKFLOW_TYPE).build());
+
+ assertThat(described.typeInfo().status()).isEqualTo(RegistrationStatus.REGISTERED);
+ // creationDate arrives as an epoch-second number; the SDK models it as Instant, so a
+ // formatted date on the wire would fail to deserialize.
+ assertThat(described.typeInfo().creationDate()).isNotNull();
+ assertThat(described.configuration().defaultTaskList().name()).isEqualTo(TASK_LIST);
+ assertThat(described.configuration().defaultChildPolicy()).isEqualTo(ChildPolicy.TERMINATE);
+
+ assertThatThrownBy(() -> swf.registerWorkflowType(RegisterWorkflowTypeRequest.builder()
+ .domain(DOMAIN)
+ .name(WORKFLOW_TYPE.name())
+ .version(WORKFLOW_TYPE.version())
+ .build()))
+ .isInstanceOf(TypeAlreadyExistsException.class);
+ }
+
+ @Test
+ @Order(5)
+ @DisplayName("Start execution seeds the initial history")
+ void startExecution() {
+ runId = swf.startWorkflowExecution(StartWorkflowExecutionRequest.builder()
+ .domain(DOMAIN)
+ .workflowId("sdk-wf-1")
+ .workflowType(WORKFLOW_TYPE)
+ .input("{\"sdk\":true}")
+ .tagList("sdk", "compat")
+ .build())
+ .runId();
+ assertThat(runId).isNotBlank();
+
+ GetWorkflowExecutionHistoryResponse history = swf.getWorkflowExecutionHistory(GetWorkflowExecutionHistoryRequest.builder()
+ .domain(DOMAIN)
+ .execution(execution())
+ .build());
+
+ assertThat(history.events()).hasSize(2);
+ HistoryEvent started = history.events().get(0);
+ assertThat(started.eventId()).isEqualTo(1L);
+ assertThat(started.eventType()).isEqualTo(EventType.WORKFLOW_EXECUTION_STARTED);
+ assertThat(started.eventTimestamp()).isNotNull();
+ assertThat(started.workflowExecutionStartedEventAttributes().input()).isEqualTo("{\"sdk\":true}");
+ assertThat(started.workflowExecutionStartedEventAttributes().taskList().name()).isEqualTo(TASK_LIST);
+ assertThat(started.workflowExecutionStartedEventAttributes().tagList()).contains("sdk", "compat");
+ assertThat(history.events().get(1).eventType()).isEqualTo(EventType.DECISION_TASK_SCHEDULED);
+
+ assertThatThrownBy(() -> swf.startWorkflowExecution(StartWorkflowExecutionRequest.builder()
+ .domain(DOMAIN)
+ .workflowId("sdk-wf-1")
+ .workflowType(WORKFLOW_TYPE)
+ .build()))
+ .isInstanceOf(WorkflowExecutionAlreadyStartedException.class);
+ }
+
+ @Test
+ @Order(6)
+ @DisplayName("Decider schedules an activity, worker completes it, decider closes the execution")
+ void deciderAndWorkerHandshake() {
+ PollForDecisionTaskResponse decisionTask = pollDecisionTask();
+ assertThat(decisionTask.taskToken()).isNotBlank();
+ assertThat(decisionTask.workflowExecution().runId()).isEqualTo(runId);
+ assertThat(decisionTask.workflowType().name()).isEqualTo(WORKFLOW_TYPE.name());
+ assertThat(decisionTask.previousStartedEventId()).isZero();
+ assertThat(decisionTask.events()).extracting(HistoryEvent::eventType)
+ .contains(EventType.DECISION_TASK_STARTED);
+
+ swf.respondDecisionTaskCompleted(RespondDecisionTaskCompletedRequest.builder()
+ .taskToken(decisionTask.taskToken())
+ .executionContext("sdk-step-1")
+ .decisions(Decision.builder()
+ .decisionType(DecisionType.SCHEDULE_ACTIVITY_TASK)
+ .scheduleActivityTaskDecisionAttributes(
+ ScheduleActivityTaskDecisionAttributes.builder()
+ .activityId("sdk-act-1")
+ .activityType(ACTIVITY_TYPE)
+ .input("{\"work\":1}")
+ .build())
+ .build())
+ .build());
+
+ PollForActivityTaskResponse activityTask = swf.pollForActivityTask(PollForActivityTaskRequest.builder()
+ .domain(DOMAIN)
+ .taskList(TaskList.builder().name(TASK_LIST).build())
+ .identity("sdk-worker")
+ .build());
+ assertThat(activityTask.taskToken()).isNotBlank();
+ assertThat(activityTask.activityId()).isEqualTo("sdk-act-1");
+ assertThat(activityTask.activityType().name()).isEqualTo(ACTIVITY_TYPE.name());
+ assertThat(activityTask.input()).isEqualTo("{\"work\":1}");
+
+ swf.respondActivityTaskCompleted(RespondActivityTaskCompletedRequest.builder()
+ .taskToken(activityTask.taskToken())
+ .result("{\"done\":true}")
+ .build());
+
+ PollForDecisionTaskResponse afterActivity = pollDecisionTask();
+ assertThat(afterActivity.events()).extracting(HistoryEvent::eventType)
+ .contains(EventType.ACTIVITY_TASK_COMPLETED);
+ ActivityTaskCompletedEventAttributes completed = afterActivity.events().stream()
+ .filter(event -> event.eventType() == EventType.ACTIVITY_TASK_COMPLETED)
+ .findFirst()
+ .orElseThrow()
+ .activityTaskCompletedEventAttributes();
+ assertThat(completed.result()).isEqualTo("{\"done\":true}");
+
+ swf.respondDecisionTaskCompleted(RespondDecisionTaskCompletedRequest.builder()
+ .taskToken(afterActivity.taskToken())
+ .decisions(Decision.builder()
+ .decisionType(DecisionType.COMPLETE_WORKFLOW_EXECUTION)
+ .completeWorkflowExecutionDecisionAttributes(attrs -> attrs.result("{\"ok\":true}"))
+ .build())
+ .build());
+
+ DescribeWorkflowExecutionResponse described = swf.describeWorkflowExecution(
+ DescribeWorkflowExecutionRequest.builder().domain(DOMAIN).execution(execution()).build());
+ assertThat(described.executionInfo().executionStatus()).isEqualTo(ExecutionStatus.CLOSED);
+ assertThat(described.executionInfo().closeStatus()).isEqualTo(CloseStatus.COMPLETED);
+ assertThat(described.executionInfo().closeTimestamp()).isNotNull();
+ assertThat(described.openCounts().openActivityTasks()).isZero();
+ assertThat(described.latestExecutionContext()).isEqualTo("sdk-step-1");
+ }
+
+ @Test
+ @Order(7)
+ @DisplayName("History deserializes every event into its typed attributes")
+ void historyIsFullyTyped() {
+ List events = swf.getWorkflowExecutionHistory(
+ GetWorkflowExecutionHistoryRequest.builder()
+ .domain(DOMAIN).execution(execution()).build())
+ .events();
+
+ assertThat(events).extracting(HistoryEvent::eventType).containsExactly(
+ EventType.WORKFLOW_EXECUTION_STARTED,
+ EventType.DECISION_TASK_SCHEDULED,
+ EventType.DECISION_TASK_STARTED,
+ EventType.DECISION_TASK_COMPLETED,
+ EventType.ACTIVITY_TASK_SCHEDULED,
+ EventType.ACTIVITY_TASK_STARTED,
+ EventType.ACTIVITY_TASK_COMPLETED,
+ EventType.DECISION_TASK_SCHEDULED,
+ EventType.DECISION_TASK_STARTED,
+ EventType.DECISION_TASK_COMPLETED,
+ EventType.WORKFLOW_EXECUTION_COMPLETED);
+
+ // eventIds are contiguous from 1, as SWF guarantees.
+ for (int i = 0; i < events.size(); i++) {
+ assertThat(events.get(i).eventId()).isEqualTo(i + 1L);
+ }
+
+ HistoryEvent scheduled = events.get(4);
+ assertThat(scheduled.activityTaskScheduledEventAttributes().activityId()).isEqualTo("sdk-act-1");
+ assertThat(scheduled.activityTaskScheduledEventAttributes().startToCloseTimeout()).isEqualTo("300");
+ assertThat(scheduled.activityTaskScheduledEventAttributes().taskList().name()).isEqualTo(TASK_LIST);
+ }
+
+ @Test
+ @Order(8)
+ @DisplayName("Signal and terminate drive a second execution")
+ void signalAndTerminate() {
+ String signalRunId = swf.startWorkflowExecution(StartWorkflowExecutionRequest.builder()
+ .domain(DOMAIN)
+ .workflowId("sdk-wf-2")
+ .workflowType(WORKFLOW_TYPE)
+ .build())
+ .runId();
+ WorkflowExecution second = WorkflowExecution.builder()
+ .workflowId("sdk-wf-2").runId(signalRunId).build();
+
+ swf.signalWorkflowExecution(SignalWorkflowExecutionRequest.builder()
+ .domain(DOMAIN)
+ .workflowId("sdk-wf-2")
+ .runId(signalRunId)
+ .signalName("sdk-signal")
+ .input("{\"resume\":true}")
+ .build());
+
+ assertThat(swf.getWorkflowExecutionHistory(GetWorkflowExecutionHistoryRequest.builder()
+ .domain(DOMAIN).execution(second).build())
+ .events())
+ .filteredOn(event -> event.eventType() == EventType.WORKFLOW_EXECUTION_SIGNALED)
+ .singleElement()
+ .satisfies(event -> {
+ assertThat(event.workflowExecutionSignaledEventAttributes().signalName())
+ .isEqualTo("sdk-signal");
+ assertThat(event.workflowExecutionSignaledEventAttributes().input())
+ .isEqualTo("{\"resume\":true}");
+ });
+
+ swf.terminateWorkflowExecution(TerminateWorkflowExecutionRequest.builder()
+ .domain(DOMAIN)
+ .workflowId("sdk-wf-2")
+ .runId(signalRunId)
+ .reason("sdk-test")
+ .build());
+
+ assertThat(swf.describeWorkflowExecution(DescribeWorkflowExecutionRequest.builder()
+ .domain(DOMAIN).execution(second).build())
+ .executionInfo().closeStatus())
+ .isEqualTo(CloseStatus.TERMINATED);
+ }
+
+ @Test
+ @Order(9)
+ @DisplayName("Counts and closed-execution listing reflect the finished work")
+ void countsAndListing() {
+ assertThat(swf.countClosedWorkflowExecutions(builder -> builder
+ .domain(DOMAIN)
+ .startTimeFilter(filter -> filter.oldestDate(java.time.Instant.EPOCH)))
+ .count())
+ .isGreaterThanOrEqualTo(2);
+
+ assertThat(swf.listClosedWorkflowExecutions(builder -> builder
+ .domain(DOMAIN)
+ .startTimeFilter(filter -> filter.oldestDate(java.time.Instant.EPOCH)))
+ .executionInfos())
+ .extracting(info -> info.execution().workflowId())
+ .contains("sdk-wf-1", "sdk-wf-2");
+ }
+
+ // ── helpers ─────────────────────────────────────────────────────────────
+
+ private static WorkflowExecution execution() {
+ return WorkflowExecution.builder().workflowId("sdk-wf-1").runId(runId).build();
+ }
+
+ /**
+ * Polls until a task arrives. The emulator answers an idle poll immediately with an
+ * empty token rather than long-polling, so a decider loops instead of blocking.
+ */
+ private static PollForDecisionTaskResponse pollDecisionTask() {
+ for (int attempt = 0; attempt < 20; attempt++) {
+ PollForDecisionTaskResponse task = swf.pollForDecisionTask(PollForDecisionTaskRequest.builder()
+ .domain(DOMAIN)
+ .taskList(TaskList.builder().name(TASK_LIST).build())
+ .identity("sdk-decider")
+ .build());
+ if (task.taskToken() != null && !task.taskToken().isEmpty()) {
+ return task;
+ }
+ }
+ throw new AssertionError("no decision task became available");
+ }
+}
diff --git a/docs/services/swf.md b/docs/services/swf.md
new file mode 100644
index 0000000000..b7f0ac851a
--- /dev/null
+++ b/docs/services/swf.md
@@ -0,0 +1,262 @@
+# SWF
+
+**Protocol:** JSON 1.0 (`X-Amz-Target: SimpleWorkflowService.*`)
+**Endpoint:** `POST http://localhost:4566/`
+
+Domains, workflow and activity type registration, and the workflow execution state
+machine: decision tasks, activity tasks, timers, signals, child workflows, and timeouts.
+
+## Supported Actions
+
+
+| Action | Description |
+| --- | --- |
+| `RegisterDomain` | Create a domain with a workflow-execution retention period |
+| `DescribeDomain` | Get a domain's status, description, ARN, and retention configuration |
+| `ListDomains` | List domains by registration status |
+| `DeprecateDomain` | Deprecate a domain, blocking new registrations and executions |
+| `UndeprecateDomain` | Return a deprecated domain to REGISTERED |
+| `RegisterWorkflowType` | Register a workflow type and its execution defaults |
+| `DescribeWorkflowType` | Get a workflow type's status and registered defaults |
+| `ListWorkflowTypes` | List workflow types by registration status, optionally by name |
+| `DeprecateWorkflowType` | Deprecate a workflow type, blocking new executions |
+| `UndeprecateWorkflowType` | Return a deprecated workflow type to REGISTERED |
+| `DeleteWorkflowType` | Delete a deprecated workflow type |
+| `RegisterActivityType` | Register an activity type and its task timeout defaults |
+| `DescribeActivityType` | Get an activity type's status and registered defaults |
+| `ListActivityTypes` | List activity types by registration status, optionally by name |
+| `DeprecateActivityType` | Deprecate an activity type, blocking new task scheduling |
+| `UndeprecateActivityType` | Return a deprecated activity type to REGISTERED |
+| `DeleteActivityType` | Delete a deprecated activity type |
+| `StartWorkflowExecution` | Start an execution, resolving unset fields from the type defaults |
+| `DescribeWorkflowExecution` | Get an execution's status, configuration, and open task counts |
+| `GetWorkflowExecutionHistory` | Read an execution's history, paginated and optionally reversed |
+| `ListOpenWorkflowExecutions` | List open executions with execution, type, tag, and time filters |
+| `ListClosedWorkflowExecutions` | List closed executions, additionally filtered by close status |
+| `CountOpenWorkflowExecutions` | Count open executions matching the same filters |
+| `CountClosedWorkflowExecutions` | Count closed executions matching the same filters |
+| `CountPendingActivityTasks` | Count activity tasks awaiting a worker on a task list |
+| `CountPendingDecisionTasks` | Count decision tasks awaiting a decider on a task list |
+| `PollForDecisionTask` | Claim a decision task with the execution history the decider needs |
+| `RespondDecisionTaskCompleted` | Apply a decider's decisions in order |
+| `PollForActivityTask` | Claim an activity task with its input |
+| `RecordActivityTaskHeartbeat` | Report progress and learn whether cancellation was requested |
+| `RespondActivityTaskCompleted` | Complete an activity task with a result |
+| `RespondActivityTaskFailed` | Fail an activity task with a reason and details |
+| `RespondActivityTaskCanceled` | Confirm an activity task was canceled |
+| `SignalWorkflowExecution` | Deliver a signal to an open execution |
+| `RequestCancelWorkflowExecution` | Ask an execution's decider to cancel it |
+| `TerminateWorkflowExecution` | Close an execution immediately, applying its child policy |
+| `ListTagsForResource` | List a domain's tags |
+| `TagResource` | Add tags to a domain |
+| `UntagResource` | Remove tags from a domain |
+
+
+All 39 modeled operations are implemented.
+
+## Decisions
+
+`RespondDecisionTaskCompleted` applies decisions in order:
+
+| Decision | Behavior |
+|----------|----------|
+| `ScheduleActivityTask` | Schedules an activity task; timeouts fall back to the activity type's registration defaults |
+| `RequestCancelActivityTask` | Requests cancellation; a task that has not started yet is canceled immediately |
+| `CompleteWorkflowExecution` | Closes the execution as `COMPLETED` |
+| `FailWorkflowExecution` | Closes the execution as `FAILED` |
+| `CancelWorkflowExecution` | Closes the execution as `CANCELED` |
+| `ContinueAsNewWorkflowExecution` | Closes the run as `CONTINUED_AS_NEW` and starts a successor run |
+| `RecordMarker` | Appends `MarkerRecorded` |
+| `StartTimer` / `CancelTimer` | Starts or cancels a timer; a due timer fires `TimerFired` |
+| `SignalExternalWorkflowExecution` | Delivers a signal to another execution in the same domain |
+| `RequestCancelExternalWorkflowExecution` | Requests cancellation of another execution |
+| `StartChildWorkflowExecution` | Starts a child execution and reports its outcome back to the parent |
+| `ScheduleLambdaFunction` | Invokes the function through Floci's Lambda service and records its result (see [Lambda functions](#lambda-functions)) |
+
+A decision that cannot be applied appends its `*Failed` event with the AWS cause
+(`ACTIVITY_TYPE_DOES_NOT_EXIST`, `ACTIVITY_ID_ALREADY_IN_USE`, `TIMER_ID_UNKNOWN`,
+`UNHANDLED_DECISION`, …) instead of failing the request, and the decider is given a
+fresh decision task. A closing decision must be last in the batch: a batch with anything
+after it is rejected with `ValidationException` ("Close must be last decision in list") and
+no decision is applied.
+
+## Timeouts
+
+A background sweep expires timeouts and appends the matching event:
+
+| Timeout | Event | `timeoutType` |
+|---------|-------|---------------|
+| Activity schedule-to-start | `ActivityTaskTimedOut` | `SCHEDULE_TO_START` |
+| Activity start-to-close | `ActivityTaskTimedOut` | `START_TO_CLOSE` |
+| Activity schedule-to-close | `ActivityTaskTimedOut` | `SCHEDULE_TO_CLOSE` |
+| Activity heartbeat | `ActivityTaskTimedOut` | `HEARTBEAT` |
+| Decision task start-to-close | `DecisionTaskTimedOut` | `START_TO_CLOSE` |
+| Workflow execution start-to-close | `WorkflowExecutionTimedOut` | `START_TO_CLOSE` |
+
+Any timeout other than the workflow's own schedules a new decision task. The literal
+`NONE` disables a timeout, as in AWS.
+
+## Child policy
+
+When an execution closes, its `childPolicy` is applied to still-open children:
+`TERMINATE` terminates them with cause `CHILD_POLICY_APPLIED`, `REQUEST_CANCEL` requests
+cancellation, and `ABANDON` leaves them running.
+
+## Lambda functions
+
+`ScheduleLambdaFunction` runs a real function: Floci invokes it through its own Lambda
+service, which executes it in a container exactly as an `Invoke` API call would, and records
+the outcome in history. Deploy the function with the Lambda API first — SWF resolves it by
+name in the region its domain was registered in.
+
+The execution needs a `lambdaRole`, taken from `StartWorkflowExecution`'s `lambdaRole` or,
+when absent, the workflow type's `defaultLambdaRole`. The role is not evaluated as a policy;
+its presence is what SWF requires in order to invoke.
+
+| Outcome | History |
+|---|---|
+| Success | `LambdaFunctionScheduled` → `LambdaFunctionStarted` → `LambdaFunctionCompleted` with the response as `result` |
+| Handler raised | `…Scheduled` → `…Started` → `LambdaFunctionFailed` with `reason` `Handled`/`Unhandled` and the error payload as `details` |
+| Function not found | `…Scheduled` → `…Started` → `LambdaFunctionFailed` with `reason` `ResourceNotFoundException` |
+| No `lambdaRole` | `…Scheduled` → `StartLambdaFunctionFailed` with cause `ASSUME_ROLE_FAILED`; the function is never started |
+
+A decision with no `input` delivers `{}` to the handler, and reusing an `id` is accepted —
+SWF does not report `ID_ALREADY_IN_USE` for Lambda invocations the way it does for activity
+ids. Every outcome schedules a fresh decision task so the decider can react.
+
+## Regions
+
+SWF names are unique per region, so all state is region-scoped: registering `orders` in
+`us-east-1` and again in `eu-west-1` creates two independent domains, each with its own
+description, retention period, and ARN. Types, executions, and task tokens follow the same
+rule — a `runId` from one region does not resolve in another, `ListDomains` and the type
+listings only report the caller's region, and a decision or activity task is only handed to a
+poller in the region that owns it.
+
+## Configuration
+
+```yaml
+floci:
+ services:
+ swf:
+ enabled: true
+ timeout-sweep-enabled: true
+ timeout-sweep-interval-seconds: 1
+```
+
+| Setting | Env var | Default | Description |
+|---------|---------|---------|-------------|
+| `enabled` | `FLOCI_SERVICES_SWF_ENABLED` | `true` | Enable the service |
+| `timeout-sweep-enabled` | `FLOCI_SERVICES_SWF_TIMEOUT_SWEEP_ENABLED` | `true` | Run the background timeout sweep |
+| `timeout-sweep-interval-seconds` | `FLOCI_SERVICES_SWF_TIMEOUT_SWEEP_INTERVAL_SECONDS` | `1` | Sweep interval |
+
+## Example
+
+Register a domain and the types an execution needs:
+
+```bash
+aws --endpoint-url http://localhost:4566 swf register-domain \
+ --name orders --workflow-execution-retention-period-in-days 7
+
+aws --endpoint-url http://localhost:4566 swf register-workflow-type \
+ --domain orders --name OrderWorkflow --workflow-version 1.0 \
+ --default-task-list name=orders-tl \
+ --default-task-start-to-close-timeout 60 \
+ --default-execution-start-to-close-timeout 3600 \
+ --default-child-policy TERMINATE
+
+aws --endpoint-url http://localhost:4566 swf register-activity-type \
+ --domain orders --name ChargeCard --activity-version 1.0 \
+ --default-task-list name=orders-tl \
+ --default-task-schedule-to-start-timeout 60 \
+ --default-task-start-to-close-timeout 300
+```
+
+Start an execution:
+
+```bash
+aws --endpoint-url http://localhost:4566 swf start-workflow-execution \
+ --domain orders --workflow-id order-1234 \
+ --workflow-type name=OrderWorkflow,version=1.0 \
+ --input '{"orderId":"1234"}'
+```
+
+Poll as a decider and schedule the activity:
+
+```bash
+aws --endpoint-url http://localhost:4566 swf poll-for-decision-task \
+ --domain orders --task-list name=orders-tl --identity decider-1 > task.json
+
+TASK_TOKEN=$(jq -r .taskToken task.json)
+
+cat > decisions.json <<'EOF'
+[{"decisionType": "ScheduleActivityTask",
+ "scheduleActivityTaskDecisionAttributes": {
+ "activityId": "charge-1",
+ "activityType": {"name": "ChargeCard", "version": "1.0"},
+ "input": "{\"amount\":4200}"}}]
+EOF
+
+aws --endpoint-url http://localhost:4566 swf respond-decision-task-completed \
+ --task-token "$TASK_TOKEN" --decisions file://decisions.json
+```
+
+Poll as a worker and complete the activity:
+
+```bash
+aws --endpoint-url http://localhost:4566 swf poll-for-activity-task \
+ --domain orders --task-list name=orders-tl --identity worker-1 > activity.json
+
+ACTIVITY_TOKEN=$(jq -r .taskToken activity.json)
+
+aws --endpoint-url http://localhost:4566 swf respond-activity-task-completed \
+ --task-token "$ACTIVITY_TOKEN" --result '{"charged":true}'
+```
+
+Read the history:
+
+```bash
+aws --endpoint-url http://localhost:4566 swf get-workflow-execution-history \
+ --domain orders --execution workflowId=order-1234,runId=
+```
+
+## Errors
+
+Faults use the AWS codes and messages, so SDK error handling works unchanged:
+
+| Fault | Raised by |
+|-------|-----------|
+| `UnknownResourceFault` | Unknown domain, type, execution, or task token; also an activity task token whose task has already closed, reported as `Unknown activity, scheduledEventId = N` |
+| `DomainAlreadyExistsFault` | `RegisterDomain` for an existing domain; `UndeprecateDomain` on a registered domain |
+| `DomainDeprecatedFault` | Registering into, or starting an execution in, a deprecated domain |
+| `TypeAlreadyExistsFault` | Registering an existing type; undeprecating a registered type |
+| `TypeDeprecatedFault` | Starting an execution of a deprecated workflow type |
+| `TypeNotDeprecatedFault` | `DeleteWorkflowType` / `DeleteActivityType` before deprecation |
+| `WorkflowExecutionAlreadyStartedFault` | `StartWorkflowExecution` while an execution with that `workflowId` is open |
+| `DefaultUndefinedFault` | A required field is absent from both the request and the type's defaults |
+| `TooManyTagsFault` | More than 50 tags on a domain |
+| `ValidationException` | Missing required member, a value outside an enum, or a closing decision that is not last |
+
+## Limitations
+
+- **Long polling.** `PollForDecisionTask` and `PollForActivityTask` return immediately
+ instead of holding the connection for up to 60 seconds. Workers that loop on an empty
+ poll behave the same; workers that rely on the call blocking will spin.
+- **Task tokens are in-memory.** Tokens do not survive a restart even under persistent
+ storage modes, matching the fact that SWF tokens are not durable handles.
+- **Retention.** `workflowExecutionRetentionPeriodInDays` is stored and returned but
+ closed executions are not pruned.
+- **Pagination.** `maximumPageSize` and `nextPageToken` are honored on every paginated
+ operation — the history, the execution listings, the registration listings (`ListDomains`,
+ `ListWorkflowTypes`, `ListActivityTypes`) and `PollForDecisionTask`. All of them apply the
+ service's 1000 cap, rejecting a larger value rather than clamping it. Tokens are opaque and
+ are not interchangeable with real SWF tokens.
+- **`PollForDecisionTask` continuation.** A request carrying `nextPageToken` continues the
+ earlier poll instead of claiming a new task, so it returns the same `startedEventId`,
+ `previousStartedEventId` and `workflowExecution` with the next page of that task's history.
+ `startAtPreviousStartedEvent` trims the window to events from `previousStartedEventId`
+ onward, which the service treats as inclusive.
+- **Decision batches are all-or-nothing.** A batch containing an unknown `decisionType`, or a
+ closing decision that is not last, is rejected with `ValidationException` before anything is
+ applied: no `DecisionTaskCompleted`, no earlier decision, and the task token stays claimable
+ for a corrected batch.
diff --git a/mkdocs.yml b/mkdocs.yml
index b220ae8a18..015029f406 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -90,6 +90,7 @@ nav:
- Secrets Manager: services/secrets-manager.md
- CloudFormation: services/cloudformation.md
- Step Functions: services/step-functions.md
+ - SWF: services/swf.md
- IAM: services/iam.md
- STS: services/sts.md
- ElastiCache: services/elasticache.md
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index eeac0f375d..a1414c77b9 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -550,6 +550,7 @@ public interface EmulatorConfig {
KmsServiceConfig kms();
CognitoServiceConfig cognito();
StepFunctionsServiceConfig stepfunctions();
+ SwfServiceConfig swf();
CloudFormationServiceConfig cloudformation();
AcmServiceConfig acm();
AthenaServiceConfig athena();
@@ -1080,6 +1081,26 @@ public interface EmulatorConfig {
boolean allowPlaintextHttp();
}
+ interface SwfServiceConfig {
+ @WithDefault("true")
+ boolean enabled();
+
+ /**
+ * Run the background sweep that expires activity, decision, workflow and timer
+ * timeouts. Setting this to {@code false} leaves timeouts recorded but never
+ * fired, which is useful for tests that drive the clock themselves.
+ */
+ @WithDefault("true")
+ boolean timeoutSweepEnabled();
+
+ /**
+ * How often the timeout sweep runs. SWF timeouts are specified in whole seconds,
+ * so a 1s sweep bounds the observable lateness of an expiry at one second.
+ */
+ @WithDefault("1")
+ long timeoutSweepIntervalSeconds();
+ }
+
interface CloudFormationServiceConfig {
@WithDefault("true")
boolean enabled();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java
index 853a2d138a..5b3e40c751 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamsJsonHandler;
import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler;
+import io.github.hectorvent.floci.services.swf.SwfJsonHandler;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
@@ -45,6 +46,7 @@ public class AwsJsonController {
private final StepFunctionsJsonHandler sfnJsonHandler;
private final CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler;
private final CloudControlJsonHandler cloudControlJsonHandler;
+ private final SwfJsonHandler swfJsonHandler;
@Inject
public AwsJsonController(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
@@ -54,7 +56,8 @@ public class AwsJsonController {
SqsJsonHandler sqsJsonHandler, SnsJsonHandler snsJsonHandler,
StepFunctionsJsonHandler sfnJsonHandler,
CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler,
- CloudControlJsonHandler cloudControlJsonHandler) {
+ CloudControlJsonHandler cloudControlJsonHandler,
+ SwfJsonHandler swfJsonHandler) {
this.objectMapper = objectMapper;
this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
this.catalog = catalog;
@@ -66,6 +69,7 @@ public class AwsJsonController {
this.sfnJsonHandler = sfnJsonHandler;
this.cloudWatchMetricsJsonHandler = cloudWatchMetricsJsonHandler;
this.cloudControlJsonHandler = cloudControlJsonHandler;
+ this.swfJsonHandler = swfJsonHandler;
}
@POST
@@ -110,6 +114,7 @@ public class AwsJsonController {
case "sqs" -> sqsJsonHandler.handle(action, request, region);
case "sns" -> snsJsonHandler.handle(action, request, region);
case "states" -> sfnJsonHandler.handle(action, request, region);
+ case "swf" -> swfJsonHandler.handle(action, request, region);
case "monitoring" -> cloudWatchMetricsJsonHandler.handle(action, request, region);
case "cloudcontrol" -> cloudControlJsonHandler.handle(action, request, region);
default -> null;
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index 5ad0e0737c..b5d9384ac0 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -202,6 +202,10 @@ public class ResolvedServiceCatalog {
"stepfunctions", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON, ServiceProtocol.CBOR),
Set.of("AWSStepFunctions."), Set.of("states"), Set.of("SFN"), Set.of()),
+ descriptor("swf", "swf", config.services().swf().enabled(), true,
+ "swf", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
+ protocols(ServiceProtocol.JSON),
+ Set.of("SimpleWorkflowService."), Set.of("swf"), Set.of(), Set.of()),
descriptor("cloudformation", "cloudformation", config.services().cloudformation().enabled(), true,
null, null, 5000L, null, ServiceProtocol.QUERY,
protocols(ServiceProtocol.QUERY),
diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/LambdaInvocationResult.java b/src/main/java/io/github/hectorvent/floci/services/swf/LambdaInvocationResult.java
new file mode 100644
index 0000000000..2fb7b3b9df
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/swf/LambdaInvocationResult.java
@@ -0,0 +1,12 @@
+package io.github.hectorvent.floci.services.swf;
+
+/**
+ * A Lambda invocation's outcome, reduced to what SWF records in history.
+ *
+ * @param payload the function's response body, recorded as the LambdaFunctionCompleted
+ * {@code result} or, on a handler error, the Failed {@code details}
+ * @param functionError the Lambda {@code FunctionError} header ({@code Handled}/{@code Unhandled}),
+ * or {@code null} when the invocation succeeded
+ */
+record LambdaInvocationResult(String payload, String functionError) {
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/LambdaInvoker.java b/src/main/java/io/github/hectorvent/floci/services/swf/LambdaInvoker.java
new file mode 100644
index 0000000000..784e0b27ed
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/swf/LambdaInvoker.java
@@ -0,0 +1,21 @@
+package io.github.hectorvent.floci.services.swf;
+
+/**
+ * The slice of Lambda invocation SWF needs, so {@link SwfService} depends on a two-method
+ * seam rather than on {@code LambdaService} itself.
+ *
+ * This keeps the service unit-testable without a Docker daemon or the Lambda container
+ * stack: {@code SwfServiceTest} supplies a stub, while at runtime {@link SwfLambdaInvoker}
+ * delegates to the real Lambda service and its containers.
+ */
+interface LambdaInvoker {
+
+ /**
+ * Invokes {@code functionName} synchronously and returns its response.
+ *
+ * @throws io.github.hectorvent.floci.core.common.AwsException if the function cannot be
+ * resolved or invoked, so the caller can record the AWS error code as the
+ * LambdaFunctionFailed {@code reason}
+ */
+ LambdaInvocationResult invoke(String region, String functionName, byte[] payload);
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/SwfException.java b/src/main/java/io/github/hectorvent/floci/services/swf/SwfException.java
new file mode 100644
index 0000000000..c666733321
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/swf/SwfException.java
@@ -0,0 +1,30 @@
+package io.github.hectorvent.floci.services.swf;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+
+/**
+ * An SWF fault, which carries two different spellings of its name.
+ *
+ *
The response body's {@code __type} is namespaced
+ * ({@code com.amazonaws.swf.base.model#UnknownResourceFault}), while the
+ * {@code x-amzn-query-error} header carries the bare fault name. botocore prefers
+ * the header when both are present, so a namespaced value there makes the AWS CLI
+ * print {@code com.amazonaws.swf.base.model#UnknownResourceFault} as the error code
+ * where real SWF prints {@code UnknownResourceFault}. Keeping {@link #getErrorCode()}
+ * bare and overriding {@link #jsonType()} to add the namespace reproduces the live
+ * service on both surfaces.
+ */
+class SwfException extends AwsException {
+
+ private final String jsonType;
+
+ SwfException(String errorCode, String jsonType, String message, int httpStatus) {
+ super(errorCode, message, httpStatus);
+ this.jsonType = jsonType;
+ }
+
+ @Override
+ public String jsonType() {
+ return jsonType;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/SwfFaults.java b/src/main/java/io/github/hectorvent/floci/services/swf/SwfFaults.java
new file mode 100644
index 0000000000..aed81868ab
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/swf/SwfFaults.java
@@ -0,0 +1,133 @@
+package io.github.hectorvent.floci.services.swf;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.swf.model.SwfConstants;
+
+/**
+ * Factory for SWF faults.
+ *
+ *
SWF answers every modeled fault with HTTP 400 and a namespaced {@code __type}
+ * of {@code com.amazonaws.swf.base.model#} (validation failures use the
+ * Coral namespace instead). The AWS SDKs key on the part after {@code #}, so the
+ * namespace must be present for the response to deserialize into the typed
+ * exception the caller catches.
+ */
+final class SwfFaults {
+
+ private SwfFaults() {
+ }
+
+ static AwsException unknownDomain(String domain) {
+ return fault(SwfConstants.UNKNOWN_RESOURCE, "Unknown domain: " + domain);
+ }
+
+ static AwsException unknownExecution(String workflowId, String runId) {
+ return fault(SwfConstants.UNKNOWN_RESOURCE,
+ "Unknown execution, workflowId = " + workflowId + ", runId = " + runId);
+ }
+
+ static AwsException unknownExecution(String runId) {
+ return fault(SwfConstants.UNKNOWN_RESOURCE, "Unknown execution: WorkflowExecution=[runId=" + runId + "]");
+ }
+
+ static AwsException unknownWorkflowType(String name, String version) {
+ return fault(SwfConstants.UNKNOWN_RESOURCE,
+ "Unknown type: WorkflowType=[name=" + name + ", version=" + version + "]");
+ }
+
+ static AwsException unknownActivityType(String name, String version) {
+ return fault(SwfConstants.UNKNOWN_RESOURCE,
+ "Unknown type: ActivityType=[name=" + name + ", version=" + version + "]");
+ }
+
+ static AwsException unknownTaskToken() {
+ return fault(SwfConstants.UNKNOWN_RESOURCE, "Unknown or expired task token");
+ }
+
+ /**
+ * Raised when an activity task token resolves but the task is no longer open (completed,
+ * failed, canceled, or timed out). The live service names the scheduled event rather
+ * than reporting a bad token, since the token itself was valid.
+ */
+ static AwsException unknownActivity(long scheduledEventId) {
+ return fault(SwfConstants.UNKNOWN_RESOURCE,
+ "Unknown activity, scheduledEventId = " + scheduledEventId);
+ }
+
+ static AwsException domainAlreadyExists(String domain) {
+ return fault(SwfConstants.DOMAIN_ALREADY_EXISTS, domain);
+ }
+
+ static AwsException domainDeprecated(String domain) {
+ return fault(SwfConstants.DOMAIN_DEPRECATED, domain);
+ }
+
+ static AwsException workflowTypeAlreadyExists(String name, String version) {
+ return fault(SwfConstants.TYPE_ALREADY_EXISTS,
+ "WorkflowType=[name=" + name + ", version=" + version + "]");
+ }
+
+ static AwsException activityTypeAlreadyExists(String name, String version) {
+ return fault(SwfConstants.TYPE_ALREADY_EXISTS,
+ "ActivityType=[name=" + name + ", version=" + version + "]");
+ }
+
+ static AwsException workflowTypeDeprecated(String name, String version) {
+ return fault(SwfConstants.TYPE_DEPRECATED,
+ "WorkflowType=[name=" + name + ", version=" + version + "]");
+ }
+
+ static AwsException activityTypeDeprecated(String name, String version) {
+ return fault(SwfConstants.TYPE_DEPRECATED,
+ "ActivityType=[name=" + name + ", version=" + version + "]");
+ }
+
+ /**
+ * Raised by DeleteWorkflowType/DeleteActivityType before the type is deprecated. Unlike
+ * the other type faults, the live service answers with prose rather than the type
+ * descriptor, and uses the same wording for both workflow and activity types.
+ */
+ static AwsException typeNotDeprecated() {
+ return fault(SwfConstants.TYPE_NOT_DEPRECATED,
+ "The type is currently registered and cannot be deleted in its current state");
+ }
+
+ /**
+ * The live service returns this fault with an empty message; the runId of the
+ * already-open execution is not disclosed.
+ */
+ static AwsException executionAlreadyStarted() {
+ return fault(SwfConstants.WORKFLOW_EXECUTION_ALREADY_STARTED, "");
+ }
+
+ static AwsException defaultUndefined(String field) {
+ return fault(SwfConstants.DEFAULT_UNDEFINED, field);
+ }
+
+ /**
+ * The live service rejects a corrupt {@code nextPageToken} with this exact message rather
+ * than returning the first page.
+ */
+ static AwsException invalidPageToken() {
+ return validation("Invalid token");
+ }
+
+ static AwsException validation(String message) {
+ return new SwfException(SwfConstants.VALIDATION,
+ SwfConstants.VALIDATION_NAMESPACE + SwfConstants.VALIDATION, message, 400);
+ }
+
+ static AwsException validationConstraint(String value, String field, String constraint) {
+ return validation("1 validation error detected: Value '" + value + "' at '" + field
+ + "' failed to satisfy constraint: " + constraint);
+ }
+
+ static AwsException missingRequired(String field) {
+ return validation("1 validation error detected: Value null at '" + field
+ + "' failed to satisfy constraint: Member must not be null");
+ }
+
+ static AwsException fault(String code, String message) {
+ return new SwfException(code, SwfConstants.FAULT_NAMESPACE + code, message, 400);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/SwfJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/swf/SwfJsonHandler.java
new file mode 100644
index 0000000000..0e1d2c7db9
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/swf/SwfJsonHandler.java
@@ -0,0 +1,775 @@
+package io.github.hectorvent.floci.services.swf;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.swf.SwfService.Decision;
+import io.github.hectorvent.floci.services.swf.SwfService.ExecutionFilter;
+import io.github.hectorvent.floci.services.swf.SwfService.StartWorkflowExecutionRequest;
+import io.github.hectorvent.floci.services.swf.model.SwfActivityTask;
+import io.github.hectorvent.floci.services.swf.model.SwfActivityType;
+import io.github.hectorvent.floci.services.swf.model.SwfDecisionTask;
+import io.github.hectorvent.floci.services.swf.model.SwfDomain;
+import io.github.hectorvent.floci.services.swf.model.SwfHistoryEvent;
+import io.github.hectorvent.floci.services.swf.model.SwfWorkflowExecution;
+import io.github.hectorvent.floci.services.swf.model.SwfWorkflowType;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.core.Response;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.function.Function;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Translates the SWF JSON 1.0 wire protocol to and from {@link SwfService}.
+ *
+ * Two wire details this class is responsible for:
+ *
+ * - Timestamps are epoch-second numbers, not ISO strings — the AWS SDKs parse
+ * {@code 1.786560427599E9} and reject a formatted date.
+ * - Operations SWF models with no output shape must answer HTTP 200 with an
+ * empty body, not {@code {}} — {@code Content-Length: 0} is what the SDKs
+ * expect for a void operation.
+ *
+ */
+@ApplicationScoped
+public class SwfJsonHandler {
+
+ private final SwfService service;
+ private final ObjectMapper objectMapper;
+ private final RegionResolver regionResolver;
+
+ @Inject
+ public SwfJsonHandler(SwfService service, ObjectMapper objectMapper, RegionResolver regionResolver) {
+ this.service = service;
+ this.objectMapper = objectMapper;
+ this.regionResolver = regionResolver;
+ }
+
+ public Response handle(String action, JsonNode request, String region) {
+ return switch (action) {
+ case "RegisterDomain" -> registerDomain(request, region);
+ case "DescribeDomain" -> describeDomain(request, region);
+ case "ListDomains" -> listDomains(request, region);
+ case "DeprecateDomain" -> voidResponse(() -> service.deprecateDomain(region, text(request, "name")));
+ case "UndeprecateDomain" -> voidResponse(() -> service.undeprecateDomain(region, text(request, "name")));
+
+ case "RegisterWorkflowType" -> registerWorkflowType(request, region);
+ case "DescribeWorkflowType" -> describeWorkflowType(request, region);
+ case "ListWorkflowTypes" -> listWorkflowTypes(request, region);
+ case "DeprecateWorkflowType" -> voidResponse(() -> service.deprecateWorkflowType(region,
+ text(request, "domain"), nested(request, "workflowType", "name"),
+ nested(request, "workflowType", "version")));
+ case "UndeprecateWorkflowType" -> voidResponse(() -> service.undeprecateWorkflowType(region,
+ text(request, "domain"), nested(request, "workflowType", "name"),
+ nested(request, "workflowType", "version")));
+ case "DeleteWorkflowType" -> voidResponse(() -> service.deleteWorkflowType(region,
+ text(request, "domain"), nested(request, "workflowType", "name"),
+ nested(request, "workflowType", "version")));
+
+ case "RegisterActivityType" -> registerActivityType(request, region);
+ case "DescribeActivityType" -> describeActivityType(request, region);
+ case "ListActivityTypes" -> listActivityTypes(request, region);
+ case "DeprecateActivityType" -> voidResponse(() -> service.deprecateActivityType(region,
+ text(request, "domain"), nested(request, "activityType", "name"),
+ nested(request, "activityType", "version")));
+ case "UndeprecateActivityType" -> voidResponse(() -> service.undeprecateActivityType(region,
+ text(request, "domain"), nested(request, "activityType", "name"),
+ nested(request, "activityType", "version")));
+ case "DeleteActivityType" -> voidResponse(() -> service.deleteActivityType(region,
+ text(request, "domain"), nested(request, "activityType", "name"),
+ nested(request, "activityType", "version")));
+
+ case "StartWorkflowExecution" -> startWorkflowExecution(request, region);
+ case "DescribeWorkflowExecution" -> describeWorkflowExecution(request, region);
+ case "GetWorkflowExecutionHistory" -> getWorkflowExecutionHistory(request, region);
+ case "ListOpenWorkflowExecutions" -> listExecutions(request, region, false);
+ case "ListClosedWorkflowExecutions" -> listExecutions(request, region, true);
+ case "CountOpenWorkflowExecutions" -> countExecutions(request, region, false);
+ case "CountClosedWorkflowExecutions" -> countExecutions(request, region, true);
+ case "CountPendingActivityTasks" -> count(service.countPendingActivityTasks(region,
+ text(request, "domain"), nested(request, "taskList", "name")));
+ case "CountPendingDecisionTasks" -> count(service.countPendingDecisionTasks(region,
+ text(request, "domain"), nested(request, "taskList", "name")));
+
+ case "PollForDecisionTask" -> pollForDecisionTask(request, region);
+ case "RespondDecisionTaskCompleted" -> respondDecisionTaskCompleted(request);
+ case "PollForActivityTask" -> pollForActivityTask(request, region);
+ case "RecordActivityTaskHeartbeat" -> recordActivityTaskHeartbeat(request);
+ case "RespondActivityTaskCompleted" -> voidResponse(() -> service.respondActivityTaskCompleted(
+ text(request, "taskToken"), text(request, "result")));
+ case "RespondActivityTaskFailed" -> voidResponse(() -> service.respondActivityTaskFailed(
+ text(request, "taskToken"), text(request, "reason"), text(request, "details")));
+ case "RespondActivityTaskCanceled" -> voidResponse(() -> service.respondActivityTaskCanceled(
+ text(request, "taskToken"), text(request, "details")));
+
+ case "SignalWorkflowExecution" -> voidResponse(() -> service.signalWorkflowExecution(region,
+ text(request, "domain"), text(request, "workflowId"), text(request, "runId"),
+ text(request, "signalName"), text(request, "input")));
+ case "RequestCancelWorkflowExecution" -> voidResponse(() -> service.requestCancelWorkflowExecution(region,
+ text(request, "domain"), text(request, "workflowId"), text(request, "runId")));
+ case "TerminateWorkflowExecution" -> voidResponse(() -> service.terminateWorkflowExecution(region,
+ text(request, "domain"), text(request, "workflowId"), text(request, "runId"),
+ text(request, "reason"), text(request, "details"), text(request, "childPolicy")));
+
+ case "ListTagsForResource" -> listTagsForResource(request);
+ case "TagResource" -> voidResponse(() -> service.tagResource(
+ text(request, "resourceArn"), parseTags(request.path("tags"))));
+ case "UntagResource" -> voidResponse(() -> service.untagResource(
+ text(request, "resourceArn"), parseStringList(request.path("tagKeys"))));
+
+ default -> null;
+ };
+ }
+
+ // ──────────────────────────────── Domains ────────────────────────────────
+
+ private Response registerDomain(JsonNode request, String region) {
+ service.registerDomain(
+ text(request, "name"),
+ text(request, "description"),
+ text(request, "workflowExecutionRetentionPeriodInDays"),
+ parseTags(request.path("tags")),
+ region);
+ return empty();
+ }
+
+ private Response describeDomain(JsonNode request, String region) {
+ SwfDomain domain = service.describeDomain(region, text(request, "name"));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("domainInfo", domainInfo(domain, region));
+ response.putObject("configuration")
+ .put("workflowExecutionRetentionPeriodInDays", domain.getWorkflowExecutionRetentionPeriodInDays());
+ return Response.ok(response).build();
+ }
+
+ private Response listDomains(JsonNode request, String region) {
+ List domains = service.listDomains(region, text(request, "registrationStatus"));
+ if (request.path("reverseOrder").asBoolean(false)) {
+ domains = new ArrayList<>(domains);
+ java.util.Collections.reverse(domains);
+ }
+ return pagedList(request, "domainInfos", domains, domain -> domainInfo(domain, region));
+ }
+
+ private ObjectNode domainInfo(SwfDomain domain, String region) {
+ ObjectNode info = objectMapper.createObjectNode();
+ info.put("name", domain.getName());
+ info.put("status", domain.getStatus());
+ putIfPresent(info, "description", domain.getDescription());
+ info.put("arn", service.domainArnFor(domain, region));
+ return info;
+ }
+
+ // ───────────────────────────── Workflow types ────────────────────────────
+
+ private Response registerWorkflowType(JsonNode request, String region) {
+ SwfWorkflowType type = new SwfWorkflowType();
+ type.setName(text(request, "name"));
+ type.setVersion(text(request, "version"));
+ type.setDescription(text(request, "description"));
+ type.setDefaultTaskStartToCloseTimeout(text(request, "defaultTaskStartToCloseTimeout"));
+ type.setDefaultExecutionStartToCloseTimeout(text(request, "defaultExecutionStartToCloseTimeout"));
+ type.setDefaultTaskList(nested(request, "defaultTaskList", "name"));
+ type.setDefaultTaskPriority(text(request, "defaultTaskPriority"));
+ type.setDefaultChildPolicy(text(request, "defaultChildPolicy"));
+ type.setDefaultLambdaRole(text(request, "defaultLambdaRole"));
+ service.registerWorkflowType(region, text(request, "domain"), type);
+ return empty();
+ }
+
+ private Response describeWorkflowType(JsonNode request, String region) {
+ SwfWorkflowType type = service.describeWorkflowType(region, text(request, "domain"),
+ nested(request, "workflowType", "name"), nested(request, "workflowType", "version"));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("typeInfo", workflowTypeInfo(type));
+
+ ObjectNode configuration = response.putObject("configuration");
+ putIfPresent(configuration, "defaultTaskStartToCloseTimeout", type.getDefaultTaskStartToCloseTimeout());
+ putIfPresent(configuration, "defaultExecutionStartToCloseTimeout",
+ type.getDefaultExecutionStartToCloseTimeout());
+ putTaskList(configuration, "defaultTaskList", type.getDefaultTaskList());
+ putIfPresent(configuration, "defaultTaskPriority", type.getDefaultTaskPriority());
+ putIfPresent(configuration, "defaultChildPolicy", type.getDefaultChildPolicy());
+ putIfPresent(configuration, "defaultLambdaRole", type.getDefaultLambdaRole());
+ return Response.ok(response).build();
+ }
+
+ private Response listWorkflowTypes(JsonNode request, String region) {
+ List types = service.listWorkflowTypes(region, text(request, "domain"), text(request, "name"),
+ text(request, "registrationStatus"), request.path("reverseOrder").asBoolean(false));
+ return pagedList(request, "typeInfos", types, this::workflowTypeInfo);
+ }
+
+ private ObjectNode workflowTypeInfo(SwfWorkflowType type) {
+ ObjectNode info = objectMapper.createObjectNode();
+ info.set("workflowType", typeNode(type.getName(), type.getVersion()));
+ info.put("status", type.getStatus());
+ putIfPresent(info, "description", type.getDescription());
+ info.put("creationDate", type.getCreationDate());
+ if (type.getDeprecationDate() != null) {
+ info.put("deprecationDate", type.getDeprecationDate());
+ }
+ return info;
+ }
+
+ // ───────────────────────────── Activity types ────────────────────────────
+
+ private Response registerActivityType(JsonNode request, String region) {
+ SwfActivityType type = new SwfActivityType();
+ type.setName(text(request, "name"));
+ type.setVersion(text(request, "version"));
+ type.setDescription(text(request, "description"));
+ type.setDefaultTaskStartToCloseTimeout(text(request, "defaultTaskStartToCloseTimeout"));
+ type.setDefaultTaskHeartbeatTimeout(text(request, "defaultTaskHeartbeatTimeout"));
+ type.setDefaultTaskList(nested(request, "defaultTaskList", "name"));
+ type.setDefaultTaskPriority(text(request, "defaultTaskPriority"));
+ type.setDefaultTaskScheduleToStartTimeout(text(request, "defaultTaskScheduleToStartTimeout"));
+ type.setDefaultTaskScheduleToCloseTimeout(text(request, "defaultTaskScheduleToCloseTimeout"));
+ service.registerActivityType(region, text(request, "domain"), type);
+ return empty();
+ }
+
+ private Response describeActivityType(JsonNode request, String region) {
+ SwfActivityType type = service.describeActivityType(region, text(request, "domain"),
+ nested(request, "activityType", "name"), nested(request, "activityType", "version"));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("typeInfo", activityTypeInfo(type));
+
+ ObjectNode configuration = response.putObject("configuration");
+ putIfPresent(configuration, "defaultTaskStartToCloseTimeout", type.getDefaultTaskStartToCloseTimeout());
+ putIfPresent(configuration, "defaultTaskHeartbeatTimeout", type.getDefaultTaskHeartbeatTimeout());
+ putTaskList(configuration, "defaultTaskList", type.getDefaultTaskList());
+ putIfPresent(configuration, "defaultTaskPriority", type.getDefaultTaskPriority());
+ putIfPresent(configuration, "defaultTaskScheduleToStartTimeout",
+ type.getDefaultTaskScheduleToStartTimeout());
+ putIfPresent(configuration, "defaultTaskScheduleToCloseTimeout",
+ type.getDefaultTaskScheduleToCloseTimeout());
+ return Response.ok(response).build();
+ }
+
+ private Response listActivityTypes(JsonNode request, String region) {
+ List types = service.listActivityTypes(region, text(request, "domain"), text(request, "name"),
+ text(request, "registrationStatus"), request.path("reverseOrder").asBoolean(false));
+ return pagedList(request, "typeInfos", types, this::activityTypeInfo);
+ }
+
+ private ObjectNode activityTypeInfo(SwfActivityType type) {
+ ObjectNode info = objectMapper.createObjectNode();
+ info.set("activityType", typeNode(type.getName(), type.getVersion()));
+ info.put("status", type.getStatus());
+ putIfPresent(info, "description", type.getDescription());
+ info.put("creationDate", type.getCreationDate());
+ if (type.getDeprecationDate() != null) {
+ info.put("deprecationDate", type.getDeprecationDate());
+ }
+ return info;
+ }
+
+ // ─────────────────────────────── Executions ──────────────────────────────
+
+ private Response startWorkflowExecution(JsonNode request, String region) {
+ String runId = service.startWorkflowExecution(new StartWorkflowExecutionRequest(
+ region,
+ text(request, "domain"),
+ text(request, "workflowId"),
+ nested(request, "workflowType", "name"),
+ nested(request, "workflowType", "version"),
+ nested(request, "taskList", "name"),
+ text(request, "taskPriority"),
+ text(request, "input"),
+ text(request, "executionStartToCloseTimeout"),
+ text(request, "taskStartToCloseTimeout"),
+ text(request, "childPolicy"),
+ parseStringList(request.path("tagList")),
+ text(request, "lambdaRole")));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("runId", runId);
+ return Response.ok(response).build();
+ }
+
+ private Response describeWorkflowExecution(JsonNode request, String region) {
+ SwfWorkflowExecution execution = service.describeWorkflowExecution(region, text(request, "domain"),
+ nested(request, "execution", "workflowId"), nested(request, "execution", "runId"));
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.set("executionInfo", executionInfo(execution));
+
+ ObjectNode configuration = response.putObject("executionConfiguration");
+ configuration.put("taskStartToCloseTimeout", execution.getTaskStartToCloseTimeout());
+ configuration.put("executionStartToCloseTimeout", execution.getExecutionStartToCloseTimeout());
+ putTaskList(configuration, "taskList", execution.getTaskList());
+ putIfPresent(configuration, "taskPriority", execution.getTaskPriority());
+ configuration.put("childPolicy", execution.getChildPolicy());
+ putIfPresent(configuration, "lambdaRole", execution.getLambdaRole());
+
+ ObjectNode openCounts = response.putObject("openCounts");
+ openCounts.put("openActivityTasks", service.openActivityCount(execution));
+ openCounts.put("openDecisionTasks", service.openDecisionTaskCount(execution));
+ openCounts.put("openTimers", service.openTimerCount(execution));
+ openCounts.put("openChildWorkflowExecutions", service.openChildCount(execution));
+ openCounts.put("openLambdaFunctions", 0);
+
+ if (execution.getLatestActivityTaskTimestamp() != null) {
+ response.put("latestActivityTaskTimestamp", execution.getLatestActivityTaskTimestamp());
+ }
+ putIfPresent(response, "latestExecutionContext", execution.getLatestExecutionContext());
+ return Response.ok(response).build();
+ }
+
+ /**
+ * Applies {@code maximumPageSize} and {@code nextPageToken} to an already-ordered list,
+ * appending each item on the page via {@code render} and setting {@code nextPageToken}
+ * only when more items remain.
+ *
+ * Measured against the live service: the token is absent on the final page even when
+ * that page is exactly full; a {@code maximumPageSize} of 0 (or absent) means "no caller
+ * limit"; above 1000 is a ValidationException; and an unparseable token is rejected rather
+ * than silently restarting from the beginning.
+ */
+ private Response pagedList(JsonNode request, String itemsField, List items,
+ Function render) {
+ int pageSize = service.pageSize(optionalInt(request, "maximumPageSize"));
+ int from = Math.min(decodePageToken(text(request, "nextPageToken")).offset(), items.size());
+ int to = Math.min(from + pageSize, items.size());
+
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode array = response.putArray(itemsField);
+ for (T item : items.subList(from, to)) {
+ array.add(render.apply(item));
+ }
+ if (to < items.size()) {
+ response.put("nextPageToken", encodePageToken(to, null));
+ }
+ return Response.ok(response).build();
+ }
+
+ private Response getWorkflowExecutionHistory(JsonNode request, String region) {
+ boolean reverseOrder = request.path("reverseOrder").asBoolean(false);
+ List events = service.getWorkflowExecutionHistory(region, text(request, "domain"),
+ nested(request, "execution", "workflowId"), nested(request, "execution", "runId"), reverseOrder);
+
+ return pagedList(request, "events", events, this::historyEvent);
+ }
+
+ private Response listExecutions(JsonNode request, String region, boolean closed) {
+ List executions = service.listExecutions(region, text(request, "domain"),
+ buildFilter(request, closed), closed);
+ if (request.path("reverseOrder").asBoolean(false)) {
+ executions = new ArrayList<>(executions);
+ java.util.Collections.reverse(executions);
+ }
+
+ return pagedList(request, "executionInfos", executions, this::executionInfo);
+ }
+
+ private Response countExecutions(JsonNode request, String region, boolean closed) {
+ List executions = service.listExecutions(region, text(request, "domain"),
+ buildFilter(request, closed), closed);
+ return count(executions.size());
+ }
+
+ private Response count(int value) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("count", value);
+ response.put("truncated", false);
+ return Response.ok(response).build();
+ }
+
+ private ObjectNode executionInfo(SwfWorkflowExecution execution) {
+ ObjectNode info = objectMapper.createObjectNode();
+ info.set("execution", executionNode(execution.getWorkflowId(), execution.getRunId()));
+ info.set("workflowType", typeNode(execution.getWorkflowTypeName(), execution.getWorkflowTypeVersion()));
+ info.put("startTimestamp", execution.getStartTimestamp());
+ if (execution.getCloseTimestamp() != null) {
+ info.put("closeTimestamp", execution.getCloseTimestamp());
+ }
+ info.put("executionStatus", execution.getExecutionStatus());
+ putIfPresent(info, "closeStatus", execution.getCloseStatus());
+ if (execution.getParentWorkflowId() != null) {
+ info.set("parent", executionNode(execution.getParentWorkflowId(), execution.getParentRunId()));
+ }
+ if (!execution.getTagList().isEmpty()) {
+ ArrayNode tags = info.putArray("tagList");
+ execution.getTagList().forEach(tags::add);
+ }
+ info.put("cancelRequested", execution.isCancelRequested());
+ return info;
+ }
+
+ /**
+ * Builds the filter from whichever of the mutually exclusive filter members is present.
+ * SWF applies at most one of executionFilter/typeFilter/tagFilter, plus the time filter
+ * that matches the list flavour (startTimeFilter for open, either for closed).
+ */
+ private ExecutionFilter buildFilter(JsonNode request, boolean closed) {
+ ExecutionFilter filter = ExecutionFilter.all();
+
+ JsonNode executionFilter = request.path("executionFilter");
+ if (executionFilter.hasNonNull("workflowId")) {
+ String workflowId = executionFilter.path("workflowId").asText();
+ filter = filter.and(execution -> workflowId.equals(execution.getWorkflowId()));
+ }
+
+ JsonNode typeFilter = request.path("typeFilter");
+ if (typeFilter.hasNonNull("name")) {
+ String name = typeFilter.path("name").asText();
+ String version = typeFilter.path("version").asText(null);
+ filter = filter.and(execution -> name.equals(execution.getWorkflowTypeName())
+ && (version == null || version.isEmpty() || version.equals(execution.getWorkflowTypeVersion())));
+ }
+
+ JsonNode tagFilter = request.path("tagFilter");
+ if (tagFilter.hasNonNull("tag")) {
+ String tag = tagFilter.path("tag").asText();
+ filter = filter.and(execution -> execution.getTagList().contains(tag));
+ }
+
+ if (closed) {
+ JsonNode closeStatusFilter = request.path("closeStatusFilter");
+ if (closeStatusFilter.hasNonNull("status")) {
+ String status = closeStatusFilter.path("status").asText();
+ filter = filter.and(execution -> status.equals(execution.getCloseStatus()));
+ }
+ filter = filter.and(timeFilter(request.path("closeTimeFilter"),
+ execution -> execution.getCloseTimestamp() != null ? execution.getCloseTimestamp() : 0.0));
+ }
+ return filter.and(timeFilter(request.path("startTimeFilter"),
+ SwfWorkflowExecution::getStartTimestamp));
+ }
+
+ private ExecutionFilter timeFilter(JsonNode filterNode,
+ java.util.function.ToDoubleFunction extractor) {
+ if (filterNode == null || filterNode.isMissingNode() || filterNode.isNull()) {
+ return ExecutionFilter.all();
+ }
+ Double oldest = filterNode.hasNonNull("oldestDate") ? filterNode.path("oldestDate").asDouble() : null;
+ Double latest = filterNode.hasNonNull("latestDate") ? filterNode.path("latestDate").asDouble() : null;
+ if (oldest == null && latest == null) {
+ return ExecutionFilter.all();
+ }
+ return execution -> {
+ double value = extractor.applyAsDouble(execution);
+ return (oldest == null || value >= oldest) && (latest == null || value <= latest);
+ };
+ }
+
+ // ─────────────────────────────── Task polling ────────────────────────────
+
+ /**
+ * {@code PollForDecisionTask}.
+ *
+ * A request carrying {@code nextPageToken} continues an earlier poll rather than starting
+ * a new one — the live service documents that "calling PollForDecisionTask with a
+ * nextPageToken doesn't return a new decision task", and answers with the same task's next
+ * history page, same {@code startedEventId} and {@code workflowExecution}. The token
+ * therefore names the task it belongs to, and a continuation resolves that task instead of
+ * claiming another.
+ */
+ private Response pollForDecisionTask(JsonNode request, String region) {
+ String pageToken = text(request, "nextPageToken");
+ SwfDecisionTask task;
+ int offset;
+ if (pageToken != null && !pageToken.isEmpty()) {
+ Page page = decodePageToken(pageToken);
+ if (page.taskToken() == null) {
+ throw SwfFaults.invalidPageToken();
+ }
+ task = service.decisionTaskForToken(page.taskToken());
+ offset = page.offset();
+ } else {
+ Optional maybeTask = service.pollForDecisionTask(region,
+ text(request, "domain"), nested(request, "taskList", "name"),
+ text(request, "identity"));
+ if (maybeTask.isEmpty()) {
+ return Response.ok(emptyPollResponse()).build();
+ }
+ task = maybeTask.get();
+ offset = 0;
+ }
+
+ boolean reverseOrder = request.path("reverseOrder").asBoolean(false);
+ List events = service.getWorkflowExecutionHistory(region, task.getDomain(),
+ task.getWorkflowId(), task.getRunId(), reverseOrder);
+
+ // startAtPreviousStartedEvent trims the history to what the decider has not seen,
+ // starting *at* previousStartedEventId — inclusive, measured against the live service.
+ long from = task.getPreviousStartedEventId();
+ if (request.path("startAtPreviousStartedEvent").asBoolean(false) && from > 0) {
+ events = events.stream().filter(e -> e.getEventId() >= from).toList();
+ }
+
+ int pageSize = service.pageSize(optionalInt(request, "maximumPageSize"));
+ int end = Math.min(offset + pageSize, events.size());
+
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("taskToken", task.getTaskToken());
+ response.put("startedEventId", task.getStartedEventId());
+ response.set("workflowExecution", executionNode(task.getWorkflowId(), task.getRunId()));
+ ArrayNode array = response.putArray("events");
+ for (SwfHistoryEvent event : events.subList(Math.min(offset, events.size()), end)) {
+ array.add(historyEvent(event));
+ }
+ response.put("previousStartedEventId", task.getPreviousStartedEventId());
+ if (end < events.size()) {
+ response.put("nextPageToken", encodePageToken(end, task.getTaskToken()));
+ }
+
+ SwfWorkflowExecution execution = service.describeWorkflowExecution(region, task.getDomain(),
+ task.getWorkflowId(), task.getRunId());
+ response.set("workflowType", typeNode(execution.getWorkflowTypeName(),
+ execution.getWorkflowTypeVersion()));
+ return Response.ok(response).build();
+ }
+
+ /**
+ * An empty poll answers 200 with {@code taskToken: ""}. The SDKs treat the empty
+ * token as "no task"; omitting the member makes them raise on a missing required field.
+ */
+ private ObjectNode emptyPollResponse() {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("taskToken", "");
+ response.put("startedEventId", 0);
+ response.put("previousStartedEventId", 0);
+ return response;
+ }
+
+ private Response pollForActivityTask(JsonNode request, String region) {
+ Optional maybeTask = service.pollForActivityTask(region, text(request, "domain"),
+ nested(request, "taskList", "name"), text(request, "identity"));
+ if (maybeTask.isEmpty()) {
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("taskToken", "");
+ response.put("activityId", "");
+ response.put("startedEventId", 0);
+ return Response.ok(response).build();
+ }
+
+ SwfActivityTask task = maybeTask.get();
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("taskToken", task.getTaskToken());
+ response.put("activityId", task.getActivityId());
+ response.put("startedEventId", task.getStartedEventId());
+ response.set("workflowExecution", executionNode(task.getWorkflowId(), task.getRunId()));
+ response.set("activityType", typeNode(task.getActivityTypeName(), task.getActivityTypeVersion()));
+ putIfPresent(response, "input", task.getInput());
+ return Response.ok(response).build();
+ }
+
+ private Response recordActivityTaskHeartbeat(JsonNode request) {
+ boolean cancelRequested = service.recordActivityTaskHeartbeat(text(request, "taskToken"),
+ text(request, "details"));
+ ObjectNode response = objectMapper.createObjectNode();
+ response.put("cancelRequested", cancelRequested);
+ return Response.ok(response).build();
+ }
+
+ private Response respondDecisionTaskCompleted(JsonNode request) {
+ service.respondDecisionTaskCompleted(text(request, "taskToken"),
+ parseDecisions(request.path("decisions")), text(request, "executionContext"));
+ return empty();
+ }
+
+ /**
+ * Unwraps each decision from its {@code DecisionAttributes} envelope. The
+ * attribute member name is the decision type with a lower-cased first letter, which is
+ * how the model names every one of the thirteen decision types.
+ */
+ private List parseDecisions(JsonNode decisionsNode) {
+ List decisions = new ArrayList<>();
+ if (!decisionsNode.isArray()) {
+ return decisions;
+ }
+ for (JsonNode node : decisionsNode) {
+ String type = node.path("decisionType").asText(null);
+ if (type == null || type.isEmpty()) {
+ throw SwfFaults.missingRequired("decisions.1.member.decisionType");
+ }
+ String attributesField = Character.toLowerCase(type.charAt(0)) + type.substring(1)
+ + "DecisionAttributes";
+ decisions.add(new Decision(type, toMap(node.path(attributesField))));
+ }
+ return decisions;
+ }
+
+ private Response listTagsForResource(JsonNode request) {
+ Map tags = service.listTagsForResource(text(request, "resourceArn"));
+ ObjectNode response = objectMapper.createObjectNode();
+ ArrayNode array = response.putArray("tags");
+ tags.forEach((key, value) -> {
+ ObjectNode entry = array.addObject();
+ entry.put("key", key);
+ if (value != null) {
+ entry.put("value", value);
+ }
+ });
+ return Response.ok(response).build();
+ }
+
+ // ──────────────────────────── Wire serialization ─────────────────────────
+
+ private ObjectNode historyEvent(SwfHistoryEvent event) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("eventTimestamp", event.getEventTimestamp());
+ node.put("eventType", event.getEventType());
+ node.put("eventId", event.getEventId());
+ if (!event.getAttributes().isEmpty()) {
+ node.set(event.attributesFieldName(), objectMapper.valueToTree(event.getAttributes()));
+ }
+ return node;
+ }
+
+ private ObjectNode typeNode(String name, String version) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("name", name);
+ node.put("version", version);
+ return node;
+ }
+
+ private ObjectNode executionNode(String workflowId, String runId) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("workflowId", workflowId);
+ node.put("runId", runId);
+ return node;
+ }
+
+ private void putTaskList(ObjectNode parent, String field, String taskList) {
+ if (taskList != null && !taskList.isEmpty()) {
+ parent.putObject(field).put("name", taskList);
+ }
+ }
+
+ private static void putIfPresent(ObjectNode node, String field, String value) {
+ if (value != null && !value.isEmpty()) {
+ node.put(field, value);
+ }
+ }
+
+ /**
+ * Operations SWF models without an output shape answer 200 with no body. Returning
+ * {@code {}} instead makes strict SDK response handlers log a shape mismatch.
+ */
+ private Response empty() {
+ return Response.ok().build();
+ }
+
+ private Response voidResponse(Runnable action) {
+ action.run();
+ return empty();
+ }
+
+ private static String text(JsonNode request, String field) {
+ JsonNode node = request.get(field);
+ return node != null && !node.isNull() ? node.asText() : null;
+ }
+
+ private static String nested(JsonNode request, String field, String key) {
+ JsonNode parent = request.get(field);
+ if (parent == null || parent.isNull()) {
+ return null;
+ }
+ JsonNode node = parent.get(key);
+ return node != null && !node.isNull() ? node.asText() : null;
+ }
+
+ /**
+ * Reads an optional integer, rejecting wrong types rather than letting
+ * {@code asInt()} coerce a string or fraction to 0 and silently mean "use the default".
+ */
+ private static Integer optionalInt(JsonNode request, String field) {
+ JsonNode node = request.get(field);
+ if (node == null || node.isNull()) {
+ return null;
+ }
+ if (!node.isIntegralNumber()) {
+ throw SwfFaults.validationConstraint(node.toString(), field, "Member must be an integer.");
+ }
+ return node.intValue();
+ }
+
+ private static Map parseTags(JsonNode tagsNode) {
+ Map tags = new LinkedHashMap<>();
+ if (tagsNode != null && tagsNode.isArray()) {
+ for (JsonNode entry : tagsNode) {
+ String key = entry.path("key").asText(null);
+ if (key != null) {
+ tags.put(key, entry.path("value").asText(""));
+ }
+ }
+ }
+ return tags;
+ }
+
+ private static List parseStringList(JsonNode arrayNode) {
+ if (arrayNode == null || !arrayNode.isArray()) {
+ return null;
+ }
+ List values = new ArrayList<>();
+ for (JsonNode node : arrayNode) {
+ values.add(node.asText());
+ }
+ return values;
+ }
+
+ @SuppressWarnings("unchecked")
+ private Map toMap(JsonNode node) {
+ if (node == null || !node.isObject()) {
+ return Map.of();
+ }
+ return objectMapper.convertValue(node, Map.class);
+ }
+
+ /**
+ * A decoded continuation token: how far the caller has read, and — for
+ * {@code PollForDecisionTask} — which decision task the page belongs to.
+ *
+ * SWF tokens are opaque blobs, so the encoding is ours to choose; a corrupt one is
+ * rejected with {@code ValidationException: Invalid token} rather than restarting at the
+ * first page, which would turn a caller's paging loop into an infinite one.
+ */
+ private record Page(int offset, String taskToken) {
+
+ static final Page FIRST = new Page(0, null);
+ }
+
+ private static String encodePageToken(int offset, String taskToken) {
+ String body = "offset=" + offset + (taskToken == null ? "" : "\ntask=" + taskToken);
+ return java.util.Base64.getEncoder()
+ .encodeToString(body.getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ }
+
+ private static Page decodePageToken(String token) {
+ if (token == null || token.isEmpty()) {
+ return Page.FIRST;
+ }
+ String decoded;
+ try {
+ decoded = new String(java.util.Base64.getDecoder().decode(token),
+ java.nio.charset.StandardCharsets.UTF_8);
+ } catch (IllegalArgumentException e) {
+ throw SwfFaults.invalidPageToken();
+ }
+ if (!decoded.startsWith("offset=")) {
+ throw SwfFaults.invalidPageToken();
+ }
+ int split = decoded.indexOf("\ntask=");
+ String offsetPart = split < 0 ? decoded.substring("offset=".length())
+ : decoded.substring("offset=".length(), split);
+ String taskToken = split < 0 ? null : decoded.substring(split + "\ntask=".length());
+ try {
+ int offset = Integer.parseInt(offsetPart);
+ if (offset < 0 || (taskToken != null && taskToken.isEmpty())) {
+ throw SwfFaults.invalidPageToken();
+ }
+ return new Page(offset, taskToken);
+ } catch (NumberFormatException e) {
+ throw SwfFaults.invalidPageToken();
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/SwfLambdaInvoker.java b/src/main/java/io/github/hectorvent/floci/services/swf/SwfLambdaInvoker.java
new file mode 100644
index 0000000000..477a1f48e9
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/swf/SwfLambdaInvoker.java
@@ -0,0 +1,39 @@
+package io.github.hectorvent.floci.services.swf;
+
+import io.github.hectorvent.floci.services.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.InvocationType;
+import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.nio.charset.StandardCharsets;
+
+/**
+ * Runtime {@link LambdaInvoker}: runs the function through Floci's own Lambda service, which
+ * executes it in a container exactly as an {@code Invoke} API call would.
+ *
+ *
Uses {@link InvocationType#RequestResponse} because SWF needs the response body to record
+ * as the LambdaFunctionCompleted {@code result} — an {@code Event} invocation would return
+ * immediately with nothing to record, the same reason the EventBridge and Scheduler invokers
+ * pick {@code Event} for their fire-and-forget targets and this one does not.
+ */
+@ApplicationScoped
+public class SwfLambdaInvoker implements LambdaInvoker {
+
+ private final LambdaService lambdaService;
+
+ @Inject
+ public SwfLambdaInvoker(LambdaService lambdaService) {
+ this.lambdaService = lambdaService;
+ }
+
+ @Override
+ public LambdaInvocationResult invoke(String region, String functionName, byte[] payload) {
+ InvokeResult result = lambdaService.invoke(region, functionName, payload,
+ InvocationType.RequestResponse);
+ byte[] body = result.getPayload();
+ return new LambdaInvocationResult(
+ body == null ? "" : new String(body, StandardCharsets.UTF_8),
+ result.getFunctionError());
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/swf/SwfService.java b/src/main/java/io/github/hectorvent/floci/services/swf/SwfService.java
new file mode 100644
index 0000000000..b7f5f12df6
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/swf/SwfService.java
@@ -0,0 +1,2155 @@
+package io.github.hectorvent.floci.services.swf;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.Resettable;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.swf.model.SwfActivityTask;
+import io.github.hectorvent.floci.services.swf.model.SwfActivityType;
+import io.github.hectorvent.floci.services.swf.model.SwfConstants;
+import io.github.hectorvent.floci.services.swf.model.SwfDecisionTask;
+import io.github.hectorvent.floci.services.swf.model.SwfDomain;
+import io.github.hectorvent.floci.services.swf.model.SwfHistoryEvent;
+import io.github.hectorvent.floci.services.swf.model.SwfTimer;
+import io.github.hectorvent.floci.services.swf.model.SwfWorkflowExecution;
+import io.github.hectorvent.floci.services.swf.model.SwfWorkflowType;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Clock;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Predicate;
+
+/**
+ * Amazon SWF domain logic: registration, the workflow execution state machine, and
+ * the decision/activity task lifecycle.
+ *
+ *
Storage layout. Domains and types are keyed by ARN-like composite keys and live in
+ * {@link StorageBackend}s so they survive restarts under persistent storage modes.
+ * Executions are keyed {@code domain/workflowId/runId}. Task tokens are an in-memory
+ * index only: SWF tokens do not outlive a service restart, and a token that resolved
+ * after a restart would point at a decision the emulator can no longer honour.
+ *
+ *
Event ordering. Every state transition appends to the execution's history under the
+ * execution's monotonic {@code nextEventId}. All mutation is serialized per domain via
+ * {@link #domainLock(String, String)} because deciders and workers poll concurrently, and a
+ * torn history (two events sharing an id, or an activity closing twice) is
+ * indistinguishable from corruption to an SDK-driven decider.
+ *
+ *
The lock is per domain rather than per execution because several invariants span
+ * more than one execution: StartWorkflowExecution must see any concurrently inserted run
+ * of the same workflowId to reject it, and a closing execution mutates its parent
+ * (ChildWorkflowExecution* events) and its children (childPolicy). A parent and a child
+ * always live in the same domain, so one lock covers a whole family and never has to be
+ * nested — nesting would deadlock, since a closing child takes its parent while a closing
+ * parent takes its children.
+ *
+ *
Timeouts are enforced by {@link SwfTimeoutSweeper} calling {@link #sweep()}, not by
+ * per-task threads.
+ */
+@ApplicationScoped
+public class SwfService implements Resettable {
+
+ private static final Logger LOG = Logger.getLogger(SwfService.class);
+
+ private static final int MAX_TAGS = 50;
+ /** SWF caps maximumPageSize at 1000 on every paginated operation. */
+ private static final int MAX_PAGE_SIZE = 1000;
+
+ private final StorageBackend domainStore;
+ private final StorageBackend workflowTypeStore;
+ private final StorageBackend activityTypeStore;
+ private final StorageBackend executionStore;
+
+ private final Map decisionTokens = new ConcurrentHashMap<>();
+ private final Map activityTokens = new ConcurrentHashMap<>();
+ private final Map domainLocks = new ConcurrentHashMap<>();
+
+ private final RegionResolver regionResolver;
+ private final Clock clock;
+ private final LambdaInvoker lambdaInvoker;
+
+
+ @Inject
+ public SwfService(StorageFactory storageFactory, RegionResolver regionResolver, Clock clock,
+ LambdaInvoker lambdaInvoker) {
+ this.domainStore = storageFactory.create("swf", "swf-domains.json",
+ new TypeReference