mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(stepfunctions): let Express executions reuse names and type the nested StartExecution refusal (#3059)
StartExecution enforced execution-name uniqueness on Express state machines, but AWS does not: an Express name is immediately reusable and every start is its own concurrent execution. Uniqueness, and the 90-day reuse window, applies to Standard workflows only. - StepFunctionsService.startExecution now gives an Express execution a per-start ARN (express:<stateMachine>:<name>:<uuid>) and skips the execution-store collision check, so a reused name starts a new, independent execution instead of failing with ExecutionAlreadyExists. This also closes a data-loss hazard: same-name Express starts would otherwise share one store key, letting a completing execution overwrite another. Standard behavior (idempotent same-input replay while RUNNING, ExecutionAlreadyExists otherwise) is unchanged. - AslExecutor.invokeNestedStateMachine now wraps the child StartExecution call so a refusal becomes a typed, catchable error (StepFunctions.ExecutionAlreadyExistsException) instead of States.Runtime, which no Catch or Retry can match. This mirrors the aws-sdk:sfn:startExecution path, which keeps its Sfn. prefix and is unchanged. Tests cover Express name reuse and a same-name no-clobber regression at the service level; nested-refusal typed-error, catch, retry and Sfn-vs-StepFunctions prefix cases for bare, .sync and .sync:2; a wire-level StartExecution integration test; and a .sync/.sync:2 success guard. The Express idempotency test that pinned the old divergence is removed. AWS Compatibility: Express StartExecution is non-idempotent and enforces no name uniqueness, and the express:<stateMachine>:<name>:<id> ARN shape matches the Step Functions resource-ARN definition; the optimized states:startExecution integration reports StepFunctions.<Code>Exception for a Standard-child collision. Left as documented deviations, not changed here: the 90-day Standard name-reuse window is not modeled, and finished Express executions are retained rather than evicted.
This commit is contained in:
1 parent
2d26f93e7d
commit
8a2161ab5e
7 files changed
+466
-17
No files matched your search
@@ -261,6 +261,27 @@ with `States.QueryEvaluationError` where AWS answers a string, and `0/0` fails t
|
||||
it, because NaN is dropped as not-a-number without even a refusal to read it from. A state that
|
||||
fails is one a `Catch` fires on, which is the half of the divergence worth keeping.
|
||||
|
||||
## Execution names
|
||||
|
||||
A Standard execution name is unique per account, Region and state machine. Starting a Standard
|
||||
execution with a name and input that match one still running returns that original execution, so a
|
||||
retried call is idempotent; any other reuse of the name, whether a different input or a name whose
|
||||
execution has already closed, fails with `ExecutionAlreadyExists`.
|
||||
|
||||
One deviation. AWS frees a Standard name 90 days after the execution closes; Floci keeps it taken for
|
||||
the life of the emulator, so a closed name never becomes reusable on its own.
|
||||
|
||||
An Express execution name is not unique. Every `StartExecution` on an Express state machine is its
|
||||
own execution that runs alongside any others of the same name, and its ARN carries a per-start id
|
||||
after the name (`express:<stateMachine>:<name>:<id>`). Reusing an Express name never returns an
|
||||
earlier execution and never fails with `ExecutionAlreadyExists`.
|
||||
|
||||
One more. AWS keeps no record of an Express execution once it ends, only its logs, and does not serve
|
||||
`DescribeExecution`, `GetExecutionHistory` or `ListExecutions` for one. Floci keeps every Express
|
||||
execution, running or finished, in its execution store (and, in persistent mode, in
|
||||
`sfn-executions.json`), and nothing evicts them while the emulator runs. A workload that
|
||||
starts the same Express name in a tight loop therefore grows that store without bound.
|
||||
|
||||
## Nested workflows
|
||||
|
||||
A parent workflow calls a child workflow through one of several integrations, and they differ in
|
||||
@@ -281,6 +302,12 @@ integrations, and only the casing of the result tells them apart.
|
||||
SDK call itself succeeded, so the task result carries `Status`, `Error` and `Cause` and the parent
|
||||
decides what to do next.
|
||||
|
||||
A `Name` a Standard child already used fails the calling task with the child's collision error, named
|
||||
for the integration that raised it: `StepFunctions.ExecutionAlreadyExistsException` through
|
||||
`states:startExecution` in any of its modes, and `Sfn.ExecutionAlreadyExistsException` through
|
||||
`aws-sdk:sfn:startExecution`. An Express child starts a new execution instead, so the same `Name`
|
||||
never fails it.
|
||||
|
||||
## AWS SDK task integrations
|
||||
|
||||
A resource of the form `arn:aws:states:::aws-sdk:<service>:<action>` calls the service's API and
|
||||
@@ -297,7 +324,7 @@ the wire and the task fails with `Sfn.StateMachineDoesNotExistException`.
|
||||
|
||||
| Resource | Result | Notable failure |
|
||||
| --- | --- | --- |
|
||||
| `arn:aws:states:::aws-sdk:sfn:startExecution` | `{ExecutionArn, StartDate}` | `Sfn.ExecutionAlreadyExistsException` when `Name` is reused |
|
||||
| `arn:aws:states:::aws-sdk:sfn:startExecution` | `{ExecutionArn, StartDate}` | `Sfn.ExecutionAlreadyExistsException` when `Name` is reused on a Standard child |
|
||||
| `arn:aws:states:::aws-sdk:sfn:startSyncExecution` | execution envelope | `Sfn.StateMachineTypeNotSupportedException` for a Standard child |
|
||||
| `arn:aws:states:::aws-sdk:sfn:sendTaskSuccess` | `{}` | `Sfn.InvalidTokenException` when no task is waiting on the token |
|
||||
| `arn:aws:states:::aws-sdk:sfn:sendTaskFailure` | `{}` | `Sfn.InvalidTokenException` |
|
||||
|
||||
@@ -1161,6 +1161,16 @@ public class AslExecutor {
|
||||
: service + "." + errorCode + "Exception";
|
||||
}
|
||||
|
||||
/**
|
||||
* The optimized {@code states:startExecution} integration names a refused StartExecution with the
|
||||
* {@code StepFunctions.} prefix on AWS, e.g. {@code StepFunctions.ExecutionAlreadyExistsException},
|
||||
* where {@code aws-sdk:sfn:startExecution} uses the {@code Sfn.} prefix. Only the prefix differs;
|
||||
* the {@code Exception}-suffix rule is the one {@link #sdkExceptionName} already applies.
|
||||
*/
|
||||
private static String optimizedSfnErrorName(String errorCode) {
|
||||
return sdkExceptionName("StepFunctions", errorCode);
|
||||
}
|
||||
|
||||
private static String sdkTimestamp(double epochSeconds) {
|
||||
return SDK_TIMESTAMP.format(Instant.ofEpochMilli(Math.round(epochSeconds * 1000)));
|
||||
}
|
||||
@@ -1372,8 +1382,15 @@ public class AslExecutor {
|
||||
childName = null;
|
||||
}
|
||||
|
||||
io.github.hectorvent.floci.services.stepfunctions.model.Execution exec =
|
||||
sfnService.get().startExecution(smArn, childName, childInput, region);
|
||||
io.github.hectorvent.floci.services.stepfunctions.model.Execution exec;
|
||||
try {
|
||||
exec = sfnService.get().startExecution(smArn, childName, childInput, region);
|
||||
} catch (AwsException e) {
|
||||
// A StartExecution refusal (e.g. a reused STANDARD name) is a typed task failure a Catch or
|
||||
// Retry can name, not a States.Runtime that nothing can catch. Same bridge as
|
||||
// invokeAwsSdkSfnStartExecution, under the prefix this optimized integration reports on AWS.
|
||||
throw new FailStateException(optimizedSfnErrorName(e.getErrorCode()), e.getMessage());
|
||||
}
|
||||
String execArn = exec.getExecutionArn();
|
||||
|
||||
if ("".equals(mode)) {
|
||||
|
||||
+12
-3
@@ -528,17 +528,26 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
var sm = describeStateMachine(selection.stateMachineArn());
|
||||
var mockedTestCase = resolveMockedTestCase(sm, selection);
|
||||
var execName = (name != null && !name.isBlank()) ? name : UUID.randomUUID().toString();
|
||||
var arn = regionResolver.buildArn("states", region, "execution:" + sm.getName() + ":" + execName);
|
||||
boolean express = "EXPRESS".equals(sm.getType());
|
||||
// An EXPRESS name is not unique on AWS: every start is its own execution that runs alongside
|
||||
// the others, so the ARN (which is also the execution-store key) carries a per-start id after
|
||||
// the name, under the express: namespace startSyncExecution already uses. A STANDARD execution
|
||||
// keeps the name-derived ARN whose uniqueness AWS enforces.
|
||||
var arn = express
|
||||
? regionResolver.buildArn("states", region,
|
||||
"express:" + sm.getName() + ":" + execName + ":" + UUID.randomUUID())
|
||||
: regionResolver.buildArn("states", region, "execution:" + sm.getName() + ":" + execName);
|
||||
|
||||
Execution exec;
|
||||
ExecutionHistory history;
|
||||
synchronized (executionStartLock) {
|
||||
Optional<Execution> existing = executionStore.get(arn);
|
||||
Optional<Execution> existing = express ? Optional.empty() : executionStore.get(arn);
|
||||
if (existing.isPresent()) {
|
||||
Execution prior = existing.get();
|
||||
// AWS idempotency (STANDARD only): the same name + same input while the original is still
|
||||
// RUNNING returns the original execution as a success; a different input, or a closed
|
||||
// execution with that name, is a conflict. EXPRESS workflows get no idempotency guarantee.
|
||||
// execution with that name, is a conflict. An EXPRESS start never reaches this branch:
|
||||
// its names are reusable and each start got its own ARN above.
|
||||
if ("STANDARD".equals(sm.getType())
|
||||
&& "RUNNING".equals(prior.getStatus())
|
||||
&& Objects.equals(prior.getInput(), input)) {
|
||||
|
||||
+118
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
|
||||
@@ -18,6 +19,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -26,8 +29,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -162,4 +167,117 @@ class AslExecutorNestedStartExecutionTest {
|
||||
assertEquals("States.Runtime", exec.getError());
|
||||
verify(childSfn, never()).startExecution(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
// ── Nested StartExecution refusal → typed, catchable error on the optimized states:startExecution
|
||||
// path. AWS reports StepFunctions.<Code>Exception here (the aws-sdk:sfn: path uses Sfn.<Code>),
|
||||
// never the uncatchable States.Runtime it collapsed to before this fix.
|
||||
|
||||
private static final String PARAMS = "{\"StateMachineArn\":\"" + CHILD_ARN + "\"}";
|
||||
|
||||
private static String parentMode(String mode) {
|
||||
return "{\"StartAt\":\"Nest\",\"States\":{"
|
||||
+ "\"Nest\":{\"Type\":\"Task\","
|
||||
+ "\"Resource\":\"arn:aws:states:::states:startExecution" + mode + "\","
|
||||
+ "\"Parameters\":" + PARAMS + ",\"End\":true}}}";
|
||||
}
|
||||
|
||||
private static String parentCatch(String errorEquals) {
|
||||
return "{\"StartAt\":\"Nest\",\"States\":{"
|
||||
+ "\"Nest\":{\"Type\":\"Task\","
|
||||
+ "\"Resource\":\"arn:aws:states:::states:startExecution\","
|
||||
+ "\"Parameters\":" + PARAMS + ","
|
||||
+ "\"Catch\":[{\"ErrorEquals\":[\"" + errorEquals + "\"],\"Next\":\"Recover\"}],\"End\":true},"
|
||||
+ "\"Recover\":{\"Type\":\"Pass\",\"End\":true}}}";
|
||||
}
|
||||
|
||||
private static String parentRetry(String errorEquals) {
|
||||
return "{\"StartAt\":\"Nest\",\"States\":{"
|
||||
+ "\"Nest\":{\"Type\":\"Task\","
|
||||
+ "\"Resource\":\"arn:aws:states:::states:startExecution\","
|
||||
+ "\"Parameters\":" + PARAMS + ","
|
||||
+ "\"Retry\":[{\"ErrorEquals\":[\"" + errorEquals + "\"],\"MaxAttempts\":1,\"IntervalSeconds\":0}],"
|
||||
+ "\"End\":true}}}";
|
||||
}
|
||||
|
||||
private void childRefuses(String errorCode) {
|
||||
doThrow(new AwsException(errorCode, "Execution already exists: " + CHILD_ARN, 400))
|
||||
.when(childSfn).startExecution(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", ".sync", ".sync:2"})
|
||||
void childRefusalIsATypedFailure(String mode) {
|
||||
childRefuses("ExecutionAlreadyExists");
|
||||
Execution exec = runParent(parentMode(mode), "{}");
|
||||
assertEquals("FAILED", exec.getStatus());
|
||||
assertEquals("StepFunctions.ExecutionAlreadyExistsException", exec.getError());
|
||||
}
|
||||
|
||||
@Test
|
||||
void childRefusalIsCaughtByItsTypedName() {
|
||||
childRefuses("ExecutionAlreadyExists");
|
||||
Execution exec = runParent(parentCatch("StepFunctions.ExecutionAlreadyExistsException"), "{}");
|
||||
assertEquals("SUCCEEDED", exec.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void childRefusalIsCaughtByStatesTaskFailed() {
|
||||
childRefuses("ExecutionAlreadyExists");
|
||||
Execution exec = runParent(parentCatch("States.TaskFailed"), "{}");
|
||||
assertEquals("SUCCEEDED", exec.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void childRefusalIsRetriedByItsTypedName() {
|
||||
childRefuses("ExecutionAlreadyExists");
|
||||
Execution exec = runParent(parentRetry("StepFunctions.ExecutionAlreadyExistsException"), "{}");
|
||||
assertEquals("FAILED", exec.getStatus());
|
||||
assertEquals("StepFunctions.ExecutionAlreadyExistsException", exec.getError());
|
||||
// MaxAttempts=1: the initial attempt plus one retry both reach the child.
|
||||
verify(childSfn, times(2)).startExecution(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sfnPrefixedCatchDoesNotMatchTheOptimizedPath() {
|
||||
// The aws-sdk integration's Sfn. prefix must NOT catch the optimized path's StepFunctions. error
|
||||
// (catchMatches is exact for non-States names), so the task still fails with the typed name.
|
||||
childRefuses("ExecutionAlreadyExists");
|
||||
Execution exec = runParent(parentCatch("Sfn.ExecutionAlreadyExistsException"), "{}");
|
||||
assertEquals("FAILED", exec.getStatus());
|
||||
assertEquals("StepFunctions.ExecutionAlreadyExistsException", exec.getError());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingChildIsATypedFailure() {
|
||||
childRefuses("StateMachineDoesNotExist");
|
||||
Execution exec = runParent(parentMode(""), "{}");
|
||||
assertEquals("FAILED", exec.getStatus());
|
||||
assertEquals("StepFunctions.StateMachineDoesNotExistException", exec.getError());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {".sync", ".sync:2"})
|
||||
void syncChildSuccessIsUndisturbedByTheWrap(String mode) throws Exception {
|
||||
// Regression guard: wrapping the start call in try/catch must not disturb the .sync/.sync:2
|
||||
// success branches. The child starts RUNNING (setUp) then the poll observes it SUCCEEDED.
|
||||
Execution done = new Execution();
|
||||
done.setExecutionArn("arn:aws:states:us-east-1:000000000000:execution:child:e1");
|
||||
done.setStateMachineArn(CHILD_ARN);
|
||||
done.setName("e1");
|
||||
done.setStatus("SUCCEEDED");
|
||||
done.setStartDate(1.0);
|
||||
done.setStopDate(2.0);
|
||||
done.setOutput("{\"ok\":true}");
|
||||
when(childSfn.describeExecution(any())).thenReturn(done);
|
||||
|
||||
Execution exec = runParent(parentMode(mode), "{}");
|
||||
assertEquals("SUCCEEDED", exec.getStatus());
|
||||
var output = mapper.readTree(exec.getOutput());
|
||||
if (".sync:2".equals(mode)) {
|
||||
assertTrue(output.path("ok").asBoolean(), "sync:2 returns the parsed child output");
|
||||
} else {
|
||||
assertEquals("SUCCEEDED", output.path("status").asText(), "sync returns the execution envelope");
|
||||
assertEquals("{\"ok\":true}", output.path("output").asText(), "envelope output is the child output JSON string");
|
||||
}
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
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 static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Integration coverage for the direct {@code StartExecution} API's name semantics, exercising the real
|
||||
* JSON handler + service + {@code AwsExceptionMapper} path. An EXPRESS state machine accepts a reused
|
||||
* execution name (each start is its own execution with its own {@code express:} ARN); a STANDARD state
|
||||
* machine still rejects a name collision with a 400 {@code ExecutionAlreadyExists}. The no-clobber
|
||||
* (data-loss) proof is at the service level in {@code StepFunctionsServiceStartExecutionExpressTest};
|
||||
* this test deliberately does not call DescribeExecution/ListExecutions on an EXPRESS ARN, which AWS
|
||||
* does not support for EXPRESS.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class StepFunctionsExpressStartExecutionIntegrationTest {
|
||||
|
||||
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";
|
||||
private static final String PASS_DEFINITION =
|
||||
"{\"StartAt\":\"P\",\"States\":{\"P\":{\"Type\":\"Pass\",\"End\":true}}}";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void expressAcceptsReusedNameAsDistinctExecutions() {
|
||||
String smArn = createStateMachine("express-name-reuse", "EXPRESS", PASS_DEFINITION);
|
||||
|
||||
Response first = startNamed(smArn, "again", "{}");
|
||||
first.then().statusCode(200);
|
||||
Response second = startNamed(smArn, "again", "{}");
|
||||
second.then().statusCode(200);
|
||||
|
||||
String arn1 = first.jsonPath().getString("executionArn");
|
||||
String arn2 = second.jsonPath().getString("executionArn");
|
||||
assertNotEquals(arn1, arn2, "each EXPRESS start must be its own execution");
|
||||
assertTrue(arn1.startsWith("arn:aws:states:"), arn1);
|
||||
assertTrue(arn1.contains(":express:express-name-reuse:again:"), arn1);
|
||||
assertTrue(arn2.contains(":express:express-name-reuse:again:"), arn2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void standardRejectsReusedNameWithExecutionAlreadyExists() {
|
||||
String smArn = createStateMachine("standard-name-reuse-control", null, PASS_DEFINITION);
|
||||
|
||||
// Same name + different input is a conflict for STANDARD whether the first is still running or
|
||||
// closed, so this control is deterministic regardless of the async execution's timing.
|
||||
startNamed(smArn, "again", "{\"n\":1}").then().statusCode(200);
|
||||
Response conflict = startNamed(smArn, "again", "{\"n\":2}");
|
||||
conflict.then().statusCode(400);
|
||||
assertTrue(conflict.asString().contains("ExecutionAlreadyExists"), conflict.asString());
|
||||
}
|
||||
|
||||
private static String createStateMachine(String name, String type, String definition) {
|
||||
var typeField = type != null ? "\"type\": \"%s\",".formatted(type) : "";
|
||||
var resp = given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"name": "%s",
|
||||
%s
|
||||
"roleArn": "%s",
|
||||
"definition": %s
|
||||
}
|
||||
""".formatted(name, typeField, ROLE_ARN, quote(definition)))
|
||||
.when().post("/");
|
||||
resp.then().statusCode(200);
|
||||
return resp.jsonPath().getString("stateMachineArn");
|
||||
}
|
||||
|
||||
private static Response startNamed(String smArn, String name, String input) {
|
||||
return given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.StartExecution")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"stateMachineArn": "%s", "name": "%s", "input": %s}
|
||||
""".formatted(smArn, name, quote(input)))
|
||||
.when().post("/");
|
||||
}
|
||||
|
||||
private static String quote(String raw) {
|
||||
return "\"" + raw
|
||||
.replace("\\", "\\\\")
|
||||
.replace("\"", "\\\"")
|
||||
.replace("\n", "\\n")
|
||||
.replace("\r", "\\r")
|
||||
.replace("\t", "\\t")
|
||||
+ "\"";
|
||||
}
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.Activity;
|
||||
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 com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CyclicBarrier;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* EXPRESS StartExecution name reuse for {@link StepFunctionsService}, over a real service with
|
||||
* in-memory stores and a mocked {@link AslExecutor}. AWS lets an EXPRESS name be reused immediately:
|
||||
* every start is its own concurrent execution with its own ARN, so a same-name start must never
|
||||
* conflict and must never overwrite an earlier execution's record (the data-loss regression this
|
||||
* branch is named for).
|
||||
*
|
||||
* <p>CI-only: {@code mock(AslExecutor.class)} forces AslExecutor to load, which needs Vert.x (absent
|
||||
* in the offline sandbox), as in {@code StepFunctionsServiceStartExecutionRaceTest}. The STANDARD
|
||||
* idempotency/conflict decision stays in {@code StepFunctionsServiceStartExecutionIdempotencyTest}.
|
||||
*/
|
||||
class StepFunctionsServiceStartExecutionExpressTest {
|
||||
|
||||
private static final String SM_ARN = "arn:aws:states:us-east-1:000000000000:stateMachine:test-sm";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String EXPRESS_ARN_PREFIX =
|
||||
"arn:aws:states:us-east-1:000000000000:express:test-sm:";
|
||||
|
||||
private AccountAwareStorageBackend<Execution> execStore;
|
||||
private AslExecutor executor;
|
||||
|
||||
private StepFunctionsService buildService() {
|
||||
AccountAwareStorageBackend<StateMachine> smStore = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
execStore = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
AccountAwareStorageBackend<Activity> actStore = AccountAwareStorageBackend.inMemory("000000000000");
|
||||
|
||||
StorageFactory factory = mock(StorageFactory.class);
|
||||
doReturn(smStore).doReturn(execStore).doReturn(actStore)
|
||||
.when(factory).create(anyString(), anyString(), any());
|
||||
|
||||
RegionResolver region = mock(RegionResolver.class);
|
||||
when(region.buildArn(eq("states"), any(), anyString()))
|
||||
.thenAnswer(i -> "arn:aws:states:us-east-1:000000000000:" + i.getArgument(2));
|
||||
|
||||
// A mock executor: executeAsync is a no-op, so the completion callback fires only when a test
|
||||
// invokes it explicitly (mirroring what AslExecutor would do on the worker thread).
|
||||
executor = mock(AslExecutor.class);
|
||||
StepFunctionsService svc =
|
||||
new StepFunctionsService(factory, region, executor, new ObjectMapper(), mock(SfnMockLoader.class));
|
||||
|
||||
StateMachine sm = new StateMachine();
|
||||
sm.setStateMachineArn(SM_ARN);
|
||||
sm.setName("test-sm");
|
||||
sm.setRoleArn("arn:aws:iam::000000000000:role/r");
|
||||
sm.setType("EXPRESS");
|
||||
sm.setDefinition("{\"StartAt\":\"P\",\"States\":{\"P\":{\"Type\":\"Pass\",\"End\":true}}}");
|
||||
smStore.put(SM_ARN, sm);
|
||||
return svc;
|
||||
}
|
||||
|
||||
/** Asserts {@code arn} is express:<sm>:<name>:<uuid> and returns the trailing uuid segment. */
|
||||
private static String expressUuid(String arn, String name) {
|
||||
String prefix = EXPRESS_ARN_PREFIX + name + ":";
|
||||
assertTrue(arn.startsWith(prefix), "not an express ARN for " + name + ": " + arn);
|
||||
return arn.substring(prefix.length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameNameStartsTwiceAsTwoIndependentExecutions() {
|
||||
StepFunctionsService service = buildService();
|
||||
Execution e1 = service.startExecution(SM_ARN, "again", "{\"n\":1}", REGION);
|
||||
Execution e2 = service.startExecution(SM_ARN, "again", "{\"n\":2}", REGION);
|
||||
|
||||
assertNotEquals(e1.getExecutionArn(), e2.getExecutionArn(), "each EXPRESS start gets its own ARN");
|
||||
assertEquals("again", e1.getName());
|
||||
assertEquals("again", e2.getName());
|
||||
// ARN shape: express:<stateMachineName>:<executionName>:<uuid>
|
||||
UUID.fromString(expressUuid(e1.getExecutionArn(), "again"));
|
||||
UUID.fromString(expressUuid(e2.getExecutionArn(), "again"));
|
||||
// Both are stored under their own key, each carrying its own input; neither shadows the other.
|
||||
assertEquals("{\"n\":1}", execStore.get(e1.getExecutionArn()).get().getInput());
|
||||
assertEquals("{\"n\":2}", execStore.get(e2.getExecutionArn()).get().getInput());
|
||||
verify(executor, times(2)).executeAsync(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void completingTheFirstStartDoesNotClobberTheSecond() {
|
||||
StepFunctionsService service = buildService();
|
||||
Execution e1 = service.startExecution(SM_ARN, "again", "{\"n\":1}", REGION);
|
||||
Execution e2 = service.startExecution(SM_ARN, "again", "{\"n\":2}", REGION);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<BiConsumer<Execution, List<HistoryEvent>>> onUpdate =
|
||||
ArgumentCaptor.forClass(BiConsumer.class);
|
||||
verify(executor, times(2)).executeAsync(any(), any(), any(), any(), onUpdate.capture());
|
||||
|
||||
// Complete the FIRST start exactly as AslExecutor would: mutate its Execution, fire its callback.
|
||||
e1.setStatus("SUCCEEDED");
|
||||
e1.setOutput("{\"done\":1}");
|
||||
onUpdate.getAllValues().get(0).accept(e1, new ArrayList<>());
|
||||
|
||||
assertEquals("SUCCEEDED", execStore.get(e1.getExecutionArn()).get().getStatus());
|
||||
// The second execution, on its own key, is untouched by the first's completion.
|
||||
Execution stored2 = execStore.get(e2.getExecutionArn()).get();
|
||||
assertEquals("RUNNING", stored2.getStatus());
|
||||
assertEquals("{\"n\":2}", stored2.getInput());
|
||||
assertNull(stored2.getOutput());
|
||||
}
|
||||
|
||||
@Test
|
||||
void closedNameIsImmediatelyReusable() {
|
||||
StepFunctionsService service = buildService();
|
||||
Execution e1 = service.startExecution(SM_ARN, "again", "{\"n\":1}", REGION);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<BiConsumer<Execution, List<HistoryEvent>>> onUpdate =
|
||||
ArgumentCaptor.forClass(BiConsumer.class);
|
||||
verify(executor, times(1)).executeAsync(any(), any(), any(), any(), onUpdate.capture());
|
||||
e1.setStatus("SUCCEEDED");
|
||||
onUpdate.getValue().accept(e1, new ArrayList<>());
|
||||
|
||||
// Reusing the (now closed) name starts a fresh, independent execution rather than conflicting.
|
||||
Execution e2 = service.startExecution(SM_ARN, "again", "{\"n\":1}", REGION);
|
||||
assertNotEquals(e1.getExecutionArn(), e2.getExecutionArn());
|
||||
assertEquals("RUNNING", execStore.get(e2.getExecutionArn()).get().getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentSameNameStartsAllLaunchIndependently() throws Exception {
|
||||
StepFunctionsService service = buildService();
|
||||
int n = 16;
|
||||
List<String> arns = new CopyOnWriteArrayList<>();
|
||||
List<Throwable> errors = new CopyOnWriteArrayList<>();
|
||||
CyclicBarrier barrier = new CyclicBarrier(n);
|
||||
ExecutorService pool = Executors.newFixedThreadPool(n);
|
||||
List<Future<?>> futures = new ArrayList<>();
|
||||
try {
|
||||
for (int i = 0; i < n; i++) {
|
||||
futures.add(pool.submit(() -> {
|
||||
try {
|
||||
barrier.await();
|
||||
arns.add(service.startExecution(SM_ARN, "again", "{\"n\":1}", REGION).getExecutionArn());
|
||||
} catch (Throwable t) {
|
||||
errors.add(t);
|
||||
}
|
||||
}));
|
||||
}
|
||||
for (Future<?> f : futures) {
|
||||
f.get(30, TimeUnit.SECONDS);
|
||||
}
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
assertTrue(errors.isEmpty(), "no EXPRESS same-name start should error: " + errors);
|
||||
assertEquals(n, arns.size());
|
||||
assertEquals(n, arns.stream().distinct().count(), "every EXPRESS start is its own execution");
|
||||
verify(executor, times(n)).executeAsync(any(), any(), any(), any(), any());
|
||||
}
|
||||
}
|
||||
+2
-11
@@ -25,7 +25,8 @@ import static org.mockito.Mockito.when;
|
||||
* return-existing / conflict branch, which resolves before {@code aslExecutor.executeAsync}, so the
|
||||
* executor is never touched (it cannot be loaded in this offline sandbox: it needs Vert.x). The
|
||||
* create-and-launch path and the concurrency race are covered by
|
||||
* {@code StepFunctionsServiceStartExecutionRaceTest} (CI-only).
|
||||
* {@code StepFunctionsServiceStartExecutionRaceTest} (CI-only); EXPRESS name reuse (which AWS allows,
|
||||
* so it never conflicts) is covered by {@code StepFunctionsServiceStartExecutionExpressTest}.
|
||||
*/
|
||||
class StepFunctionsServiceStartExecutionIdempotencyTest {
|
||||
|
||||
@@ -101,14 +102,4 @@ class StepFunctionsServiceStartExecutionIdempotencyTest {
|
||||
() -> service.startExecution(SM_ARN, "run", "{\"a\":1}", REGION));
|
||||
assertEquals("ExecutionAlreadyExists", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expressGetsNoIdempotentReturn() {
|
||||
StepFunctionsService service = buildService("EXPRESS");
|
||||
seedExecution("run", "{\"a\":1}", "RUNNING");
|
||||
// STANDARD-only idempotency: EXPRESS with the same name+input still conflicts (it does not take the
|
||||
// return-existing branch). AWS actually allows EXPRESS name reuse: a known divergence, out of scope.
|
||||
assertThrows(AwsException.class,
|
||||
() -> service.startExecution(SM_ARN, "run", "{\"a\":1}", REGION));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user