diff --git a/docs/services/emr-serverless.md b/docs/services/emr-serverless.md index a4d7355dbc..33e7eedada 100644 --- a/docs/services/emr-serverless.md +++ b/docs/services/emr-serverless.md @@ -103,7 +103,9 @@ runner mode a Spark run executes; see [Running Spark job runs](#running-spark-jo application is refused. * **Idempotency**: `clientToken` is the idempotency token. Repeating a request with the same token returns the original run; reusing the token with a different request answers `ConflictException` - (HTTP 409) "Request did not match the original". + (HTTP 409) "Request did not match the original". The two are compared as the run each would start holds them: + `executionTimeoutMinutes` left out or 720, and `tags` left out or empty, count as the same; a member the run would + hold otherwise, such as a `mode` given where the original left it out, or a tag with an empty value, does not. * **Execution timeout**: `executionTimeoutMinutes` is 0 to 1,000,000, 0 meaning no timeout. From release `emr-7.11.0`, a `BATCH` run's timeout must be 1 to 10080 minutes (7 days), as the model and the 7.11.0 release notes say; a run outside that is refused with `ValidationException`. The AWS runtime for @@ -117,7 +119,8 @@ runner mode a Spark run executes; see [Running Spark job runs](#running-spark-jo error the model declares for this, with that sentence as its message: AWS's own message is not recorded, so the wording is Floci's reading. It terminates the application's sessions (see [Sessions](#sessions)). -* **ListJobRuns** returns the newest runs first, filtered by `states`, `createdAtAfter`, +* **ListJobRuns** returns the newest runs first, the later of two started within the same millisecond + first too, filtered by `states`, `createdAtAfter`, `createdAtBefore` and `mode`, at most 50 per page. With several `states`, the runs are grouped by state in the order the filter names them. A state or mode that does not exist, or more than 8 states, is refused with `ValidationException`. An unknown application has no runs. A `nextToken` @@ -160,7 +163,9 @@ and its lifecycle but runs no driver for it. Spark (`emr-spark-8.0.0` on), whose `interactiveConfiguration.sessionEnabled` is `true`. As for a job run, a `CREATED` or `STOPPED` application is started unless its auto-start is off, when the session is refused, and so is one on a terminated application. Each of these refusals is `ValidationException` in Floci's own wording, as AWS's is - not recorded. `clientToken` is the idempotency token, as for a job run. An application holds at most 25 sessions + not recorded. `clientToken` is the idempotency token, compared as for a job run: `idleTimeoutMinutes` left out or + 60, `tags` left out or empty, and `configurationOverrides` without a `runtimeConfiguration` count as the same. An + application holds at most 25 sessions that have not ended, as "Each EMR Serverless application supports up to 25 concurrent sessions by default"; a 26th is refused with `ServiceQuotaExceededException` (HTTP 402). Of `configurationOverrides`, only `runtimeConfiguration` is kept: "Only runtime configuration overrides are supported." A `runtimeConfiguration` with a member of the wrong @@ -185,8 +190,8 @@ and its lifecycle but runs no driver for it. time-limited to 1 hour". AWS's endpoint is an `https://` URL without a port; a Spark Connect URL holds no path, so Floci's is its address alone, port included, and the token names the session. A session that has ended, or is `TERMINATING`, is refused with `ValidationException`, in Floci's own wording. -* **ListSessions** returns the newest sessions first, filtered by `states`, `createdAtAfter` and `createdAtBefore`, at - most 50 per page, grouped by state as `ListJobRuns` groups runs. +* **ListSessions** returns the newest sessions first, as `ListJobRuns` orders runs, filtered by `states`, + `createdAtAfter` and `createdAtBefore`, at most 50 per page, grouped by state as `ListJobRuns` groups runs. * **GetResourceDashboard** takes a `resourceType` of `SESSION`, the only one, and gives a link like `GetDashboardForJobRun`'s, valid for an hour, to a page about the session on Floci's address, which stands in for the session's Spark UI or Spark History Server. `accessSystemProfileLogs` changes nothing. diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java index acc1fd697d..5172c41573 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java @@ -3,6 +3,7 @@ package io.floci.aws.services.emrserverless; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; @@ -179,6 +180,8 @@ public class EmrServerlessJobRunService implements Resettable { private final Set executing = new HashSet<>(); // Raised by each reset, so a run's thread from before it writes nothing back after the wipe. private long generation; + // The latest sequence a run was given, nextSequence. + private long lastSequence; @Inject public EmrServerlessJobRunService(StorageFactory storageFactory, EmrServerlessService applications, @@ -282,7 +285,7 @@ public class EmrServerlessJobRunService implements Resettable { JobRunRecord existing = EmrServerlessService.startedWithClientToken(store.scan(key -> true), body.getClientToken(), JobRunRecord::getClientToken, record -> inRequestRegion(record.getJobRun())); if (existing != null) { - if (!original.equals(existing.getRequest())) { + if (!sameRun(existing.getRequest(), applicationId, body)) { throw new AwsException("ConflictException", "Request did not match the original", 409); } return settle(existing).getJobRun(); @@ -411,8 +414,8 @@ public class EmrServerlessJobRunService implements Resettable { String.valueOf(createdAtBefore), String.valueOf(mode)); PaginatedResult page = EmrServerlessService.pageByState(matching, record -> record.getJobRun().getJobRunId(), record -> record.getJobRun().getState(), - record -> record.getJobRun().getCreatedAt(), states, maxResults, MAX_LIST_RESULTS, nextToken, - namespace); + record -> record.getJobRun().getCreatedAt(), JobRunRecord::getSequence, states, maxResults, + MAX_LIST_RESULTS, nextToken, namespace); return new PaginatedResult<>(page.items().stream().map(EmrServerlessJobRunService::toSummary).toList(), page.nextToken()); } @@ -508,6 +511,50 @@ public class EmrServerlessJobRunService implements Resettable { } } + /** + * Sets on {@code run} what a run takes from the request that starts it, as it holds it: its name, role, policy, + * configuration overrides, driver, tags (none where the request gives none), execution timeout + * ({@value #DEFAULT_EXECUTION_TIMEOUT_MINUTES} minutes where it gives none), mode and retry policy. + */ + private static void requested(JobRun run, StartJobRunRequest request) { + run.setName(request.getName()); + run.setExecutionRole(request.getExecutionRoleArn()); + run.setExecutionIamPolicy(request.getExecutionIamPolicy()); + run.setConfigurationOverrides(request.getConfigurationOverrides()); + run.setJobDriver(request.getJobDriver()); + run.setTags(request.getTags() != null ? new LinkedHashMap<>(request.getTags()) : new LinkedHashMap<>()); + run.setExecutionTimeoutMinutes(request.getExecutionTimeoutMinutes() != null + ? request.getExecutionTimeoutMinutes() : DEFAULT_EXECUTION_TIMEOUT_MINUTES); + run.setMode(request.getMode()); + run.setRetryPolicy(request.getRetryPolicy()); + } + + /** + * Whether a retry asks for the run its original started: on the same application, with what the two would have + * the run hold alike, {@link #requested}. A member the run holds the same way whether it is left out or given, + * the execution timeout at its default or the tags empty, is alike; one the run would hold otherwise, such as a + * mode given where the original left it out, is not. + */ + private boolean sameRun(JsonNode original, String applicationId, StartJobRunRequest retried) { + ObjectNode first = ((ObjectNode) original).deepCopy(); + String firstApplication = first.path("applicationId").asText(null); + first.remove("applicationId"); + return applicationId.equals(firstApplication) + && held(objectMapper.convertValue(first, StartJobRunRequest.class)).equals(held(retried)); + } + + private JsonNode held(StartJobRunRequest request) { + JobRun run = new JobRun(); + requested(run, request); + return objectMapper.valueToTree(run); + } + + // The sequence of a run created at now, after the last this service gave. + private long nextSequence(Instant now) { + lastSequence = EmrServerlessService.nextSequence(lastSequence, now); + return lastSequence; + } + private JobRunRecord newRun(Application app, StartJobRunRequest request, JsonNode original) { AwsArnUtils.Arn applicationArn = AwsArnUtils.parse(app.getArn()); String jobRunId = EmrServerlessService.newId(); @@ -516,26 +563,17 @@ public class EmrServerlessJobRunService implements Resettable { JobRun run = new JobRun(); run.setApplicationId(app.getApplicationId()); run.setJobRunId(jobRunId); - run.setName(request.getName()); run.setArn(AwsArnUtils.Arn.of("emr-serverless", applicationArn.region(), applicationArn.accountId(), applicationArn.resource() + "/jobruns/" + jobRunId).toString()); run.setCreatedBy(EmrServerlessService.createdBy(iamService, requestContext, regionResolver, applicationArn.accountId())); run.setCreatedAt(now); run.setUpdatedAt(now); - run.setExecutionRole(request.getExecutionRoleArn()); - run.setExecutionIamPolicy(request.getExecutionIamPolicy()); + requested(run, request); run.setState(sparkRunner != null ? STATE_SCHEDULED : STATE_RUNNING); run.setStateDetails(""); run.setReleaseLabel(app.getReleaseLabel()); - run.setConfigurationOverrides(request.getConfigurationOverrides()); - run.setJobDriver(request.getJobDriver()); - run.setTags(request.getTags() != null ? new LinkedHashMap<>(request.getTags()) : new LinkedHashMap<>()); run.setNetworkConfiguration(app.getNetworkConfiguration()); - run.setExecutionTimeoutMinutes(request.getExecutionTimeoutMinutes() != null - ? request.getExecutionTimeoutMinutes() : DEFAULT_EXECUTION_TIMEOUT_MINUTES); - run.setMode(request.getMode()); - run.setRetryPolicy(request.getRetryPolicy()); run.setAttempt(FIRST_ATTEMPT); run.setAttemptCreatedAt(now); run.setAttemptUpdatedAt(now); @@ -546,6 +584,7 @@ public class EmrServerlessJobRunService implements Resettable { JobRunRecord record = new JobRunRecord(); record.setJobRun(run); + record.setSequence(nextSequence(now)); record.setClientToken(request.getClientToken()); record.setRequest(original); record.setApplicationType(app.getType()); diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessService.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessService.java index d6cd9bd856..ada395398f 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessService.java @@ -46,6 +46,7 @@ import java.util.UUID; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; +import java.util.function.ToLongFunction; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -645,22 +646,30 @@ public class EmrServerlessService { return violations; } + // The shape of pageByState's cursors, which a nextToken names: the state group, the creation time, the sequence. + private static final String CURSOR_SHAPE = "group-created-sequence"; + /** * A page of ListJobRuns' runs or ListSessions' sessions: {@code matching}, newest first, and, where {@code states} * names any, "grouped by the state", in the order it names them, as each operation's {@code states} member reads. - * A {@code nextToken} resumes only the listing {@code namespace} names. + * Of two created within the same millisecond, the later {@code sequence}, {@link #nextSequence}, is the newer; one + * stored before sequences were kept has 0, and its id orders it among those. A {@code nextToken} resumes only the + * listing {@code namespace} names, in this cursor's shape: one given before sequences were kept, whose cursors + * hold none, is refused rather than resuming at the wrong place. */ static PaginatedResult pageByState(List matching, Function id, Function state, - Function createdAt, List states, Integer maxResults, - int defaultMaxResults, String nextToken, String namespace) { + Function createdAt, ToLongFunction sequence, + List states, Integer maxResults, int defaultMaxResults, + String nextToken, String namespace) { Map cursors = new HashMap<>(); for (T item : matching) { int group = states == null || states.isEmpty() ? 0 : states.indexOf(state.apply(item)); - cursors.put(id.apply(item), String.format("%02d%020d%s", group, - Long.MAX_VALUE - createdAt.apply(item).toEpochMilli(), id.apply(item))); + cursors.put(id.apply(item), String.format("%02d%020d%020d%s", group, + Long.MAX_VALUE - createdAt.apply(item).toEpochMilli(), + Long.MAX_VALUE - sequence.applyAsLong(item), id.apply(item))); } return Pagination.paginate(matching, item -> cursors.get(id.apply(item)), - maxResults != null ? maxResults : defaultMaxResults, nextToken, namespace, + maxResults != null ? maxResults : defaultMaxResults, nextToken, namespace + "|" + CURSOR_SHAPE, token -> new AwsException("ValidationException", "Invalid nextToken.", 400)); } @@ -785,6 +794,17 @@ public class EmrServerlessService { return null; } + /** + * The sequence of a run or session created at {@code now}, after {@code last}, the latest its service gave: the + * microseconds of {@code now}, or one past {@code last} when that is not later. It orders the run after every one + * created before it, within the same millisecond too; one an earlier Floci process created has a sequence below + * {@code now}'s microseconds, the clock having moved on since, so none is reused. + */ + static long nextSequence(long last, Instant now) { + long micros = now.getEpochSecond() * 1_000_000L + now.getNano() / 1_000; + return Math.max(micros, last + 1); + } + /** * What a retry of StartJobRun or StartSession must repeat: the application and every member of the body but * the client token itself. Read back from its JSON text, so that its numbers compare equal to those of a stored diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java index ed1a39ec22..c248582d2d 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSessionService.java @@ -3,6 +3,7 @@ package io.floci.aws.services.emrserverless; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; @@ -132,6 +133,8 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta private final Map grants = new ConcurrentHashMap<>(); // Raised by each reset, so a server's thread from before it writes nothing back after the wipe. private long generation; + // The latest sequence a session was given, EmrServerlessService.nextSequence. + private long lastSequence; @Inject public EmrServerlessSessionService(StorageFactory storageFactory, EmrServerlessService applications, @@ -217,7 +220,7 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta SessionRecord existing = EmrServerlessService.startedWithClientToken(store.scan(key -> true), body.getClientToken(), SessionRecord::getClientToken, record -> inRequestRegion(record.getSession())); if (existing != null) { - if (!original.equals(existing.getRequest())) { + if (!sameSession(existing.getRequest(), applicationId, body)) { throw new AwsException("ConflictException", "Request did not match the original", 409); } return copy(settle(existing).getSession()); @@ -250,7 +253,7 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta throw SmithyValidationErrors.validationException(violations); } applications.getApplication(applicationId); - List matching = new ArrayList<>(); + List matching = new ArrayList<>(); for (SessionRecord record : store.scan(key -> true)) { Session session = record.getSession(); if (!applicationId.equals(session.getApplicationId()) || !inRequestRegion(session)) { @@ -262,14 +265,17 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta || (createdAtBefore != null && !session.getCreatedAt().isBefore(createdAtBefore))) { continue; } - matching.add(session); + matching.add(record); } String namespace = String.join("|", "ListSessions", applicationId, String.valueOf(states != null ? states : List.of()), String.valueOf(createdAtAfter), String.valueOf(createdAtBefore)); - PaginatedResult page = EmrServerlessService.pageByState(matching, Session::getSessionId, - Session::getState, Session::getCreatedAt, states, maxResults, MAX_LIST_RESULTS, nextToken, namespace); - return new PaginatedResult<>(page.items().stream().map(SessionSummary::of).toList(), page.nextToken()); + PaginatedResult page = EmrServerlessService.pageByState(matching, + record -> record.getSession().getSessionId(), record -> record.getSession().getState(), + record -> record.getSession().getCreatedAt(), SessionRecord::getSequence, states, maxResults, + MAX_LIST_RESULTS, nextToken, namespace); + return new PaginatedResult<>(page.items().stream().map(record -> SessionSummary.of(record.getSession())) + .toList(), page.nextToken()); } /** @@ -569,10 +575,9 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta session.setSessionId(sessionId); session.setArn(AwsArnUtils.Arn.of("emr-serverless", applicationArn.region(), applicationArn.accountId(), applicationArn.resource() + "/sessions/" + sessionId).toString()); - session.setName(request.getName()); + requested(session, request); session.setStateDetails(""); session.setReleaseLabel(app.getReleaseLabel()); - session.setExecutionRoleArn(request.getExecutionRoleArn()); session.setCreatedBy(EmrServerlessService.createdBy(iamService, requestContext, regionResolver, applicationArn.accountId())); session.setCreatedAt(now); @@ -585,19 +590,12 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta } else { session.setState(STATE_SUBMITTED); } - // "Only runtime configuration overrides are supported." - if (request.getConfigurationOverrides() != null - && request.getConfigurationOverrides().get("runtimeConfiguration") != null) { - session.setConfigurationOverrides(Map.of("runtimeConfiguration", - request.getConfigurationOverrides().get("runtimeConfiguration"))); - } session.setNetworkConfiguration(app.getNetworkConfiguration()); - session.setIdleTimeoutMinutes(request.getIdleTimeoutMinutes() != null - ? request.getIdleTimeoutMinutes() : DEFAULT_IDLE_TIMEOUT_MINUTES); - session.setTags(request.getTags() != null ? new LinkedHashMap<>(request.getTags()) : new LinkedHashMap<>()); SessionRecord record = new SessionRecord(); record.setSession(session); + lastSequence = EmrServerlessService.nextSequence(lastSequence, now); + record.setSequence(lastSequence); record.setClientToken(request.getClientToken()); record.setRequest(original); record.setContainerSession(sparkRunner != null); @@ -818,6 +816,43 @@ public class EmrServerlessSessionService implements SparkConnectTargets, Resetta } } + /** + * Sets on {@code session} what a session takes from the request that starts it, as it holds it: its name, role, + * runtime configuration overrides alone, as "Only runtime configuration overrides are supported", idle timeout + * ({@value #DEFAULT_IDLE_TIMEOUT_MINUTES} minutes where the request gives none) and tags (none where it gives + * none). + */ + private static void requested(Session session, StartSessionRequest request) { + session.setName(request.getName()); + session.setExecutionRoleArn(request.getExecutionRoleArn()); + if (request.getConfigurationOverrides() != null + && request.getConfigurationOverrides().get("runtimeConfiguration") != null) { + session.setConfigurationOverrides(Map.of("runtimeConfiguration", + request.getConfigurationOverrides().get("runtimeConfiguration"))); + } + session.setIdleTimeoutMinutes(request.getIdleTimeoutMinutes() != null + ? request.getIdleTimeoutMinutes() : DEFAULT_IDLE_TIMEOUT_MINUTES); + session.setTags(request.getTags() != null ? new LinkedHashMap<>(request.getTags()) : new LinkedHashMap<>()); + } + + /** + * Whether a retry asks for the session its original started: on the same application, with what the two would + * have the session hold alike, {@link #requested}, as a job run's retry is compared. + */ + private boolean sameSession(JsonNode original, String applicationId, StartSessionRequest retried) { + ObjectNode first = ((ObjectNode) original).deepCopy(); + String firstApplication = first.path("applicationId").asText(null); + first.remove("applicationId"); + return applicationId.equals(firstApplication) + && held(objectMapper.convertValue(first, StartSessionRequest.class)).equals(held(retried)); + } + + private JsonNode held(StartSessionRequest request) { + Session session = new Session(); + requested(session, request); + return objectMapper.valueToTree(session); + } + /** * Ends a session whose time has run out by now: an idle one once its idle timeout has passed since it went idle, * and any once its 24 hours have passed since it started, whichever comes first. An idle timeout of 0 ends diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/JobRunRecord.java b/src/main/java/io/floci/aws/services/emrserverless/model/JobRunRecord.java index 1aee92e546..ec23d51928 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/model/JobRunRecord.java +++ b/src/main/java/io/floci/aws/services/emrserverless/model/JobRunRecord.java @@ -20,6 +20,8 @@ import java.util.Map; public class JobRunRecord { private JobRun jobRun; private String clientToken; + // Orders it among those created within the same millisecond: EmrServerlessService.nextSequence. + private long sequence; private JsonNode request; private String applicationType; private boolean containerRun; @@ -30,6 +32,8 @@ public class JobRunRecord { public void setJobRun(JobRun jobRun) { this.jobRun = jobRun; } public String getClientToken() { return clientToken; } public void setClientToken(String clientToken) { this.clientToken = clientToken; } + public long getSequence() { return sequence; } + public void setSequence(long sequence) { this.sequence = sequence; } public JsonNode getRequest() { return request; } public void setRequest(JsonNode request) { this.request = request; } public String getApplicationType() { return applicationType; } diff --git a/src/main/java/io/floci/aws/services/emrserverless/model/SessionRecord.java b/src/main/java/io/floci/aws/services/emrserverless/model/SessionRecord.java index 3ea453a051..75a29682be 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/model/SessionRecord.java +++ b/src/main/java/io/floci/aws/services/emrserverless/model/SessionRecord.java @@ -11,6 +11,8 @@ import io.quarkus.runtime.annotations.RegisterForReflection; public class SessionRecord { private Session session; private String clientToken; + // Orders it among those created within the same millisecond: EmrServerlessService.nextSequence. + private long sequence; private JsonNode request; // Whether Floci runs a Spark Connect server for it, as it does in the docker runner mode. private boolean containerSession; @@ -19,6 +21,8 @@ public class SessionRecord { public void setSession(Session session) { this.session = session; } public String getClientToken() { return clientToken; } public void setClientToken(String clientToken) { this.clientToken = clientToken; } + public long getSequence() { return sequence; } + public void setSequence(long sequence) { this.sequence = sequence; } public JsonNode getRequest() { return request; } public void setRequest(JsonNode request) { this.request = request; } public boolean isContainerSession() { return containerSession; } diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java index 9e9f9d1cd2..28fc8b5d65 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; @@ -14,6 +15,7 @@ import io.floci.aws.services.emrserverless.model.JobDriver; import io.floci.aws.services.emrserverless.model.JobRun; import io.floci.aws.services.emrserverless.model.JobRunAttemptSummary; import io.floci.aws.services.emrserverless.model.JobRunRecord; +import io.floci.aws.services.emrserverless.model.JobRunSummary; import io.floci.aws.services.emrserverless.model.MaximumCapacity; import io.floci.aws.services.emrserverless.model.MonitoringConfiguration; import io.floci.aws.services.emrserverless.model.RuntimeConfiguration; @@ -25,8 +27,10 @@ import io.floci.aws.testing.MutableClock; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.time.Clock; import java.time.Duration; import java.time.Instant; +import java.time.ZoneOffset; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -101,6 +105,66 @@ class EmrServerlessJobRunServiceTest { return request; } + @Test + void runsStartedWithinTheSameMillisecondListNewestFirst() { + EmrServerlessJobRunService service = new EmrServerlessJobRunService(store, applications, iamService, + new RegionResolver(REGION, ACCOUNT_ID), null, objectMapper, 0, + Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC)); + List started = new ArrayList<>(); + for (int run = 0; run < 12; run++) { + started.add(service.startJobRun(applicationId, request(null, null)).getJobRunId()); + } + + List listed = service.listJobRuns(applicationId, null, null, null, null, null, null).items().stream() + .map(JobRunSummary::getId).toList(); + + assertEquals(started.reversed(), listed); + } + + @Test + void aRetryIsTheOriginalRunWhereTheRunWouldHoldTheSameAndConflictsWhereItWouldNot() { + EmrServerlessJobRunService service = service(0); + StartJobRunRequest first = request(null, 720L); + first.setTags(Map.of()); + JobRun original = service.startJobRun(applicationId, first); + // The run holds the default timeout and no tags either way. + StartJobRunRequest retry = request(null, null); + retry.setClientToken(first.getClientToken()); + // A mode, an empty-valued tag and a name the original's run does not hold. + StartJobRunRequest batch = request("BATCH", null); + batch.setClientToken(first.getClientToken()); + StartJobRunRequest emptyTag = request(null, null); + emptyTag.setClientToken(first.getClientToken()); + emptyTag.setTags(Map.of("team", "")); + StartJobRunRequest renamed = request(null, null); + renamed.setClientToken(first.getClientToken()); + renamed.setName("another"); + + assertEquals(original.getJobRunId(), service.startJobRun(applicationId, retry).getJobRunId()); + for (StartJobRunRequest conflicting : List.of(batch, emptyTag, renamed)) { + assertEquals("ConflictException", assertThrows(AwsException.class, + () -> service.startJobRun(applicationId, conflicting)).getErrorCode()); + } + } + + @Test + void aNextTokenGivenBeforeRunsKeptASequenceIsRefused() { + EmrServerlessJobRunService service = service(0); + List ids = new ArrayList<>(); + for (int run = 0; run < 3; run++) { + ids.add(service.startJobRun(applicationId, request(null, null)).getJobRunId()); + } + // A token of the listing's earlier cursors, the creation time and the id, under its earlier namespace. + String earlier = Pagination.paginate(ids, id -> id, 1, null, + String.join("|", "ListJobRuns", applicationId, "[]", "null", "null", "null"), + token -> new AwsException("ValidationException", "Invalid nextToken.", 400)).nextToken(); + + AwsException refused = assertThrows(AwsException.class, + () -> service.listJobRuns(applicationId, null, null, null, null, 1, earlier)); + + assertEquals("ValidationException", refused.getErrorCode()); + } + @Test void runSucceedsAsSoonAsItStartsByDefault() { JobRun run = service(0).startJobRun(applicationId, request(null, null)); diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServiceTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServiceTest.java index 3220129f5c..563b6e34d2 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServiceTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessSessionServiceTest.java @@ -20,7 +20,11 @@ import io.floci.aws.testing.MutableClock; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.time.Clock; import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; @@ -45,15 +49,17 @@ class EmrServerlessSessionServiceTest { private EmrServerlessService applications; private EmrServerlessSessionService sessions; private MutableClock clock; + private IamService iamService; + private RegionResolver regionResolver; @BeforeEach void setUp() { EmulatorConfig config = mock(EmulatorConfig.class); when(config.defaultAccountId()).thenReturn(ACCOUNT_ID); clock = new MutableClock(); - RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT_ID); + regionResolver = new RegionResolver(REGION, ACCOUNT_ID); applications = new EmrServerlessService(config, new InMemoryStorageFactory(ACCOUNT_ID), regionResolver, clock); - IamService iamService = mock(IamService.class); + iamService = mock(IamService.class); when(iamService.resolveCallerArn(any())).thenReturn(Optional.empty()); EmrServerlessJobRunService jobRuns = new EmrServerlessJobRunService(AccountAwareStorageBackend.inMemory( ACCOUNT_ID), applications, iamService, regionResolver, null, objectMapper, 0, clock); @@ -264,6 +270,50 @@ class EmrServerlessSessionServiceTest { assertEquals(EmrServerlessSessionService.TOKEN_EXPIRED, sessions.route(token).orElseThrow().refusal()); } + @Test + void sessionsStartedWithinTheSameMillisecondListNewestFirst() { + EmrServerlessJobRunService jobRuns = new EmrServerlessJobRunService(AccountAwareStorageBackend.inMemory( + ACCOUNT_ID), applications, iamService, regionResolver, null, objectMapper, 0, clock); + EmrServerlessSessionService frozen = new EmrServerlessSessionService(AccountAwareStorageBackend.inMemory( + ACCOUNT_ID), applications, jobRuns, iamService, regionResolver, null, objectMapper, + Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC), "http://localhost:4566/"); + String applicationId = application("emr-7.13.0", "SPARK", true); + List started = new ArrayList<>(); + for (int session = 0; session < 12; session++) { + started.add(frozen.startSession(applicationId, request()).getSessionId()); + } + + List listed = frozen.listSessions(applicationId, null, null, null, null, null).items().stream() + .map(SessionSummary::getSessionId).toList(); + + assertEquals(started.reversed(), listed); + } + + @Test + void aRetryIsTheOriginalSessionWhereTheSessionWouldHoldTheSameAndConflictsWhereItWouldNot() { + String applicationId = application("emr-7.13.0", "SPARK", true); + StartSessionRequest first = request(); + first.setIdleTimeoutMinutes(60L); + first.setTags(Map.of()); + first.setConfigurationOverrides(Map.of()); + Session original = sessions.startSession(applicationId, first); + // The session holds the default idle timeout, no tags and no overrides either way. + StartSessionRequest retry = request(); + retry.setClientToken(first.getClientToken()); + StartSessionRequest emptyTag = request(); + emptyTag.setClientToken(first.getClientToken()); + emptyTag.setTags(Map.of("team", "")); + StartSessionRequest renamed = request(); + renamed.setClientToken(first.getClientToken()); + renamed.setName("another"); + + assertEquals(original.getSessionId(), sessions.startSession(applicationId, retry).getSessionId()); + for (StartSessionRequest conflicting : List.of(emptyTag, renamed)) { + assertEquals("ConflictException", assertThrows(AwsException.class, + () -> sessions.startSession(applicationId, conflicting)).getErrorCode()); + } + } + @Test void listSessionsFiltersByStateAndGroupsByTheFiltersOrder() { String applicationId = application("emr-7.13.0", "SPARK", true);