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

@@ -120,6 +120,13 @@ public class EmrServerlessService {
app.setNetworkConfiguration(request.getNetworkConfiguration());
app.setImageConfiguration(request.getImageConfiguration());
app.setWorkerTypeSpecifications(request.getWorkerTypeSpecifications());
app.setMonitoringConfiguration(request.getMonitoringConfiguration());
app.setRuntimeConfiguration(request.getRuntimeConfiguration());
app.setSchedulerConfiguration(request.getSchedulerConfiguration());
app.setDiskEncryptionConfiguration(request.getDiskEncryptionConfiguration());
app.setInteractiveConfiguration(request.getInteractiveConfiguration());
app.setIdentityCenterConfiguration(request.getIdentityCenterConfiguration());
app.setJobLevelCostAllocationConfiguration(request.getJobLevelCostAllocationConfiguration());
storage.put(id, app);
return app;
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.emrserverless.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@@ -10,12 +11,19 @@ public class CreateApplicationRequest {
private AutoStartConfiguration autoStartConfiguration;
private AutoStopConfiguration autoStopConfiguration;
private String clientToken;
private DiskEncryptionConfiguration diskEncryptionConfiguration;
private IdentityCenterConfiguration identityCenterConfiguration;
private ImageConfiguration imageConfiguration;
private Map<String, InitialCapacityConfig> initialCapacity;
private InteractiveConfiguration interactiveConfiguration;
private JobLevelCostAllocationConfiguration jobLevelCostAllocationConfiguration;
private MaximumCapacity maximumCapacity;
private MonitoringConfiguration monitoringConfiguration;
private String name;
private NetworkConfiguration networkConfiguration;
private String releaseLabel;
private List<RuntimeConfiguration> runtimeConfiguration;
private SchedulerConfiguration schedulerConfiguration;
private Map<String, String> tags;
private String type;
private Map<String, WorkerTypeSpecification> workerTypeSpecifications;
@@ -28,18 +36,32 @@ public class CreateApplicationRequest {
public void setAutoStopConfiguration(AutoStopConfiguration autoStopConfiguration) { this.autoStopConfiguration = autoStopConfiguration; }
public String getClientToken() { return clientToken; }
public void setClientToken(String clientToken) { this.clientToken = clientToken; }
public DiskEncryptionConfiguration getDiskEncryptionConfiguration() { return diskEncryptionConfiguration; }
public void setDiskEncryptionConfiguration(DiskEncryptionConfiguration diskEncryptionConfiguration) { this.diskEncryptionConfiguration = diskEncryptionConfiguration; }
public IdentityCenterConfiguration getIdentityCenterConfiguration() { return identityCenterConfiguration; }
public void setIdentityCenterConfiguration(IdentityCenterConfiguration identityCenterConfiguration) { this.identityCenterConfiguration = identityCenterConfiguration; }
public ImageConfiguration getImageConfiguration() { return imageConfiguration; }
public void setImageConfiguration(ImageConfiguration imageConfiguration) { this.imageConfiguration = imageConfiguration; }
public Map<String, InitialCapacityConfig> getInitialCapacity() { return initialCapacity; }
public void setInitialCapacity(Map<String, InitialCapacityConfig> initialCapacity) { this.initialCapacity = initialCapacity; }
public InteractiveConfiguration getInteractiveConfiguration() { return interactiveConfiguration; }
public void setInteractiveConfiguration(InteractiveConfiguration interactiveConfiguration) { this.interactiveConfiguration = interactiveConfiguration; }
public JobLevelCostAllocationConfiguration getJobLevelCostAllocationConfiguration() { return jobLevelCostAllocationConfiguration; }
public void setJobLevelCostAllocationConfiguration(JobLevelCostAllocationConfiguration jobLevelCostAllocationConfiguration) { this.jobLevelCostAllocationConfiguration = jobLevelCostAllocationConfiguration; }
public MaximumCapacity getMaximumCapacity() { return maximumCapacity; }
public void setMaximumCapacity(MaximumCapacity maximumCapacity) { this.maximumCapacity = maximumCapacity; }
public MonitoringConfiguration getMonitoringConfiguration() { return monitoringConfiguration; }
public void setMonitoringConfiguration(MonitoringConfiguration monitoringConfiguration) { this.monitoringConfiguration = monitoringConfiguration; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public NetworkConfiguration getNetworkConfiguration() { return networkConfiguration; }
public void setNetworkConfiguration(NetworkConfiguration networkConfiguration) { this.networkConfiguration = networkConfiguration; }
public String getReleaseLabel() { return releaseLabel; }
public void setReleaseLabel(String releaseLabel) { this.releaseLabel = releaseLabel; }
public List<RuntimeConfiguration> getRuntimeConfiguration() { return runtimeConfiguration; }
public void setRuntimeConfiguration(List<RuntimeConfiguration> runtimeConfiguration) { this.runtimeConfiguration = runtimeConfiguration; }
public SchedulerConfiguration getSchedulerConfiguration() { return schedulerConfiguration; }
public void setSchedulerConfiguration(SchedulerConfiguration schedulerConfiguration) { this.schedulerConfiguration = schedulerConfiguration; }
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
public String getType() { return type; }
@@ -1,10 +1,14 @@
package io.github.hectorvent.floci.services.emrserverless.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public class GetApplicationResponse {
// The application is stored with the clientToken CreateApplication's retries are matched on, which
// GetApplication's Application does not have. It is left out here, not on Application, so storage keeps it.
@JsonIgnoreProperties("clientToken")
private Application application;
public Application getApplication() {
@@ -6,9 +6,12 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
public class ImageConfiguration {
private String imageUri;
private String resolvedImageDigest;
private Boolean applicationLevelDigestResolution;
public String getImageUri() { return imageUri; }
public void setImageUri(String imageUri) { this.imageUri = imageUri; }
public String getResolvedImageDigest() { return resolvedImageDigest; }
public void setResolvedImageDigest(String resolvedImageDigest) { this.resolvedImageDigest = resolvedImageDigest; }
public Boolean getApplicationLevelDigestResolution() { return applicationLevelDigestResolution; }
public void setApplicationLevelDigestResolution(Boolean applicationLevelDigestResolution) { this.applicationLevelDigestResolution = applicationLevelDigestResolution; }
}
@@ -9,15 +9,17 @@ import java.util.Map;
@RegisterForReflection
public class RuntimeConfiguration {
private Map<String, Object> properties = new LinkedHashMap<>();
// Not named properties, as the other configurations' is: a configuration has a properties member,
// which Jackson would bind to a field of that name, replacing every member read before it.
private final Map<String, Object> members = new LinkedHashMap<>();
@JsonAnyGetter
public Map<String, Object> getProperties() {
return properties;
public Map<String, Object> getMembers() {
return members;
}
@JsonAnySetter
public void setProperty(String key, Object value) {
properties.put(key, value);
public void setMember(String key, Object value) {
members.put(key, value);
}
}
@@ -127,6 +127,7 @@ import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.LongSupplier;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@ApplicationScoped
@@ -185,8 +186,9 @@ public class AslExecutor {
private static final int INLINE_MAP_MAX_CONCURRENCY = 40;
private static final int DISTRIBUTED_MAP_MAX_CONCURRENCY = 10_000;
// How often a .sync integration (ecs:runTask, elasticmapreduce, states:startExecution) re-reads the job
// it waits on. The wait itself is bounded by the Task's TimeoutSeconds and the execution's budget.
// How often a .sync integration (ecs:runTask, elasticmapreduce, emr-serverless, states:startExecution)
// re-reads the job it waits on. The wait itself is bounded by the Task's TimeoutSeconds and the
// execution's budget.
private static final long SYNC_POLL_INTERVAL_MS = 100;
// AWS caps the string input of States.Base64Encode/Base64Decode/Hash at 10,000 characters
@@ -270,6 +272,7 @@ public class AslExecutor {
private final WebClient webClient;
private final ApiGatewayTaskInvoker apiGatewayTaskInvoker;
private final EmrTaskInvoker emrTaskInvoker;
private final EmrServerlessTaskInvoker emrServerlessTaskInvoker;
private final EmulatorConfig config;
private final NestedTaskCredentials nestedTaskCredentials;
private final CustomResourceLiveness customResourceLiveness;
@@ -301,14 +304,15 @@ public class AslExecutor {
CustomResourceLiveness customResourceLiveness, RedshiftDataJsonHandler redshiftDataHandler,
ServiceRegistry serviceRegistry, NestedTaskCredentials nestedTaskCredentials,
LambdaTaskAuthorizer lambdaTaskAuthorizer, ApiGatewayTaskInvoker apiGatewayTaskInvoker,
EmrTaskInvoker emrTaskInvoker) {
EmrTaskInvoker emrTaskInvoker, EmrServerlessTaskInvoker emrServerlessTaskInvoker) {
this(lambdaExecutor, targetResolver, dynamoDb, dynamoDbJsonHandler,
sqsJsonHandler, snsJsonHandler, cloudFormationHandler,
ec2Service, s3Service, ecsService, ecsJsonHandler,
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, redshiftDataHandler, serviceRegistry,
nestedTaskCredentials, lambdaTaskAuthorizer, null, null, apiGatewayTaskInvoker, emrTaskInvoker);
nestedTaskCredentials, lambdaTaskAuthorizer, null, null, apiGatewayTaskInvoker, emrTaskInvoker,
emrServerlessTaskInvoker);
}
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver,
@@ -326,9 +330,11 @@ public class AslExecutor {
RedshiftDataJsonHandler redshiftDataHandler, ServiceRegistry serviceRegistry,
NestedTaskCredentials nestedTaskCredentials, LambdaTaskAuthorizer lambdaTaskAuthorizer,
Duration expressMaxExecutionTimeOverride, LongSupplier nanoTimeOverride,
ApiGatewayTaskInvoker apiGatewayTaskInvoker, EmrTaskInvoker emrTaskInvoker) {
ApiGatewayTaskInvoker apiGatewayTaskInvoker, EmrTaskInvoker emrTaskInvoker,
EmrServerlessTaskInvoker emrServerlessTaskInvoker) {
this.apiGatewayTaskInvoker = apiGatewayTaskInvoker;
this.emrTaskInvoker = emrTaskInvoker;
this.emrServerlessTaskInvoker = emrServerlessTaskInvoker;
this.nestedTaskCredentials = nestedTaskCredentials;
this.serviceRegistry = serviceRegistry;
this.lambdaTaskAuthorizer = lambdaTaskAuthorizer;
@@ -391,7 +397,8 @@ public class AslExecutor {
ec2Service, s3Service, ecsService, ecsJsonHandler,
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, null, null, null, null, null, null, null, null);
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, null, null, null, null, null, null, null, null,
null);
}
// Kept for tests that do not exercise the Redshift Data API integration.
@@ -412,7 +419,7 @@ public class AslExecutor {
ec2Service, s3Service, ecsService, ecsJsonHandler,
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
clock, sleeper, maxWaitSecondsOverride, null, null, null, null, null, null, null, null);
clock, sleeper, maxWaitSecondsOverride, null, null, null, null, null, null, null, null, null);
}
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore,
@@ -1456,6 +1463,14 @@ public class AslExecutor {
jobSubmitted);
}
// EMR Serverless optimized integrations: request-response and .sync, with no .waitForTaskToken
// variant either.
if (integration.isOptimizedService("emr-serverless") && taskToken == null) {
String region = extractRegionFromArn(sm.getStateMachineArn());
return invokeEmrServerless(integration, input, region, executionArn, executionDeadlineNanos,
taskDeadlineNanos, jobSubmitted);
}
// AWS SDK service integrations: Step Functions
if (integration.isSdkService("sfn")) {
String region = extractRegionFromArn(sm.getStateMachineArn());
@@ -2209,11 +2224,7 @@ public class AslExecutor {
}
}
/**
* The {@code elasticmapreduce:} integrations. A {@code .sync} Task records its call's response as
* submitted and polls the cluster or step as {@code ecs:runTask.sync} polls its tasks, bounded by
* the same two clocks; whatever ends the wait first abandons the job.
*/
/** The {@code elasticmapreduce:} integrations; a {@code .sync} Task waits on its cluster or step. */
private JsonNode invokeEmr(StatesIntegration integration, JsonNode input, String region, String executionArn,
long executionDeadlineNanos, long taskDeadlineNanos,
Consumer<JsonNode> jobSubmitted) throws Exception {
@@ -2221,10 +2232,36 @@ public class AslExecutor {
if (integration.suffix().isEmpty()) {
return job.response();
}
return awaitSyncJob(job.response(), () -> emrTaskInvoker.poll(job, region),
() -> emrTaskInvoker.abandon(job, region), executionArn, executionDeadlineNanos, taskDeadlineNanos,
jobSubmitted);
}
/** The {@code emr-serverless:} integrations; a {@code .sync} Task waits on its application or job run. */
private JsonNode invokeEmrServerless(StatesIntegration integration, JsonNode input, String region,
String executionArn, long executionDeadlineNanos, long taskDeadlineNanos,
Consumer<JsonNode> jobSubmitted) throws Exception {
EmrServerlessTaskInvoker.Job job = emrServerlessTaskInvoker.start(integration, input, region);
if (integration.suffix().isEmpty()) {
return job.response();
}
return awaitSyncJob(job.response(), () -> emrServerlessTaskInvoker.poll(job, region),
() -> emrServerlessTaskInvoker.abandon(job, region), executionArn, executionDeadlineNanos,
taskDeadlineNanos, jobSubmitted);
}
/**
* The wait of a {@code .sync} Task whose job has started: records the call's response as submitted
* and polls the job as {@code ecs:runTask.sync} polls its tasks, bounded by the same two clocks;
* whatever ends the wait first abandons the job.
*/
private JsonNode awaitSyncJob(JsonNode submitted, Supplier<Optional<JsonNode>> poll, Runnable abandon,
String executionArn, long executionDeadlineNanos, long taskDeadlineNanos,
Consumer<JsonNode> jobSubmitted) throws Exception {
try {
jobSubmitted.accept(job.response());
jobSubmitted.accept(submitted);
} catch (RuntimeException e) {
emrTaskInvoker.abandon(job, region);
abandon.run();
throw e;
}
while (true) {
@@ -2232,14 +2269,14 @@ public class AslExecutor {
sleepOrTimeOutTask(TimeUnit.MILLISECONDS.toNanos(SYNC_POLL_INTERVAL_MS),
executionDeadlineNanos, taskDeadlineNanos);
} catch (TaskTimedOutException | ExecutionTimedOutException | InterruptedException e) {
emrTaskInvoker.abandon(job, region);
abandon.run();
throw e;
}
if (abortedByCaller(executionArn)) {
emrTaskInvoker.abandon(job, region);
abandon.run();
throw new ExecutionAbortedException();
}
Optional<JsonNode> result = emrTaskInvoker.poll(job, region);
Optional<JsonNode> result = poll.get();
if (result.isPresent()) {
return result.get();
}
@@ -0,0 +1,294 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.MissingNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.RequestShapeModel;
import io.github.hectorvent.floci.services.emrserverless.EmrServerlessController;
import io.github.hectorvent.floci.services.emrserverless.model.CreateApplicationRequest;
import io.github.hectorvent.floci.services.emrserverless.model.StartJobRunRequest;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Supplier;
import static io.github.hectorvent.floci.services.stepfunctions.OptimizedIntegrations.failed;
import static io.github.hectorvent.floci.services.stepfunctions.OptimizedIntegrations.refused;
import static io.github.hectorvent.floci.services.stepfunctions.OptimizedIntegrations.requiredText;
import static io.github.hectorvent.floci.services.stepfunctions.OptimizedIntegrations.unsupported;
/**
* The optimized {@code arn:<partition>:states:::emr-serverless:*} integrations, the six APIs the Step
* Functions guide's "EMR Serverless service integration APIs" table lists, each with {@code .sync}, run
* through {@link EmrServerlessController} in the state machine's Region. A Task names the API's
* members in PascalCase where the API writes them in camelCase, so a request and a response are
* walked against the vendored model: a structure's members are recased, a map's keys (tags,
* {@code initialCapacity}, a configuration's {@code properties}) are kept. A member, the ids included,
* may be written in either case. A {@code .sync} Task calls
* {@link #start}, then {@link #poll} until its application or job run is done; {@link AslExecutor}
* owns the wait between polls.
*/
@ApplicationScoped
public class EmrServerlessTaskInvoker {
private static final Logger LOG = Logger.getLogger(EmrServerlessTaskInvoker.class);
private static final RequestShapeModel SHAPES =
RequestShapeModel.load("aws/emr-serverless-shapes.json", "EMR Serverless shapes");
// The exception prefix the Step Functions guide gives EMR Serverless, for its AWS SDK integration.
// No record shows the optimized integration's, and EMR's differs between the two (EMR. and Emr.).
private static final String ERROR_PREFIX = "EmrServerless.";
// What EMR Serverless answers an undo when the application or run is gone, or past the state it undoes.
private static final Set<String> NOTHING_TO_UNDO =
Set.of(ERROR_PREFIX + "ResourceNotFoundException", ERROR_PREFIX + "ValidationException");
// What each .sync waits for: the state the guide names, and the states it can no longer reach it
// from. A created application may already be starting when it is read.
private static final Map<String, Wait> WAITS = Map.of(
"createApplication", new Wait(Set.of("CREATED", "STARTING", "STARTED", "STOPPING", "STOPPED"),
Set.of("TERMINATED")),
"startApplication", new Wait(Set.of("STARTED"), Set.of("STOPPING", "STOPPED", "TERMINATED")),
"stopApplication", new Wait(Set.of("STOPPED"), Set.of("STARTING", "STARTED", "TERMINATED")),
"deleteApplication", new Wait(Set.of("TERMINATED"), Set.of()),
"startJobRun", new Wait(Set.of("SUCCESS"), Set.of("FAILED", "CANCELLED")),
"cancelJobRun", new Wait(Set.of("CANCELLED"), Set.of("SUCCESS", "FAILED")));
private final EmrServerlessController emrServerless;
private final ObjectMapper objectMapper;
@Inject
public EmrServerlessTaskInvoker(EmrServerlessController emrServerless, ObjectMapper objectMapper) {
this.emrServerless = emrServerless;
this.objectMapper = objectMapper;
}
/**
* A started call: the integration's response, and the application, or job run, a {@code .sync}
* Task waits on.
*/
record Job(String api, String applicationId, String jobRunId, ObjectNode response) {}
private record Wait(Set<String> done, Set<String> deadEnds) {}
Job start(StatesIntegration integration, JsonNode input, String region) {
String api = integration.api();
if (!WAITS.containsKey(api) || !integration.suffix().isEmpty() && !".sync".equals(integration.suffix())) {
throw unsupported(integration);
}
JsonNode request = input != null && input.isObject() ? input : objectMapper.createObjectNode();
return switch (api) {
case "createApplication" -> createApplication(request, region);
case "startApplication" -> {
String applicationId = requiredId(request, "ApplicationId");
call(region, () -> emrServerless.startApplication(applicationId));
yield applicationJob(api, applicationId);
}
case "stopApplication" -> {
String applicationId = requiredId(request, "ApplicationId");
call(region, () -> emrServerless.stopApplication(applicationId));
yield applicationJob(api, applicationId);
}
case "deleteApplication" -> {
String applicationId = requiredId(request, "ApplicationId");
call(region, () -> emrServerless.deleteApplication(applicationId));
yield applicationJob(api, applicationId);
}
case "startJobRun" -> startJobRun(request, region);
case "cancelJobRun" -> {
String applicationId = requiredId(request, "ApplicationId");
String jobRunId = requiredId(request, "JobRunId");
ObjectNode response = toStates(call(region, () -> emrServerless.cancelJobRun(applicationId, jobRunId)),
"CancelJobRunResponse");
yield new Job(api, applicationId, jobRunId, response);
}
default -> throw unsupported(integration);
};
}
/**
* The Task's result once the job is done, empty while it runs. The guide finds no difference
* between a {@code .sync} response and the API's, so the result is the starting call's own:
* state machines read a {@code createApplication.sync} result's {@code ApplicationId} and a
* {@code startJobRun.sync} result's {@code JobRunId}.
*/
Optional<JsonNode> poll(Job job, String region) {
JsonNode described;
String state;
if (job.jobRunId() != null) {
described = toStates(call(region, () -> emrServerless.getJobRun(job.applicationId(), job.jobRunId(), null)),
"GetJobRunResponse");
state = described.path("JobRun").path("State").asText();
} else {
described = toStates(call(region, () -> emrServerless.getApplication(job.applicationId())),
"GetApplicationResponse");
state = described.path("Application").path("State").asText();
}
Wait wait = WAITS.get(job.api());
if (wait.deadEnds().contains(state)) {
throw failed(described);
}
return wait.done().contains(state) ? Optional.of(job.response()) : Optional.empty();
}
/**
* Best effort, for a {@code .sync} Task that ends before its job does: Step Functions "will make a
* best-effort attempt to cancel the task". The call is the one each integration's IAM policy grants
* beyond its own and the read it waits with: DeleteApplication for {@code createApplication.sync},
* StopApplication for {@code startApplication.sync} and CancelJobRun for {@code startJobRun.sync}.
*/
void abandon(Job job, String region) {
Supplier<Object> undo = switch (job.api()) {
case "createApplication" -> () -> emrServerless.deleteApplication(job.applicationId());
case "startApplication" -> () -> emrServerless.stopApplication(job.applicationId());
case "startJobRun" -> () -> emrServerless.cancelJobRun(job.applicationId(), job.jobRunId());
default -> null;
};
if (undo == null) {
return;
}
try {
call(region, undo);
} catch (AslExecutor.FailStateException e) {
// Being best effort, nothing left to undo leaves the Task ending as it was. Any other answer, like
// any other failure, is a fault and is raised.
if (!NOTHING_TO_UNDO.contains(e.error)) {
throw e;
}
LOG.warnv("emr-serverless:{0}.sync ended before application {1} (job run {2}) was done, and it could "
+ "not be undone: {3}", job.api(), job.applicationId(), job.jobRunId(), e.getMessage());
}
}
private Job createApplication(JsonNode request, String region) {
CreateApplicationRequest create = read(request, "CreateApplicationRequest", CreateApplicationRequest.class);
if (create.getClientToken() == null) {
create.setClientToken(idempotencyToken());
}
ObjectNode response = toStates(call(region, () -> emrServerless.createApplication(create)),
"CreateApplicationResponse");
return new Job("createApplication", response.path("ApplicationId").asText(), null, response);
}
private Job startJobRun(JsonNode request, String region) {
String applicationId = requiredId(request, "ApplicationId");
StartJobRunRequest start = read(request, "StartJobRunRequest", StartJobRunRequest.class);
if (start.getClientToken() == null) {
start.setClientToken(idempotencyToken());
}
ObjectNode response = toStates(call(region, () -> emrServerless.startJobRun(applicationId, start)),
"StartJobRunResponse");
return new Job("startJobRun", applicationId, response.path("JobRunId").asText(), response);
}
/** The guide's {@code {"ApplicationId": "string"}}, where the API answers nothing. */
private Job applicationJob(String api, String applicationId) {
return new Job(api, applicationId, null, objectMapper.createObjectNode().put("ApplicationId", applicationId));
}
/**
* The model marks {@code clientToken} an idempotency token, which the SDK fills in when the caller
* leaves it out; the guide's examples leave it out of requests the API cannot take without one.
*/
private static String idempotencyToken() {
return UUID.randomUUID().toString();
}
/**
* The request as the API's model class, its members renamed to the model's own. Only the model's
* members are left by then, so one the class has no property for is refused rather than dropped.
*/
private <T> T read(JsonNode request, String shape, Class<T> type) {
try {
return objectMapper.readerFor(type).with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.treeToValue(recase(request, shape, false), type);
} catch (JsonProcessingException e) {
throw refused("The request does not match the EMR Serverless model: " + e.getOriginalMessage());
}
}
private ObjectNode toStates(Object response, String shape) {
return (ObjectNode) recase(objectMapper.valueToTree(response), shape, true);
}
/**
* {@code node} with every structure's members renamed, to PascalCase when {@code toStates}, else to
* the model's names, which a member written in either case matches. A map keeps its keys. A member
* the model does not have is dropped, as the API has no place for it, such as a request's
* {@code ApplicationId}, which travels in the path.
*/
private JsonNode recase(JsonNode node, String shapeName, boolean toStates) {
RequestShapeModel.Shape shape = shapeName == null ? null : SHAPES.shapes().get(shapeName);
if (shape == null) {
return node.deepCopy();
}
return switch (shape.type()) {
case "structure" -> node.isObject() ? recaseStructure(node, shape, toStates) : node.deepCopy();
case "list" -> {
if (!node.isArray()) {
yield node.deepCopy();
}
ArrayNode items = objectMapper.createArrayNode();
node.forEach(item -> items.add(recase(item, shape.element(), toStates)));
yield items;
}
case "map" -> {
if (!node.isObject()) {
yield node.deepCopy();
}
ObjectNode entries = objectMapper.createObjectNode();
node.properties().forEach(entry ->
entries.set(entry.getKey(), recase(entry.getValue(), shape.element(), toStates)));
yield entries;
}
default -> node.deepCopy();
};
}
/** The structure's members in the model's order, each from the first field naming it in any case. */
private ObjectNode recaseStructure(JsonNode node, RequestShapeModel.Shape shape, boolean toStates) {
ObjectNode members = objectMapper.createObjectNode();
for (Map.Entry<String, String> member : shape.members().entrySet()) {
String name = member.getKey();
JsonNode value = field(node, name);
if (!value.isMissingNode()) {
String recased = toStates ? Character.toUpperCase(name.charAt(0)) + name.substring(1) : name;
members.set(recased, recase(value, member.getValue(), toStates));
}
}
return members;
}
/** The id {@code name} names, read as every other member is, in either case. */
private static String requiredId(JsonNode request, String name) {
return requiredText(field(request, name), name);
}
/** The first of {@code node}'s fields named {@code name} in any case, or a missing node. */
private static JsonNode field(JsonNode node, String name) {
for (Map.Entry<String, JsonNode> field : node.properties()) {
if (field.getKey().equalsIgnoreCase(name)) {
return field.getValue();
}
}
return MissingNode.getInstance();
}
/** Runs in the state machine's Region, which EMR Serverless reads to find its applications. */
private <T> T call(String region, Supplier<T> body) {
try {
return RequestScopes.callAs(null, region, body);
} catch (AwsException e) {
throw new AslExecutor.FailStateException(ERROR_PREFIX + e.getErrorCode(), e.getMessage());
}
}
}
@@ -15,6 +15,11 @@ import java.util.List;
import java.util.Optional;
import java.util.Set;
import static io.github.hectorvent.floci.services.stepfunctions.OptimizedIntegrations.failed;
import static io.github.hectorvent.floci.services.stepfunctions.OptimizedIntegrations.refused;
import static io.github.hectorvent.floci.services.stepfunctions.OptimizedIntegrations.required;
import static io.github.hectorvent.floci.services.stepfunctions.OptimizedIntegrations.unsupported;
/**
* The optimized {@code arn:<partition>:states:::elasticmapreduce:*} integrations. Each one is an EMR
* API under renamed fields, as the Step Functions guide's "Optimized Amazon EMR APIs" table lists
@@ -233,26 +238,4 @@ public class EmrTaskInvoker {
}
return response.getEntity() instanceof ObjectNode body ? body : objectMapper.createObjectNode();
}
/** A job that ended without succeeding: the cause is its describe response, as a JSON string. */
private static AslExecutor.FailStateException failed(JsonNode described) {
return new AslExecutor.FailStateException("States.TaskFailed", described.toString());
}
/** A field the integration's request names a cluster, step or member by, as a non-blank string. */
private static String required(JsonNode request, String field) {
JsonNode value = request.path(field);
if (!value.isTextual() || value.asText().isBlank()) {
throw refused("The field " + field + " is required.");
}
return value.asText();
}
private static AslExecutor.FailStateException refused(String cause) {
return new AslExecutor.FailStateException("States.TaskFailed", cause);
}
private static AslExecutor.FailStateException unsupported(StatesIntegration integration) {
return new AslExecutor.FailStateException("States.TaskFailed", "Unsupported resource: " + integration);
}
}
@@ -0,0 +1,37 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
/** What the invokers of the optimized integrations share in reading a Task's request and failing it. */
final class OptimizedIntegrations {
private OptimizedIntegrations() {
}
/** A field the integration's request names a resource or member by, as a non-blank string. */
static String required(JsonNode request, String field) {
return requiredText(request.path(field), field);
}
/** {@code value}, the one the caller found the request giving {@code field}, as a non-blank string. */
static String requiredText(JsonNode value, String field) {
if (!value.isTextual() || value.asText().isBlank()) {
throw refused("The field " + field + " is required.");
}
return value.asText();
}
/** A request the integration refuses before the service sees it. */
static AslExecutor.FailStateException refused(String cause) {
return new AslExecutor.FailStateException("States.TaskFailed", cause);
}
/** A job that ended without succeeding: the cause is its describe response, as a JSON string. */
static AslExecutor.FailStateException failed(JsonNode described) {
return new AslExecutor.FailStateException("States.TaskFailed", described.toString());
}
static AslExecutor.FailStateException unsupported(StatesIntegration integration) {
return new AslExecutor.FailStateException("States.TaskFailed", "Unsupported resource: " + integration);
}
}