feat(stepfunctions): add the emr-serverless optimized integrations (#6386)

A Task can now use the six optimized EMR Serverless integrations the
Step Functions guide lists: createApplication, startApplication,
stopApplication, deleteApplication, startJobRun and cancelJobRun, each
request-response and .sync. Each calls Floci's EMR Serverless in the
state machine's Region. They failed with "Unsupported resource" before.

A Task names the API's members in PascalCase where the API writes them
in camelCase, so a request and a response are mapped against botocore's
EMR Serverless model, now vendored as aws/emr-serverless-shapes.json by
tools/aws/regen_emr_serverless_shapes.py: a structure's members are
renamed, a map keeps the keys the state machine wrote (tags,
InitialCapacity's DRIVER, a configuration's Properties such as
spark.executor.memory), and a member the model does not have is
dropped. A member, ApplicationId and JobRunId included, may be written
in either case. One the model has and Floci's request class lacks is
refused rather than dropped, and a test holds the classes to the model.
request_shapes.py can now keep output shapes for it. A request
without ClientToken gets a random one, as the SDK fills an idempotency
token in; the guide's examples leave it out.

The result is the API's response in PascalCase, or {"ApplicationId"}
where the API answers nothing, as the guide's table says. The guide
finds no difference between a .sync response and the API's, so a .sync
result is the starting call's own: state machines read a
createApplication.sync result's ApplicationId and a startJobRun.sync
result's JobRunId. A .sync Task records TaskSubmitted and polls
GetApplication or GetJobRun until the state the guide names, as the
elasticmapreduce ones do; a run that ends FAILED or CANCELLED, or an
application that can no longer get there, fails the Task with
States.TaskFailed and the describe response as the cause. A wait that
ends early cancels the run of a startJobRun.sync, stops the application
of a startApplication.sync and deletes the one a createApplication.sync
made, the call each integration's IAM policy grants beyond its own and
its read. EMR Serverless answering that the application or run is gone
or past undoing is logged and leaves the Task ending as it was; any
other failure is raised.

An EMR Serverless error keeps its code under EmrServerless., the
exception prefix the guide gives the service; no record shows the
optimized integration's. A Task without the ApplicationId, or a
cancelJobRun without the JobRunId, it acts on fails with
States.TaskFailed before EMR Serverless sees it.

CreateApplication now stores the configurations UpdateApplication
already did (runtime, monitoring, scheduler, disk encryption,
interactive, Identity Center and job-level cost allocation), and
ImageConfiguration keeps applicationLevelDigestResolution. Both were
dropped, from a Task and from the API alike. A runtime configuration
kept only its properties, lifted out of their member: Jackson bound the
properties member to the field of that name holding every member read.
It keeps its classification and properties now, on update as well.

GetApplication no longer returns the application's clientToken, which
its Application has no member for and which the .sync waits read. The
token stays with the stored application, which CreateApplication's
retries are matched on.

The .sync wait loop the elasticmapreduce integrations had is now shared
by both, as are their request and failure helpers, and the two EMR
Step Functions tests share their state machine helpers.

Part of #6046 (part 11).
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-23 22:16:08 -05:00
1 parent 6215b6fd38
commit 15de90c3ff
25 files changed
+2297 -117

No files matched your search

@@ -140,7 +140,8 @@ public class EmrServerlessIntegrationTest {
.statusCode(200)
.body("application.applicationId", equalTo(applicationId))
.body("application.name", equalTo("my-test-app"))
.body("application.state", equalTo("CREATED"));
.body("application.state", equalTo("CREATED"))
.body("application", not(hasKey("clientToken")));
}
@Test
@@ -239,7 +240,10 @@ public class EmrServerlessIntegrationTest {
},
"interactiveConfiguration": {
"studioEnabled": true
}
},
"runtimeConfiguration": [
{"classification": "spark-defaults", "properties": {"spark.executor.memory": "4g"}}
]
}
""")
.when()
@@ -256,7 +260,9 @@ public class EmrServerlessIntegrationTest {
.statusCode(200)
.body("application.releaseLabel", equalTo("emr-6.7.0"))
.body("application.monitoringConfiguration", notNullValue())
.body("application.interactiveConfiguration", notNullValue());
.body("application.interactiveConfiguration", notNullValue())
.body("application.runtimeConfiguration[0].classification", equalTo("spark-defaults"))
.body("application.runtimeConfiguration[0].properties.'spark.executor.memory'", equalTo("4g"));
}
@Test
@@ -369,4 +375,57 @@ public class EmrServerlessIntegrationTest {
+ "Value '[CREATING, CREATED, STARTING, STARTED, STOPPING, STOPPED, TERMINATED, CREATED]' "
+ "at 'states' failed to satisfy constraint: Member must have length less than or equal to 7"));
}
@Test
@Order(11)
void createApplicationKeepsEveryConfigurationItTakes() {
String id = givenReq()
.body("""
{
"name": "configured-app",
"releaseLabel": "emr-7.5.0",
"type": "SPARK",
"clientToken": "%s",
"imageConfiguration": {
"imageUri": "public.ecr.aws/emr-serverless/spark/emr-7.5.0:latest",
"applicationLevelDigestResolution": true
},
"runtimeConfiguration": [
{"classification": "spark-defaults", "properties": {"spark.driver.cores": "2"}}
],
"monitoringConfiguration": {"s3MonitoringConfiguration": {"logUri": "s3://bucket/logs/"}},
"schedulerConfiguration": {"queueTimeoutMinutes": 30, "maxConcurrentRuns": 5},
"diskEncryptionConfiguration": {
"encryptionKeyArn": "arn:aws:kms:us-east-1:000000000000:key/1234abcd-12ab-34cd-56ef-1234567890ab"
},
"interactiveConfiguration": {"studioEnabled": true, "livyEndpointEnabled": false},
"identityCenterConfiguration": {
"identityCenterInstanceArn": "arn:aws:sso:::instance/ssoins-1234567890abcdef"
},
"jobLevelCostAllocationConfiguration": {"enabled": true}
}
""".formatted(UUID.randomUUID()))
.when()
.post("/applications")
.then()
.statusCode(200)
.extract().path("applicationId");
givenReq()
.when()
.get("/applications/" + id)
.then()
.statusCode(200)
.body("application.imageConfiguration.applicationLevelDigestResolution", equalTo(true))
.body("application.runtimeConfiguration[0].classification", equalTo("spark-defaults"))
.body("application.runtimeConfiguration[0].properties.'spark.driver.cores'", equalTo("2"))
.body("application.monitoringConfiguration.s3MonitoringConfiguration.logUri", equalTo("s3://bucket/logs/"))
.body("application.schedulerConfiguration.maxConcurrentRuns", equalTo(5))
.body("application.diskEncryptionConfiguration.encryptionKeyArn",
equalTo("arn:aws:kms:us-east-1:000000000000:key/1234abcd-12ab-34cd-56ef-1234567890ab"))
.body("application.interactiveConfiguration.studioEnabled", equalTo(true))
.body("application.identityCenterConfiguration.identityCenterInstanceArn",
equalTo("arn:aws:sso:::instance/ssoins-1234567890abcdef"))
.body("application.jobLevelCostAllocationConfiguration.enabled", equalTo(true));
}
}
@@ -0,0 +1,82 @@
package io.github.hectorvent.floci.services.emrserverless;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import io.github.hectorvent.floci.core.common.RequestShapeModel;
import io.github.hectorvent.floci.services.emrserverless.model.CreateApplicationRequest;
import io.github.hectorvent.floci.services.emrserverless.model.StartJobRunRequest;
import io.github.hectorvent.floci.services.emrserverless.model.UpdateApplicationRequest;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* The request classes against botocore's model: a member a class has no property for is one the API
* takes that Floci would drop, or refuse when a Step Functions Task sends it.
*/
class EmrServerlessRequestModelTest {
private static final RequestShapeModel SHAPES =
RequestShapeModel.load("aws/emr-serverless-shapes.json", "EMR Serverless shapes");
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
void theRequestClassesTakeEveryMemberOfTheModel() {
List<String> missing = new ArrayList<>();
collectMissing("CreateApplicationRequest", type(CreateApplicationRequest.class), "CreateApplication", missing);
collectMissing("UpdateApplicationRequest", type(UpdateApplicationRequest.class), "UpdateApplication", missing);
collectMissing("StartJobRunRequest", type(StartJobRunRequest.class), "StartJobRun", missing);
assertEquals(List.of(), missing);
}
/**
* The members under {@code path} that {@code type} has no property for, at every level. A map, or
* a class that takes any property, holds whatever it is given.
*/
private static void collectMissing(String shapeName, JavaType type, String path, List<String> missing) {
RequestShapeModel.Shape shape = SHAPES.shapes().get(shapeName);
if (shape == null) {
return;
}
switch (shape.type()) {
case "list", "map" -> {
if (type.getContentType() != null) {
collectMissing(shape.element(), type.getContentType(), path + "[]", missing);
}
}
case "structure" -> {
if (type.isContainerType() || type.getRawClass() == Object.class) {
return;
}
BeanDescription bean = MAPPER.getDeserializationConfig().introspect(type);
if (bean.findAnySetterAccessor() != null) {
return;
}
Map<String, BeanPropertyDefinition> properties = new HashMap<>();
bean.findProperties().forEach(property -> properties.put(property.getName(), property));
shape.members().forEach((member, memberShape) -> {
BeanPropertyDefinition property = properties.get(member);
if (property == null) {
missing.add(path + "." + member);
} else {
collectMissing(memberShape, property.getPrimaryType(), path + "." + member, missing);
}
});
}
default -> {
}
}
}
private static JavaType type(Class<?> type) {
return MAPPER.constructType(type);
}
}
@@ -73,10 +73,11 @@ class EmrServerlessServiceTest {
}
@Test
void applicationTimestampsSurviveAReload() {
void applicationTimestampsAndClientTokenSurviveAReload() {
Path file = tempDir.resolve("emr-serverless-applications.json");
Application app = new Application();
app.setApplicationId("00abc");
app.setClientToken("create-00abc");
app.setCreatedAt(Instant.parse("2026-10-21T12:00:00.123Z"));
app.setUpdatedAt(Instant.parse("2026-10-21T12:01:00.456Z"));
new PersistentStorage<>(file, APPLICATIONS).put("00abc", app);
@@ -87,5 +88,6 @@ class EmrServerlessServiceTest {
Application reloaded = reader.get("00abc").orElseThrow();
assertEquals(app.getCreatedAt(), reloaded.getCreatedAt());
assertEquals(app.getUpdatedAt(), reloaded.getUpdatedAt());
assertEquals("create-00abc", reloaded.getClientToken());
}
}
@@ -0,0 +1,281 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.emrserverless.EmrServerlessController;
import io.github.hectorvent.floci.services.emrserverless.EmrServerlessJobRunService;
import io.github.hectorvent.floci.services.emrserverless.EmrServerlessService;
import io.github.hectorvent.floci.services.emrserverless.model.Application;
import io.github.hectorvent.floci.services.emrserverless.model.JobRun;
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* The {@code .sync} waits of the {@code emr-serverless:} integrations, on an application or job run
* held in a state Floci's instant lifecycle never shows. Time is a test clock the waits move forward.
*/
class AslExecutorEmrServerlessSyncTest {
private static final String REGION = "eu-west-3";
private static final String APPLICATION_ID = "00syncapp0000001";
private static final String JOB_RUN_ID = "00syncrun0000001";
private static final String APPLICATION_ARN =
"arn:aws:emr-serverless:eu-west-3:000000000000:/applications/" + APPLICATION_ID;
private static final String JOB_RUN_ARN = APPLICATION_ARN + "/jobruns/" + JOB_RUN_ID;
private static final String START_JOB_RUN = """
{"ApplicationId": "00syncapp0000001", "ExecutionRoleArn": "arn:aws:iam::000000000000:role/job",
"JobDriver": {"SparkSubmit": {"EntryPoint": "s3://bucket/app.py"}}}
""";
private static final String APPLICATION = """
{"ApplicationId": "00syncapp0000001"}
""";
private final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
private final AtomicLong testNanos = new AtomicLong();
private EmrServerlessService applications;
private EmrServerlessJobRunService jobRuns;
private StepFunctionsService sfnService;
private AslExecutor executor;
private List<HistoryEvent> history;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
applications = mock(EmrServerlessService.class);
jobRuns = mock(EmrServerlessJobRunService.class);
when(jobRuns.startJobRun(eq(APPLICATION_ID), any())).thenReturn(jobRun("RUNNING"));
when(applications.createApplication(any())).thenReturn(application("CREATING"));
sfnService = mock(StepFunctionsService.class);
when(sfnService.describeExecution(any())).thenAnswer(invocation ->
AslExecutorFixture.execution(invocation.getArgument(0), "RUNNING"));
Instance<StepFunctionsService> instance = mock(Instance.class);
when(instance.get()).thenReturn(sfnService);
executor = AslExecutorFixture.builder()
.objectMapper(objectMapper)
.sfnService(instance)
.customResourceLiveness(null)
.emrServerlessTaskInvoker(new EmrServerlessTaskInvoker(
new EmrServerlessController(applications, jobRuns), objectMapper))
.nanoTime(testNanos::get)
.sleeper(testNanos::addAndGet)
.build();
}
@Test
void startJobRunSyncWaitsUntilTheRunSucceedsAndAnswersWithTheStartingCall() throws Exception {
AtomicInteger polls = new AtomicInteger();
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null))
.thenAnswer(invocation -> jobRun(polls.incrementAndGet() < 3 ? "RUNNING" : "SUCCESS"));
Execution execution = run(task("startJobRun.sync"), START_JOB_RUN);
assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause());
assertEquals(3, polls.get());
JsonNode output = objectMapper.readTree(execution.getOutput());
assertEquals(objectMapper.createObjectNode().put("ApplicationId", APPLICATION_ID)
.put("JobRunId", JOB_RUN_ID).put("Arn", JOB_RUN_ARN), output);
HistoryEvent submitted = history.stream().filter(event -> event.getType().equals("TaskSubmitted"))
.findFirst().orElseThrow();
assertEquals(output, objectMapper.readTree(String.valueOf(
submitted.getDetails().get("output"))));
}
@Test
void startJobRunSyncFailsWithTheRunWhenTheRunFails() throws Exception {
JobRun failed = jobRun("FAILED");
failed.setStateDetails("Job failed, please check complete logs in configured logging destination.");
failed.setTags(Map.of("team", "data"));
failed.setConfigurationOverrides(Map.of("applicationConfiguration", List.of(Map.of(
"classification", "spark-defaults", "properties", Map.of("spark.executor.memory", "4g")))));
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(failed);
Execution execution = run(task("startJobRun.sync"), START_JOB_RUN);
assertEquals("FAILED", execution.getStatus());
assertEquals("States.TaskFailed", execution.getError());
JsonNode run = objectMapper.readTree(execution.getCause()).path("JobRun");
assertEquals("FAILED", run.path("State").asText());
assertEquals(failed.getStateDetails(), run.path("StateDetails").asText());
assertEquals("data", run.path("Tags").path("team").asText());
assertEquals("4g", run.path("ConfigurationOverrides").path("ApplicationConfiguration").path(0)
.path("Properties").path("spark.executor.memory").asText());
verify(jobRuns, never()).cancelJobRun(anyString(), anyString());
}
@Test
void startJobRunSyncCancelsItsRunWhenTheTaskTimesOut() {
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("RUNNING"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID)).thenReturn(jobRun("CANCELLED"));
Execution execution = run(timingOut("startJobRun.sync"), START_JOB_RUN);
assertEquals("FAILED", execution.getStatus());
assertEquals("States.Timeout", execution.getError());
verify(jobRuns).cancelJobRun(APPLICATION_ID, JOB_RUN_ID);
}
@Test
void startJobRunSyncStillTimesOutWhenEmrServerlessRefusesTheCancel() {
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("RUNNING"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID))
.thenThrow(new AwsException("ValidationException", "Job run is not in a cancellable state", 400));
Execution execution = run(timingOut("startJobRun.sync"), START_JOB_RUN);
assertEquals("States.Timeout", execution.getError());
verify(jobRuns).cancelJobRun(APPLICATION_ID, JOB_RUN_ID);
}
@Test
void anInternalErrorCancellingTheRunFailsTheTaskWithIt() {
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("RUNNING"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID))
.thenThrow(new AwsException("InternalServerException", "Request processing failed", 500));
Execution execution = run(timingOut("startJobRun.sync"), START_JOB_RUN);
assertEquals("EmrServerless.InternalServerException", execution.getError());
assertEquals("Request processing failed", execution.getCause());
}
@Test
void aFaultWhileCancellingTheRunIsNotPassedOver() {
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("RUNNING"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID)).thenThrow(new IllegalStateException("store closed"));
Execution execution = run(timingOut("startJobRun.sync"), START_JOB_RUN);
assertEquals("FAILED", execution.getStatus());
assertEquals("States.Runtime", execution.getError());
assertEquals("store closed", execution.getCause());
}
@Test
void cancelJobRunSyncFailsWhenTheRunSucceedsInstead() throws Exception {
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID)).thenReturn(jobRun("CANCELLING"));
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("SUCCESS"));
Execution execution = run(task("cancelJobRun.sync"),
"{\"ApplicationId\": \"" + APPLICATION_ID + "\", \"JobRunId\": \"" + JOB_RUN_ID + "\"}");
assertEquals("States.TaskFailed", execution.getError());
assertEquals("SUCCESS", objectMapper.readTree(execution.getCause()).path("JobRun").path("State").asText());
}
@Test
void createApplicationSyncDeletesTheApplicationWhenTheTaskTimesOut() {
Application creating = application("CREATING");
creating.setClientToken("kept-by-floci");
when(applications.getApplication(APPLICATION_ID)).thenReturn(creating);
Execution execution = run(timingOut("createApplication.sync"),
"{\"Name\": \"sync\", \"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}");
assertEquals("States.Timeout", execution.getError());
verify(applications).deleteApplication(APPLICATION_ID);
}
@Test
void createApplicationSyncFailsWithTheApplicationWhenItTerminates() throws Exception {
Application terminated = application("TERMINATED");
terminated.setClientToken("kept-by-floci");
when(applications.getApplication(APPLICATION_ID)).thenReturn(terminated);
Execution execution = run(task("createApplication.sync"),
"{\"Name\": \"sync\", \"ReleaseLabel\": \"emr-7.5.0\", \"Type\": \"SPARK\"}");
assertEquals("States.TaskFailed", execution.getError());
JsonNode application = objectMapper.readTree(execution.getCause()).path("Application");
assertEquals("TERMINATED", application.path("State").asText());
assertFalse(application.has("ClientToken") || application.has("clientToken"), execution.getCause());
}
@Test
void startApplicationSyncStopsTheApplicationWhenTheExecutionIsStopped() {
when(applications.getApplication(APPLICATION_ID)).thenReturn(application("STARTING"));
AtomicInteger parentReads = new AtomicInteger();
when(sfnService.describeExecution(any())).thenAnswer(invocation ->
AslExecutorFixture.execution(invocation.getArgument(0),
parentReads.incrementAndGet() < 3 ? "RUNNING" : "ABORTED"));
run(task("startApplication.sync"), APPLICATION);
verify(applications).startApplication(APPLICATION_ID);
verify(applications).stopApplication(APPLICATION_ID);
assertEquals(List.of(), history.stream().map(HistoryEvent::getType)
.filter(type -> type.equals("TaskFailed") || type.equals("TaskSucceeded")).toList());
}
@Test
void stopApplicationSyncLeavesTheApplicationAsItIsWhenTheTaskTimesOut() {
when(applications.getApplication(APPLICATION_ID)).thenReturn(application("STOPPING"));
Execution execution = run(timingOut("stopApplication.sync"), APPLICATION);
assertEquals("States.Timeout", execution.getError());
verify(applications).stopApplication(APPLICATION_ID);
verify(applications, never()).startApplication(anyString());
verify(applications, never()).deleteApplication(anyString());
}
private static String timingOut(String api) {
return """
{"StartAt": "EmrServerless", "States": {"EmrServerless": {"Type": "Task",
"Resource": "arn:aws:states:::emr-serverless:%s", "TimeoutSeconds": 1, "End": true}}}
""".formatted(api);
}
private static String task(String api) {
return """
{"StartAt": "EmrServerless", "States": {"EmrServerless": {"Type": "Task",
"Resource": "arn:aws:states:::emr-serverless:%s", "End": true}}}
""".formatted(api);
}
private static JobRun jobRun(String state) {
JobRun run = new JobRun();
run.setApplicationId(APPLICATION_ID);
run.setJobRunId(JOB_RUN_ID);
run.setArn(JOB_RUN_ARN);
run.setState(state);
run.setCreatedAt(Instant.parse("2026-10-22T12:00:00Z"));
run.setUpdatedAt(Instant.parse("2026-10-22T12:00:00Z"));
return run;
}
private static Application application(String state) {
Application application = new Application();
application.setApplicationId(APPLICATION_ID);
application.setArn(APPLICATION_ARN);
application.setName("sync");
application.setState(state);
return application;
}
private Execution run(String definition, String input) {
history = new ArrayList<>();
return AslExecutorFixture.runSync(executor, REGION, "emr-serverless-sync-test", definition, input, history);
}
}
@@ -8,7 +8,6 @@ import io.github.hectorvent.floci.services.emr.model.EmrCluster;
import io.github.hectorvent.floci.services.emr.model.EmrStep;
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;
@@ -35,7 +34,6 @@ import static org.mockito.Mockito.when;
class AslExecutorEmrSyncTest {
private static final String REGION = "eu-west-3";
private static final String ACCOUNT = "000000000000";
private static final String CLUSTER_ID = "j-SYNCTEST00001";
private static final String STEP_ID = "s-SYNCTEST00001";
private static final String ADD_STEP = """
@@ -64,7 +62,8 @@ class AslExecutorEmrSyncTest {
return cluster;
});
sfnService = mock(StepFunctionsService.class);
when(sfnService.describeExecution(any())).thenAnswer(invocation -> parent(invocation.getArgument(0), "RUNNING"));
when(sfnService.describeExecution(any())).thenAnswer(invocation ->
AslExecutorFixture.execution(invocation.getArgument(0), "RUNNING"));
Instance<StepFunctionsService> instance = mock(Instance.class);
when(instance.get()).thenReturn(sfnService);
executor = AslExecutorFixture.builder()
@@ -140,7 +139,8 @@ class AslExecutorEmrSyncTest {
when(emrService.describeCluster(CLUSTER_ID)).thenReturn(cluster("STARTING"));
AtomicInteger parentReads = new AtomicInteger();
when(sfnService.describeExecution(any())).thenAnswer(invocation ->
parent(invocation.getArgument(0), parentReads.incrementAndGet() < 3 ? "RUNNING" : "ABORTED"));
AslExecutorFixture.execution(invocation.getArgument(0),
parentReads.incrementAndGet() < 3 ? "RUNNING" : "ABORTED"));
Execution execution = run(task("createCluster.sync"), CREATE_CLUSTER);
@@ -174,13 +174,6 @@ class AslExecutorEmrSyncTest {
return cluster;
}
private static Execution parent(String executionArn, String status) {
Execution parent = new Execution();
parent.setExecutionArn(executionArn);
parent.setStatus(status);
return parent;
}
private static List<String> fieldNames(JsonNode node) {
List<String> names = new ArrayList<>();
node.fieldNames().forEachRemaining(names::add);
@@ -188,21 +181,7 @@ class AslExecutorEmrSyncTest {
}
private Execution run(String definition, String input) {
StateMachine stateMachine = new StateMachine();
stateMachine.setName("emr-sync-test");
stateMachine.setStateMachineArn("arn:aws:states:%s:%s:stateMachine:emr-sync-test".formatted(REGION, ACCOUNT));
stateMachine.setRoleArn("arn:aws:iam::%s:role/test-role".formatted(ACCOUNT));
stateMachine.setDefinition(definition);
Execution execution = new Execution();
execution.setName("emr-sync-execution");
execution.setExecutionArn("arn:aws:states:%s:%s:execution:emr-sync-test:emr-sync-execution"
.formatted(REGION, ACCOUNT));
execution.setStateMachineArn(stateMachine.getStateMachineArn());
execution.setInput(input);
history = new ArrayList<>();
executor.executeSync(stateMachine, execution, history, (updated, events) -> { });
return execution;
return AslExecutorFixture.runSync(executor, REGION, "emr-sync-test", definition, input, history);
}
}
@@ -21,11 +21,15 @@ import io.github.hectorvent.floci.services.scheduler.SchedulerController;
import io.github.hectorvent.floci.services.scheduler.SchedulerService;
import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
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 io.vertx.mutiny.core.Vertx;
import jakarta.enterprise.inject.Instance;
import java.time.Clock;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.LongSupplier;
@@ -37,11 +41,13 @@ import static org.mockito.Mockito.mock;
* <p>Every other collaborator defaults to what the convenience constructors pass: a Mockito mock
* for each integration, the system clock, a real sleeper, {@code System.nanoTime()} for deadlines,
* no Wait cap override, AWS's 5-minute Express limit, and no RDS Data, Redshift Data, service
* registry, Lambda task authorizer or EMR task invoker. A Lambda target resolver is built over the function store
* unless a test supplies its own.
* registry, Lambda task authorizer, EMR or EMR Serverless task invoker. A Lambda target resolver is built over
* the function store unless a test supplies its own.
*/
final class AslExecutorFixture {
private static final String ACCOUNT = "000000000000";
private AslExecutorFixture() {
}
@@ -49,6 +55,37 @@ final class AslExecutorFixture {
return new Builder();
}
/**
* Runs {@code definition} on {@code input} to its end, as the execution {@code <name>-execution} of
* the state machine {@code name} in {@code region}, and returns it; its events go to {@code history}.
*/
static Execution runSync(AslExecutor executor, String region, String name, String definition, String input,
List<HistoryEvent> history) {
StateMachine stateMachine = new StateMachine();
stateMachine.setName(name);
stateMachine.setStateMachineArn("arn:aws:states:%s:%s:stateMachine:%s".formatted(region, ACCOUNT, name));
stateMachine.setRoleArn("arn:aws:iam::%s:role/test-role".formatted(ACCOUNT));
stateMachine.setDefinition(definition);
Execution execution = new Execution();
execution.setName(name + "-execution");
execution.setExecutionArn("arn:aws:states:%s:%s:execution:%s:%s-execution"
.formatted(region, ACCOUNT, name, name));
execution.setStateMachineArn(stateMachine.getStateMachineArn());
execution.setInput(input);
executor.executeSync(stateMachine, execution, history, (updated, events) -> { });
return execution;
}
/** The execution a {@code .sync} wait reads to learn whether it was stopped, in {@code status}. */
static Execution execution(String executionArn, String status) {
Execution execution = new Execution();
execution.setExecutionArn(executionArn);
execution.setStatus(status);
return execution;
}
static final class Builder {
private LambdaExecutorService lambdaExecutor = mock(LambdaExecutorService.class);
@@ -83,6 +120,7 @@ final class AslExecutorFixture {
private Duration expressMaxExecutionTime;
private LongSupplier nanoTime;
private EmrTaskInvoker emrTaskInvoker;
private EmrServerlessTaskInvoker emrServerlessTaskInvoker;
private Builder() {
}
@@ -242,6 +280,11 @@ final class AslExecutorFixture {
return this;
}
Builder emrServerlessTaskInvoker(EmrServerlessTaskInvoker emrServerlessTaskInvoker) {
this.emrServerlessTaskInvoker = emrServerlessTaskInvoker;
return this;
}
AslExecutor build() {
return new AslExecutor(lambdaExecutor,
targetResolver != null ? targetResolver : new LambdaTargetResolver(functionStore, null),
@@ -251,7 +294,7 @@ final class AslExecutorFixture {
jsonataEvaluator != null ? jsonataEvaluator : new JsonataEvaluator(objectMapper),
sfnService, config, vertx, customResourceLiveness, clock, sleeper, maxWaitSeconds,
redshiftDataHandler, serviceRegistry, null, lambdaTaskAuthorizer, expressMaxExecutionTime,
nanoTime, null, emrTaskInvoker);
nanoTime, null, emrTaskInvoker, emrServerlessTaskInvoker);
}
}
}
@@ -3,7 +3,6 @@ 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.github.hectorvent.floci.testing.StepFunctionsExecutions;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
@@ -11,10 +10,10 @@ import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.EmrRequests.emr;
import static io.restassured.RestAssured.given;
import static io.github.hectorvent.floci.testing.StepFunctionsExecutions.historyInRegion;
import static io.github.hectorvent.floci.testing.StepFunctionsExecutions.runInRegion;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -27,7 +26,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class StepFunctionsEmrIntegrationTest {
private static final String REGION = "eu-west-3";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";
private static final String RESOURCE = "arn:aws:states:::elasticmapreduce:";
private static final String GROUPS_CLUSTER = """
{"Name": "sfn-emr", "ReleaseLabel": "emr-7.5.0",
@@ -233,35 +231,12 @@ class StepFunctionsEmrIntegrationTest {
assertEquals(cause, execution.jsonPath().getString("cause"));
}
private Response run(String definition) {
String stateMachineArn = sfn("CreateStateMachine", MAPPER.createObjectNode()
.put("name", "sfn-emr-" + UUID.randomUUID())
.put("definition", definition)
.put("roleArn", ROLE_ARN).toString())
.then().statusCode(200).extract().path("stateMachineArn");
String executionArn = sfn("StartExecution", MAPPER.createObjectNode()
.put("stateMachineArn", stateMachineArn).put("input", "{}").toString())
.then().statusCode(200).extract().path("executionArn");
return StepFunctionsExecutions.waitForTerminalState(executionArn);
private static Response run(String definition) {
return runInRegion(REGION, definition);
}
private List<JsonNode> history(Response execution) throws Exception {
String body = sfn("GetExecutionHistory", MAPPER.createObjectNode()
.put("executionArn", execution.jsonPath().getString("executionArn")).toString())
.then().statusCode(200).extract().asString();
List<JsonNode> events = new ArrayList<>();
MAPPER.readTree(body).path("events").forEach(events::add);
return events;
}
private static Response sfn(String action, String body) {
return given()
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260215/" + REGION
+ "/states/aws4_request, SignedHeaders=host, Signature=abc")
.header("X-Amz-Target", "AWSStepFunctions." + action)
.contentType("application/x-amz-json-1.0")
.body(body)
.when().post("/");
private static List<JsonNode> history(Response execution) throws Exception {
return historyInRegion(REGION, execution);
}
private static List<String> fieldNames(JsonNode node) {
@@ -0,0 +1,225 @@
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.Test;
import java.util.ArrayList;
import java.util.List;
import static io.github.hectorvent.floci.testing.EmrServerlessRequests.emrServerless;
import static io.github.hectorvent.floci.testing.StepFunctionsExecutions.historyInRegion;
import static io.github.hectorvent.floci.testing.StepFunctionsExecutions.runInRegion;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* The {@code emr-serverless:} optimized integrations against Floci's EMR Serverless, from a state
* machine in a Region other than the default, so every call has to reach the applications of the
* state machine's own.
*/
@QuarkusTest
class StepFunctionsEmrServerlessIntegrationTest {
private static final String REGION = "eu-west-3";
private static final String JOB_ROLE_ARN = "arn:aws:iam::000000000000:role/emr-serverless-job";
private static final String RESOURCE = "arn:aws:states:::emr-serverless:";
private static final String APPLICATION = """
{"Name": "sfn-emr-serverless", "ReleaseLabel": "emr-7.5.0", "Type": "SPARK",
"Tags": {"Team": "data"},
"InitialCapacity": {"DRIVER": {"WorkerCount": 1,
"WorkerConfiguration": {"Cpu": "2vCPU", "Memory": "4GB"}}},
"MaximumCapacity": {"Cpu": "8vCPU", "Memory": "32GB"},
"RuntimeConfiguration": [{"Classification": "spark-defaults",
"Properties": {"spark.driver.cores": "2"}}],
"MonitoringConfiguration": {"S3MonitoringConfiguration": {"LogUri": "s3://bucket/app-logs/"}}}
""";
private static final String JOB_DRIVER = """
{"SparkSubmit": {"EntryPoint": "s3://bucket/jobs/app.py", "EntryPointArguments": ["1"],
"SparkSubmitParameters": "--conf spark.executor.cores=4"}}
""";
private static final ObjectMapper MAPPER = new ObjectMapper();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void anApplicationIsCreatedStartedRunsAJobAndIsStoppedAndDeleted() throws Exception {
// Stop names its application as the API does, applicationId, which a Task may write as well.
String definition = """
{"StartAt": "Create", "States": {
"Create": {"Type": "Task", "Resource": "%1$screateApplication.sync", "Parameters": %2$s,
"ResultPath": "$.app", "Next": "Start"},
"Start": {"Type": "Task", "Resource": "%1$sstartApplication.sync",
"Parameters": {"ApplicationId.$": "$.app.ApplicationId"},
"ResultPath": "$.started", "Next": "Run"},
"Run": {"Type": "Task", "Resource": "%1$sstartJobRun.sync",
"Parameters": {"ApplicationId.$": "$.app.ApplicationId", "Name": "nightly",
"ExecutionRoleArn": "%3$s", "JobDriver": %4$s,
"ConfigurationOverrides": {
"ApplicationConfiguration": [{"Classification": "spark-defaults",
"Properties": {"spark.executor.memory": "4g"}}],
"MonitoringConfiguration": {
"S3MonitoringConfiguration": {"LogUri": "s3://bucket/logs/"}}},
"Tags": {"Run": "nightly"}},
"ResultPath": "$.run", "Next": "Stop"},
"Stop": {"Type": "Task", "Resource": "%1$sstopApplication.sync",
"Parameters": {"applicationId.$": "$.app.ApplicationId"},
"ResultPath": "$.stopped", "Next": "Delete"},
"Delete": {"Type": "Task", "Resource": "%1$sdeleteApplication.sync",
"Parameters": {"ApplicationId.$": "$.app.ApplicationId"},
"ResultPath": "$.deleted", "End": true}}}
""".formatted(RESOURCE, APPLICATION, JOB_ROLE_ARN, JOB_DRIVER);
Response execution = run(definition);
assertEquals("SUCCEEDED", execution.jsonPath().getString("status"), execution.asString());
JsonNode output = MAPPER.readTree(execution.jsonPath().getString("output"));
JsonNode app = output.path("app");
String applicationId = app.path("ApplicationId").asText();
assertEquals(List.of("ApplicationId", "Name", "Arn"), fieldNames(app));
assertEquals("sfn-emr-serverless", app.path("Name").asText());
assertEquals(MAPPER.createObjectNode().put("ApplicationId", applicationId), output.path("started"));
assertEquals(MAPPER.createObjectNode().put("ApplicationId", applicationId), output.path("stopped"));
assertEquals(MAPPER.createObjectNode().put("ApplicationId", applicationId), output.path("deleted"));
JsonNode run = output.path("run");
String jobRunId = run.path("JobRunId").asText();
assertEquals(List.of("ApplicationId", "JobRunId", "Arn"), fieldNames(run));
assertEquals(applicationId, run.path("ApplicationId").asText());
// The application and the run as the API reports them: members in camelCase, and every map
// with the keys the state machine wrote.
emrServerless(REGION).when().get("/applications/" + applicationId)
.then().statusCode(200)
.body("application.state", equalTo("TERMINATED"))
.body("application.arn", equalTo(app.path("Arn").asText()))
.body("application.tags.Team", equalTo("data"))
.body("application.initialCapacity.DRIVER.workerCount", equalTo(1))
.body("application.initialCapacity.DRIVER.workerConfiguration.cpu", equalTo("2vCPU"))
.body("application.maximumCapacity.memory", equalTo("32GB"))
.body("application.runtimeConfiguration[0].classification", equalTo("spark-defaults"))
.body("application.runtimeConfiguration[0].properties.'spark.driver.cores'", equalTo("2"))
.body("application.monitoringConfiguration.s3MonitoringConfiguration.logUri",
equalTo("s3://bucket/app-logs/"));
emrServerless(REGION).when().get("/applications/" + applicationId + "/jobruns/" + jobRunId)
.then().statusCode(200)
.body("jobRun.state", equalTo("SUCCESS"))
.body("jobRun.name", equalTo("nightly"))
.body("jobRun.arn", equalTo(run.path("Arn").asText()))
.body("jobRun.executionRole", equalTo(JOB_ROLE_ARN))
.body("jobRun.jobDriver.sparkSubmit.entryPoint", equalTo("s3://bucket/jobs/app.py"))
.body("jobRun.jobDriver.sparkSubmit.entryPointArguments[0]", equalTo("1"))
.body("jobRun.configurationOverrides.applicationConfiguration[0].classification",
equalTo("spark-defaults"))
.body("jobRun.configurationOverrides.applicationConfiguration[0].properties.'spark.executor.memory'",
equalTo("4g"))
.body("jobRun.configurationOverrides.monitoringConfiguration.s3MonitoringConfiguration.logUri",
equalTo("s3://bucket/logs/"))
.body("jobRun.tags.Run", equalTo("nightly"));
emrServerless("us-east-1").when().get("/applications/" + applicationId)
.then().statusCode(404);
List<JsonNode> submitted = history(execution).stream()
.filter(event -> "TaskSubmitted".equals(event.path("type").asText())).toList();
assertEquals(5, submitted.size());
JsonNode runSubmitted = submitted.get(2).path("taskSubmittedEventDetails");
assertEquals("emr-serverless", runSubmitted.path("resourceType").asText());
assertEquals("startJobRun.sync", runSubmitted.path("resource").asText());
assertEquals(run, MAPPER.readTree(runSubmitted.path("output").asText()));
}
@Test
void aStreamingRunIsCancelledAndWaitedOn() throws Exception {
String definition = """
{"StartAt": "Create", "States": {
"Create": {"Type": "Task", "Resource": "%1$screateApplication", "Parameters": %2$s,
"ResultPath": "$.app", "Next": "Run"},
"Run": {"Type": "Task", "Resource": "%1$sstartJobRun",
"Parameters": {"ApplicationId.$": "$.app.ApplicationId", "Mode": "STREAMING",
"ExecutionRoleArn": "%3$s", "JobDriver": %4$s},
"ResultPath": "$.run", "Next": "Cancel"},
"Cancel": {"Type": "Task", "Resource": "%1$scancelJobRun.sync",
"Parameters": {"ApplicationId.$": "$.app.ApplicationId", "JobRunId.$": "$.run.JobRunId"},
"ResultPath": "$.cancelled", "End": true}}}
""".formatted(RESOURCE, APPLICATION, JOB_ROLE_ARN, JOB_DRIVER);
Response execution = run(definition);
assertEquals("SUCCEEDED", execution.jsonPath().getString("status"), execution.asString());
JsonNode output = MAPPER.readTree(execution.jsonPath().getString("output"));
String applicationId = output.path("app").path("ApplicationId").asText();
String jobRunId = output.path("run").path("JobRunId").asText();
assertEquals(MAPPER.createObjectNode().put("ApplicationId", applicationId).put("JobRunId", jobRunId),
output.path("cancelled"));
emrServerless(REGION).when().get("/applications/" + applicationId + "/jobruns/" + jobRunId)
.then().statusCode(200)
.body("jobRun.state", equalTo("CANCELLED"))
.body("jobRun.mode", equalTo("STREAMING"));
}
@Test
void emrServerlessErrorsKeepTheirCodeUnderTheServicesPrefix() {
assertFails(task("startApplication.sync", "{\"ApplicationId\": \"00nosuchapp00000\"}"),
"EmrServerless.ResourceNotFoundException", "Application 00nosuchapp00000 not found");
String finishedRun = """
{"StartAt": "Create", "States": {
"Create": {"Type": "Task", "Resource": "%1$screateApplication", "Parameters": %2$s,
"ResultPath": "$.app", "Next": "Run"},
"Run": {"Type": "Task", "Resource": "%1$sstartJobRun.sync",
"Parameters": {"ApplicationId.$": "$.app.ApplicationId",
"ExecutionRoleArn": "%3$s", "JobDriver": %4$s},
"ResultPath": "$.run", "Next": "Cancel"},
"Cancel": {"Type": "Task", "Resource": "%1$scancelJobRun",
"Parameters": {"ApplicationId.$": "$.app.ApplicationId", "JobRunId.$": "$.run.JobRunId"},
"End": true}}}
""".formatted(RESOURCE, APPLICATION, JOB_ROLE_ARN, JOB_DRIVER);
assertFails(finishedRun, "EmrServerless.ValidationException", "Job run is not in a cancellable state");
}
@Test
void aTaskWithoutTheFieldsItsApiActsOnOrWithAnUnsupportedPatternFails() {
assertFails(task("deleteApplication", "{}"), "States.TaskFailed", "The field ApplicationId is required.");
assertFails(task("startJobRun", "{\"ExecutionRoleArn\": \"" + JOB_ROLE_ARN + "\", \"JobDriver\": "
+ JOB_DRIVER + "}"), "States.TaskFailed", "The field ApplicationId is required.");
assertFails(task("cancelJobRun.sync", "{\"ApplicationId\": \"00anyapp00000000\"}"),
"States.TaskFailed", "The field JobRunId is required.");
assertFails(task("startJobRun.sync:2", "{\"ApplicationId\": \"00anyapp00000000\"}"),
"States.TaskFailed", "Unsupported resource: " + RESOURCE + "startJobRun.sync:2");
assertFails(task("listApplications", "{}"),
"States.TaskFailed", "Unsupported resource: " + RESOURCE + "listApplications");
}
private static String task(String api, String parameters) {
return """
{"StartAt": "EmrServerless", "States": {"EmrServerless": {"Type": "Task", "Resource": "%s%s",
"Parameters": %s, "End": true}}}
""".formatted(RESOURCE, api, parameters);
}
private void assertFails(String definition, String error, String cause) {
Response execution = run(definition);
assertEquals("FAILED", execution.jsonPath().getString("status"), execution.asString());
assertEquals(error, execution.jsonPath().getString("error"));
assertEquals(cause, execution.jsonPath().getString("cause"));
}
private static Response run(String definition) {
return runInRegion(REGION, definition);
}
private static List<JsonNode> history(Response execution) throws Exception {
return historyInRegion(REGION, execution);
}
private static List<String> fieldNames(JsonNode node) {
List<String> names = new ArrayList<>();
node.fieldNames().forEachRemaining(names::add);
return names;
}
}
@@ -1,8 +1,13 @@
package io.github.hectorvent.floci.testing;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.response.Response;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
@@ -13,6 +18,8 @@ public final class StepFunctionsExecutions {
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final Duration TERMINAL_STATE_TIMEOUT = Duration.ofSeconds(10);
private static final Duration POLL_INTERVAL = Duration.ofMillis(100);
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";
private static final ObjectMapper MAPPER = new ObjectMapper();
private StepFunctionsExecutions() {}
@@ -39,4 +46,40 @@ public final class StepFunctionsExecutions {
.until(() -> describeExecution(executionArn),
response -> !"RUNNING".equals(response.jsonPath().getString("status")));
}
/**
* Creates a state machine in {@code region} from {@code definition}, runs it on an empty input and
* returns the terminal DescribeExecution response.
*/
public static Response runInRegion(String region, String definition) {
String stateMachineArn = callInRegion(region, "CreateStateMachine", MAPPER.createObjectNode()
.put("name", "sfn-" + UUID.randomUUID())
.put("definition", definition)
.put("roleArn", ROLE_ARN).toString())
.then().statusCode(200).extract().path("stateMachineArn");
String executionArn = callInRegion(region, "StartExecution", MAPPER.createObjectNode()
.put("stateMachineArn", stateMachineArn).put("input", "{}").toString())
.then().statusCode(200).extract().path("executionArn");
return waitForTerminalState(executionArn);
}
/** The history events of an execution that {@link #runInRegion} ran in {@code region}. */
public static List<JsonNode> historyInRegion(String region, Response execution) throws Exception {
String body = callInRegion(region, "GetExecutionHistory", MAPPER.createObjectNode()
.put("executionArn", execution.jsonPath().getString("executionArn")).toString())
.then().statusCode(200).extract().asString();
List<JsonNode> events = new ArrayList<>();
MAPPER.readTree(body).path("events").forEach(events::add);
return events;
}
private static Response callInRegion(String region, String action, String body) {
return given()
.header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260215/" + region
+ "/states/aws4_request, SignedHeaders=host, Signature=abc")
.header("X-Amz-Target", "AWSStepFunctions." + action)
.contentType(SFN_CONTENT_TYPE)
.body(body)
.when().post("/");
}
}