mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
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:
1 parent
6215b6fd38
commit
15de90c3ff
25 files changed
+2297
-117
No files matched your search
@@ -23,6 +23,9 @@
|
||||
# by tools/aws/regen_ecs_shapes.py.
|
||||
# src/main/resources/aws/ecr-request-shapes.json, the ECR request constraints, is generated
|
||||
# from botocore's ECR model by tools/aws/regen_ecr_shapes.py.
|
||||
# src/main/resources/aws/emr-serverless-shapes.json, the shapes the Step Functions emr-serverless
|
||||
# integrations recase against, is generated from botocore's EMR Serverless model by
|
||||
# tools/aws/regen_emr_serverless_shapes.py.
|
||||
# src/test/resources/aws/rest-routes.json, the REST routes IamRestRouteCoverageTest checks, is
|
||||
# generated from botocore's models by tools/aws/regen_rest_routes.py.
|
||||
|
||||
@@ -222,6 +225,7 @@ aws-data-sync: ## Regenerate src/main/resources/aws/*.json and the IAM managed-p
|
||||
$(PYTHON) tools/aws/regen_apigateway_types.py
|
||||
$(PYTHON) tools/aws/regen_sesv2_shapes.py
|
||||
$(PYTHON) tools/aws/regen_ecs_shapes.py
|
||||
$(PYTHON) tools/aws/regen_emr_serverless_shapes.py
|
||||
$(PYTHON) tools/aws/regen_query_services.py
|
||||
$(PYTHON) tools/aws/regen_rest_routes.py
|
||||
$(PYTHON) tools/aws/regen_managed_policies.py
|
||||
@@ -277,6 +281,12 @@ aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
|
||||
echo " Run 'make aws-data-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_emr_serverless_shapes.py --check || { \
|
||||
echo ""; \
|
||||
echo "error: src/main/resources/aws/emr-serverless-shapes.json is out of date."; \
|
||||
echo " Run 'make aws-data-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_query_services.py --check || { \
|
||||
echo ""; \
|
||||
echo "error: src/main/resources/aws/query-services.json is out of date."; \
|
||||
|
||||
@@ -46,6 +46,11 @@ another.
|
||||
`ListApplications` refuses a `states` filter naming a state that does not exist, or more than 7, and a
|
||||
`maxResults` outside 1 to 50, with the `ValidationException` AWS's validation layer answers.
|
||||
|
||||
`CreateApplication` stores every configuration `UpdateApplication` does, `runtimeConfiguration`,
|
||||
`monitoringConfiguration`, `schedulerConfiguration`, `diskEncryptionConfiguration`,
|
||||
`interactiveConfiguration`, `identityCenterConfiguration` and `jobLevelCostAllocationConfiguration`
|
||||
among them, and `GetApplication` returns each as it was written.
|
||||
|
||||
`DeleteApplication` leaves the application in `TERMINATED` state. `GetApplication` continues to
|
||||
report that state so lifecycle waiters can observe it, while an unfiltered `ListApplications`
|
||||
omits the terminated application. A terminated application cannot be started or stopped again.
|
||||
@@ -85,6 +90,9 @@ response shape, and settles when it is read.
|
||||
* `createdBy` is the caller's ARN, as `GetCallerIdentity` reports it. `releaseLabel` and
|
||||
`networkConfiguration` come from the application.
|
||||
|
||||
A state machine drives applications and job runs through the `emr-serverless:` integrations, `.sync`
|
||||
included; see [Step Functions: Amazon EMR Serverless tasks](step-functions.md#amazon-emr-serverless-tasks).
|
||||
|
||||
## Limitations and Differences from AWS
|
||||
|
||||
* **Jobs do not execute**: `StartJobRun` records a job run and moves it through its states, but no Spark or Hive job runs.
|
||||
|
||||
@@ -81,12 +81,13 @@ that does not match the selected task account fails with
|
||||
`resourceType` is the integrated service (`states`, `ecs`, `aws-sdk:sqs`) and `resource` the
|
||||
API with its suffix (`startExecution.sync:2`, `runTask.sync`), as AWS names them. A `.sync`
|
||||
Task (`states:startExecution.sync` and `.sync:2`, `ecs:runTask.sync`, the `elasticmapreduce:`
|
||||
ones) also records
|
||||
and `emr-serverless:` ones) also records
|
||||
`TaskSubmitted` after `TaskStarted`, once the call that started its job has returned and before
|
||||
it waits on the job. `taskSubmittedEventDetails` carries `resourceType`, `resource`,
|
||||
`outputDetails`, and that call's response as `output`, in PascalCase: `{"ExecutionArn",
|
||||
"StartDate"}` with `StartDate` in epoch milliseconds for a nested execution, `{"Failures",
|
||||
"Tasks"}` for an ECS task, `{"ClusterId"}`, `{"StepId"}` or `{}` for an EMR one. AWS folds the SDK's `SdkHttpMetadata` and `SdkResponseMetadata`
|
||||
"Tasks"}` for an ECS task, `{"ClusterId"}`, `{"StepId"}` or `{}` for an EMR one, the API's
|
||||
response or `{"ApplicationId"}` for an EMR Serverless one. AWS folds the SDK's `SdkHttpMetadata` and `SdkResponseMetadata`
|
||||
into that response as well; Floci records the response fields alone.
|
||||
- A direct Lambda function ARN emits `LambdaFunctionScheduled`, `LambdaFunctionStarted`,
|
||||
and then `LambdaFunctionSucceeded` or `LambdaFunctionFailed`. `LambdaFunctionScheduled`
|
||||
@@ -270,7 +271,8 @@ One deviation. Every pause is capped at `floci.services.stepfunctions.max-wait-s
|
||||
ASL carries two `TimeoutSeconds` fields and Floci enforces both, in the two terminal shapes
|
||||
AWS uses. The state machine's own field bounds every state; a `Task`'s own field bounds one that
|
||||
waits: for a task token (an activity, or a `.waitForTaskToken` integration) or for a job to end
|
||||
(`ecs:runTask.sync`, the `elasticmapreduce:` `.sync` ones, `states:startExecution.sync` and `.sync:2`). A Lambda or other SDK task that
|
||||
(`ecs:runTask.sync`, the `elasticmapreduce:` and `emr-serverless:` `.sync` ones, `states:startExecution.sync`
|
||||
and `.sync:2`). A Lambda or other SDK task that
|
||||
returns directly is not bound by it.
|
||||
|
||||
The state machine's own `TimeoutSeconds` is the whole execution's budget. It is checked before
|
||||
@@ -304,7 +306,9 @@ this resource was aborted`. A `StopExecution` that lands while the state waits e
|
||||
stops the job with the same cause, and so does the execution's budget, and so does a failure in
|
||||
another branch of the `Parallel`, or in another iteration of the `Map`, that the `Task` is in.
|
||||
An `addStep.sync` step is cancelled with `CancelSteps` instead, and the cluster of a
|
||||
`createCluster.sync` is left running (see [Amazon EMR tasks](#amazon-emr-tasks)).
|
||||
`createCluster.sync` is left running (see [Amazon EMR tasks](#amazon-emr-tasks)). An EMR Serverless
|
||||
job run is cancelled, a started application stopped and a created one deleted (see
|
||||
[Amazon EMR Serverless tasks](#amazon-emr-serverless-tasks)).
|
||||
|
||||
One deviation. AWS starts the `TimeoutSeconds` clock when a worker picks the task up, the instant
|
||||
it emits `ActivityStarted`. Floci emits `ActivityStarted` at schedule time, so both clocks start
|
||||
@@ -902,6 +906,61 @@ integration's own fields, before EMR sees it: a `ClusterId` (every API but `crea
|
||||
`.waitForTaskToken`, which AWS does not offer for EMR, and `.sync` on any other API fail as an
|
||||
unsupported resource.
|
||||
|
||||
## Amazon EMR Serverless tasks
|
||||
|
||||
`arn:...:states:::emr-serverless:` serves the six optimized EMR Serverless integrations the Step
|
||||
Functions guide lists, each request-response and `.sync`. Each one calls Floci's EMR Serverless in
|
||||
the state machine's Region:
|
||||
|
||||
| Resource | EMR Serverless calls | Result | `.sync` waits until |
|
||||
| --- | --- | --- | --- |
|
||||
| `createApplication` | `CreateApplication` | `{ApplicationId, Name, Arn}` | the application is past `CREATING` |
|
||||
| `startApplication` | `StartApplication` | `{ApplicationId}` | `STARTED` |
|
||||
| `stopApplication` | `StopApplication` | `{ApplicationId}` | `STOPPED` |
|
||||
| `deleteApplication` | `DeleteApplication` | `{ApplicationId}` | `TERMINATED` |
|
||||
| `startJobRun` | `StartJobRun` | `{ApplicationId, JobRunId, Arn}` | the run is `SUCCESS` |
|
||||
| `cancelJobRun` | `CancelJobRun` | `{ApplicationId, JobRunId}` | the run is `CANCELLED` |
|
||||
|
||||
The request is the API's, with its members in PascalCase (`ReleaseLabel`, `JobDriver.SparkSubmit.EntryPoint`,
|
||||
`ConfigurationOverrides.MonitoringConfiguration`) and the application and run named by `ApplicationId`
|
||||
and `JobRunId`; the result is the API's response in PascalCase, or `{ApplicationId}` where the API
|
||||
answers nothing, as the guide's table says. Member names are mapped against botocore's EMR Serverless
|
||||
model, so a map keeps the keys the state machine wrote: tag keys, `InitialCapacity`'s `DRIVER` and
|
||||
`EXECUTOR`, and a configuration's `Properties` such as `spark.executor.memory`. A member may be written
|
||||
in either case, the API's `applicationId` as well as `ApplicationId`. A member the model does not have
|
||||
is dropped. A request without `ClientToken` gets a random one, as the SDK fills in an
|
||||
idempotency token; the guide's examples leave it out of requests the API requires it for.
|
||||
|
||||
A `.sync` result is the starting call's own result, since the guide finds no difference between
|
||||
the two responses: state machines read a `createApplication.sync` result's `ApplicationId` and a
|
||||
`startJobRun.sync` result's `JobRunId`. The Task records `TaskSubmitted` with that result, then
|
||||
polls `GetApplication` or `GetJobRun` every 100 ms under the same two clocks as the other `.sync`
|
||||
integrations (see [Timeouts](#timeouts)). A state the wait can no longer end from fails the Task
|
||||
with `States.TaskFailed` and the `GetApplication` or `GetJobRun` response, in PascalCase, as the
|
||||
cause: a `startJobRun.sync` run that ends `FAILED` or `CANCELLED`, a `cancelJobRun.sync` run that
|
||||
ends `SUCCESS` or `FAILED`, an application that is `TERMINATED` before `createApplication.sync` sees
|
||||
it created, stops or terminates before `startApplication.sync` sees it `STARTED`, or starts or
|
||||
terminates before `stopApplication.sync` sees it `STOPPED`. No source gives these failures' error or
|
||||
cause. When the wait ends early, Step Functions "will make a best-effort attempt to cancel the task":
|
||||
`startJobRun.sync` cancels its run, `startApplication.sync` stops the application and
|
||||
`createApplication.sync` deletes it, the one call each integration's IAM policy grants beyond its
|
||||
own and the read it polls with. If EMR Serverless answers that the application or run is gone or past
|
||||
undoing (`ResourceNotFoundException`, `ValidationException`), the Task ends as it would have; any other
|
||||
failure fails it. `stopApplication.sync`, `deleteApplication.sync` and
|
||||
`cancelJobRun.sync` leave the application or run as it is. EMR Serverless in Floci reaches each
|
||||
application state at once, and a job run's as its configured duration says, so an application's
|
||||
wait ends at its first poll.
|
||||
|
||||
An error from EMR Serverless fails the Task with its code under the `EmrServerless.` prefix, such as
|
||||
`EmrServerless.ResourceNotFoundException` for an unknown application or
|
||||
`EmrServerless.ValidationException` "Job run is not in a cancellable state" for a finished run; the
|
||||
cause is EMR Serverless's message. `EmrServerless` is the exception prefix the guide gives the
|
||||
service's AWS SDK integration; no record shows the optimized integration's, which differs from the
|
||||
SDK one for EMR (`EMR.` against `Emr.`). A request without `ApplicationId`, or a `cancelJobRun`
|
||||
without `JobRunId`, fails with `States.TaskFailed` before EMR Serverless sees it, in Floci's words.
|
||||
`.waitForTaskToken`, which AWS does not offer for EMR Serverless, and `.sync:2` fail as an
|
||||
unsupported resource.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
+7
@@ -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;
|
||||
|
||||
+22
@@ -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; }
|
||||
|
||||
+4
@@ -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() {
|
||||
|
||||
+3
@@ -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; }
|
||||
}
|
||||
+7
-5
@@ -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();
|
||||
}
|
||||
|
||||
+294
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-22
@@ -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);
|
||||
}
|
||||
}
|
||||
+37
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,959 @@
|
||||
{
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_emr_serverless_shapes.py",
|
||||
"botocore": "botocore 1.43.113 (installed package)"
|
||||
},
|
||||
"operations": {
|
||||
"CancelJobRun": "CancelJobRunRequest",
|
||||
"CreateApplication": "CreateApplicationRequest",
|
||||
"DeleteApplication": "DeleteApplicationRequest",
|
||||
"GetApplication": "GetApplicationRequest",
|
||||
"GetDashboardForJobRun": "GetDashboardForJobRunRequest",
|
||||
"GetJobRun": "GetJobRunRequest",
|
||||
"GetResourceDashboard": "GetResourceDashboardRequest",
|
||||
"GetSession": "GetSessionRequest",
|
||||
"GetSessionEndpoint": "GetSessionEndpointRequest",
|
||||
"ListApplications": "ListApplicationsRequest",
|
||||
"ListJobRunAttempts": "ListJobRunAttemptsRequest",
|
||||
"ListJobRuns": "ListJobRunsRequest",
|
||||
"ListSessions": "ListSessionsRequest",
|
||||
"ListTagsForResource": "ListTagsForResourceRequest",
|
||||
"StartApplication": "StartApplicationRequest",
|
||||
"StartJobRun": "StartJobRunRequest",
|
||||
"StartSession": "StartSessionRequest",
|
||||
"StopApplication": "StopApplicationRequest",
|
||||
"TagResource": "TagResourceRequest",
|
||||
"TerminateSession": "TerminateSessionRequest",
|
||||
"UntagResource": "UntagResourceRequest",
|
||||
"UpdateApplication": "UpdateApplicationRequest"
|
||||
},
|
||||
"shapes": {
|
||||
"Application": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"applicationId": "ApplicationId",
|
||||
"name": "ApplicationName",
|
||||
"arn": "ApplicationArn",
|
||||
"releaseLabel": "ReleaseLabel",
|
||||
"type": "EngineType",
|
||||
"state": "ApplicationState",
|
||||
"stateDetails": "String256",
|
||||
"initialCapacity": "InitialCapacityConfigMap",
|
||||
"maximumCapacity": "MaximumAllowedResources",
|
||||
"createdAt": "Date",
|
||||
"updatedAt": "Date",
|
||||
"tags": "TagMap",
|
||||
"autoStartConfiguration": "AutoStartConfig",
|
||||
"autoStopConfiguration": "AutoStopConfig",
|
||||
"networkConfiguration": "NetworkConfiguration",
|
||||
"architecture": "Architecture",
|
||||
"imageConfiguration": "ImageConfiguration",
|
||||
"workerTypeSpecifications": "WorkerTypeSpecificationMap",
|
||||
"runtimeConfiguration": "ConfigurationList",
|
||||
"monitoringConfiguration": "MonitoringConfiguration",
|
||||
"diskEncryptionConfiguration": "DiskEncryptionConfiguration",
|
||||
"interactiveConfiguration": "InteractiveConfiguration",
|
||||
"schedulerConfiguration": "SchedulerConfiguration",
|
||||
"identityCenterConfiguration": "IdentityCenterConfiguration",
|
||||
"jobLevelCostAllocationConfiguration": "JobLevelCostAllocationConfiguration"
|
||||
}
|
||||
},
|
||||
"ApplicationArn": {
|
||||
"type": "string"
|
||||
},
|
||||
"ApplicationId": {
|
||||
"type": "string"
|
||||
},
|
||||
"ApplicationList": {
|
||||
"type": "list",
|
||||
"member": "ApplicationSummary"
|
||||
},
|
||||
"ApplicationName": {
|
||||
"type": "string"
|
||||
},
|
||||
"ApplicationState": {
|
||||
"type": "string"
|
||||
},
|
||||
"ApplicationSummary": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"id": "ApplicationId",
|
||||
"name": "ApplicationName",
|
||||
"arn": "ApplicationArn",
|
||||
"releaseLabel": "ReleaseLabel",
|
||||
"type": "EngineType",
|
||||
"state": "ApplicationState",
|
||||
"stateDetails": "String256",
|
||||
"createdAt": "Date",
|
||||
"updatedAt": "Date",
|
||||
"architecture": "Architecture"
|
||||
}
|
||||
},
|
||||
"Architecture": {
|
||||
"type": "string"
|
||||
},
|
||||
"Arn": {
|
||||
"type": "string"
|
||||
},
|
||||
"AttemptNumber": {
|
||||
"type": "integer"
|
||||
},
|
||||
"AutoStartConfig": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"enabled": "Boolean"
|
||||
}
|
||||
},
|
||||
"AutoStopConfig": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"enabled": "Boolean",
|
||||
"idleTimeoutMinutes": "AutoStopConfigIdleTimeoutMinutesInteger"
|
||||
}
|
||||
},
|
||||
"AutoStopConfigIdleTimeoutMinutesInteger": {
|
||||
"type": "integer"
|
||||
},
|
||||
"Boolean": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"CancelJobRunRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"CancelJobRunResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"applicationId": "ApplicationId",
|
||||
"jobRunId": "JobRunId"
|
||||
}
|
||||
},
|
||||
"ClientToken": {
|
||||
"type": "string"
|
||||
},
|
||||
"CloudWatchLoggingConfiguration": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"enabled": "Boolean",
|
||||
"logGroupName": "LogGroupName",
|
||||
"logStreamNamePrefix": "LogStreamNamePrefix",
|
||||
"encryptionKeyArn": "EncryptionKeyArn",
|
||||
"logTypes": "LogTypeMap"
|
||||
}
|
||||
},
|
||||
"Configuration": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"classification": "String1024",
|
||||
"properties": "SensitivePropertiesMap",
|
||||
"configurations": "ConfigurationList"
|
||||
}
|
||||
},
|
||||
"ConfigurationList": {
|
||||
"type": "list",
|
||||
"member": "Configuration"
|
||||
},
|
||||
"ConfigurationOverrides": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"applicationConfiguration": "ConfigurationList",
|
||||
"monitoringConfiguration": "MonitoringConfiguration",
|
||||
"diskEncryptionConfiguration": "DiskEncryptionConfiguration"
|
||||
}
|
||||
},
|
||||
"ConfigurationPropertyValue": {
|
||||
"type": "string"
|
||||
},
|
||||
"CpuSize": {
|
||||
"type": "string"
|
||||
},
|
||||
"CreateApplicationRequest": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"name": "ApplicationName",
|
||||
"releaseLabel": "ReleaseLabel",
|
||||
"type": "EngineType",
|
||||
"clientToken": "ClientToken",
|
||||
"initialCapacity": "InitialCapacityConfigMap",
|
||||
"maximumCapacity": "MaximumAllowedResources",
|
||||
"tags": "TagMap",
|
||||
"autoStartConfiguration": "AutoStartConfig",
|
||||
"autoStopConfiguration": "AutoStopConfig",
|
||||
"networkConfiguration": "NetworkConfiguration",
|
||||
"architecture": "Architecture",
|
||||
"imageConfiguration": "ImageConfigurationInput",
|
||||
"workerTypeSpecifications": "WorkerTypeSpecificationInputMap",
|
||||
"runtimeConfiguration": "ConfigurationList",
|
||||
"monitoringConfiguration": "MonitoringConfiguration",
|
||||
"diskEncryptionConfiguration": "DiskEncryptionConfiguration",
|
||||
"interactiveConfiguration": "InteractiveConfiguration",
|
||||
"schedulerConfiguration": "SchedulerConfiguration",
|
||||
"identityCenterConfiguration": "IdentityCenterConfigurationInput",
|
||||
"jobLevelCostAllocationConfiguration": "JobLevelCostAllocationConfiguration"
|
||||
}
|
||||
},
|
||||
"CreateApplicationResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"applicationId": "ApplicationId",
|
||||
"name": "ApplicationName",
|
||||
"arn": "ApplicationArn"
|
||||
}
|
||||
},
|
||||
"Date": {
|
||||
"type": "timestamp"
|
||||
},
|
||||
"DeleteApplicationRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"DeleteApplicationResponse": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"DiskEncryptionConfiguration": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"encryptionContext": "EncryptionContext",
|
||||
"encryptionKeyArn": "EncryptionKeyArn"
|
||||
}
|
||||
},
|
||||
"DiskSize": {
|
||||
"type": "string"
|
||||
},
|
||||
"DiskType": {
|
||||
"type": "string"
|
||||
},
|
||||
"Double": {
|
||||
"type": "double"
|
||||
},
|
||||
"Duration": {
|
||||
"type": "long"
|
||||
},
|
||||
"EncryptionContext": {
|
||||
"type": "map",
|
||||
"value": "EncryptionContextValue"
|
||||
},
|
||||
"EncryptionContextValue": {
|
||||
"type": "string"
|
||||
},
|
||||
"EncryptionKeyArn": {
|
||||
"type": "string"
|
||||
},
|
||||
"EndpointUrl": {
|
||||
"type": "string"
|
||||
},
|
||||
"EngineType": {
|
||||
"type": "string"
|
||||
},
|
||||
"EntryPointArgument": {
|
||||
"type": "string"
|
||||
},
|
||||
"EntryPointArguments": {
|
||||
"type": "list",
|
||||
"member": "EntryPointArgument"
|
||||
},
|
||||
"EntryPointPath": {
|
||||
"type": "string"
|
||||
},
|
||||
"GetApplicationRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"GetApplicationResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"application": "Application"
|
||||
}
|
||||
},
|
||||
"GetDashboardForJobRunRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"GetDashboardForJobRunResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"url": "Url"
|
||||
}
|
||||
},
|
||||
"GetJobRunRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"GetJobRunResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"jobRun": "JobRun"
|
||||
}
|
||||
},
|
||||
"GetResourceDashboardRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"GetResourceDashboardResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"url": "Url"
|
||||
}
|
||||
},
|
||||
"GetSessionEndpointRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"GetSessionEndpointResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"applicationId": "ApplicationId",
|
||||
"sessionId": "SessionId",
|
||||
"endpoint": "EndpointUrl",
|
||||
"authToken": "SessionAuthToken",
|
||||
"authTokenExpiresAt": "Date"
|
||||
}
|
||||
},
|
||||
"GetSessionRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"GetSessionResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"session": "Session"
|
||||
}
|
||||
},
|
||||
"Hive": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"query": "Query",
|
||||
"initQueryFile": "InitScriptPath",
|
||||
"parameters": "HiveCliParameters"
|
||||
}
|
||||
},
|
||||
"HiveCliParameters": {
|
||||
"type": "string"
|
||||
},
|
||||
"IAMRoleArn": {
|
||||
"type": "string"
|
||||
},
|
||||
"IdentityCenterApplicationArn": {
|
||||
"type": "string"
|
||||
},
|
||||
"IdentityCenterConfiguration": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"identityCenterInstanceArn": "IdentityCenterInstanceArn",
|
||||
"identityCenterApplicationArn": "IdentityCenterApplicationArn",
|
||||
"userBackgroundSessionsEnabled": "Boolean"
|
||||
}
|
||||
},
|
||||
"IdentityCenterConfigurationInput": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"identityCenterInstanceArn": "IdentityCenterInstanceArn",
|
||||
"userBackgroundSessionsEnabled": "Boolean"
|
||||
}
|
||||
},
|
||||
"IdentityCenterInstanceArn": {
|
||||
"type": "string"
|
||||
},
|
||||
"ImageConfiguration": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"imageUri": "ImageUri",
|
||||
"resolvedImageDigest": "ImageDigest",
|
||||
"applicationLevelDigestResolution": "Boolean"
|
||||
}
|
||||
},
|
||||
"ImageConfigurationInput": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"imageUri": "ImageUri",
|
||||
"applicationLevelDigestResolution": "Boolean"
|
||||
}
|
||||
},
|
||||
"ImageDigest": {
|
||||
"type": "string"
|
||||
},
|
||||
"ImageUri": {
|
||||
"type": "string"
|
||||
},
|
||||
"InitScriptPath": {
|
||||
"type": "string"
|
||||
},
|
||||
"InitialCapacityConfig": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"workerCount": "WorkerCounts",
|
||||
"workerConfiguration": "WorkerResourceConfig"
|
||||
}
|
||||
},
|
||||
"InitialCapacityConfigMap": {
|
||||
"type": "map",
|
||||
"value": "InitialCapacityConfig"
|
||||
},
|
||||
"Integer": {
|
||||
"type": "integer"
|
||||
},
|
||||
"InteractiveConfiguration": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"studioEnabled": "Boolean",
|
||||
"livyEndpointEnabled": "Boolean",
|
||||
"sessionEnabled": "Boolean"
|
||||
}
|
||||
},
|
||||
"JobArn": {
|
||||
"type": "string"
|
||||
},
|
||||
"JobDriver": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"sparkSubmit": "SparkSubmit",
|
||||
"hive": "Hive"
|
||||
}
|
||||
},
|
||||
"JobLevelCostAllocationConfiguration": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"enabled": "Boolean"
|
||||
}
|
||||
},
|
||||
"JobRun": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"applicationId": "ApplicationId",
|
||||
"jobRunId": "JobRunId",
|
||||
"name": "String256",
|
||||
"arn": "JobArn",
|
||||
"createdBy": "RequestIdentityUserArn",
|
||||
"createdAt": "Date",
|
||||
"updatedAt": "Date",
|
||||
"executionRole": "IAMRoleArn",
|
||||
"executionIamPolicy": "JobRunExecutionIamPolicy",
|
||||
"state": "JobRunState",
|
||||
"stateDetails": "String256",
|
||||
"releaseLabel": "ReleaseLabel",
|
||||
"configurationOverrides": "ConfigurationOverrides",
|
||||
"jobDriver": "JobDriver",
|
||||
"tags": "TagMap",
|
||||
"totalResourceUtilization": "TotalResourceUtilization",
|
||||
"networkConfiguration": "NetworkConfiguration",
|
||||
"totalExecutionDurationSeconds": "Integer",
|
||||
"executionTimeoutMinutes": "Duration",
|
||||
"billedResourceUtilization": "ResourceUtilization",
|
||||
"mode": "JobRunMode",
|
||||
"retryPolicy": "RetryPolicy",
|
||||
"attempt": "AttemptNumber",
|
||||
"attemptCreatedAt": "Date",
|
||||
"attemptUpdatedAt": "Date",
|
||||
"startedAt": "Date",
|
||||
"endedAt": "Date",
|
||||
"queuedDurationMilliseconds": "Long",
|
||||
"imageConfiguration": "ImageConfiguration",
|
||||
"workerTypeSpecifications": "WorkerTypeSpecificationMap"
|
||||
}
|
||||
},
|
||||
"JobRunAttemptSummary": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"applicationId": "ApplicationId",
|
||||
"id": "JobRunId",
|
||||
"name": "String256",
|
||||
"mode": "JobRunMode",
|
||||
"arn": "JobArn",
|
||||
"createdBy": "RequestIdentityUserArn",
|
||||
"jobCreatedAt": "Date",
|
||||
"createdAt": "Date",
|
||||
"updatedAt": "Date",
|
||||
"executionRole": "IAMRoleArn",
|
||||
"state": "JobRunState",
|
||||
"stateDetails": "String256",
|
||||
"releaseLabel": "ReleaseLabel",
|
||||
"type": "JobRunType",
|
||||
"attempt": "AttemptNumber"
|
||||
}
|
||||
},
|
||||
"JobRunAttempts": {
|
||||
"type": "list",
|
||||
"member": "JobRunAttemptSummary"
|
||||
},
|
||||
"JobRunExecutionIamPolicy": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"policy": "PolicyDocument",
|
||||
"policyArns": "PolicyArnList"
|
||||
}
|
||||
},
|
||||
"JobRunId": {
|
||||
"type": "string"
|
||||
},
|
||||
"JobRunMode": {
|
||||
"type": "string"
|
||||
},
|
||||
"JobRunState": {
|
||||
"type": "string"
|
||||
},
|
||||
"JobRunSummary": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"applicationId": "ApplicationId",
|
||||
"id": "JobRunId",
|
||||
"name": "String256",
|
||||
"mode": "JobRunMode",
|
||||
"arn": "JobArn",
|
||||
"createdBy": "RequestIdentityUserArn",
|
||||
"createdAt": "Date",
|
||||
"updatedAt": "Date",
|
||||
"executionRole": "IAMRoleArn",
|
||||
"state": "JobRunState",
|
||||
"stateDetails": "String256",
|
||||
"releaseLabel": "ReleaseLabel",
|
||||
"type": "JobRunType",
|
||||
"attempt": "AttemptNumber",
|
||||
"attemptCreatedAt": "Date",
|
||||
"attemptUpdatedAt": "Date"
|
||||
}
|
||||
},
|
||||
"JobRunType": {
|
||||
"type": "string"
|
||||
},
|
||||
"JobRuns": {
|
||||
"type": "list",
|
||||
"member": "JobRunSummary"
|
||||
},
|
||||
"ListApplicationsRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"ListApplicationsResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"applications": "ApplicationList",
|
||||
"nextToken": "NextToken"
|
||||
}
|
||||
},
|
||||
"ListJobRunAttemptsRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"ListJobRunAttemptsResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"jobRunAttempts": "JobRunAttempts",
|
||||
"nextToken": "NextToken"
|
||||
}
|
||||
},
|
||||
"ListJobRunsRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"ListJobRunsResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"jobRuns": "JobRuns",
|
||||
"nextToken": "NextToken"
|
||||
}
|
||||
},
|
||||
"ListSessionsRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"ListSessionsResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"sessions": "Sessions",
|
||||
"nextToken": "NextToken"
|
||||
}
|
||||
},
|
||||
"ListTagsForResourceRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"ListTagsForResourceResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"tags": "TagMap"
|
||||
}
|
||||
},
|
||||
"LogGroupName": {
|
||||
"type": "string"
|
||||
},
|
||||
"LogStreamNamePrefix": {
|
||||
"type": "string"
|
||||
},
|
||||
"LogTypeList": {
|
||||
"type": "list",
|
||||
"member": "LogTypeString"
|
||||
},
|
||||
"LogTypeMap": {
|
||||
"type": "map",
|
||||
"value": "LogTypeList"
|
||||
},
|
||||
"LogTypeString": {
|
||||
"type": "string"
|
||||
},
|
||||
"Long": {
|
||||
"type": "long"
|
||||
},
|
||||
"ManagedPersistenceMonitoringConfiguration": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"enabled": "Boolean",
|
||||
"encryptionKeyArn": "EncryptionKeyArn"
|
||||
}
|
||||
},
|
||||
"MaximumAllowedResources": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"cpu": "CpuSize",
|
||||
"memory": "MemorySize",
|
||||
"disk": "DiskSize"
|
||||
}
|
||||
},
|
||||
"MemorySize": {
|
||||
"type": "string"
|
||||
},
|
||||
"MonitoringConfiguration": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"s3MonitoringConfiguration": "S3MonitoringConfiguration",
|
||||
"managedPersistenceMonitoringConfiguration": "ManagedPersistenceMonitoringConfiguration",
|
||||
"cloudWatchLoggingConfiguration": "CloudWatchLoggingConfiguration",
|
||||
"prometheusMonitoringConfiguration": "PrometheusMonitoringConfiguration"
|
||||
}
|
||||
},
|
||||
"NetworkConfiguration": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"subnetIds": "SubnetIds",
|
||||
"securityGroupIds": "SecurityGroupIds"
|
||||
}
|
||||
},
|
||||
"NextToken": {
|
||||
"type": "string"
|
||||
},
|
||||
"PolicyArnList": {
|
||||
"type": "list",
|
||||
"member": "Arn"
|
||||
},
|
||||
"PolicyDocument": {
|
||||
"type": "string"
|
||||
},
|
||||
"PrometheusMonitoringConfiguration": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"remoteWriteUrl": "PrometheusUrlString"
|
||||
}
|
||||
},
|
||||
"PrometheusUrlString": {
|
||||
"type": "string"
|
||||
},
|
||||
"Query": {
|
||||
"type": "string"
|
||||
},
|
||||
"ReleaseLabel": {
|
||||
"type": "string"
|
||||
},
|
||||
"RequestIdentityUserArn": {
|
||||
"type": "string"
|
||||
},
|
||||
"ResourceUtilization": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"vCPUHour": "Double",
|
||||
"memoryGBHour": "Double",
|
||||
"storageGBHour": "Double"
|
||||
}
|
||||
},
|
||||
"RetryPolicy": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"maxAttempts": "AttemptNumber",
|
||||
"maxFailedAttemptsPerHour": "RetryPolicyMaxFailedAttemptsPerHourInteger"
|
||||
}
|
||||
},
|
||||
"RetryPolicyMaxFailedAttemptsPerHourInteger": {
|
||||
"type": "integer"
|
||||
},
|
||||
"S3MonitoringConfiguration": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"logUri": "UriString",
|
||||
"encryptionKeyArn": "EncryptionKeyArn"
|
||||
}
|
||||
},
|
||||
"SchedulerConfiguration": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"queueTimeoutMinutes": "Integer",
|
||||
"maxConcurrentRuns": "Integer"
|
||||
}
|
||||
},
|
||||
"SecurityGroupIds": {
|
||||
"type": "list",
|
||||
"member": "SecurityGroupString"
|
||||
},
|
||||
"SecurityGroupString": {
|
||||
"type": "string"
|
||||
},
|
||||
"SensitivePropertiesMap": {
|
||||
"type": "map",
|
||||
"value": "ConfigurationPropertyValue"
|
||||
},
|
||||
"Session": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"applicationId": "ApplicationId",
|
||||
"sessionId": "SessionId",
|
||||
"arn": "SessionArn",
|
||||
"name": "String256",
|
||||
"state": "SessionState",
|
||||
"stateDetails": "String1024",
|
||||
"releaseLabel": "ReleaseLabel",
|
||||
"executionRoleArn": "IAMRoleArn",
|
||||
"createdBy": "RequestIdentityUserArn",
|
||||
"createdAt": "Date",
|
||||
"updatedAt": "Date",
|
||||
"startedAt": "Date",
|
||||
"endedAt": "Date",
|
||||
"idleSince": "Date",
|
||||
"configurationOverrides": "SessionConfigurationOverrides",
|
||||
"networkConfiguration": "NetworkConfiguration",
|
||||
"idleTimeoutMinutes": "Duration",
|
||||
"tags": "TagMap",
|
||||
"totalResourceUtilization": "TotalResourceUtilization",
|
||||
"billedResourceUtilization": "ResourceUtilization",
|
||||
"totalExecutionDurationSeconds": "Long"
|
||||
}
|
||||
},
|
||||
"SessionArn": {
|
||||
"type": "string"
|
||||
},
|
||||
"SessionAuthToken": {
|
||||
"type": "string"
|
||||
},
|
||||
"SessionConfigurationOverrides": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"runtimeConfiguration": "ConfigurationList"
|
||||
}
|
||||
},
|
||||
"SessionId": {
|
||||
"type": "string"
|
||||
},
|
||||
"SessionState": {
|
||||
"type": "string"
|
||||
},
|
||||
"SessionSummary": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"applicationId": "ApplicationId",
|
||||
"sessionId": "SessionId",
|
||||
"arn": "SessionArn",
|
||||
"name": "String256",
|
||||
"state": "SessionState",
|
||||
"stateDetails": "String1024",
|
||||
"releaseLabel": "ReleaseLabel",
|
||||
"executionRoleArn": "IAMRoleArn",
|
||||
"createdBy": "RequestIdentityUserArn",
|
||||
"createdAt": "Date",
|
||||
"updatedAt": "Date"
|
||||
}
|
||||
},
|
||||
"Sessions": {
|
||||
"type": "list",
|
||||
"member": "SessionSummary"
|
||||
},
|
||||
"SparkSubmit": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"entryPoint": "EntryPointPath",
|
||||
"entryPointArguments": "EntryPointArguments",
|
||||
"sparkSubmitParameters": "SparkSubmitParameters"
|
||||
}
|
||||
},
|
||||
"SparkSubmitParameters": {
|
||||
"type": "string"
|
||||
},
|
||||
"StartApplicationRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"StartApplicationResponse": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"StartJobRunRequest": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"clientToken": "ClientToken",
|
||||
"executionRoleArn": "IAMRoleArn",
|
||||
"executionIamPolicy": "JobRunExecutionIamPolicy",
|
||||
"jobDriver": "JobDriver",
|
||||
"configurationOverrides": "ConfigurationOverrides",
|
||||
"tags": "TagMap",
|
||||
"executionTimeoutMinutes": "Duration",
|
||||
"name": "String256",
|
||||
"mode": "JobRunMode",
|
||||
"retryPolicy": "RetryPolicy"
|
||||
}
|
||||
},
|
||||
"StartJobRunResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"applicationId": "ApplicationId",
|
||||
"jobRunId": "JobRunId",
|
||||
"arn": "JobArn"
|
||||
}
|
||||
},
|
||||
"StartSessionRequest": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"clientToken": "ClientToken",
|
||||
"executionRoleArn": "IAMRoleArn",
|
||||
"configurationOverrides": "SessionConfigurationOverrides",
|
||||
"tags": "TagMap",
|
||||
"idleTimeoutMinutes": "Duration",
|
||||
"name": "String256"
|
||||
}
|
||||
},
|
||||
"StartSessionResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"applicationId": "ApplicationId",
|
||||
"sessionId": "SessionId",
|
||||
"arn": "SessionArn"
|
||||
}
|
||||
},
|
||||
"StopApplicationRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"StopApplicationResponse": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"String1024": {
|
||||
"type": "string"
|
||||
},
|
||||
"String256": {
|
||||
"type": "string"
|
||||
},
|
||||
"SubnetIds": {
|
||||
"type": "list",
|
||||
"member": "SubnetString"
|
||||
},
|
||||
"SubnetString": {
|
||||
"type": "string"
|
||||
},
|
||||
"TagMap": {
|
||||
"type": "map",
|
||||
"value": "TagValue"
|
||||
},
|
||||
"TagResourceRequest": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"tags": "TagMap"
|
||||
}
|
||||
},
|
||||
"TagResourceResponse": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"TagValue": {
|
||||
"type": "string"
|
||||
},
|
||||
"TerminateSessionRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"TerminateSessionResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"applicationId": "ApplicationId",
|
||||
"sessionId": "SessionId"
|
||||
}
|
||||
},
|
||||
"TotalResourceUtilization": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"vCPUHour": "Double",
|
||||
"memoryGBHour": "Double",
|
||||
"storageGBHour": "Double"
|
||||
}
|
||||
},
|
||||
"UntagResourceRequest": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"UntagResourceResponse": {
|
||||
"type": "structure",
|
||||
"members": {}
|
||||
},
|
||||
"UpdateApplicationRequest": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"clientToken": "ClientToken",
|
||||
"initialCapacity": "InitialCapacityConfigMap",
|
||||
"maximumCapacity": "MaximumAllowedResources",
|
||||
"autoStartConfiguration": "AutoStartConfig",
|
||||
"autoStopConfiguration": "AutoStopConfig",
|
||||
"networkConfiguration": "NetworkConfiguration",
|
||||
"architecture": "Architecture",
|
||||
"imageConfiguration": "ImageConfigurationInput",
|
||||
"workerTypeSpecifications": "WorkerTypeSpecificationInputMap",
|
||||
"interactiveConfiguration": "InteractiveConfiguration",
|
||||
"releaseLabel": "ReleaseLabel",
|
||||
"runtimeConfiguration": "ConfigurationList",
|
||||
"monitoringConfiguration": "MonitoringConfiguration",
|
||||
"diskEncryptionConfiguration": "DiskEncryptionConfiguration",
|
||||
"schedulerConfiguration": "SchedulerConfiguration",
|
||||
"identityCenterConfiguration": "IdentityCenterConfigurationInput",
|
||||
"jobLevelCostAllocationConfiguration": "JobLevelCostAllocationConfiguration"
|
||||
}
|
||||
},
|
||||
"UpdateApplicationResponse": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"application": "Application"
|
||||
}
|
||||
},
|
||||
"UriString": {
|
||||
"type": "string"
|
||||
},
|
||||
"Url": {
|
||||
"type": "string"
|
||||
},
|
||||
"WorkerCounts": {
|
||||
"type": "long"
|
||||
},
|
||||
"WorkerResourceConfig": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"cpu": "CpuSize",
|
||||
"memory": "MemorySize",
|
||||
"disk": "DiskSize",
|
||||
"diskType": "DiskType"
|
||||
}
|
||||
},
|
||||
"WorkerTypeSpecification": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"imageConfiguration": "ImageConfiguration"
|
||||
}
|
||||
},
|
||||
"WorkerTypeSpecificationInput": {
|
||||
"type": "structure",
|
||||
"members": {
|
||||
"imageConfiguration": "ImageConfigurationInput"
|
||||
}
|
||||
},
|
||||
"WorkerTypeSpecificationInputMap": {
|
||||
"type": "map",
|
||||
"value": "WorkerTypeSpecificationInput"
|
||||
},
|
||||
"WorkerTypeSpecificationMap": {
|
||||
"type": "map",
|
||||
"value": "WorkerTypeSpecification"
|
||||
}
|
||||
}
|
||||
}
|
||||
+62
-3
@@ -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));
|
||||
}
|
||||
}
|
||||
+82
@@ -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);
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -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());
|
||||
}
|
||||
}
|
||||
+281
@@ -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);
|
||||
}
|
||||
}
|
||||
+5
-26
@@ -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);
|
||||
}
|
||||
}
|
||||
+46
-3
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-31
@@ -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) {
|
||||
|
||||
+225
@@ -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("/");
|
||||
}
|
||||
}
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate src/main/resources/aws/emr-serverless-shapes.json from botocore's EMR Serverless model.
|
||||
|
||||
The Step Functions `emr-serverless:` integrations take and return the API's members in PascalCase,
|
||||
where the EMR Serverless API writes them in camelCase. Their keys cannot all be recased: a tag map,
|
||||
`initialCapacity` or a configuration's `properties` keep the keys their caller wrote. The Java side
|
||||
(`EmrServerlessTaskInvoker`) walks a request or response against the shapes to tell the two apart,
|
||||
so this script keeps the input shape of every operation and, unlike the request checks, its output
|
||||
shape too; for every shape reachable from one, its type and the shapes of its members, list elements
|
||||
or map values.
|
||||
|
||||
The model is botocore's `emr-serverless/2021-07-13/service-2.json` (Apache-2.0,
|
||||
https://github.com/boto/botocore). It is located, in order, at `--botocore-data`, the
|
||||
`local/aws/botocore` checkout, then the installed `botocore` package, which `requirements.txt`
|
||||
pins so CI regenerates the same bytes.
|
||||
|
||||
Run from anywhere in the repo:
|
||||
python3 tools/aws/regen_emr_serverless_shapes.py # rewrite the vendored file in place
|
||||
python3 tools/aws/regen_emr_serverless_shapes.py --check # exit 1 when the vendored file is stale
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import request_shapes
|
||||
|
||||
OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/emr-serverless-shapes.json"
|
||||
MODEL = Path("emr-serverless/2021-07-13")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT, description=__doc__,
|
||||
outputs=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -5,6 +5,7 @@ model and an output file and hand the rest to `main()`. `regen_resource_groups_s
|
||||
`regen_ecr_shapes.py` vendor constraints as well, through `build_constraints()`. The output keeps only what `RequestShapeModel` reads: the input
|
||||
shape of every operation, reduced to the members carried in the JSON body, and for every shape
|
||||
reachable from one, its type and the shapes of its members, list elements or map values.
|
||||
`regen_emr_serverless_shapes.py` keeps every operation's output shape too, with `outputs=True`.
|
||||
|
||||
Members bound to the URI, the query string or a header are left out: they never reach the body.
|
||||
A model without such members, as DynamoDB's, comes out whole.
|
||||
@@ -30,7 +31,7 @@ def load_model(data: Path, model: Path) -> dict:
|
||||
return load_json_model(source)
|
||||
|
||||
|
||||
def build(model: dict, provenance: str, generator: str) -> dict:
|
||||
def build(model: dict, provenance: str, generator: str, outputs: bool = False) -> dict:
|
||||
shapes = model["shapes"]
|
||||
kept: dict[str, dict] = {}
|
||||
|
||||
@@ -59,6 +60,8 @@ def build(model: dict, provenance: str, generator: str) -> dict:
|
||||
if "input" in operation:
|
||||
operations[name] = operation["input"]["shape"]
|
||||
keep(operation["input"]["shape"], body_only=True)
|
||||
if outputs and "output" in operation:
|
||||
keep(operation["output"]["shape"], body_only=True)
|
||||
|
||||
return {
|
||||
"_source": {
|
||||
@@ -114,7 +117,8 @@ def generator_name(script: str) -> str:
|
||||
return path.relative_to(REPO_ROOT).as_posix() if path.is_relative_to(REPO_ROOT) else path.name
|
||||
|
||||
|
||||
def main(argv: list[str] | None, *, script: str, model: Path, output: Path, description: str) -> int:
|
||||
def main(argv: list[str] | None, *, script: str, model: Path, output: Path, description: str,
|
||||
outputs: bool = False) -> int:
|
||||
parser = argparse.ArgumentParser(description=description, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation")
|
||||
parser.add_argument("--botocore-data", type=Path, help="botocore data directory")
|
||||
@@ -122,7 +126,7 @@ def main(argv: list[str] | None, *, script: str, model: Path, output: Path, desc
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
data, provenance = resolve_botocore_data(args.botocore_data)
|
||||
fresh = render(build(load_model(data, model), provenance, generator_name(script)))
|
||||
fresh = render(build(load_model(data, model), provenance, generator_name(script), outputs))
|
||||
|
||||
if args.check:
|
||||
current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""Tests for request_shapes, the generator behind regen_dynamodb_shapes, regen_sesv2_shapes and regen_ecs_shapes,
|
||||
and of the constraints regen_resource_groups_shapes and regen_ecr_shapes vendor.
|
||||
"""Tests for request_shapes, the generator behind regen_dynamodb_shapes, regen_sesv2_shapes, regen_ecs_shapes and
|
||||
regen_emr_serverless_shapes, and of the constraints regen_resource_groups_shapes and regen_ecr_shapes vendor.
|
||||
|
||||
Run with: pytest tools/aws -q (or: make aws-data-test)
|
||||
"""
|
||||
@@ -14,6 +14,7 @@ import pytest
|
||||
import regen_dynamodb_shapes
|
||||
import regen_ecr_shapes
|
||||
import regen_ecs_shapes
|
||||
import regen_emr_serverless_shapes
|
||||
import regen_sesv2_shapes
|
||||
import request_shapes as r
|
||||
|
||||
@@ -106,6 +107,29 @@ def test_drops_uri_and_query_members():
|
||||
assert "NextToken" not in doc["shapes"]
|
||||
|
||||
|
||||
def test_keeps_output_shapes_when_asked():
|
||||
doc = r.build(SESV2_MODEL, "botocore test", "tools/aws/regen_emr_serverless_shapes.py", outputs=True)
|
||||
|
||||
assert doc["operations"] == {"GetEmailIdentity": "GetEmailIdentityRequest", "SendEmail": "SendEmailRequest"}
|
||||
assert doc["shapes"]["SendEmailResponse"] == {"type": "structure", "members": {"MessageId": "OutboundMessageId"}}
|
||||
assert doc["shapes"]["OutboundMessageId"] == {"type": "string"}
|
||||
assert doc["shapes"]["GetEmailIdentityRequest"] == {"type": "structure", "members": {}}
|
||||
|
||||
|
||||
def test_emr_serverless_shapes_keep_the_output_shapes(monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr(r, "main", lambda argv, **kwargs: calls.append((argv, kwargs)) or 0)
|
||||
|
||||
assert regen_emr_serverless_shapes.main(["--check"]) == 0
|
||||
assert calls == [(["--check"], {
|
||||
"script": regen_emr_serverless_shapes.__file__,
|
||||
"model": Path("emr-serverless/2021-07-13"),
|
||||
"output": r.REPO_ROOT / "src/main/resources/aws/emr-serverless-shapes.json",
|
||||
"description": regen_emr_serverless_shapes.__doc__,
|
||||
"outputs": True,
|
||||
})]
|
||||
|
||||
|
||||
def _main(output: Path) -> int:
|
||||
return r.main(["--check", "--output", str(output)], script=r.__file__, model=Path("svc/service-2.json"),
|
||||
output=output, description="test")
|
||||
|
||||
Reference in new issue
Block a user