Light, fluffy, and always free - The AWS Local Emulator alternative
feat(stepfunctions): add ecs:runTask service integration (#1564)
Alex Banna6277f16fee87
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.javaindex 5d1b279d9e..cc5cc67c11 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java@@ -281,9 +281,11 @@ public class EcsJsonHandler {String startedBy = req.has("startedBy") ? req.path("startedBy").asText() : null;List<ContainerOverride> containerOverrides =parseContainerOverrides(req.path("overrides").path("containerOverrides"));+ NetworkConfiguration networkConfiguration =+ parseNetworkConfiguration(req.path("networkConfiguration"));List<EcsTask> launched = service.runTask(cluster, taskDefinition, count,- launchType, group, startedBy, containerOverrides, region);+ launchType, group, startedBy, containerOverrides, networkConfiguration, region);ObjectNode resp = objectMapper.createObjectNode();ArrayNode arr = objectMapper.createArrayNode();@@ -444,7 +446,10 @@ public class EcsJsonHandler {return result;}- private NetworkConfiguration parseNetworkConfiguration(JsonNode node) {+ /** Parse an ECS {@code networkConfiguration} node (camelCase, as the data-plane API uses).+ * Public so the Step Functions ecs:runTask integration can reuse it after recasing its+ * PascalCase input, rather than duplicating the awsvpc parsing. */+ public NetworkConfiguration parseNetworkConfiguration(JsonNode node) {if (node == null || !node.isObject() || !node.hasNonNull("awsvpcConfiguration")) {return null;}@@ -1033,7 +1038,9 @@ public class EcsJsonHandler {return n;}- private ObjectNode taskNode(EcsTask t) {+ /** Renders an ECS task to its data-plane JSON shape. Reused by the Step Functions+ * ecs:runTask integration ({@link io.github.hectorvent.floci.services.stepfunctions.AslExecutor}). */+ public ObjectNode taskNode(EcsTask t) {ObjectNode n = objectMapper.createObjectNode();n.put("taskArn", t.getTaskArn());n.put("clusterArn", t.getClusterArn());@@ -1358,7 +1365,9 @@ public class EcsJsonHandler {return result;}- private List<ContainerOverride> parseContainerOverrides(JsonNode node) {+ /** Parses ECS container overrides from data-plane JSON. Reused by the Step Functions+ * ecs:runTask integration ({@link io.github.hectorvent.floci.services.stepfunctions.AslExecutor}). */+ public List<ContainerOverride> parseContainerOverrides(JsonNode node) {List<ContainerOverride> result = new ArrayList<>();if (!node.isArray()) {return result;diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.javaindex cf3f20ad73..602ebf4a61 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java@@ -411,11 +411,12 @@ public class EcsService {public List<EcsTask> runTask(String clusterRef, String taskDefinitionRef, int count,LaunchType launchType, String group, String startedBy,- List<ContainerOverride> containerOverrides, String region) {+ List<ContainerOverride> containerOverrides,+ NetworkConfiguration networkConfiguration, String region) {EcsCluster cluster = resolveClusterOrDefault(clusterRef, region);TaskDefinition taskDef = resolveTaskDefinitionOrThrow(taskDefinitionRef, region);return launchTasks(cluster, taskDef, count, launchType, group, startedBy, null,- containerOverrides, region);+ containerOverrides, networkConfiguration, region);}public List<EcsTask> startTask(String clusterRef, List<String> containerInstanceRefs,@@ -426,7 +427,7 @@ public class EcsService {for (String instanceRef : containerInstanceRefs) {ContainerInstance instance = resolveContainerInstanceOrThrow(cluster.getClusterArn(), instanceRef);List<EcsTask> launched = launchTasks(cluster, taskDef, 1, LaunchType.EC2,- group, startedBy, instance.getContainerInstanceArn(), null, region);+ group, startedBy, instance.getContainerInstanceArn(), null, null, region);result.addAll(launched);}return result;@@ -435,7 +436,8 @@ public class EcsService {private List<EcsTask> launchTasks(EcsCluster cluster, TaskDefinition taskDef, int count,LaunchType launchType, String group, String startedBy,String containerInstanceArn,- List<ContainerOverride> containerOverrides, String region) {+ List<ContainerOverride> containerOverrides,+ NetworkConfiguration networkConfiguration, String region) {// Fail loudly instead of silently launching zero containers and leaving// a task that looks RUNNING with nothing behind it.if (taskDef.getContainerDefinitions() == null || taskDef.getContainerDefinitions().isEmpty()) {@@ -464,6 +466,7 @@ public class EcsService {task.setCreatedAt(Instant.now());task.setContainers(List.of());task.setContainerInstanceArn(containerInstanceArn);+ task.setNetworkConfiguration(networkConfiguration);tasks.put(taskArn, task);@@ -1362,7 +1365,8 @@ public class EcsService {for (int i = 0; i < toStart; i++) {try {List<EcsTask> launched = runTask(clusterName, svc.getTaskDefinition(), 1,- svc.getLaunchType(), svc.getServiceName(), "ecs-svc", null, region);+ svc.getLaunchType(), svc.getServiceName(), "ecs-svc", null,+ svc.getNetworkConfiguration(), region);LOG.infov("Service reconciler started task {0} for service {1}",launched.getFirst().getTaskArn(), svc.getServiceName());} catch (Exception e) {diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.javaindex a01fca5be8..e57657d7d4 100644--- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EcsTask.java@@ -29,6 +29,7 @@ public class EcsTask {private boolean protectionEnabled;private Instant protectedUntil;private Map<String, String> tags = new HashMap<>();+ private NetworkConfiguration networkConfiguration;public String getTaskArn() { return taskArn; }public void setTaskArn(String taskArn) { this.taskArn = taskArn; }@@ -69,6 +70,14 @@ public class EcsTask {public String getStartedBy() { return startedBy; }public void setStartedBy(String startedBy) { this.startedBy = startedBy; }+ /** The awsvpc network configuration the task was launched with, or null. Carried through from+ * the RunTask request (including the ecs:runTask Step Functions integration) so it survives the+ * launch; awsvpc ENI attachments are not emulated in the local mock profile. */+ public NetworkConfiguration getNetworkConfiguration() { return networkConfiguration; }+ public void setNetworkConfiguration(NetworkConfiguration networkConfiguration) {+ this.networkConfiguration = networkConfiguration;+ }+public String getStoppedReason() { return stoppedReason; }public void setStoppedReason(String stoppedReason) { this.stoppedReason = stoppedReason; }diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.javaindex f40a76ff07..404baef896 100644--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java@@ -9,6 +9,14 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHanimport io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;import io.github.hectorvent.floci.services.ec2.Ec2Service;+import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;+import io.github.hectorvent.floci.services.ecs.EcsService;+import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;+import io.github.hectorvent.floci.services.ecs.model.ContainerOverride;+import io.github.hectorvent.floci.services.ecs.model.EcsTask;+import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration;+import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;+import io.github.hectorvent.floci.services.ecs.model.LaunchType;import io.github.hectorvent.floci.services.s3.S3Service;import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;@@ -38,9 +46,11 @@ import org.jboss.logging.Logger;import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.HashMap;+import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Map;+import java.util.Set;import java.util.UUID;import java.util.concurrent.Callable;import java.util.concurrent.CompletableFuture;@@ -58,6 +68,10 @@ public class AslExecutor {private static final Logger LOG = Logger.getLogger(AslExecutor.class);private static final int MAX_WAIT_SECONDS = 30;+ // ecs:runTask.sync polling — wait up to ~60s for the task to reach STOPPED.+ private static final int ECS_SYNC_POLL_ATTEMPTS = 600;+ private static final long ECS_SYNC_POLL_INTERVAL_MS = 100;+private static final String QUERY_LANGUAGE_JSONATA = "JSONata";private final LambdaExecutorService lambdaExecutor;@@ -68,6 +82,8 @@ public class AslExecutor {private final CloudFormationQueryHandler cloudFormationHandler;private final Ec2Service ec2Service;private final S3Service s3Service;+ private final EcsService ecsService;+ private final EcsJsonHandler ecsJsonHandler;private final ObjectMapper objectMapper;private final JsonataEvaluator jsonataEvaluator;private final Instance<StepFunctionsService> sfnService;@@ -82,6 +98,7 @@ public class AslExecutor {DynamoDbService dynamoDbService, DynamoDbJsonHandler dynamoDbJsonHandler,SqsJsonHandler sqsJsonHandler, CloudFormationQueryHandler cloudFormationHandler,Ec2Service ec2Service, S3Service s3Service,+ EcsService ecsService, EcsJsonHandler ecsJsonHandler,ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,Instance<StepFunctionsService> sfnService) {this.lambdaExecutor = lambdaExecutor;@@ -92,6 +109,8 @@ public class AslExecutor {this.cloudFormationHandler = cloudFormationHandler;this.ec2Service = ec2Service;this.s3Service = s3Service;+ this.ecsService = ecsService;+ this.ecsJsonHandler = ecsJsonHandler;this.objectMapper = objectMapper;this.jsonataEvaluator = jsonataEvaluator;this.sfnService = sfnService;@@ -468,6 +487,21 @@ public class AslExecutor {return invokeS3PutObject(input);}+ // ECS optimized integration: arn:aws:states:::ecs:runTask (request-response, .sync, .waitForTaskToken).+ // The .waitForTaskToken suffix is already stripped by executeTaskState, so a waitForTaskToken+ // variant arrives here as the bare runTask resource and simply launches the task while the token+ // future blocks for SendTaskSuccess.+ if (resource.startsWith("arn:aws:states:::ecs:runTask")) {+ // A non-null taskToken means the original resource ended with .waitForTaskToken (stripped+ // upstream). Its failure semantics match .sync — a task placement failure fails the state —+ // whereas request-response returns the {Tasks,Failures} envelope without failing the state.+ String mode = taskToken != null+ ? ".waitForTaskToken"+ : resource.substring("arn:aws:states:::ecs:runTask".length());+ String region = extractRegionFromArn(sm.getStateMachineArn());+ return invokeEcsRunTask(mode, input, region);+ }+// Nested state machine integrationif (resource.startsWith("arn:aws:states:::states:startExecution")) {String mode = resource.substring("arn:aws:states:::states:startExecution".length());@@ -654,6 +688,223 @@ public class AslExecutor {"Nested execution timed out: " + execArn);}+ /**+ * Optimized ECS RunTask integration. Step Functions passes PascalCase parameters+ * ({@code Cluster}, {@code TaskDefinition}, {@code Overrides.ContainerOverrides}, …)+ * and expects PascalCase results, whereas Floci's ECS handlers use the lowerCamelCase+ * of the ECS data-plane API — {@link #recaseKeys} bridges the two ends.+ *+ * @param mode "" for request-response (returns the RunTask {@code {Tasks,Failures}} response+ * without failing on a placement failure), ".sync" to block until the task reaches+ * STOPPED, or ".waitForTaskToken" to launch and let the token future carry the result+ * (both ".sync" and ".waitForTaskToken" fail the state on a placement failure).+ */+ private JsonNode invokeEcsRunTask(String mode, JsonNode input, String region) throws Exception {+ String taskDefinition = input.path("TaskDefinition").asText(null);+ if (taskDefinition == null || taskDefinition.isBlank()) {+ throw new FailStateException("States.TaskFailed",+ "TaskDefinition is required for the ecs:runTask integration");+ }+ String cluster = input.hasNonNull("Cluster") ? input.path("Cluster").asText() : null;+ int count = input.path("Count").asInt(1);++ LaunchType launchType = null;+ String launchTypeRaw = input.path("LaunchType").asText(null);+ if (launchTypeRaw != null && !launchTypeRaw.isBlank()) {+ try {+ launchType = LaunchType.valueOf(launchTypeRaw);+ } catch (IllegalArgumentException e) {+ throw new FailStateException("States.TaskFailed", "Unsupported LaunchType: " + launchTypeRaw);+ }+ }+ String group = input.path("Group").asText(null);+ String startedBy = input.path("StartedBy").asText(null);++ // Parameters are PascalCase; the ECS handler's parsers expect the camelCase of the+ // data-plane API, so recase each sub-tree before reusing them.+ JsonNode overridesNode = recaseKeys(objectMapper,+ input.path("Overrides").path("ContainerOverrides"), false);+ List<ContainerOverride> overrides = ecsJsonHandler.parseContainerOverrides(overridesNode);++ // NetworkConfiguration (awsvpc) is threaded through so it is not dropped at the boundary;+ // awsvpc ENI attachments themselves are not emulated in the local mock profile.+ JsonNode networkConfigNode = recaseKeys(objectMapper, input.path("NetworkConfiguration"), false);+ NetworkConfiguration networkConfiguration = ecsJsonHandler.parseNetworkConfiguration(networkConfigNode);++ List<EcsTask> launched;+ try {+ launched = ecsService.runTask(cluster, taskDefinition, count, launchType, group, startedBy,+ overrides, networkConfiguration, region);+ } catch (AwsException e) {+ throw new FailStateException("ECS." + e.getErrorCode(), e.getMessage());+ }+ // A task placement failure (no task launched) fails the state only for the .sync and+ // .waitForTaskToken patterns, and AWS surfaces it with the AmazonECS.Unknown error name.+ // Request-response never fails on a placement failure — it returns the { Tasks, Failures }+ // envelope (possibly with empty Tasks) so the caller can inspect Failures itself.+ boolean callbackOrSync = ".sync".equals(mode) || ".waitForTaskToken".equals(mode);+ if (launched.isEmpty() && callbackOrSync) {+ throw new FailStateException("AmazonECS.Unknown", "ecs:runTask launched no tasks");+ }++ if (mode.isEmpty() || ".waitForTaskToken".equals(mode)) {+ // Request-response: return the RunTask response shape { Tasks: [...], Failures: [] }.+ // The .waitForTaskToken launch phase lands here too — its return value is discarded once+ // the task token supplies the real result, so returning the envelope just completes the launch.+ ObjectNode resp = objectMapper.createObjectNode();+ ArrayNode tasks = resp.putArray("Tasks");+ for (EcsTask t : launched) {+ tasks.add(recaseKeys(objectMapper, ecsJsonHandler.taskNode(t), true));+ }+ resp.putArray("Failures");+ return resp;+ }++ if (!".sync".equals(mode)) {+ // Only request-response (""), .sync and .waitForTaskToken are valid; reject typos rather+ // than silently treating an unknown suffix as .sync.+ throw new FailStateException("States.TaskFailed", "Unsupported ecs:runTask mode: " + mode);+ }++ // .sync — wait until every launched task reaches STOPPED, then surface success or failure.+ // All tasks must be polled (not just the first): with Count > 1, a failure in any task must+ // fail the state, otherwise tasks beyond the first would run unmonitored.+ List<String> taskArns = launched.stream().map(EcsTask::getTaskArn).toList();+ for (int i = 0; i < ECS_SYNC_POLL_ATTEMPTS; i++) {+ Thread.sleep(ECS_SYNC_POLL_INTERVAL_MS);+ List<EcsTask> described = ecsService.describeTasks(cluster, taskArns, region);+ boolean allStopped = described.size() == taskArns.size()+ && described.stream().allMatch(t -> "STOPPED".equals(t.getLastStatus()));+ if (!allStopped) {+ continue;+ }+ // All terminal. Like real Step Functions, fail the state if any task's essential+ // container exited non-zero or a task never ran a container (e.g. it failed to start).+ for (EcsTask task : described) {+ String cause = ecsTaskFailureCause(task, nonEssentialContainerNames(task, region));+ if (cause != null) {+ throw new FailStateException("States.TaskFailed", cause);+ }+ }+ // Success: a single task returns its description; multiple tasks return the array.+ if (described.size() == 1) {+ return recaseKeys(objectMapper, ecsJsonHandler.taskNode(described.get(0)), true);+ }+ ArrayNode arr = objectMapper.createArrayNode();+ for (EcsTask task : described) {+ arr.add(recaseKeys(objectMapper, ecsJsonHandler.taskNode(task), true));+ }+ return arr;+ }+ throw new FailStateException("States.Timeout",+ "ecs:runTask.sync timed out waiting for tasks to stop: " + taskArns);+ }++ /** A failure cause if the ECS task did not complete cleanly (non-zero exit or no container ran), or null on success. */+ private static String ecsTaskFailureCause(EcsTask task, Set<String> nonEssentialNames) {+ boolean ranAContainer = task.getContainers() != null && !task.getContainers().isEmpty();+ Integer nonZeroExit = null;+ boolean hasNullExitCode = false;+ if (ranAContainer) {+ for (var c : task.getContainers()) {+ // Only essential containers decide the task outcome, like real Step Functions; a+ // non-essential sidecar (log shipper, metrics agent) exiting non-zero is ignored.+ // Anything not explicitly marked non-essential defaults to essential.+ if (nonEssentialNames.contains(c.getName())) {+ continue;+ }+ if (c.getExitCode() == null) {+ // A STOPPED container with no exit code never completed (OOM-killed, failed to+ // start, force-stopped) — AWS treats that as a failure, not a clean exit.+ hasNullExitCode = true;+ } else if (c.getExitCode() != 0) {+ nonZeroExit = c.getExitCode();+ }+ }+ }+ if (nonZeroExit == null && !hasNullExitCode && ranAContainer) {+ return null;+ }+ if (task.getStoppedReason() != null) {+ return task.getStoppedReason();+ }+ if (nonZeroExit != null) {+ return "Essential container exited with code " + nonZeroExit;+ }+ if (hasNullExitCode) {+ return "Essential container stopped without an exit code";+ }+ return "Task stopped without running a container";+ }++ /**+ * Names of the task's containers that are explicitly {@code essential: false} in its task+ * definition. Their exit status does not fail the state. Falls back to an empty set (treat all+ * as essential) when the task definition can't be resolved, preserving the conservative default.+ */+ private Set<String> nonEssentialContainerNames(EcsTask task, String region) {+ try {+ TaskDefinition td = ecsService.describeTaskDefinition(task.getTaskDefinitionArn(), region);+ Set<String> names = new HashSet<>();+ if (td.getContainerDefinitions() != null) {+ for (ContainerDefinition cd : td.getContainerDefinitions()) {+ if (!cd.isEssential()) {+ names.add(cd.getName());+ }+ }+ }+ return names;+ } catch (RuntimeException e) {+ // Tolerated: if the task definition can't be resolved we conservatively treat every+ // container as essential (empty non-essential set), but log it so the loss of the+ // essential/non-essential distinction is diagnosable.+ LOG.warnv("ecs:runTask: could not resolve task definition {0} to classify essential "+ + "containers; treating all as essential ({1})", task.getTaskDefinitionArn(), e.getMessage());+ return Set.of();+ }+ }++ /**+ * Returns a deep copy of {@code node} with the first character of every object key+ * recased. Step Functions optimized service integrations use PascalCase member names+ * while Floci's ECS wire handlers use the lowerCamelCase of the data-plane API.+ *+ * @param upperFirst true to map lowerCamelCase → PascalCase (results handed back to the+ * state machine); false to map PascalCase → lowerCamelCase (parameters+ * handed to the ECS handlers).+ */+ static JsonNode recaseKeys(ObjectMapper mapper, JsonNode node, boolean upperFirst) {+ if (node == null) {+ return null;+ }+ if (node.isObject()) {+ ObjectNode out = mapper.createObjectNode();+ Iterator<Map.Entry<String, JsonNode>> fields = node.fields();+ while (fields.hasNext()) {+ Map.Entry<String, JsonNode> e = fields.next();+ out.set(recaseKey(e.getKey(), upperFirst), recaseKeys(mapper, e.getValue(), upperFirst));+ }+ return out;+ }+ if (node.isArray()) {+ ArrayNode out = mapper.createArrayNode();+ for (JsonNode item : node) {+ out.add(recaseKeys(mapper, item, upperFirst));+ }+ return out;+ }+ return node.deepCopy();+ }++ private static String recaseKey(String key, boolean upperFirst) {+ if (key == null || key.isEmpty()) {+ return key;+ }+ char first = key.charAt(0);+ char recased = upperFirst ? Character.toUpperCase(first) : Character.toLowerCase(first);+ return recased == first ? key : recased + key.substring(1);+ }+private boolean isActivityArn(String resource) {// arn:aws:states:{region}:{account}:activity:{name}// Distinguish from integration ARNs like arn:aws:states:::lambda:invoke (empty region/account)diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.javaindex d8792ab37b..e8f5efde4e 100644--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorCatchTest.java@@ -77,6 +77,8 @@ class AslExecutorCatchTest {mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class),mock(io.github.hectorvent.floci.services.ec2.Ec2Service.class),mock(io.github.hectorvent.floci.services.s3.S3Service.class),+ mock(io.github.hectorvent.floci.services.ecs.EcsService.class),+ mock(io.github.hectorvent.floci.services.ecs.EcsJsonHandler.class),objectMapper,new JsonataEvaluator(objectMapper),mock(Instance.class));diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.javanew file mode 100644index 0000000000..1469a0c4d9--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java@@ -0,0 +1,162 @@+package io.github.hectorvent.floci.services.stepfunctions;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;+import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;+import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;+import io.github.hectorvent.floci.services.ecs.EcsService;+import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration;+import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;+import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;+import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;+import io.github.hectorvent.floci.services.stepfunctions.model.Execution;+import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;+import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;+import jakarta.enterprise.inject.Instance;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;++import java.util.ArrayList;+import java.util.List;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyInt;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++/**+ * Covers the ecs:runTask integration's mode-specific failure semantics and the threading of+ * NetworkConfiguration through to {@link EcsService#runTask}:+ * <ul>+ * <li>request-response never fails the state on a placement failure — it returns the+ * {@code {Tasks,Failures}} envelope, even with no launched tasks;</li>+ * <li>{@code .sync} (and {@code .waitForTaskToken}) fail the state on a placement failure,+ * using the AWS error name {@code AmazonECS.Unknown};</li>+ * <li>an awsvpc {@code NetworkConfiguration} in the parameters is parsed and passed to runTask+ * rather than dropped.</li>+ * </ul>+ */+class AslExecutorEcsRunTaskModeTest {++ private static final String REGION = "us-east-2";+ private static final String ACCOUNT = "000000000000";++ private final ObjectMapper objectMapper = new ObjectMapper();+ private EcsService ecsService;+ private AslExecutor executor;++ @BeforeEach+ void setUp() {+ ecsService = mock(EcsService.class);+ // A real handler so parseNetworkConfiguration / parseContainerOverrides actually run.+ EcsJsonHandler ecsJsonHandler = new EcsJsonHandler(ecsService, objectMapper);++ executor = new AslExecutor(+ mock(LambdaExecutorService.class),+ mock(LambdaFunctionStore.class),+ mock(DynamoDbService.class),+ mock(DynamoDbJsonHandler.class),+ mock(SqsJsonHandler.class),+ mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class),+ mock(io.github.hectorvent.floci.services.ec2.Ec2Service.class),+ mock(io.github.hectorvent.floci.services.s3.S3Service.class),+ ecsService,+ ecsJsonHandler,+ objectMapper,+ new JsonataEvaluator(objectMapper),+ mock(Instance.class));+ }++ @Test+ void requestResponseDoesNotFailWhenNoTasksLaunched() throws Exception {+ // No tasks could be placed (AWS: 200 with a non-empty Failures list). Request-response+ // must return the envelope and let execution continue, not fail the state.+ when(ecsService.runTask(any(), any(), anyInt(), any(), any(), any(), any(), any(), any()))+ .thenReturn(new ArrayList<>());++ Execution execution = run("arn:aws:states:::ecs:runTask",+ "{\"TaskDefinition\":\"my-task-def\"}");++ assertEquals("SUCCEEDED", execution.getStatus());+ JsonNode output = objectMapper.readTree(execution.getOutput());+ assertTrue(output.path("Tasks").isArray(), "Tasks should be an array");+ assertEquals(0, output.path("Tasks").size());+ assertTrue(output.path("Failures").isArray(), "Failures should be an array");+ }++ @Test+ void syncFailsWithAmazonEcsUnknownWhenNoTasksLaunched() throws Exception {+ when(ecsService.runTask(any(), any(), anyInt(), any(), any(), any(), any(), any(), any()))+ .thenReturn(new ArrayList<>());++ Execution execution = run("arn:aws:states:::ecs:runTask.sync",+ "{\"TaskDefinition\":\"my-task-def\"}");++ assertEquals("FAILED", execution.getStatus());+ assertEquals("AmazonECS.Unknown", execution.getError());+ }++ @Test+ void networkConfigurationIsThreadedThroughToRunTask() throws Exception {+ when(ecsService.runTask(any(), any(), anyInt(), any(), any(), any(), any(), any(), any()))+ .thenReturn(new ArrayList<>());++ run("arn:aws:states:::ecs:runTask", """+ {+ "TaskDefinition": "my-task-def",+ "LaunchType": "FARGATE",+ "NetworkConfiguration": {+ "AwsvpcConfiguration": {+ "Subnets": ["subnet-123"],+ "SecurityGroups": ["sg-abc"],+ "AssignPublicIp": "ENABLED"+ }+ }+ }+ """);++ ArgumentCaptor<NetworkConfiguration> captor = ArgumentCaptor.forClass(NetworkConfiguration.class);+ verify(ecsService).runTask(+ any(), any(), anyInt(), any(), any(), any(), any(), captor.capture(), any());++ NetworkConfiguration passed = captor.getValue();+ assertNotNull(passed, "NetworkConfiguration should be parsed and passed, not dropped");+ assertNotNull(passed.getAwsvpcConfiguration());+ assertEquals(List.of("subnet-123"), passed.getAwsvpcConfiguration().getSubnets());+ assertEquals(List.of("sg-abc"), passed.getAwsvpcConfiguration().getSecurityGroups());+ assertEquals("ENABLED", passed.getAwsvpcConfiguration().getAssignPublicIp());+ }++ private Execution run(String resource, String input) {+ String definition = """+ {+ "StartAt": "RunTask",+ "States": {+ "RunTask": { "Type": "Task", "Resource": "%s", "End": true }+ }+ }+ """.formatted(resource);++ StateMachine stateMachine = new StateMachine();+ stateMachine.setName("ecs-runtask-test");+ stateMachine.setStateMachineArn("arn:aws:states:%s:%s:stateMachine:ecs-runtask-test".formatted(REGION, ACCOUNT));+ stateMachine.setRoleArn("arn:aws:iam::%s:role/test-role".formatted(ACCOUNT));+ stateMachine.setDefinition(definition);++ Execution execution = new Execution();+ execution.setName("ecs-runtask-execution");+ execution.setExecutionArn("arn:aws:states:%s:%s:execution:ecs-runtask-test:ecs-runtask-execution".formatted(REGION, ACCOUNT));+ execution.setStateMachineArn(stateMachine.getStateMachineArn());+ execution.setInput(input);++ List<HistoryEvent> history = new ArrayList<>();+ executor.executeSync(stateMachine, execution, history, (updated, events) -> { });+ return execution;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorRecaseKeysTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorRecaseKeysTest.javanew file mode 100644index 0000000000..ea1c1a134d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorRecaseKeysTest.java@@ -0,0 +1,76 @@+package io.github.hectorvent.floci.services.stepfunctions;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * Unit tests for the PascalCase ↔ lowerCamelCase key bridge used by the Step Functions+ * ecs:runTask integration (Step Functions optimized integrations use PascalCase member+ * names; Floci's ECS handlers use the lowerCamelCase of the data-plane API).+ */+class AslExecutorRecaseKeysTest {++ private final ObjectMapper mapper = new ObjectMapper();++ @Test+ void camelToPascal_recasesNestedObjectsAndArrays() throws Exception {+ JsonNode camel = mapper.readTree("""+ {+ "taskArn": "arn:aws:ecs:...:task/abc",+ "lastStatus": "STOPPED",+ "containers": [+ { "name": "runner", "exitCode": 0 }+ ]+ }+ """);++ JsonNode pascal = AslExecutor.recaseKeys(mapper, camel, true);++ assertEquals("arn:aws:ecs:...:task/abc", pascal.path("TaskArn").asText());+ assertEquals("STOPPED", pascal.path("LastStatus").asText());+ assertEquals("runner", pascal.path("Containers").get(0).path("Name").asText());+ assertEquals(0, pascal.path("Containers").get(0).path("ExitCode").asInt());+ // Original camelCase keys must be gone.+ assertTrue(pascal.path("taskArn").isMissingNode());+ }++ @Test+ void pascalToCamel_isInverseForContainerOverrides() throws Exception {+ JsonNode pascal = mapper.readTree("""+ [+ {+ "Name": "runner",+ "Command": ["terraform", "apply"],+ "Environment": [ { "Name": "TF_VAR_x", "Value": "1" } ]+ }+ ]+ """);++ JsonNode camel = AslExecutor.recaseKeys(mapper, pascal, false);++ JsonNode first = camel.get(0);+ assertEquals("runner", first.path("name").asText());+ assertEquals("terraform", first.path("command").get(0).asText());+ assertEquals("TF_VAR_x", first.path("environment").get(0).path("name").asText());+ assertEquals("1", first.path("environment").get(0).path("value").asText());+ }++ @Test+ void roundTrip_preservesScalarValuesAndTypes() throws Exception {+ JsonNode original = mapper.readTree("""+ { "count": 2, "enabled": true, "ratio": 1.5, "note": null }+ """);++ JsonNode back = AslExecutor.recaseKeys(mapper,+ AslExecutor.recaseKeys(mapper, original, true), false);++ assertEquals(2, back.path("count").asInt());+ assertTrue(back.path("enabled").asBoolean());+ assertEquals(1.5, back.path("ratio").asDouble());+ assertTrue(back.path("note").isNull());+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsEcsRunTaskIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsEcsRunTaskIntegrationTest.javanew file mode 100644index 0000000000..51004fe4e9--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsEcsRunTaskIntegrationTest.java@@ -0,0 +1,247 @@+package io.github.hectorvent.floci.services.stepfunctions;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.quarkus.test.junit.QuarkusTestProfile;+import io.quarkus.test.junit.TestProfile;+import io.restassured.response.Response;+import org.junit.jupiter.api.BeforeAll;+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 java.util.Map;++import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.*;++/**+ * Integration tests for the Step Functions ecs:runTask optimized service integration+ * ({@code arn:aws:states:::ecs:runTask} and {@code .sync}).+ *+ * <p>These assert the wiring that is deterministic regardless of the host: request+ * routing for both modes, PascalCase parameter parsing, PascalCase result shaping+ * ({@code Tasks}/{@code Failures}), parameter validation, and error propagation. The+ * happy-path container-execution {@code .sync} poll-to-STOPPED is exercised empirically+ * against a live emulator with Docker available (it is not asserted here, to keep the+ * unit suite independent of a container runtime / image registry).+ */+@QuarkusTest+@TestProfile(StepFunctionsEcsRunTaskIntegrationTest.EcsMockProfile.class)+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class StepFunctionsEcsRunTaskIntegrationTest {++ /**+ * Runs ECS in mock mode so RunTask transitions tasks to RUNNING without a container+ * runtime. These tests assert only the Step Functions↔ECS wiring (routing, casing,+ * validation, error propagation), which is independent of real container execution.+ */+ public static final class EcsMockProfile implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of("floci.services.ecs.mock", "true");+ }+ }++ private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";+ private static final String ECS_CONTENT_TYPE = "application/x-amz-json-1.1";+ private static final String ECS_TARGET_PREFIX = "AmazonEC2ContainerServiceV20141113.";+ private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";+ private static final String CLUSTER = "sfn-ecs-cluster";+ private static final String TASK_FAMILY = "sfn-ecs-task";+ private static final ObjectMapper mapper = new ObjectMapper();++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ @Order(0)+ void setup_clusterAndTaskDefinition() {+ ecs("CreateCluster", "{\"clusterName\":\"" + CLUSTER + "\"}").then().statusCode(200);+ ecs("RegisterTaskDefinition", """+ {+ "family": "%s",+ "containerDefinitions": [+ { "name": "runner", "image": "floci-test/runner:latest", "memory": 128 }+ ]+ }+ """.formatted(TASK_FAMILY)).then().statusCode(200);+ }++ @Test+ @Order(1)+ void runTask_returnsPascalCaseTasksEnvelope() throws Exception {+ String output = executeSfn("ecs-run", "arn:aws:states:::ecs:runTask", """+ {+ "Cluster": "%s",+ "TaskDefinition": "%s",+ "LaunchType": "FARGATE"+ }+ """.formatted(CLUSTER, TASK_FAMILY));++ JsonNode result = mapper.readTree(output);+ // Optimized integration returns the RunTask response with PascalCase keys.+ assertTrue(result.has("Tasks"), "expected PascalCase Tasks: " + output);+ assertTrue(result.has("Failures"), "expected PascalCase Failures: " + output);+ assertEquals(1, result.path("Tasks").size());+ JsonNode task = result.path("Tasks").get(0);+ assertFalse(task.path("TaskArn").asText().isBlank(), "TaskArn should be populated");+ assertFalse(task.path("LastStatus").asText().isBlank(), "LastStatus should be populated");+ assertTrue(task.path("TaskDefinitionArn").asText().contains(TASK_FAMILY));+ // Casing bridge must not leak lowerCamelCase keys into the state output.+ assertTrue(task.path("taskArn").isMissingNode(), "lowerCamelCase keys must not leak");+ }++ @Test+ @Order(2)+ void runTask_missingTaskDefinition_failsState() throws Exception {+ String definition = buildDefinition("arn:aws:states:::ecs:runTask", """+ { "Cluster": "%s" }+ """.formatted(CLUSTER));+ String execArn = startExecution(createStateMachine("ecs-no-taskdef", definition), "{}");++ Response failed = waitForFailedExecution(execArn);+ assertEquals("States.TaskFailed", failed.jsonPath().getString("error"));+ }++ @Test+ @Order(3)+ void runTaskSync_unknownTaskDefinition_propagatesEcsError() throws Exception {+ String definition = buildDefinition("arn:aws:states:::ecs:runTask.sync", """+ {+ "Cluster": "%s",+ "TaskDefinition": "does-not-exist-family"+ }+ """.formatted(CLUSTER));+ String execArn = startExecution(createStateMachine("ecs-sync-unknown-taskdef", definition), "{}");++ // .sync dispatch reaches EcsService.runTask, which rejects the unknown task+ // definition; the error is surfaced as a State failure rather than hanging.+ Response failed = waitForFailedExecution(execArn);+ String error = failed.jsonPath().getString("error");+ assertNotNull(error);+ assertTrue(error.startsWith("ECS."), "expected an ECS.* error, got: " + error);+ }++ // ── Helpers ─────────────────────────────────────────────────────────────────++ private static Response ecs(String action, String body) {+ return given()+ .header("X-Amz-Target", ECS_TARGET_PREFIX + action)+ .contentType(ECS_CONTENT_TYPE)+ .body(body)+ .when()+ .post("/");+ }++ private String executeSfn(String nameSuffix, String resource, String parameters) throws Exception {+ String definition = buildDefinition(resource, parameters);+ String smArn = createStateMachine(nameSuffix, definition);+ String execArn = startExecution(smArn, "{}");+ return waitForExecution(execArn);+ }++ private String buildDefinition(String resource, String parameters) {+ return """+ {+ "StartAt": "Run",+ "States": {+ "Run": {+ "Type": "Task",+ "Resource": "%s",+ "Parameters": %s,+ "End": true+ }+ }+ }+ """.formatted(resource, parameters.strip());+ }++ private String createStateMachine(String name, String definition) {+ Response resp = given()+ .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")+ .contentType(SFN_CONTENT_TYPE)+ .body("""+ {+ "name": "%s",+ "definition": %s,+ "roleArn": "%s"+ }+ """.formatted(name + "-" + System.currentTimeMillis(), quote(definition), ROLE_ARN))+ .when()+ .post("/");+ resp.then().statusCode(200);+ return resp.jsonPath().getString("stateMachineArn");+ }++ private String startExecution(String smArn, String input) {+ Response resp = given()+ .header("X-Amz-Target", "AWSStepFunctions.StartExecution")+ .contentType(SFN_CONTENT_TYPE)+ .body("""+ { "stateMachineArn": "%s", "input": %s }+ """.formatted(smArn, quote(input)))+ .when()+ .post("/");+ resp.then().statusCode(200);+ return resp.jsonPath().getString("executionArn");+ }++ private String waitForExecution(String execArn) throws InterruptedException {+ for (int i = 0; i < 80; i++) {+ Response resp = describeExecution(execArn);+ String status = resp.jsonPath().getString("status");+ if ("SUCCEEDED".equals(status)) {+ return resp.jsonPath().getString("output");+ }+ if ("FAILED".equals(status) || "ABORTED".equals(status)) {+ fail("Execution " + status + ": " + resp.body().asString());+ }+ Thread.sleep(100);+ }+ fail("Execution did not complete within timeout");+ return null;+ }++ private Response waitForFailedExecution(String execArn) throws InterruptedException {+ for (int i = 0; i < 80; i++) {+ Response resp = describeExecution(execArn);+ String status = resp.jsonPath().getString("status");+ if ("FAILED".equals(status)) {+ return resp;+ }+ if ("SUCCEEDED".equals(status)) {+ fail("Execution should have failed but succeeded: " + resp.body().asString());+ }+ Thread.sleep(100);+ }+ fail("Execution did not complete within timeout");+ return null;+ }++ private Response describeExecution(String execArn) {+ return given()+ .header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")+ .contentType(SFN_CONTENT_TYPE)+ .body("""+ {"executionArn": "%s"}+ """.formatted(execArn))+ .when()+ .post("/");+ }++ private static String quote(String raw) {+ return "\"" + raw+ .replace("\\", "\\\\")+ .replace("\"", "\\\"")+ .replace("\n", "\\n")+ .replace("\r", "\\r")+ .replace("\t", "\\t")+ + "\"";+ }+}