feat(stepfunctions): dispatch the seven Task service integrations of #2663 (#2686)

* feat(sfn): support the aws-sdk:sfn:startSyncExecution task integration

Calling an Express child workflow from a Standard parent goes through
arn:aws:states:::aws-sdk:sfn:startSyncExecution, which reached the end of the
dispatch chain and failed with "Unsupported resource".

The integration reuses the existing StartSyncExecution service call and differs
from the optimized states:startExecution.sync integration in two observable
ways: the response envelope uses PascalCase field names with Output as a JSON
string, and a child execution that fails is reported through Status instead of
failing the calling task.

* feat(stepfunctions): dispatch the six remaining Task service integrations

events:putEvents, aws-sdk:sfn:startExecution, aws-sdk:sfn:sendTaskSuccess,
aws-sdk:sfn:sendTaskFailure, aws-sdk:scheduler:createSchedule and
aws-sdk:scheduler:updateSchedule reached the end of the dispatch chain in
invokeResource and failed with "Unsupported resource", although Floci already
serves all six APIs. Each branch maps the Task Arguments onto the client the
direct call already goes through: putEvents onto EventBridgeHandler, and the
scheduler pair onto the controller's own parse and SchedulerService.

Two conventions of the aws-sdk: integrations, measured against us-east-1 through
test-state, now hold for the whole family and correct the startSyncExecution
envelope with them. A timestamp is the SDK's ISO-8601 rendering rather than the
epoch seconds the wire response carries, and an error names the SDK exception
class, so it always ends in Exception.

SendTaskSuccess and SendTaskFailure report whether the token resolved a waiting
task, which is what lets the Task integration fail with Sfn.InvalidTokenException
instead of reporting a delivery that never happened. The direct API keeps
tolerating an unknown token.

Closes #2663

* fix(stepfunctions): make scheduler argument validation reachable for Retry and Catch

parseScheduleRequest raises the same AwsException the scheduler service raises,
so a Task whose Target.EventBridgeParameters is incomplete failed the execution
with States.Runtime and skipped the state's Catch. It now runs inside the same
translation as the service call and fails with Scheduler.ValidationException.

* fix(scheduler): answer a malformed EcsParameters list with ValidationException

A CapacityProviderStrategy, PlacementConstraints, PlacementStrategy or Tags list
holding anything but objects made ObjectMapper.convertValue raise
IllegalArgumentException, which CreateSchedule and UpdateSchedule answered with
a server error and the aws-sdk:scheduler Task integration turned into
States.Runtime. The conversion failure is now named per field and carries the
400 the rest of the parser's validations carry.

* fix(scheduler): answer a malformed awsvpcConfiguration list with ValidationException

Subnets and SecurityGroups went through a bare ObjectMapper.convertValue, so an
element that is not a string left the same unhandled IllegalArgumentException the
EcsParameters object lists left. They now read through a stringList sibling of
mapList and carry the parser's 400.

* test(stepfunctions): pass the scheduler and eventbridge dependencies to the executor under test

* fix(scheduler): refuse a scalar in an awsvpcConfiguration list instead of coercing it

* fix(scheduler): refuse a non-list EcsParameters field instead of dropping it

* test(stepfunctions): catch a malformed scheduler list as the SDK exception AWS sends

---------

Co-authored-by: Facundo Paredes <naranjax@MAC-69786.local>
Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-08-28 22:21:48 -04:00
1 parent a155e66b15
commit 14112b8ace
21 files changed
+1744 -33

No files matched your search

