mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(stepfunctions): stop a .sync job whenever its Task is cut, and record the cut state (#4660)
* fix(stepfunctions): stop a .sync job whenever its Task is cut, and record the cut state Measured on AWS (ap-northeast-1, 2026-09-29): Step Functions stops the job a .sync Task waits on however the Task ends before the job does. Besides the Task's own TimeoutSeconds and StopExecution, which #4519 covered, that is the execution's budget (child ABORTED, ECS task UserInitiated, both at the budget) and a failure in a sibling Parallel branch (both within about 0.1 s of the failure), always with the cause "The Task state in AWS Step Functions execution [<arn>] which was managing this resource was aborted". Floci left the job running in both cases: the poll loops only stopped it on the Task's own timeout, and an interrupt from a cut Parallel unwound through them untouched. AWS also records the state each cut branch was in: one TaskStateAborted per cut Task, or WaitStateAborted for a cut Wait, each chained to the failing branch's last event and recorded before ParallelStateFailed, which points at that same event. The Parallel now reads each branch's current state before it cuts them and records those events with HistoryChain.publishBeside. The execution's budget records none, as on AWS. Part of #4646 * fix(stepfunctions): read and cut a Parallel branch in one step Review of #4660: the state a branch is in was published apart from the event that enters or exits it, and read apart from the cut. A sibling failure could therefore see a TaskStateEntered with no state marked and record no TaskStateAborted, or mark a state that then exited before the cut and record TaskStateAborted after its TaskStateExited. HistoryChain now publishes the Entered and Exited events together with the marker (publishStateEntered, publishStateExited), and the Parallel reads and cuts each branch with abandonInState, all under the chain's lock. A Task whose own failure ends its branch leaves the state and records its TaskStateAborted in one step too (leaveStateAside), so a concurrent cut reports it at most once. runState leaves the state in a finally for the paths that end by throwing. * fix(stepfunctions): let the cut branch's state alone decide its aborted event Review of #4660: the cut read each branch's future after cutting it, so a branch that finished in between had its Exited event suppressed by the cut and its *StateAborted skipped by the isDone check, leaving a state with neither. The future read is not needed: runState leaves every state it entered before the branch returns, so a finished branch, the failed one included, is always read as between states. The cut now decides on the state it reads under the chain's lock and nothing else. * test(stepfunctions): assert the parent's budget aborts a nested child over HTTP StepFunctionsTimeoutSecondsIntegrationTest still said the child keeps running when the parent's TimeoutSeconds fires, which this PR changes to match AWS. The comment now says the child is aborted, and the test asserts it through ListExecutions, so the change is covered end to end and not only by the executor's unit tests. --------- Co-authored-by: mitsukado-shinagawa <mitsukado-shinagawa@users.noreply.github.com>
This commit is contained in:
1 parent
b8aec4c50f
commit
dc3beadf6a
8 files changed
+562
-32
No files matched your search
+47
-4
@@ -26,6 +26,7 @@ import org.mockito.ArgumentCaptor;
|
||||
import java.time.Clock;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
@@ -38,7 +39,7 @@ import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -106,7 +107,7 @@ class AslExecutorEcsRunTaskModeTest {
|
||||
null,
|
||||
Clock.systemUTC(),
|
||||
sleeper,
|
||||
null);
|
||||
30);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -218,7 +219,7 @@ class AslExecutorEcsRunTaskModeTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void executionBudgetCutsASyncWaitBeforeTheTasksOwnTimeout() throws Exception {
|
||||
void executionBudgetCutsASyncWaitBeforeTheTasksOwnTimeoutAndStopsTheTask() throws Exception {
|
||||
launchOneTask();
|
||||
when(ecsService.describeTasks(any(), any(), any())).thenReturn(List.of(task("RUNNING")));
|
||||
|
||||
@@ -235,12 +236,54 @@ class AslExecutorEcsRunTaskModeTest {
|
||||
|
||||
assertEquals("TIMED_OUT", execution.getStatus());
|
||||
assertNull(execution.getError());
|
||||
verify(ecsService, never()).stopTask(any(), any(), any(), any());
|
||||
// AWS stops the task on the execution's budget too (measured: UserInitiated, same reason).
|
||||
verify(ecsService).stopTask(any(), eq(task("RUNNING").getTaskArn()),
|
||||
eq("The Task state in AWS Step Functions execution [" + execution.getExecutionArn()
|
||||
+ "] which was managing this resource was aborted"), eq(REGION));
|
||||
assertTrue(history.stream().noneMatch(event -> "TaskTimedOut".equals(event.getType())),
|
||||
"the execution's budget writes nothing about the state it cut");
|
||||
assertTrue(history.stream().anyMatch(event -> "ExecutionTimedOut".equals(event.getType())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failureInASiblingParallelBranchStopsTheTask() throws Exception {
|
||||
// The sibling's Pause is held until this branch is polling, so the cut lands mid-wait.
|
||||
CountDownLatch polling = new CountDownLatch(1);
|
||||
executor = newExecutor(nanos -> {
|
||||
if (nanos == TimeUnit.SECONDS.toNanos(1)) {
|
||||
polling.await();
|
||||
return;
|
||||
}
|
||||
polling.countDown();
|
||||
TimeUnit.NANOSECONDS.sleep(nanos);
|
||||
});
|
||||
launchOneTask();
|
||||
when(ecsService.describeTasks(any(), any(), any())).thenReturn(List.of(task("RUNNING")));
|
||||
|
||||
Execution execution = runDefinition("""
|
||||
{
|
||||
"StartAt": "P",
|
||||
"States": {
|
||||
"P": { "Type": "Parallel", "End": true, "Branches": [
|
||||
{ "StartAt": "Pause", "States": {
|
||||
"Pause": { "Type": "Wait", "Seconds": 1, "Next": "Boom" },
|
||||
"Boom": { "Type": "Fail", "Error": "Boom" } } },
|
||||
{ "StartAt": "RunTask", "States": {
|
||||
"RunTask": { "Type": "Task", "Resource": "arn:aws:states:::ecs:runTask.sync",
|
||||
"Parameters": { "TaskDefinition": "my-task-def" }, "End": true } } }
|
||||
] }
|
||||
}
|
||||
}
|
||||
""", "{}");
|
||||
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
assertEquals("Boom", execution.getError());
|
||||
// The cut branch stops its task on its own thread, after the Parallel has already failed.
|
||||
verify(ecsService, timeout(5_000)).stopTask(any(), eq(task("RUNNING").getTaskArn()),
|
||||
eq("The Task state in AWS Step Functions execution [" + execution.getExecutionArn()
|
||||
+ "] which was managing this resource was aborted"), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopExecutionEndsTheSyncWaitAndStopsTheTask() throws Exception {
|
||||
executor = newExecutor(nanos -> { });
|
||||
|
||||
+24
-3
@@ -44,8 +44,8 @@ import static org.mockito.Mockito.when;
|
||||
/**
|
||||
* A {@code states:startExecution.sync} wait is bounded by the Task's {@code TimeoutSeconds}, the
|
||||
* way AWS bounds it, and no longer by a fixed poll count of its own. The timeout aborts the child,
|
||||
* a {@code Catch} on {@code States.Timeout} takes it, and a StopExecution on the parent ends the
|
||||
* wait and the child alike.
|
||||
* a {@code Catch} on {@code States.Timeout} takes it, and the parent's own budget and a
|
||||
* StopExecution on the parent each end the wait and abort the child alike.
|
||||
*/
|
||||
class AslExecutorNestedSyncTimeoutTest {
|
||||
|
||||
@@ -122,6 +122,18 @@ class AslExecutorNestedSyncTimeoutTest {
|
||||
verify(sfnService, never()).stopExecution(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void executionBudgetEndsTheParentTimedOutAndAbortsTheChild() {
|
||||
when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child("RUNNING"));
|
||||
|
||||
Execution execution = run(newExecutor(TimeUnit.NANOSECONDS::sleep), ".sync:2", 60, false, 1);
|
||||
|
||||
assertEquals("TIMED_OUT", execution.getStatus());
|
||||
assertTrue(history.stream().noneMatch(event -> "TaskTimedOut".equals(event.getType())));
|
||||
// Measured on AWS: the child is aborted on the parent's budget too, with the same cause.
|
||||
verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopExecutionOnTheParentEndsTheWaitAndAbortsTheChild() {
|
||||
AtomicInteger parentReads = new AtomicInteger();
|
||||
@@ -190,12 +202,21 @@ class AslExecutorNestedSyncTimeoutTest {
|
||||
}
|
||||
|
||||
private Execution run(AslExecutor executor, String mode, int timeoutSeconds, boolean catchTimeout) {
|
||||
return run(executor, mode, timeoutSeconds, catchTimeout, 0);
|
||||
}
|
||||
|
||||
private Execution run(AslExecutor executor, String mode, int timeoutSeconds, boolean catchTimeout,
|
||||
int executionTimeoutSeconds) {
|
||||
String timeout = timeoutSeconds > 0 ? "\"TimeoutSeconds\": %d,".formatted(timeoutSeconds) : "";
|
||||
String catcher = catchTimeout
|
||||
? "\"Catch\": [{\"ErrorEquals\": [\"States.Timeout\"], \"Next\": \"Recover\"}],"
|
||||
: "";
|
||||
String budget = executionTimeoutSeconds > 0
|
||||
? "\"TimeoutSeconds\": %d,".formatted(executionTimeoutSeconds)
|
||||
: "";
|
||||
String definition = """
|
||||
{
|
||||
%s
|
||||
"StartAt": "Child",
|
||||
"States": {
|
||||
"Child": {
|
||||
@@ -209,7 +230,7 @@ class AslExecutorNestedSyncTimeoutTest {
|
||||
"Recover": { "Type": "Pass", "End": true }
|
||||
}
|
||||
}
|
||||
""".formatted(mode, timeout, catcher, CHILD_SM_ARN);
|
||||
""".formatted(budget, mode, timeout, catcher, CHILD_SM_ARN);
|
||||
|
||||
StateMachine stateMachine = new StateMachine();
|
||||
stateMachine.setName("parent");
|
||||
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbFacade;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.ecs.EcsService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeHandler;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
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 jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
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.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.timeout;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A Parallel branch that is cut while its {@code .sync} Task waits on a child execution aborts that
|
||||
* child, the way AWS does, and the history records the state each cut branch was in. Measured on
|
||||
* AWS: a failure in one branch aborts the child of every other branch within about 0.1 s with the
|
||||
* cause below, and records one {@code TaskStateAborted} (or {@code WaitStateAborted}) per cut
|
||||
* branch, each chained to the failing branch's last event and recorded before
|
||||
* {@code ParallelStateFailed}, which is chained to that same event. When the execution's budget
|
||||
* cuts the Parallel instead, the child is aborted as well and no such event is recorded.
|
||||
*
|
||||
* <p>The failing branch pauses in a Wait that the sleeper holds until every other branch is
|
||||
* parked on its own wait, so the cut always lands while the others are mid-state.
|
||||
*/
|
||||
class AslExecutorParallelCutTest {
|
||||
|
||||
private static final String REGION = "us-east-2";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String CHILD_SM_ARN =
|
||||
"arn:aws:states:%s:%s:stateMachine:child".formatted(REGION, ACCOUNT);
|
||||
private static final String CHILD_ARN =
|
||||
"arn:aws:states:%s:%s:execution:child:run-1".formatted(REGION, ACCOUNT);
|
||||
private static final String PARENT_ARN =
|
||||
"arn:aws:states:%s:%s:execution:parent:parent-run".formatted(REGION, ACCOUNT);
|
||||
private static final String ABORT_CAUSE =
|
||||
"The Task state in AWS Step Functions execution [" + PARENT_ARN
|
||||
+ "] which was managing this resource was aborted";
|
||||
private static final long PAUSE_NANOS = TimeUnit.SECONDS.toNanos(1);
|
||||
private static final String FAILING_BRANCH = """
|
||||
{"StartAt":"Pause","States":{
|
||||
"Pause":{"Type":"Wait","Seconds":1,"Next":"Boom"},
|
||||
"Boom":{"Type":"Fail","Error":"Boom","Cause":"sibling failed"}}}""";
|
||||
private static final String NESTED_SYNC_BRANCH = """
|
||||
{"StartAt":"Nest","States":{"Nest":{"Type":"Task",
|
||||
"Resource":"arn:aws:states:::states:startExecution.sync:2",
|
||||
"Parameters":{"StateMachineArn":"%s"},"End":true}}}""".formatted(CHILD_SM_ARN);
|
||||
private static final String PASS_BRANCH = """
|
||||
{"StartAt":"Done","States":{"Done":{"Type":"Pass","End":true}}}""";
|
||||
private static final String LONG_WAIT_BRANCH = """
|
||||
{"StartAt":"Long","States":{"Long":{"Type":"Wait","Seconds":20,"End":true}}}""";
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private StepFunctionsService sfnService;
|
||||
private List<HistoryEvent> history;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
sfnService = mock(StepFunctionsService.class);
|
||||
when(sfnService.startExecution(any(), any(), any(), any())).thenReturn(child());
|
||||
when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child());
|
||||
Execution parent = new Execution();
|
||||
parent.setExecutionArn(PARENT_ARN);
|
||||
parent.setStatus("RUNNING");
|
||||
when(sfnService.describeExecution(PARENT_ARN)).thenReturn(parent);
|
||||
}
|
||||
|
||||
@Test
|
||||
void siblingFailureAbortsTheChildAndRecordsTaskStateAbortedBesideTheFailure() {
|
||||
Execution execution = run(parallel(FAILING_BRANCH, NESTED_SYNC_BRANCH), 1, 0);
|
||||
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
assertEquals("Boom", execution.getError());
|
||||
assertEquals("sibling failed", execution.getCause());
|
||||
long failure = eventOfType("FailStateEntered").getId();
|
||||
List<HistoryEvent> aborted = eventsOfType("TaskStateAborted");
|
||||
assertEquals(1, aborted.size(), "one TaskStateAborted for the one cut branch: " + types());
|
||||
assertEquals(failure, aborted.get(0).getPreviousEventId().longValue());
|
||||
assertNull(aborted.get(0).getDetails());
|
||||
HistoryEvent parallelFailed = eventOfType("ParallelStateFailed");
|
||||
assertEquals(failure, parallelFailed.getPreviousEventId().longValue());
|
||||
assertTrue(aborted.get(0).getId() < parallelFailed.getId());
|
||||
verify(sfnService, timeout(5_000)).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyCutBranchRecordsItsOwnTaskStateAbortedAgainstTheSameEvent() {
|
||||
Execution execution = run(parallel(FAILING_BRANCH, NESTED_SYNC_BRANCH, NESTED_SYNC_BRANCH), 2, 0);
|
||||
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
long failure = eventOfType("FailStateEntered").getId();
|
||||
List<HistoryEvent> aborted = eventsOfType("TaskStateAborted");
|
||||
assertEquals(2, aborted.size(), types().toString());
|
||||
assertTrue(aborted.stream().allMatch(event -> event.getPreviousEventId() == failure), types().toString());
|
||||
assertEquals(failure, eventOfType("ParallelStateFailed").getPreviousEventId().longValue());
|
||||
verify(sfnService, timeout(5_000).times(2)).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWaitCutByASiblingFailureIsRecordedAsWaitStateAborted() {
|
||||
Execution execution = run(parallel(FAILING_BRANCH, LONG_WAIT_BRANCH), 1, 0);
|
||||
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
long failure = eventOfType("FailStateEntered").getId();
|
||||
HistoryEvent aborted = eventOfType("WaitStateAborted");
|
||||
assertEquals(failure, aborted.getPreviousEventId().longValue());
|
||||
assertTrue(eventsOfType("TaskStateAborted").isEmpty(), types().toString());
|
||||
assertTrue(aborted.getId() < eventOfType("ParallelStateFailed").getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBranchThatFinishedBeforeTheFailureRecordsNoAbortedState() {
|
||||
// The failing branch's Pause really sleeps, so the Pass branch has long finished by then.
|
||||
AslExecutor.Sleeper sleeper = nanos -> TimeUnit.MILLISECONDS.sleep(200);
|
||||
Execution execution = run(parallel(FAILING_BRANCH, PASS_BRANCH), sleeper, 0);
|
||||
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
assertTrue(types().contains("PassStateExited"), types().toString());
|
||||
assertTrue(types().stream().noneMatch(type -> type.endsWith("StateAborted")), types().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void executionBudgetCuttingTheParallelAbortsTheChildAndRecordsNoAbortedState() {
|
||||
Execution execution = run(parallel(NESTED_SYNC_BRANCH), 0, 1);
|
||||
|
||||
assertEquals("TIMED_OUT", execution.getStatus());
|
||||
assertTrue(types().stream().noneMatch(type -> type.endsWith("StateAborted")), types().toString());
|
||||
verify(sfnService, timeout(5_000)).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
|
||||
}
|
||||
|
||||
private static Execution child() {
|
||||
Execution current = new Execution();
|
||||
current.setExecutionArn(CHILD_ARN);
|
||||
current.setStateMachineArn(CHILD_SM_ARN);
|
||||
current.setName("run-1");
|
||||
current.setStatus("RUNNING");
|
||||
current.setStartDate(1.0);
|
||||
return current;
|
||||
}
|
||||
|
||||
private static String parallel(String... branches) {
|
||||
return "{\"Type\":\"Parallel\",\"End\":true,\"Branches\":[" + String.join(",", branches) + "]}";
|
||||
}
|
||||
|
||||
/**
|
||||
* The failing branch's one-second Pause is held until {@code waitingBranches} other branch
|
||||
* threads have started a sleep of their own (a {@code .sync} poll, or a longer Wait); every
|
||||
* other sleep is real, so the cut interrupts it.
|
||||
*/
|
||||
private static AslExecutor.Sleeper sleeper(int waitingBranches) {
|
||||
CountDownLatch othersWaiting = new CountDownLatch(waitingBranches);
|
||||
Set<Thread> seen = ConcurrentHashMap.newKeySet();
|
||||
return nanos -> {
|
||||
if (nanos == PAUSE_NANOS) {
|
||||
othersWaiting.await();
|
||||
return;
|
||||
}
|
||||
if (seen.add(Thread.currentThread())) {
|
||||
othersWaiting.countDown();
|
||||
}
|
||||
TimeUnit.NANOSECONDS.sleep(nanos);
|
||||
};
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private AslExecutor newExecutor(AslExecutor.Sleeper sleeper) {
|
||||
Instance<StepFunctionsService> instance = mock(Instance.class);
|
||||
when(instance.get()).thenReturn(sfnService);
|
||||
return new AslExecutor(
|
||||
mock(LambdaExecutorService.class),
|
||||
mock(LambdaFunctionStore.class),
|
||||
mock(DynamoDbFacade.class),
|
||||
mock(DynamoDbJsonHandler.class),
|
||||
mock(SqsJsonHandler.class), mock(SnsJsonHandler.class),
|
||||
mock(CloudFormationQueryHandler.class),
|
||||
mock(Ec2Service.class),
|
||||
mock(S3Service.class),
|
||||
mock(EcsService.class),
|
||||
mock(EcsJsonHandler.class),
|
||||
mock(EventBridgeHandler.class),
|
||||
mock(SchedulerService.class),
|
||||
mock(SchedulerController.class),
|
||||
objectMapper,
|
||||
new JsonataEvaluator(objectMapper),
|
||||
instance,
|
||||
mock(EmulatorConfig.class),
|
||||
null,
|
||||
null,
|
||||
Clock.systemUTC(),
|
||||
sleeper,
|
||||
30);
|
||||
}
|
||||
|
||||
private Execution run(String parallelState, int waitingBranches, int executionTimeoutSeconds) {
|
||||
return run(parallelState, sleeper(waitingBranches), executionTimeoutSeconds);
|
||||
}
|
||||
|
||||
private Execution run(String parallelState, AslExecutor.Sleeper sleeper, int executionTimeoutSeconds) {
|
||||
String budget = executionTimeoutSeconds > 0
|
||||
? "\"TimeoutSeconds\":%d,".formatted(executionTimeoutSeconds)
|
||||
: "";
|
||||
String definition = "{" + budget + "\"StartAt\":\"P\",\"States\":{\"P\":" + parallelState + "}}";
|
||||
|
||||
StateMachine stateMachine = new StateMachine();
|
||||
stateMachine.setName("parent");
|
||||
stateMachine.setStateMachineArn("arn:aws:states:%s:%s:stateMachine:parent".formatted(REGION, ACCOUNT));
|
||||
stateMachine.setRoleArn("arn:aws:iam::%s:role/test-role".formatted(ACCOUNT));
|
||||
stateMachine.setDefinition(definition);
|
||||
|
||||
Execution execution = new Execution();
|
||||
execution.setName("parent-run");
|
||||
execution.setExecutionArn(PARENT_ARN);
|
||||
execution.setStateMachineArn(stateMachine.getStateMachineArn());
|
||||
execution.setInput("{}");
|
||||
|
||||
history = new ArrayList<>();
|
||||
newExecutor(sleeper).executeSync(stateMachine, execution, history, (updated, events) -> { });
|
||||
return execution;
|
||||
}
|
||||
|
||||
private List<String> types() {
|
||||
return history.stream().map(HistoryEvent::getType).toList();
|
||||
}
|
||||
|
||||
private List<HistoryEvent> eventsOfType(String type) {
|
||||
return history.stream().filter(event -> type.equals(event.getType())).toList();
|
||||
}
|
||||
|
||||
private HistoryEvent eventOfType(String type) {
|
||||
return history.stream().filter(event -> type.equals(event.getType())).findFirst()
|
||||
.orElseThrow(() -> new AssertionError("no " + type + " in " + types()));
|
||||
}
|
||||
}
|
||||
@@ -4,11 +4,14 @@ import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
class HistoryChainTest {
|
||||
|
||||
@@ -45,4 +48,83 @@ class HistoryChainTest {
|
||||
});
|
||||
assertEquals(1, history.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStateCutAfterItsEnteredEventIsReportedAndRecordsNoExitedEvent() {
|
||||
List<HistoryEvent> history = new ArrayList<>();
|
||||
HistoryChain branch = HistoryChain.of(history).fork();
|
||||
branch.publishStateEntered("Task", "TaskStateEntered", null);
|
||||
|
||||
assertEquals("Task", branch.abandonInState());
|
||||
branch.publishStateExited("TaskStateExited", null);
|
||||
|
||||
assertEquals(List.of("TaskStateEntered"), typesOf(history));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStateThatExitedBeforeTheCutIsNotReported() {
|
||||
List<HistoryEvent> history = new ArrayList<>();
|
||||
HistoryChain branch = HistoryChain.of(history).fork();
|
||||
branch.publishStateEntered("Task", "TaskStateEntered", null);
|
||||
branch.publishStateExited("TaskStateExited", null);
|
||||
|
||||
assertNull(branch.abandonInState());
|
||||
assertEquals(List.of("TaskStateEntered", "TaskStateExited"), typesOf(history));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTaskThatEndsItsBranchBeforeTheCutIsNotReportedTwice() {
|
||||
List<HistoryEvent> history = new ArrayList<>();
|
||||
HistoryChain branch = HistoryChain.of(history).fork();
|
||||
branch.publishStateEntered("Task", "TaskStateEntered", null);
|
||||
branch.leaveStateAside("TaskStateAborted", null);
|
||||
|
||||
assertNull(branch.abandonInState());
|
||||
assertEquals(List.of("TaskStateEntered", "TaskStateAborted"), typesOf(history));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTaskCutBeforeItEndsItsBranchIsReportedByTheCutOnly() {
|
||||
List<HistoryEvent> history = new ArrayList<>();
|
||||
HistoryChain branch = HistoryChain.of(history).fork();
|
||||
branch.publishStateEntered("Task", "TaskStateEntered", null);
|
||||
|
||||
assertEquals("Task", branch.abandonInState());
|
||||
branch.leaveStateAside("TaskStateAborted", null);
|
||||
|
||||
assertEquals(List.of("TaskStateEntered"), typesOf(history));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCutRacingAStateNeverDisagreesWithTheRecordedEvents() throws Exception {
|
||||
for (int round = 0; round < 2_000; round++) {
|
||||
List<HistoryEvent> history = Collections.synchronizedList(new ArrayList<>());
|
||||
HistoryChain branch = HistoryChain.of(history).fork();
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
Thread worker = new Thread(() -> {
|
||||
try {
|
||||
start.await();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
branch.publishStateEntered("Task", "TaskStateEntered", null);
|
||||
branch.publishStateExited("TaskStateExited", null);
|
||||
});
|
||||
worker.start();
|
||||
start.countDown();
|
||||
String reported = branch.abandonInState();
|
||||
worker.join();
|
||||
|
||||
List<String> types = typesOf(history);
|
||||
boolean cutMidState = types.contains("TaskStateEntered") && !types.contains("TaskStateExited");
|
||||
assertEquals(cutMidState, "Task".equals(reported), "round " + round + ": " + reported + " with " + types);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> typesOf(List<HistoryEvent> history) {
|
||||
synchronized (history) {
|
||||
return history.stream().map(HistoryEvent::getType).toList();
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -160,7 +160,7 @@ class StepFunctionsTimeoutSecondsIntegrationTest {
|
||||
@Test
|
||||
void stateMachineTimeoutSecondsCutsTheWaitForANestedExecution() throws Exception {
|
||||
// The child sleeps far past the parent's budget. The parent ends TIMED_OUT where its budget
|
||||
// runs out; the child keeps running, since nothing in ASL propagates the parent's timeout.
|
||||
// runs out, and the child is aborted with it, as AWS does (measured: ABORTED, no error).
|
||||
String childArn = createStateMachine("nested-child", """
|
||||
{
|
||||
"StartAt": "Linger",
|
||||
@@ -193,6 +193,16 @@ class StepFunctionsTimeoutSecondsIntegrationTest {
|
||||
JsonNode events = mapper.readTree(getExecutionHistory(execArn).body().asString()).path("events");
|
||||
assertEquals("ExecutionTimedOut", events.get(events.size() - 1).path("type").asText(),
|
||||
"history was " + events);
|
||||
Response children = given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.ListExecutions")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"stateMachineArn": "%s"}
|
||||
""".formatted(childArn))
|
||||
.when()
|
||||
.post("/");
|
||||
assertEquals(List.of("ABORTED"), children.jsonPath().getList("executions.status"),
|
||||
children.body().asString());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user