feat(stepfunctions): add ecs:runTask service integration (#1564)

* feat(stepfunctions): add ecs:runTask service integration

Wire the Step Functions task executor to the existing docker-backed ECS
service so state machines can launch ECS tasks via the optimized
integrations:

  arn:aws:states:::ecs:runTask         (request-response)
  arn:aws:states:::ecs:runTask.sync    (wait until the task STOPs)

Previously AslExecutor had no ecs:runTask branch, so a state machine using
these resources failed with "Unsupported resource" even though Floci can
run ECS tasks. This unblocks orchestration patterns that launch a task and
wait for it to finish (e.g. a provisioning runner).

Step Functions optimized integrations use PascalCase member names for both
parameters and results, while Floci's ECS handlers use the lowerCamelCase
of the ECS data-plane API. A small recursive key-recasing bridge maps
parameters in (PascalCase -> camelCase) and results out (camelCase ->
PascalCase), reusing EcsJsonHandler.taskNode / parseContainerOverrides so
the output matches the ECS task shape exactly.

For .sync, the executor polls DescribeTasks until the task reaches STOPPED
and fails the state (States.TaskFailed) when an essential container exits
non-zero or the task never ran a container, matching real Step Functions.

Tests: recaseKeys unit coverage (nested objects/arrays, inverse, scalar
round-trip); integration tests for the PascalCase Tasks/Failures envelope,
TaskDefinition validation, and .sync error propagation (ECS mock profile,
so the wiring is asserted independently of a container runtime).

* fix(stepfunctions): poll all ecs:runTask.sync tasks and validate mode

Greptile review on #1564:
- .sync now polls every launched task (not just the first), so with Count > 1 a
  failure in any task fails the state instead of leaving later tasks unmonitored.
  Single task returns its description; multiple return the array.
- Reject unknown ecs:runTask mode suffixes (e.g. a '.Sync' typo) with
  States.TaskFailed instead of silently treating them as .sync.

* fix(stepfunctions): treat a STOPPED ecs task with no exit code as failed

Greptile follow-up on #1564: ecsTaskFailureCause reported success whenever no
container had a non-zero exit, but a container with a null exit code never
completed cleanly (OOM-killed, failed to start, force-stopped). Treat any null
exit code on a STOPPED task as a failure, matching AWS Step Functions.

* fix(stepfunctions): only essential containers fail an ecs:runTask.sync state

Greptile follow-up on #1564: ecsTaskFailureCause checked exit codes on all
containers, so a non-essential sidecar (log shipper, metrics agent) exiting
non-zero would fail the state. Resolve the task definition and skip containers
explicitly marked essential:false; anything not resolvable stays essential.

* fix(stepfunctions): log when an ecs:runTask task definition can't be resolved

nonEssentialContainerNames swallowed the RuntimeException from describeTaskDefinition
and silently returned an empty set (all containers treated as essential), violating
the AGENTS.md rule against silent catch blocks. Log the tolerated failure with the
task definition ARN so the lost essential/non-essential distinction is diagnosable.
No behavior change (still conservatively treats all containers as essential).

* fix(stepfunctions): request-response ecs:runTask must not fail on placement failure

Request-response returns the {Tasks,Failures} envelope even when no task is placed
(AWS: 200 with a non-empty Failures list); only .sync and .waitForTaskToken fail the
state, using the AWS error name AmazonECS.Unknown. Previously the launched.isEmpty()
check threw States.TaskFailed before the mode branch, so it fired for request-response
too. .waitForTaskToken is distinguished by its non-null task token.

Also thread NetworkConfiguration (awsvpc) through runTask -> EcsTask across all three
runTask callers (real RunTask API, service reconciler, ecs:runTask integration) so it is
no longer dropped at the boundary; awsvpc ENI attachments remain unemulated in the local
mock profile.
This commit is contained in:
Alex Banna authored and GitHub committed 2026-07-01 23:37:25 -05:00
1 parent e0a1d027b9
commit 6277f16fee
8 files changed
+769 -9

No files matched your search

@@ -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));
@@ -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;
}
}
@@ -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());
}
}
@@ -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")
+ "\"";
}
}