+60
View File
@@ -124,6 +124,66 @@ One deviation. AWS also bounds the *memory* an expression may use, refusing
same expression at 800,000 elements. Floci bounds time and depth but not memory, and its ranges
are lazy, so that expression answers immediately at any size.
## Nested workflows
A parent workflow calls a child workflow through one of several integrations, and they differ in
more than syntax:
| Resource | Child type | A child that fails | Result |
| --- | --- | --- | --- |
| `arn:aws:states:::states:startExecution` | Standard | not awaited | `{executionArn, startDate}` |
| `arn:aws:states:::states:startExecution.sync` | Standard | fails the calling task | execution envelope, `output` as a JSON string |
| `arn:aws:states:::states:startExecution.sync:2` | Standard | fails the calling task | the child output, parsed |
| `arn:aws:states:::aws-sdk:sfn:startExecution` | Standard | not awaited | `{ExecutionArn, StartDate}` |
| `arn:aws:states:::aws-sdk:sfn:startSyncExecution` | Express | reported through `Status` | PascalCase envelope, `Output` as a JSON string |
`states:startExecution` and `aws-sdk:sfn:startExecution` are the same API through two different
integrations, and only the casing of the result tells them apart.
`startSyncExecution` is the only one that does not fail the calling task when the child fails: the
SDK call itself succeeded, so the task result carries `Status`, `Error` and `Cause` and the parent
decides what to do next.
## AWS SDK task integrations
A resource of the form `arn:aws:states:::aws-sdk:<service>:<action>` calls the service's API and
returns its response. Two conventions separate that result from the same API's wire response, and
both are AWS's:
- **Field names are the SDK's**, so a `startDate` on the wire is a `StartDate` in the task result.
- **A timestamp is an ISO-8601 string** such as `2026-08-28T20:34:59.712Z`, where the wire response
carries epoch seconds.
A failure names the SDK exception class, which always ends in `Exception`:
`StartExecution` answers a missing state machine with the error code `StateMachineDoesNotExist` on
the wire and the task fails with `Sfn.StateMachineDoesNotExistException`.
| Resource | Result | Notable failure |
| --- | --- | --- |
| `arn:aws:states:::aws-sdk:sfn:startExecution` | `{ExecutionArn, StartDate}` | `Sfn.ExecutionAlreadyExistsException` when `Name` is reused |
| `arn:aws:states:::aws-sdk:sfn:startSyncExecution` | execution envelope | `Sfn.StateMachineTypeNotSupportedException` for a Standard child |
| `arn:aws:states:::aws-sdk:sfn:sendTaskSuccess` | `{}` | `Sfn.InvalidTokenException` when no task is waiting on the token |
| `arn:aws:states:::aws-sdk:sfn:sendTaskFailure` | `{}` | `Sfn.InvalidTokenException` |
| `arn:aws:states:::aws-sdk:scheduler:createSchedule` | `{ScheduleArn}` | `Scheduler.ConflictException` when the name is taken |
| `arn:aws:states:::aws-sdk:scheduler:updateSchedule` | `{ScheduleArn}` | `Scheduler.ResourceNotFoundException` |
`sendTaskSuccess` and `sendTaskFailure` resolve a token a `.waitForTaskToken` task is parked on. A
token nobody is waiting for fails the calling task rather than reporting a delivery that never
happened.
## Publishing events
`arn:aws:states:::events:putEvents` returns the PutEvents response itself, `Entries` and
`FailedEntryCount`, and one rejected entry fails the whole task with `EventBridge.FailedEntry`. The
cause is the response serialized as a string, so a `Catch` can read which entry was rejected:
```json
{"FailedEntryCount":1,"Entries":[{"EventId":"08cbdc46-…"},{"ErrorCode":"InvalidArgument","ErrorMessage":"EventBus not found: no-such-bus"}]}
```
One deviation, and it belongs to EventBridge rather than to the integration: Floci rejects an entry
addressed to an event bus that does not exist, while AWS accepts it and returns an `EventId`.
## Mocked service integrations
Floci supports the Step Functions Local mock configuration format
@@ -354,7 +354,12 @@ public class SchedulerController {
return null;
}
private ScheduleRequest parseScheduleRequest(JsonNode node) {
/**
* Reads the PascalCase CreateSchedule / UpdateSchedule body. The Step Functions
* {@code aws-sdk:scheduler:*} Task integrations pass the same shape as {@code Arguments},
* so they parse it here instead of restating the mapping.
*/
public ScheduleRequest parseScheduleRequest(JsonNode node) {
ScheduleRequest req = new ScheduleRequest();
req.setGroupName(textField(node, "GroupName"));
req.setScheduleExpression(textField(node, "ScheduleExpression"));
@@ -471,8 +476,8 @@ public class SchedulerController {
private EcsParameters parseEcsParameters(JsonNode node) {
EcsParameters ecs = new EcsParameters();
if (node.has("CapacityProviderStrategy") && node.get("CapacityProviderStrategy").isArray()) {
ecs.setCapacityProviderStrategy(mapList(node.get("CapacityProviderStrategy")));
if (node.has("CapacityProviderStrategy") && !node.get("CapacityProviderStrategy").isNull()) {
ecs.setCapacityProviderStrategy(mapList("CapacityProviderStrategy", node.get("CapacityProviderStrategy")));
}
if (node.has("EnableECSManagedTags") && !node.get("EnableECSManagedTags").isNull()) {
ecs.setEnableECSManagedTags(node.get("EnableECSManagedTags").asBoolean());
@@ -489,11 +494,11 @@ public class SchedulerController {
if (node.has("LaunchType") && !node.get("LaunchType").isNull()) {
ecs.setLaunchType(node.get("LaunchType").asText());
}
if (node.has("PlacementConstraints") && node.get("PlacementConstraints").isArray()) {
ecs.setPlacementConstraints(mapList(node.get("PlacementConstraints")));
if (node.has("PlacementConstraints") && !node.get("PlacementConstraints").isNull()) {
ecs.setPlacementConstraints(mapList("PlacementConstraints", node.get("PlacementConstraints")));
}
if (node.has("PlacementStrategy") && node.get("PlacementStrategy").isArray()) {
ecs.setPlacementStrategy(mapList(node.get("PlacementStrategy")));
if (node.has("PlacementStrategy") && !node.get("PlacementStrategy").isNull()) {
ecs.setPlacementStrategy(mapList("PlacementStrategy", node.get("PlacementStrategy")));
}
if (node.has("TaskCount") && !node.get("TaskCount").isNull()) {
ecs.setTaskCount(node.get("TaskCount").asInt());
@@ -507,8 +512,8 @@ public class SchedulerController {
if (node.has("ReferenceId") && !node.get("ReferenceId").isNull()) {
ecs.setReferenceId(node.get("ReferenceId").asText());
}
if (node.has("Tags") && node.get("Tags").isArray()) {
ecs.setTags(mapList(node.get("Tags")));
if (node.has("Tags") && !node.get("Tags").isNull()) {
ecs.setTags(mapList("Tags", node.get("Tags")));
}
if (node.has("NetworkConfiguration") && !node.get("NetworkConfiguration").isNull()) {
ecs.setNetworkConfiguration(parseNetworkConfiguration(node.get("NetworkConfiguration")));
@@ -516,10 +521,49 @@ public class SchedulerController {
return ecs;
}
private List<Map<String, Object>> mapList(JsonNode node) {
return objectMapper.convertValue(node,
objectMapper.getTypeFactory().constructCollectionType(List.class,
objectMapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class)));
/**
* Reads one of the {@code EcsParameters} lists of objects. An element that is not an object is a
* malformed body, which AWS answers with 400 {@code SerializationException}, so the conversion
* failure is named here instead of escaping as a server error.
*/
private List<Map<String, Object>> mapList(String field, JsonNode node) {
if (!node.isArray()) {
throw malformedList(field, "objects");
}
try {
return objectMapper.convertValue(node,
objectMapper.getTypeFactory().constructCollectionType(List.class,
objectMapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class)));
} catch (IllegalArgumentException e) {
throw malformedList(field, "objects");
}
}
/**
* {@link #mapList(String, JsonNode)} for the {@code awsvpcConfiguration} lists of strings.
* A number or a boolean is checked before the conversion because Jackson writes it out as a
* string rather than refusing it, which would store a value AWS never accepts.
*/
private List<String> stringList(String field, JsonNode node) {
if (!node.isArray()) {
throw malformedList(field, "strings");
}
for (JsonNode element : node) {
if (!element.isTextual()) {
throw malformedList(field, "strings");
}
}
try {
return objectMapper.convertValue(node,
objectMapper.getTypeFactory().constructCollectionType(List.class, String.class));
} catch (IllegalArgumentException e) {
throw malformedList(field, "strings");
}
}
private AwsException malformedList(String field, String elementType) {
return new AwsException("SerializationException",
"EcsParameters " + field + " must be a list of " + elementType + ".", 400);
}
private NetworkConfiguration parseNetworkConfiguration(JsonNode node) {
@@ -532,11 +576,11 @@ public class SchedulerController {
private AwsVpcConfiguration parseAwsVpcConfiguration(JsonNode node) {
AwsVpcConfiguration vpc = new AwsVpcConfiguration();
if (node.has("Subnets") && node.get("Subnets").isArray()) {
vpc.setSubnets(objectMapper.convertValue(node.get("Subnets"), objectMapper.getTypeFactory().constructCollectionType(List.class, String.class)));
if (node.has("Subnets") && !node.get("Subnets").isNull()) {
vpc.setSubnets(stringList("Subnets", node.get("Subnets")));
}
if (node.has("SecurityGroups") && node.get("SecurityGroups").isArray()) {
vpc.setSecurityGroups(objectMapper.convertValue(node.get("SecurityGroups"), objectMapper.getTypeFactory().constructCollectionType(List.class, String.class)));
if (node.has("SecurityGroups") && !node.get("SecurityGroups").isNull()) {
vpc.setSecurityGroups(stringList("SecurityGroups", node.get("SecurityGroups")));
}
if (node.has("AssignPublicIp") && !node.get("AssignPublicIp").isNull()) {
vpc.setAssignPublicIp(node.get("AssignPublicIp").asText());
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHan
import 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.eventbridge.EventBridgeHandler;
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;
@@ -19,6 +20,10 @@ 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.scheduler.SchedulerController;
import io.github.hectorvent.floci.services.scheduler.SchedulerService;
import io.github.hectorvent.floci.services.scheduler.model.Schedule;
import io.github.hectorvent.floci.services.scheduler.model.ScheduleRequest;
import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;
import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
@@ -60,6 +65,9 @@ import org.jboss.logging.Logger;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -106,6 +114,17 @@ public class AslExecutor {
private static final long ECS_SYNC_POLL_INTERVAL_MS = 100;
private static final String QUERY_LANGUAGE_JSONATA = "JSONata";
private static final String AWS_SDK_SFN_PREFIX = "arn:aws:states:::aws-sdk:sfn:";
private static final String AWS_SDK_SCHEDULER_PREFIX = "arn:aws:states:::aws-sdk:scheduler:";
/**
* A timestamp inside an {@code aws-sdk:} Task result is the SDK's ISO-8601 rendering of an
* {@code Instant} — {@code 2026-08-28T20:34:59.712Z} — where the same field on the wire
* response of the underlying API carries epoch seconds.
*/
private static final DateTimeFormatter SDK_TIMESTAMP =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
private static final Set<String> HTTP_ALLOWED_METHODS = Set.of(
"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD");
private static final Set<String> HTTP_FORBIDDEN_HEADERS = Set.of(
@@ -152,6 +171,9 @@ public class AslExecutor {
private final S3Service s3Service;
private final EcsService ecsService;
private final EcsJsonHandler ecsJsonHandler;
private final EventBridgeHandler eventBridgeHandler;
private final SchedulerService schedulerService;
private final SchedulerController schedulerController;
private final ObjectMapper objectMapper;
private final JsonataEvaluator jsonataEvaluator;
private final Instance<StepFunctionsService> sfnService;
@@ -170,6 +192,8 @@ public class AslExecutor {
SqsJsonHandler sqsJsonHandler, CloudFormationQueryHandler cloudFormationHandler,
Ec2Service ec2Service, S3Service s3Service,
EcsService ecsService, EcsJsonHandler ecsJsonHandler,
EventBridgeHandler eventBridgeHandler, SchedulerService schedulerService,
SchedulerController schedulerController,
ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,
Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx) {
this.lambdaExecutor = lambdaExecutor;
@@ -182,6 +206,9 @@ public class AslExecutor {
this.s3Service = s3Service;
this.ecsService = ecsService;
this.ecsJsonHandler = ecsJsonHandler;
this.eventBridgeHandler = eventBridgeHandler;
this.schedulerService = schedulerService;
this.schedulerController = schedulerController;
this.objectMapper = objectMapper;
this.jsonataEvaluator = jsonataEvaluator;
this.sfnService = sfnService;
@@ -798,6 +825,26 @@ public class AslExecutor {
return invokeEcsRunTask(mode, input, region);
}
// AWS SDK service integrations: Step Functions
if (resource.startsWith(AWS_SDK_SFN_PREFIX)) {
String action = resource.substring(AWS_SDK_SFN_PREFIX.length());
String region = extractRegionFromArn(sm.getStateMachineArn());
return invokeAwsSdkSfn(action, input, region);
}
// AWS SDK service integrations: EventBridge Scheduler
if (resource.startsWith(AWS_SDK_SCHEDULER_PREFIX)) {
String action = resource.substring(AWS_SDK_SCHEDULER_PREFIX.length());
String region = extractRegionFromArn(sm.getStateMachineArn());
return invokeAwsSdkScheduler(action, input, region);
}
// EventBridge optimized integration
if (resource.equals("arn:aws:states:::events:putEvents")) {
String region = extractRegionFromArn(sm.getStateMachineArn());
return invokeOptimizedPutEvents(input, region);
}
// Nested state machine integration
if (resource.startsWith("arn:aws:states:::states:startExecution")) {
String mode = resource.substring("arn:aws:states:::states:startExecution".length());
@@ -922,6 +969,194 @@ public class AslExecutor {
return s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
/**
* The {@code arn:aws:states:::aws-sdk:sfn:*} family. Every one of these calls Step Functions'
* own API and returns its raw response, which is what separates
* {@code aws-sdk:sfn:startExecution} from the optimized {@code states:startExecution}
* handled by {@link #invokeNestedStateMachine}.
*/
private JsonNode invokeAwsSdkSfn(String action, JsonNode input, String region) throws Exception {
return switch (action) {
case "startExecution" -> invokeAwsSdkSfnStartExecution(input, region);
case "startSyncExecution" -> invokeAwsSdkSfnStartSyncExecution(input, region);
case "sendTaskSuccess" -> invokeAwsSdkSfnSendTaskSuccess(input);
case "sendTaskFailure" -> invokeAwsSdkSfnSendTaskFailure(input);
default -> throw new FailStateException("States.TaskFailed",
"Unsupported resource: " + AWS_SDK_SFN_PREFIX + action);
};
}
/**
* An {@code aws-sdk:} Task failure carries the name of the SDK exception class, which always
* ends in {@code Exception}. AWS answers a missing state machine with
* {@code Sfn.StateMachineDoesNotExistException}, while the StartExecution wire response names
* that same error {@code StateMachineDoesNotExist}.
*/
private static String sdkExceptionName(String service, String errorCode) {
return errorCode.endsWith("Exception")
? service + "." + errorCode
: service + "." + errorCode + "Exception";
}
private static String sdkTimestamp(double epochSeconds) {
return SDK_TIMESTAMP.format(Instant.ofEpochMilli(Math.round(epochSeconds * 1000)));
}
/**
* Reads an SDK payload argument such as {@code Input} or {@code Output}. Its AWS type is a JSON
* string; AWS also accepts the object form and serializes it, and an absent one is an empty
* object.
*/
private String sdkPayload(JsonNode node) throws Exception {
if (node.isMissingNode() || node.isNull()) {
return "{}";
}
return node.isTextual() ? node.asText() : objectMapper.writeValueAsString(node);
}
/**
* AWS SDK integration for {@code sfn:startExecution}. Unlike the optimized
* {@code states:startExecution}, which returns {@code executionArn} and {@code startDate} in
* the casing of the wire response, this one returns the SDK's own {@code ExecutionArn} and an
* ISO-8601 {@code StartDate}. Neither waits for the child.
*/
private JsonNode invokeAwsSdkSfnStartExecution(JsonNode input, String region) throws Exception {
String smArn = input.path("StateMachineArn").asText(null);
if (smArn == null || smArn.isBlank()) {
throw new FailStateException("Sfn.InvalidArnException",
"StateMachineArn is required for StartExecution");
}
io.github.hectorvent.floci.services.stepfunctions.model.Execution exec;
try {
exec = sfnService.get().startExecution(smArn, input.path("Name").asText(null),
sdkPayload(input.path("Input")), region);
} catch (AwsException e) {
throw new FailStateException(sdkExceptionName("Sfn", e.getErrorCode()), e.getMessage());
}
ObjectNode response = objectMapper.createObjectNode();
response.put("ExecutionArn", exec.getExecutionArn());
response.put("StartDate", sdkTimestamp(exec.getStartDate()));
return response;
}
/**
* AWS SDK integration for {@code sfn:sendTaskSuccess}. AWS fails the calling task with
* {@code Sfn.InvalidTokenException} when the token names no waiting task, so a token that
* resolved nothing is never reported as a delivered result.
*/
private JsonNode invokeAwsSdkSfnSendTaskSuccess(JsonNode input) throws Exception {
String taskToken = input.path("TaskToken").asText(null);
if (!sfnService.get().sendTaskSuccess(taskToken, sdkPayload(input.path("Output")))) {
throw new FailStateException("Sfn.InvalidTokenException", "Invalid Token: 'Invalid token'");
}
return objectMapper.createObjectNode();
}
/** AWS SDK integration for {@code sfn:sendTaskFailure}, token semantics as in SendTaskSuccess. */
private JsonNode invokeAwsSdkSfnSendTaskFailure(JsonNode input) {
String taskToken = input.path("TaskToken").asText(null);
if (!sfnService.get().sendTaskFailure(taskToken, input.path("Cause").asText(null),
input.path("Error").asText(null))) {
throw new FailStateException("Sfn.InvalidTokenException", "Invalid Token: 'Invalid token'");
}
return objectMapper.createObjectNode();
}
/**
* AWS SDK integrations for {@code scheduler:createSchedule} and {@code scheduler:updateSchedule}.
* The Task {@code Arguments} are the CreateSchedule body with {@code Name} folded in, so they go
* through the controller's parse, and both actions answer with the schedule ARN alone. The parse
* rejects a malformed {@code Target} with the same {@code AwsException} the service raises, so it
* belongs inside the translation that makes those failures reachable for {@code Retry} and
* {@code Catch}.
*/
private JsonNode invokeAwsSdkScheduler(String action, JsonNode input, String region) {
boolean creating = "createSchedule".equals(action);
if (!creating && !"updateSchedule".equals(action)) {
throw new FailStateException("States.TaskFailed",
"Unsupported resource: " + AWS_SDK_SCHEDULER_PREFIX + action);
}
try {
ScheduleRequest request = schedulerController.parseScheduleRequest(input);
request.setName(input.path("Name").asText(null));
Schedule schedule = creating
? schedulerService.createSchedule(request, region)
: schedulerService.updateSchedule(request, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("ScheduleArn", schedule.getArn());
return response;
} catch (AwsException e) {
throw new FailStateException(sdkExceptionName("Scheduler", e.getErrorCode()), e.getMessage());
}
}
/**
* Optimized EventBridge integration for {@code events:putEvents}. The task result is the
* PutEvents response itself, and one failed entry fails the whole task with
* {@code EventBridge.FailedEntry}, carrying the response as the cause so the caller can see
* which entry it was.
*/
private JsonNode invokeOptimizedPutEvents(JsonNode input, String region) throws Exception {
jakarta.ws.rs.core.Response response;
try {
response = eventBridgeHandler.handle("PutEvents", input, region);
} catch (AwsException e) {
throw new FailStateException(sdkExceptionName("EventBridge", e.getErrorCode()), e.getMessage());
}
if (!(response.getEntity() instanceof JsonNode result)) {
throw new FailStateException("EventBridge.SdkClientException", "PutEvents returned no response body");
}
if (result.path("FailedEntryCount").asInt() > 0) {
throw new FailStateException("EventBridge.FailedEntry", objectMapper.writeValueAsString(result));
}
return result;
}
/**
* AWS SDK integration for {@code sfn:startSyncExecution}, the way an EXPRESS child workflow is
* called. It differs from the optimized {@code states:startExecution.sync} integration in three
* ways: the child must be EXPRESS, the response envelope uses PascalCase field names with
* {@code Output} as a JSON string, and a child execution that fails is reported through
* {@code Status} rather than failing the calling task.
*/
private JsonNode invokeAwsSdkSfnStartSyncExecution(JsonNode input, String region) throws Exception {
String smArn = input.path("StateMachineArn").asText(null);
if (smArn == null || smArn.isBlank()) {
throw new FailStateException("Sfn.InvalidArnException",
"StateMachineArn is required for StartSyncExecution");
}
io.github.hectorvent.floci.services.stepfunctions.model.Execution exec;
try {
exec = sfnService.get().startSyncExecution(smArn, input.path("Name").asText(null),
sdkPayload(input.path("Input")), region);
} catch (AwsException e) {
throw new FailStateException(sdkExceptionName("Sfn", e.getErrorCode()), e.getMessage());
}
ObjectNode envelope = objectMapper.createObjectNode();
envelope.put("ExecutionArn", exec.getExecutionArn());
envelope.put("StateMachineArn", exec.getStateMachineArn());
envelope.put("Name", exec.getName());
envelope.put("Status", exec.getStatus());
envelope.put("StartDate", sdkTimestamp(exec.getStartDate()));
if (exec.getStopDate() != null) {
envelope.put("StopDate", sdkTimestamp(exec.getStopDate()));
}
if (exec.getInput() != null) {
envelope.put("Input", exec.getInput());
}
if (exec.getOutput() != null) {
envelope.put("Output", exec.getOutput());
}
if (exec.getError() != null) {
envelope.put("Error", exec.getError());
}
if (exec.getCause() != null) {
envelope.put("Cause", exec.getCause());
}
return envelope;
}
private JsonNode invokeNestedStateMachine(String mode, JsonNode input, String region) throws Exception {
String smArn = input.path("StateMachineArn").asText(null);
if (smArn == null || smArn.isBlank()) {
@@ -727,26 +727,37 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
// ──────────────────────────── Tasks ────────────────────────────
public void sendTaskSuccess(String taskToken, String output) {
CompletableFuture<JsonNode> future = pendingTaskTokens.remove(taskToken);
if (future != null) {
try {
future.complete(objectMapper.readTree(output));
} catch (Exception e) {
future.completeExceptionally(new RuntimeException("Invalid JSON output: " + e.getMessage()));
}
} else {
/**
* @return whether the token named a task that was waiting for it. The
* {@code aws-sdk:sfn:sendTaskSuccess} Task integration fails the calling state when it
* did not, the way AWS answers an unknown token with {@code InvalidToken}.
*/
public boolean sendTaskSuccess(String taskToken, String output) {
CompletableFuture<JsonNode> future = taskToken != null ? pendingTaskTokens.remove(taskToken) : null;
if (future == null) {
LOG.warnv("SendTaskSuccess: no pending task for token {0}", taskToken);
return false;
}
try {
future.complete(objectMapper.readTree(output));
} catch (Exception e) {
future.completeExceptionally(new RuntimeException("Invalid JSON output: " + e.getMessage()));
}
return true;
}
public void sendTaskFailure(String taskToken, String cause, String error) {
CompletableFuture<JsonNode> future = pendingTaskTokens.remove(taskToken);
if (future != null) {
future.completeExceptionally(new AslExecutor.FailStateException(error, cause));
} else {
/**
* @return whether the token named a task that was waiting for it, as in
* {@link #sendTaskSuccess(String, String)}.
*/
public boolean sendTaskFailure(String taskToken, String cause, String error) {
CompletableFuture<JsonNode> future = taskToken != null ? pendingTaskTokens.remove(taskToken) : null;
if (future == null) {
LOG.warnv("SendTaskFailure: no pending task for token {0}", taskToken);
return false;
}
future.completeExceptionally(new AslExecutor.FailStateException(error, cause));
return true;
}
public void sendTaskHeartbeat(String taskToken) {
@@ -9,6 +9,8 @@ import org.junit.jupiter.api.TestMethodOrder;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
@@ -1005,4 +1007,129 @@ class SchedulerIntegrationTest {
.then()
.statusCode(405);
}
@Test
@Order(39)
void createScheduleWithMalformedEcsParameterListsReturns400() {
// CapacityProviderStrategy is a list of objects and Subnets a list of strings. An element of
// the wrong shape is a malformed body, which AWS answers with 400 SerializationException
// rather than with a server error.
given()
.contentType("application/json")
.body("""
{
"ScheduleExpression": "rate(1 hour)",
"FlexibleTimeWindow": {"Mode": "OFF"},
"Target": {
"Arn": "arn:aws:ecs:us-east-1:000000000000:cluster/batch",
"RoleArn": "arn:aws:iam::000000000000:role/scheduler-role",
"EcsParameters": {
"TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/proof:1",
"CapacityProviderStrategy": ["FARGATE"]
}
}
}
""")
.when()
.post("/schedules/ecs-scalar-capacity-provider")
.then()
.statusCode(400);
given()
.contentType("application/json")
.body("""
{
"ScheduleExpression": "rate(1 hour)",
"FlexibleTimeWindow": {"Mode": "OFF"},
"Target": {
"Arn": "arn:aws:ecs:us-east-1:000000000000:cluster/batch",
"RoleArn": "arn:aws:iam::000000000000:role/scheduler-role",
"EcsParameters": {
"TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/proof:1",
"NetworkConfiguration": {
"awsvpcConfiguration": {"Subnets": [{"Id": "subnet-a"}]}
}
}
}
}
""")
.when()
.post("/schedules/ecs-object-subnet")
.then()
.statusCode(400);
}
@Test
@Order(40)
void createScheduleWithAScalarSubnetReturnsSerializationException() {
// Jackson converts a number or a boolean to a String rather than refusing it, so a
// scalar element reaches the store unless the conversion is checked before it runs.
// AWS answers 400 SerializationException, measured through the Scheduler API.
for (String element : new String[]{"123", "true"}) {
given()
.contentType("application/json")
.body("""
{
"ScheduleExpression": "rate(1 hour)",
"FlexibleTimeWindow": {"Mode": "OFF"},
"Target": {
"Arn": "arn:aws:ecs:us-east-1:000000000000:cluster/batch",
"RoleArn": "arn:aws:iam::000000000000:role/scheduler-role",
"EcsParameters": {
"TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/proof:1",
"NetworkConfiguration": {
"awsvpcConfiguration": {"Subnets": [%s]}
}
}
}
}
""".formatted(element))
.when()
.post("/schedules/ecs-scalar-subnet-" + element)
.then()
.statusCode(400)
.body("__type", containsString("SerializationException"));
}
}
@Test
@Order(41)
void createScheduleWithANonListEcsParameterReturnsSerializationException() {
// Every EcsParameters list field answers 400 SerializationException "Expected list or null"
// on AWS when it holds a scalar, measured through the Scheduler API for all six.
record ListField(String path, String body) { }
var fields = List.of(
new ListField("CapacityProviderStrategy", "\"CapacityProviderStrategy\": \"FARGATE\""),
new ListField("PlacementConstraints", "\"PlacementConstraints\": \"distinctInstance\""),
new ListField("PlacementStrategy", "\"PlacementStrategy\": \"spread\""),
new ListField("Tags", "\"Tags\": \"owner\""),
new ListField("Subnets",
"\"NetworkConfiguration\": {\"awsvpcConfiguration\": {\"Subnets\": \"subnet-a\"}}"),
new ListField("SecurityGroups",
"\"NetworkConfiguration\": {\"awsvpcConfiguration\": {\"SecurityGroups\": \"sg-a\"}}"));
for (ListField field : fields) {
given()
.contentType("application/json")
.body("""
{
"ScheduleExpression": "rate(1 hour)",
"FlexibleTimeWindow": {"Mode": "OFF"},
"Target": {
"Arn": "arn:aws:ecs:us-east-1:000000000000:cluster/batch",
"RoleArn": "arn:aws:iam::000000000000:role/scheduler-role",
"EcsParameters": {
"TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/proof:1",
%s
}
}
}
""".formatted(field.body()))
.when()
.post("/schedules/ecs-non-list-" + field.path())
.then()
.statusCode(400)
.body("__type", containsString("SerializationException"));
}
}
}
@@ -19,7 +19,7 @@ class AslExecutorArrayParamsTest {
private AslExecutor newExecutor() {
return new AslExecutor(null, null, null, null, null, null, null, null,
null, null, mapper, null, null, null, null);
null, null, null, null, null, mapper, null, null, null, null);
}
@Test
@@ -88,6 +88,9 @@ class AslExecutorCatchTest {
mock(S3Service.class),
mock(io.github.hectorvent.floci.services.ecs.EcsService.class),
mock(io.github.hectorvent.floci.services.ecs.EcsJsonHandler.class),
mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class), mock(EmulatorConfig.class), vertx);
@@ -69,6 +69,9 @@ class AslExecutorEcsRunTaskModeTest {
mock(io.github.hectorvent.floci.services.s3.S3Service.class),
ecsService,
ecsJsonHandler,
mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class),
@@ -82,6 +82,9 @@ class AslExecutorErrorTerminationTest {
mock(S3Service.class),
mock(io.github.hectorvent.floci.services.ecs.EcsService.class),
mock(io.github.hectorvent.floci.services.ecs.EcsJsonHandler.class),
mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new CrashingJsonataEvaluator(objectMapper),
mock(Instance.class), mock(EmulatorConfig.class), vertx);
@@ -169,6 +169,9 @@ class AslExecutorHttpInvokeTest {
mock(io.github.hectorvent.floci.services.s3.S3Service.class),
mock(EcsService.class),
mock(EcsJsonHandler.class),
mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class),
@@ -23,7 +23,7 @@ class AslExecutorIntrinsicContextTest {
/** Only ObjectMapper is exercised by the path/intrinsic resolution methods under test. */
private AslExecutor newExecutor() {
return new AslExecutor(null, null, null, null, null, null, null, null,
null, null, mapper, null, null, null, null);
null, null, null, null, null, mapper, null, null, null, null);
}
@Test
@@ -48,6 +48,9 @@ class AslExecutorJsonMergeTest {
mock(S3Service.class),
mock(EcsService.class),
mock(EcsJsonHandler.class),
mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
mapper,
new JsonataEvaluator(mapper),
mock(Instance.class),
@@ -86,6 +86,9 @@ class AslExecutorLambdaInvokeResultTest {
mock(S3Service.class),
mock(io.github.hectorvent.floci.services.ecs.EcsService.class),
mock(io.github.hectorvent.floci.services.ecs.EcsJsonHandler.class),
mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class), mock(EmulatorConfig.class), vertx);
@@ -59,6 +59,9 @@ class AslExecutorMockedResponsesTest {
mock(S3Service.class),
mock(io.github.hectorvent.floci.services.ecs.EcsService.class),
mock(io.github.hectorvent.floci.services.ecs.EcsJsonHandler.class),
mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class), mock(EmulatorConfig.class), vertx);
@@ -42,6 +42,9 @@ class AslExecutorPathIntrinsicsTest {
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),
mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
mapper,
new JsonataEvaluator(mapper),
mock(Instance.class),
@@ -65,6 +65,9 @@ class AslExecutorResultWriterTest {
s3Service,
mock(io.github.hectorvent.floci.services.ecs.EcsService.class),
mock(io.github.hectorvent.floci.services.ecs.EcsJsonHandler.class),
mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
mapper,
new JsonataEvaluator(mapper),
mock(Instance.class),
@@ -76,6 +76,9 @@ class AslExecutorRetryTest {
mock(S3Service.class),
mock(io.github.hectorvent.floci.services.ecs.EcsService.class),
mock(io.github.hectorvent.floci.services.ecs.EcsJsonHandler.class),
mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class), mock(EmulatorConfig.class), vertx);
@@ -60,6 +60,9 @@ class AslExecutorTerminalStateTest {
mock(S3Service.class),
mock(io.github.hectorvent.floci.services.ecs.EcsService.class),
mock(io.github.hectorvent.floci.services.ecs.EcsJsonHandler.class),
mock(io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerService.class),
mock(io.github.hectorvent.floci.services.scheduler.SchedulerController.class),
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class), mock(EmulatorConfig.class), vertx);
@@ -0,0 +1,598 @@
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.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 static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Integration tests for the {@code arn:aws:states:::aws-sdk:} task integrations of Step Functions
* itself and of EventBridge Scheduler: {@code sfn:startExecution}, {@code sfn:sendTaskSuccess},
* {@code sfn:sendTaskFailure}, {@code scheduler:createSchedule} and {@code scheduler:updateSchedule}.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class StepFunctionsAwsSdkTaskIntegrationTest {
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String SQS_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";
private static final String ISO_INSTANT = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z";
private static final ObjectMapper mapper = new ObjectMapper();
private static String quickChildArn;
private static String slowChildArn;
private static String callbackQueueUrl;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(0)
void setup_createChildrenAndCallbackQueue() {
quickChildArn = createStateMachine("aws-sdk-task-child-quick", """
{
"StartAt": "Done",
"States": {"Done": {"Type": "Pass", "End": true}}
}
""");
slowChildArn = createStateMachine("aws-sdk-task-child-slow", """
{
"StartAt": "Linger",
"States": {
"Linger": {"Type": "Wait", "Seconds": 5, "Next": "Done"},
"Done": {"Type": "Pass", "End": true}
}
}
""");
callbackQueueUrl = createQueue("aws-sdk-task-callback");
}
// ──────────────────────────── sfn:startExecution ────────────────────────────
@Test
@Order(1)
void startExecutionReturnsThePascalCaseArnAndAnIsoStartDate() throws Exception {
var smArn = createStateMachine("aws-sdk-start-execution", """
{
"QueryLanguage": "JSONata",
"StartAt": "Start",
"States": {
"Start": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:sfn:startExecution",
"Arguments": {"StateMachineArn": "CHILD_ARN", "Input": {"amount": 1200}},
"End": true
}
}
}
""".replace("CHILD_ARN", quickChildArn));
var result = mapper.readTree(succeedingOutputOf(smArn, "{}"));
assertTrue(result.path("ExecutionArn").asText()
.contains(":execution:aws-sdk-task-child-quick:"),
"unexpected ExecutionArn: " + result.path("ExecutionArn").asText());
assertTrue(result.path("StartDate").asText().matches(ISO_INSTANT),
"StartDate is not the SDK's ISO-8601 rendering: " + result.path("StartDate"));
assertEquals(2, result.size(), "StartExecution returns ExecutionArn and StartDate only");
// The child really ran, with the Input the task passed it.
var child = describeExecution(result.path("ExecutionArn").asText());
assertEquals("{\"amount\":1200}", child.jsonPath().getString("input"));
}
@Test
@Order(2)
void startExecutionDoesNotWaitForTheChild() throws Exception {
var smArn = createStateMachine("aws-sdk-start-execution-no-wait", """
{
"QueryLanguage": "JSONata",
"StartAt": "Start",
"States": {
"Start": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:sfn:startExecution",
"Arguments": {"StateMachineArn": "CHILD_ARN"},
"End": true
}
}
}
""".replace("CHILD_ARN", slowChildArn));
var result = mapper.readTree(succeedingOutputOf(smArn, "{}"));
var child = describeExecution(result.path("ExecutionArn").asText());
assertEquals("RUNNING", child.jsonPath().getString("status"),
"the parent finished before the 5s child, so the child is still running");
}
@Test
@Order(3)
void startExecutionOnAMissingStateMachineFailsWithTheSdkExceptionName() {
var smArn = createStateMachine("aws-sdk-start-execution-missing", """
{
"QueryLanguage": "JSONata",
"StartAt": "Start",
"States": {
"Start": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:sfn:startExecution",
"Arguments": {
"StateMachineArn": "arn:aws:states:us-east-1:000000000000:stateMachine:nope"
},
"End": true
}
}
}
""");
var describe = waitForTerminalState(startExecution(smArn, "{}"));
assertEquals("FAILED", describe.jsonPath().getString("status"));
assertEquals("Sfn.StateMachineDoesNotExistException", describe.jsonPath().getString("error"));
}
@Test
@Order(4)
void startExecutionReusingAnExecutionNameFailsWithTheSdkExceptionName() {
var smArn = createStateMachine("aws-sdk-start-execution-named", """
{
"QueryLanguage": "JSONata",
"StartAt": "Start",
"States": {
"Start": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:sfn:startExecution",
"Arguments": {"StateMachineArn": "CHILD_ARN", "Name": "taken-once"},
"End": true
}
}
}
""".replace("CHILD_ARN", quickChildArn));
assertEquals("SUCCEEDED", waitForTerminalState(startExecution(smArn, "{}"))
.jsonPath().getString("status"));
var describe = waitForTerminalState(startExecution(smArn, "{}"));
assertEquals("FAILED", describe.jsonPath().getString("status"));
assertEquals("Sfn.ExecutionAlreadyExistsException", describe.jsonPath().getString("error"));
}
// ──────────────────────────── sfn:sendTaskSuccess / sendTaskFailure ────────────────────────────
@Test
@Order(5)
void sendTaskSuccessResolvesTheWaitingExecutionWithItsOutput() throws Exception {
var waitingExecArn = startExecution(createWaiterStateMachine("aws-sdk-send-success-waiter"), "{}");
var taskToken = receiveTaskToken();
var senderArn = createStateMachine("aws-sdk-send-success", """
{
"QueryLanguage": "JSONata",
"StartAt": "Resume",
"States": {
"Resume": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:sfn:sendTaskSuccess",
"Arguments": {
"TaskToken": "{% $states.input.token %}",
"Output": {"approved": true}
},
"End": true
}
}
}
""");
assertEquals("{}", succeedingOutputOf(senderArn, tokenInput(taskToken)),
"SendTaskSuccess answers with an empty response");
var waiter = waitForTerminalState(waitingExecArn);
assertEquals("SUCCEEDED", waiter.jsonPath().getString("status"));
assertTrue(mapper.readTree(waiter.jsonPath().getString("output")).path("approved").asBoolean());
}
@Test
@Order(6)
void sendTaskFailureFailsTheWaitingExecutionWithItsErrorAndCause() throws Exception {
var waitingExecArn = startExecution(createWaiterStateMachine("aws-sdk-send-failure-waiter"), "{}");
var taskToken = receiveTaskToken();
var senderArn = createStateMachine("aws-sdk-send-failure", """
{
"QueryLanguage": "JSONata",
"StartAt": "Reject",
"States": {
"Reject": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:sfn:sendTaskFailure",
"Arguments": {
"TaskToken": "{% $states.input.token %}",
"Error": "PoolClosed",
"Cause": "the pool is already closed"
},
"End": true
}
}
}
""");
assertEquals("{}", succeedingOutputOf(senderArn, tokenInput(taskToken)));
var waiter = waitForTerminalState(waitingExecArn);
assertEquals("FAILED", waiter.jsonPath().getString("status"));
assertEquals("PoolClosed", waiter.jsonPath().getString("error"));
assertEquals("the pool is already closed", waiter.jsonPath().getString("cause"));
}
@Test
@Order(7)
void sendTaskSuccessOnATokenNobodyIsWaitingForFailsTheTask() {
var smArn = createStateMachine("aws-sdk-send-success-bad-token", """
{
"QueryLanguage": "JSONata",
"StartAt": "Resume",
"States": {
"Resume": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:sfn:sendTaskSuccess",
"Arguments": {"TaskToken": "not-a-real-token", "Output": {}},
"End": true
}
}
}
""");
var describe = waitForTerminalState(startExecution(smArn, "{}"));
assertEquals("FAILED", describe.jsonPath().getString("status"));
assertEquals("Sfn.InvalidTokenException", describe.jsonPath().getString("error"));
assertEquals("Invalid Token: 'Invalid token'", describe.jsonPath().getString("cause"));
}
@Test
@Order(8)
void sendTaskFailureOnATokenNobodyIsWaitingForFailsTheTask() {
var smArn = createStateMachine("aws-sdk-send-failure-bad-token", """
{
"QueryLanguage": "JSONata",
"StartAt": "Reject",
"States": {
"Reject": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:sfn:sendTaskFailure",
"Arguments": {"TaskToken": "not-a-real-token", "Error": "E", "Cause": "c"},
"End": true
}
}
}
""");
var describe = waitForTerminalState(startExecution(smArn, "{}"));
assertEquals("FAILED", describe.jsonPath().getString("status"));
assertEquals("Sfn.InvalidTokenException", describe.jsonPath().getString("error"));
}
// ──────────────────────────── scheduler:createSchedule / updateSchedule ────────────────────────────
@Test
@Order(9)
void createScheduleReturnsTheScheduleArnAndTheScheduleIsReadable() throws Exception {
var result = mapper.readTree(succeedingOutputOf(
createStateMachine("aws-sdk-create-schedule", scheduleTask("createSchedule",
"payout-nightly", "rate(1 day)")), "{}"));
assertTrue(result.path("ScheduleArn").asText().endsWith(":schedule/default/payout-nightly"),
"unexpected ScheduleArn: " + result.path("ScheduleArn").asText());
assertEquals(1, result.size(), "CreateSchedule returns ScheduleArn only");
given().when().get("/schedules/payout-nightly")
.then().statusCode(200)
.body("ScheduleExpression", org.hamcrest.Matchers.equalTo("rate(1 day)"));
}
@Test
@Order(10)
void updateScheduleKeepsTheArnAndChangesTheExpression() throws Exception {
var result = mapper.readTree(succeedingOutputOf(
createStateMachine("aws-sdk-update-schedule", scheduleTask("updateSchedule",
"payout-nightly", "rate(2 days)")), "{}"));
assertTrue(result.path("ScheduleArn").asText().endsWith(":schedule/default/payout-nightly"));
given().when().get("/schedules/payout-nightly")
.then().statusCode(200)
.body("ScheduleExpression", org.hamcrest.Matchers.equalTo("rate(2 days)"));
}
@Test
@Order(11)
void createScheduleOnANameAlreadyTakenFailsWithConflict() {
var describe = waitForTerminalState(startExecution(
createStateMachine("aws-sdk-create-schedule-twice", scheduleTask("createSchedule",
"payout-nightly", "rate(1 day)")), "{}"));
assertEquals("FAILED", describe.jsonPath().getString("status"));
assertEquals("Scheduler.ConflictException", describe.jsonPath().getString("error"));
}
@Test
@Order(12)
void updateScheduleOnAScheduleThatDoesNotExistFailsWithResourceNotFound() {
var describe = waitForTerminalState(startExecution(
createStateMachine("aws-sdk-update-missing-schedule", scheduleTask("updateSchedule",
"no-such-schedule", "rate(1 day)")), "{}"));
assertEquals("FAILED", describe.jsonPath().getString("status"));
assertEquals("Scheduler.ResourceNotFoundException", describe.jsonPath().getString("error"));
}
@Test
@Order(13)
void createScheduleWithIncompleteEventBridgeParametersIsCatchableAsAValidationException() throws Exception {
var smArn = createStateMachine("aws-sdk-create-schedule-invalid-target", """
{
"QueryLanguage": "JSONata",
"StartAt": "Schedule",
"States": {
"Schedule": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:scheduler:createSchedule",
"Arguments": {
"Name": "payout-invalid-target",
"ScheduleExpression": "rate(1 day)",
"FlexibleTimeWindow": {"Mode": "OFF"},
"Target": {
"Arn": "TARGET_ARN",
"RoleArn": "ROLE",
"EventBridgeParameters": {"DetailType": "payout.requested"}
}
},
"Catch": [{
"ErrorEquals": ["Scheduler.ValidationException"],
"Next": "Recovered",
"Output": {"caughtError": "{% $states.errorOutput.Error %}"}
}],
"End": true
},
"Recovered": {"Type": "Pass", "End": true}
}
}
"""
.replace("TARGET_ARN", quickChildArn)
.replace("ROLE", ROLE_ARN));
var result = mapper.readTree(succeedingOutputOf(smArn, "{}"));
assertEquals("Scheduler.ValidationException", result.path("caughtError").asText(),
"a target the parser rejects must reach Catch as an SDK exception, not States.Runtime");
}
@Test
@Order(14)
void createScheduleWithAMalformedListIsCatchableAsASerializationException() throws Exception {
// A malformed EcsParameters list is refused before the conversion runs, so it reaches Catch
// as the SDK exception AWS sends rather than as States.Runtime.
for (String[] shape : new String[][]{
{"scalar-strategy", "\"CapacityProviderStrategy\": [\"FARGATE\"]"},
{"non-list-strategy", "\"CapacityProviderStrategy\": \"FARGATE\""},
{"scalar-subnet",
"\"NetworkConfiguration\": {\"awsvpcConfiguration\": {\"Subnets\": [123]}}"},
{"non-list-subnet",
"\"NetworkConfiguration\": {\"awsvpcConfiguration\": {\"Subnets\": \"subnet-a\"}}"}}) {
var smArn = createStateMachine("aws-sdk-create-schedule-" + shape[0], """
{
"QueryLanguage": "JSONata",
"StartAt": "Schedule",
"States": {
"Schedule": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:scheduler:createSchedule",
"Arguments": {
"Name": "payout-SHAPE",
"ScheduleExpression": "rate(1 day)",
"FlexibleTimeWindow": {"Mode": "OFF"},
"Target": {
"Arn": "TARGET_ARN",
"RoleArn": "ROLE",
"EcsParameters": {
"TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/p:1",
MALFORMED_FIELD
}
}
},
"Catch": [{
"ErrorEquals": ["Scheduler.SerializationException"],
"Next": "Recovered",
"Output": {"caughtError": "{% $states.errorOutput.Error %}"}
}],
"End": true
},
"Recovered": {"Type": "Pass", "End": true}
}
}
"""
.replace("MALFORMED_FIELD", shape[1])
.replace("SHAPE", shape[0])
.replace("TARGET_ARN", quickChildArn)
.replace("ROLE", ROLE_ARN));
var result = mapper.readTree(succeedingOutputOf(smArn, "{}"));
assertEquals("Scheduler.SerializationException", result.path("caughtError").asText(),
shape[0] + " must reach Catch as an SDK exception, not States.Runtime");
}
}
private static String scheduleTask(String action, String scheduleName, String expression) {
return """
{
"QueryLanguage": "JSONata",
"StartAt": "Schedule",
"States": {
"Schedule": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:scheduler:ACTION",
"Arguments": {
"Name": "SCHEDULE_NAME",
"ScheduleExpression": "EXPRESSION",
"FlexibleTimeWindow": {"Mode": "OFF"},
"Target": {"Arn": "TARGET_ARN", "RoleArn": "ROLE"}
},
"End": true
}
}
}
"""
.replace("ACTION", action)
.replace("SCHEDULE_NAME", scheduleName)
.replace("EXPRESSION", expression)
.replace("TARGET_ARN", quickChildArn)
.replace("ROLE", ROLE_ARN);
}
/** A state machine that parks on a task token and posts it to the callback queue. */
private static String createWaiterStateMachine(String name) {
return createStateMachine(name, """
{
"QueryLanguage": "JSONata",
"StartAt": "Wait",
"States": {
"Wait": {
"Type": "Task",
"Resource": "arn:aws:states:::sqs:sendMessage.waitForTaskToken",
"Arguments": {
"QueueUrl": "QUEUE_URL",
"MessageBody": {"token": "{% $states.context.Task.Token %}"}
},
"End": true
}
}
}
""".replace("QUEUE_URL", callbackQueueUrl));
}
private String receiveTaskToken() throws Exception {
for (var i = 0; i < 50; i++) {
var resp = given()
.header("X-Amz-Target", "AmazonSQS.ReceiveMessage")
.contentType(SQS_CONTENT_TYPE)
.body("{\"QueueUrl\":\"%s\",\"MaxNumberOfMessages\":1,\"WaitTimeSeconds\":1}"
.formatted(callbackQueueUrl))
.when().post("/");
resp.then().statusCode(200);
var messages = mapper.readTree(resp.body().asString()).path("Messages");
if (messages.size() == 1) {
var message = messages.get(0);
deleteMessage(message.path("ReceiptHandle").asText());
var token = mapper.readTree(message.path("Body").asText()).path("token").asText();
assertFalse(token.isBlank(), "the waiting task published a blank token");
return token;
}
Thread.sleep(100);
}
fail("The waiting execution never published its task token");
return null;
}
private static void deleteMessage(String receiptHandle) {
given()
.header("X-Amz-Target", "AmazonSQS.DeleteMessage")
.contentType(SQS_CONTENT_TYPE)
.body("{\"QueueUrl\":\"%s\",\"ReceiptHandle\":\"%s\"}"
.formatted(callbackQueueUrl, receiptHandle))
.when().post("/")
.then().statusCode(200);
}
private static String tokenInput(String taskToken) throws Exception {
return mapper.createObjectNode().put("token", taskToken).toString();
}
private String succeedingOutputOf(String smArn, String input) {
var describe = waitForTerminalState(startExecution(smArn, input));
assertEquals("SUCCEEDED", describe.jsonPath().getString("status"),
"cause: " + describe.jsonPath().getString("cause"));
return describe.jsonPath().getString("output");
}
private static String createQueue(String name) {
var resp = given()
.header("X-Amz-Target", "AmazonSQS.CreateQueue")
.contentType(SQS_CONTENT_TYPE)
.body("{\"QueueName\":\"%s\"}".formatted(name))
.when().post("/");
resp.then().statusCode(200);
return resp.jsonPath().getString("QueueUrl");
}
private static String createStateMachine(String name, String definition) {
var resp = given()
.header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"name": "%s", "roleArn": "%s", "definition": %s}
""".formatted(name, ROLE_ARN, quote(definition)))
.when().post("/");
resp.then().statusCode(200);
return resp.jsonPath().getString("stateMachineArn");
}
private static String startExecution(String smArn, String input) {
var 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 static 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 Response waitForTerminalState(String execArn) {
for (var i = 0; i < 150; i++) {
var resp = describeExecution(execArn);
if (!"RUNNING".equals(resp.jsonPath().getString("status"))) {
return resp;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
fail("Interrupted while waiting for execution " + execArn);
}
}
fail("Execution did not complete within timeout: " + execArn);
return null;
}
private static String quote(String raw) {
return "\"" + raw
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t")
+ "\"";
}
}
@@ -0,0 +1,320 @@
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.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.ArrayList;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Integration tests for the optimized {@code arn:aws:states:::events:putEvents} task integration.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class StepFunctionsPutEventsIntegrationTest {
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String SQS_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String EVENTS_CONTENT_TYPE = "application/x-amz-json-1.1";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";
private static final String RESOURCE = "arn:aws:states:::events:putEvents";
private static final String SOURCE = "floci.putevents.task";
private static final ObjectMapper mapper = new ObjectMapper();
private static String sinkQueueUrl;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(0)
void setup_routeTheSourceToASqsQueue() {
sinkQueueUrl = createQueue("put-events-task-sink");
putRule("put-events-task-rule", "{\\\"source\\\":[\\\"" + SOURCE + "\\\"]}");
putTarget("put-events-task-rule", queueArn(sinkQueueUrl));
}
@Test
@Order(1)
void publishedEventReachesTheRuleTargetAndTheResultCarriesItsEventId() throws Exception {
var smArn = createStateMachine("put-events-delivers", """
{
"QueryLanguage": "JSONata",
"StartAt": "Publish",
"States": {
"Publish": {
"Type": "Task",
"Resource": "RESOURCE_ARN",
"Arguments": {
"Entries": [{
"Source": "SOURCE_NAME",
"DetailType": "payout requested",
"Detail": "{\\"amount\\": 1200}"
}]
},
"End": true
}
}
}
""".replace("RESOURCE_ARN", RESOURCE).replace("SOURCE_NAME", SOURCE));
var result = mapper.readTree(succeedingOutputOf(smArn));
assertEquals(0, result.path("FailedEntryCount").asInt());
var eventId = result.path("Entries").get(0).path("EventId").asText();
assertFalse(eventId.isBlank());
var delivered = mapper.readTree(receiveSingleMessage(sinkQueueUrl).path("Body").asText());
assertEquals(eventId, delivered.path("id").asText());
assertEquals("payout requested", delivered.path("detail-type").asText());
assertEquals(1200, delivered.path("detail").path("amount").asInt());
}
@Test
@Order(2)
void taskResultCarriesTheSameFieldsThePutEventsApiReturns() throws Exception {
var smArn = createStateMachine("put-events-same-envelope", """
{
"QueryLanguage": "JSONata",
"StartAt": "Publish",
"States": {
"Publish": {
"Type": "Task",
"Resource": "RESOURCE_ARN",
"Arguments": {
"Entries": [{"Source": "floci.unrouted", "DetailType": "t", "Detail": "{}"}]
},
"End": true
}
}
}
""".replace("RESOURCE_ARN", RESOURCE));
var taskResult = mapper.readTree(succeedingOutputOf(smArn));
var apiResult = mapper.readTree(given()
.header("X-Amz-Target", "AWSEvents.PutEvents")
.contentType(EVENTS_CONTENT_TYPE)
.body("""
{"Entries":[{"Source":"floci.unrouted","DetailType":"t","Detail":"{}"}]}
""")
.when().post("/")
.then().statusCode(200)
.extract().body().asString());
assertEquals(fieldNames(apiResult), fieldNames(taskResult));
assertEquals(fieldNames(apiResult.path("Entries").get(0)),
fieldNames(taskResult.path("Entries").get(0)));
assertEquals(apiResult.path("FailedEntryCount").asInt(), taskResult.path("FailedEntryCount").asInt());
}
@Test
@Order(3)
void oneRejectedEntryFailsTheTaskWithFailedEntryAndTheWholeResponseAsCause() throws Exception {
var smArn = createStateMachine("put-events-failed-entry", """
{
"QueryLanguage": "JSONata",
"StartAt": "Publish",
"States": {
"Publish": {
"Type": "Task",
"Resource": "RESOURCE_ARN",
"Arguments": {
"Entries": [
{"Source": "floci.unrouted", "DetailType": "t", "Detail": "{}"},
{"EventBusName": "no-such-bus", "Source": "floci.unrouted",
"DetailType": "t", "Detail": "{}"}
]
},
"End": true
}
}
}
""".replace("RESOURCE_ARN", RESOURCE));
var describe = waitForTerminalState(startExecution(smArn));
assertEquals("FAILED", describe.jsonPath().getString("status"));
assertEquals("EventBridge.FailedEntry", describe.jsonPath().getString("error"));
// The cause is the PutEvents response itself, so the caller can tell which entry failed.
var cause = mapper.readTree(describe.jsonPath().getString("cause"));
assertEquals(1, cause.path("FailedEntryCount").asInt());
assertFalse(cause.path("Entries").get(0).path("EventId").asText().isBlank());
assertEquals("InvalidArgument", cause.path("Entries").get(1).path("ErrorCode").asText());
}
@Test
@Order(4)
void aFailedEntryIsCatchableByItsErrorName() throws Exception {
var smArn = createStateMachine("put-events-catch", """
{
"QueryLanguage": "JSONata",
"StartAt": "Publish",
"States": {
"Publish": {
"Type": "Task",
"Resource": "RESOURCE_ARN",
"Arguments": {
"Entries": [{"EventBusName": "no-such-bus", "Source": "floci.unrouted",
"DetailType": "t", "Detail": "{}"}]
},
"Catch": [{"ErrorEquals": ["EventBridge.FailedEntry"], "Next": "Recovered"}],
"End": true
},
"Recovered": {
"Type": "Pass",
"Output": {"recovered": true},
"End": true
}
}
}
""".replace("RESOURCE_ARN", RESOURCE));
assertTrue(mapper.readTree(succeedingOutputOf(smArn)).path("recovered").asBoolean());
}
private static List<String> fieldNames(JsonNode node) {
var names = new ArrayList<String>();
node.fieldNames().forEachRemaining(names::add);
return names;
}
private String succeedingOutputOf(String smArn) {
var describe = waitForTerminalState(startExecution(smArn));
assertEquals("SUCCEEDED", describe.jsonPath().getString("status"),
"cause: " + describe.jsonPath().getString("cause"));
return describe.jsonPath().getString("output");
}
private static String createQueue(String name) {
var resp = given()
.header("X-Amz-Target", "AmazonSQS.CreateQueue")
.contentType(SQS_CONTENT_TYPE)
.body("{\"QueueName\":\"%s\"}".formatted(name))
.when().post("/");
resp.then().statusCode(200);
return resp.jsonPath().getString("QueueUrl");
}
private static String queueArn(String queueUrl) {
var resp = given()
.header("X-Amz-Target", "AmazonSQS.GetQueueAttributes")
.contentType(SQS_CONTENT_TYPE)
.body("{\"QueueUrl\":\"%s\",\"AttributeNames\":[\"QueueArn\"]}".formatted(queueUrl))
.when().post("/");
resp.then().statusCode(200);
return resp.jsonPath().getString("Attributes.QueueArn");
}
private static void putRule(String name, String eventPattern) {
given()
.header("X-Amz-Target", "AWSEvents.PutRule")
.contentType(EVENTS_CONTENT_TYPE)
.body("""
{"Name":"%s","EventPattern":"%s","State":"ENABLED"}
""".formatted(name, eventPattern))
.when().post("/")
.then().statusCode(200);
}
private static void putTarget(String rule, String targetArn) {
given()
.header("X-Amz-Target", "AWSEvents.PutTargets")
.contentType(EVENTS_CONTENT_TYPE)
.body("""
{"Rule":"%s","Targets":[{"Id":"1","Arn":"%s"}]}
""".formatted(rule, targetArn))
.when().post("/")
.then().statusCode(200);
}
private JsonNode receiveSingleMessage(String queueUrl) throws Exception {
for (var i = 0; i < 20; i++) {
var resp = given()
.header("X-Amz-Target", "AmazonSQS.ReceiveMessage")
.contentType(SQS_CONTENT_TYPE)
.body("{\"QueueUrl\":\"%s\",\"MaxNumberOfMessages\":1,\"WaitTimeSeconds\":1}"
.formatted(queueUrl))
.when().post("/");
resp.then().statusCode(200);
var messages = mapper.readTree(resp.body().asString()).path("Messages");
if (messages.size() == 1) {
return messages.get(0);
}
Thread.sleep(100);
}
fail("No event was delivered to " + queueUrl);
return null;
}
private static String createStateMachine(String name, String definition) {
var resp = given()
.header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"name": "%s", "roleArn": "%s", "definition": %s}
""".formatted(name, ROLE_ARN, quote(definition)))
.when().post("/");
resp.then().statusCode(200);
return resp.jsonPath().getString("stateMachineArn");
}
private static String startExecution(String smArn) {
var resp = given()
.header("X-Amz-Target", "AWSStepFunctions.StartExecution")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"stateMachineArn": "%s", "input": "{}"}
""".formatted(smArn))
.when().post("/");
resp.then().statusCode(200);
return resp.jsonPath().getString("executionArn");
}
private static Response waitForTerminalState(String execArn) {
for (var i = 0; i < 100; i++) {
var resp = given()
.header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"executionArn": "%s"}
""".formatted(execArn))
.when().post("/");
if (!"RUNNING".equals(resp.jsonPath().getString("status"))) {
return resp;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
fail("Interrupted while waiting for execution " + execArn);
}
}
fail("Execution did not complete within timeout: " + execArn);
return null;
}
private static String quote(String raw) {
return "\"" + raw
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t")
+ "\"";
}
}
@@ -0,0 +1,283 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Integration tests for the {@code arn:aws:states:::aws-sdk:sfn:startSyncExecution} task
* integration, the way a Standard workflow calls an EXPRESS child workflow.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class StepFunctionsStartSyncExecutionIntegrationTest {
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";
private static final String RESOURCE = "arn:aws:states:::aws-sdk:sfn:startSyncExecution";
private static final ObjectMapper mapper = new ObjectMapper();
private static String succeedingChildArn;
private static String failingChildArn;
private static String standardChildArn;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(0)
void setup_createChildStateMachines() {
succeedingChildArn = createStateMachine("sync-exec-child-ok", "EXPRESS", """
{
"QueryLanguage": "JSONata",
"StartAt": "Approve",
"States": {
"Approve": {
"Type": "Pass",
"Output": {"approved": true, "echoedAmount": "{% $states.input.amount %}"},
"End": true
}
}
}
""");
failingChildArn = createStateMachine("sync-exec-child-fail", "EXPRESS", """
{
"StartAt": "Reject",
"States": {
"Reject": {
"Type": "Fail",
"Error": "PoolClosed",
"Cause": "the pool is already closed"
}
}
}
""");
standardChildArn = createStateMachine("sync-exec-child-standard", null, """
{
"StartAt": "Approve",
"States": {
"Approve": {"Type": "Pass", "End": true}
}
}
""");
}
@Test
@Order(1)
void succeedingChildReturnsPascalCaseEnvelopeWithOutputAsJsonString() throws Exception {
var parentArn = createStateMachine("sync-exec-parent-ok", null, callChild("""
{
"QueryLanguage": "JSONata",
"StartAt": "CallChild",
"States": {
"CallChild": {
"Type": "Task",
"Resource": "RESOURCE_ARN",
"Arguments": {
"StateMachineArn": "CHILD_ARN",
"Input": {"amount": 1200}
},
"Output": {
"status": "{% $states.result.Status %}",
"childOutput": "{% $states.result.Output %}",
"childArn": "{% $states.result.StateMachineArn %}",
"startDate": "{% $states.result.StartDate %}"
},
"End": true
}
}
}
""", succeedingChildArn));
var describe = waitForTerminalState(startExecution(parentArn, "{}"));
assertEquals("SUCCEEDED", describe.jsonPath().getString("status"));
var output = mapper.readTree(describe.jsonPath().getString("output"));
assertEquals("SUCCEEDED", output.path("status").asText());
assertEquals(succeedingChildArn, output.path("childArn").asText());
// The SDK renders a timestamp as ISO-8601, where the wire response carries epoch seconds.
assertTrue(output.path("startDate").asText()
.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"),
"StartDate is not the SDK's ISO-8601 rendering: " + output.path("startDate"));
// Output arrives as a JSON string, the way the AWS SDK integration returns it.
var childOutput = mapper.readTree(output.path("childOutput").asText());
assertTrue(childOutput.path("approved").asBoolean());
assertEquals(1200, childOutput.path("echoedAmount").asInt());
}
@Test
@Order(2)
void failingChildIsReportedThroughStatusWithoutFailingTheTask() throws Exception {
var parentArn = createStateMachine("sync-exec-parent-fail", null, callChild("""
{
"QueryLanguage": "JSONata",
"StartAt": "CallChild",
"States": {
"CallChild": {
"Type": "Task",
"Resource": "RESOURCE_ARN",
"Arguments": {
"StateMachineArn": "CHILD_ARN",
"Input": {}
},
"Output": {
"status": "{% $states.result.Status %}",
"error": "{% $states.result.Error %}",
"cause": "{% $states.result.Cause %}"
},
"End": true
}
}
}
""", failingChildArn));
var describe = waitForTerminalState(startExecution(parentArn, "{}"));
assertEquals("SUCCEEDED", describe.jsonPath().getString("status"));
var output = mapper.readTree(describe.jsonPath().getString("output"));
assertEquals("FAILED", output.path("status").asText());
assertEquals("PoolClosed", output.path("error").asText());
assertEquals("the pool is already closed", output.path("cause").asText());
}
@Test
@Order(3)
void standardChildFailsTheTaskWithTheServicePrefixedError() {
var parentArn = createStateMachine("sync-exec-parent-standard-child", null, """
{
"QueryLanguage": "JSONata",
"StartAt": "CallChild",
"States": {
"CallChild": {
"Type": "Task",
"Resource": "%s",
"Arguments": {
"StateMachineArn": "%s",
"Input": {}
},
"End": true
}
}
}
""".formatted(RESOURCE, standardChildArn));
var describe = waitForTerminalState(startExecution(parentArn, "{}"));
assertEquals("FAILED", describe.jsonPath().getString("status"));
assertEquals("Sfn.StateMachineTypeNotSupportedException", describe.jsonPath().getString("error"));
assertTrue(describe.jsonPath().getString("cause").contains("only supported for EXPRESS"));
}
@Test
@Order(4)
void missingStateMachineArnFailsTheTask() {
var parentArn = createStateMachine("sync-exec-parent-no-arn", null, """
{
"QueryLanguage": "JSONata",
"StartAt": "CallChild",
"States": {
"CallChild": {
"Type": "Task",
"Resource": "%s",
"Arguments": {"Input": {}},
"End": true
}
}
}
""".formatted(RESOURCE));
var describe = waitForTerminalState(startExecution(parentArn, "{}"));
assertEquals("FAILED", describe.jsonPath().getString("status"));
assertEquals("Sfn.InvalidArnException", describe.jsonPath().getString("error"));
}
/**
* Substitutes the two ARNs by token instead of {@code String.formatted}, because a JSONata
* definition contains {@code {% ... %}} delimiters that a format string reads as conversions.
*/
private static String callChild(String definition, String childArn) {
return definition
.replace("RESOURCE_ARN", RESOURCE)
.replace("CHILD_ARN", childArn);
}
private static String createStateMachine(String name, String type, String definition) {
var typeField = type != null ? "\"type\": \"%s\",".formatted(type) : "";
var resp = given()
.header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
.contentType(SFN_CONTENT_TYPE)
.body("""
{
"name": "%s",
%s
"roleArn": "%s",
"definition": %s
}
""".formatted(name, typeField, ROLE_ARN, quote(definition)))
.when().post("/");
resp.then().statusCode(200);
return resp.jsonPath().getString("stateMachineArn");
}
private static String startExecution(String smArn, String input) {
var 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 static Response waitForTerminalState(String execArn) {
for (var i = 0; i < 100; i++) {
var resp = given()
.header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
.contentType(SFN_CONTENT_TYPE)
.body("""
{"executionArn": "%s"}
""".formatted(execArn))
.when().post("/");
var status = resp.jsonPath().getString("status");
if (!"RUNNING".equals(status)) {
return resp;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
fail("Interrupted while waiting for execution " + execArn);
}
}
fail("Execution did not complete within timeout: " + execArn);
return null;
}
private static String quote(String raw) {
return "\"" + raw
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t")
+ "\"";
}
}