mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
perf(stepfunctions): wake nested waits on execution status changes (#6513)
This commit is contained in:
1 parent
985a2ea949
commit
fe928d67ab
8 files changed
+634
-67
No files matched your search
+7
-1
@@ -119,6 +119,7 @@ final class AslExecutorFixture {
|
||||
private LambdaTaskAuthorizer lambdaTaskAuthorizer;
|
||||
private Duration expressMaxExecutionTime;
|
||||
private LongSupplier nanoTime;
|
||||
private AslExecutor.NestedWaiter nestedWaiter;
|
||||
private EmrTaskInvoker emrTaskInvoker;
|
||||
private EmrServerlessTaskInvoker emrServerlessTaskInvoker;
|
||||
|
||||
@@ -270,6 +271,11 @@ final class AslExecutorFixture {
|
||||
return this;
|
||||
}
|
||||
|
||||
Builder nestedWaiter(AslExecutor.NestedWaiter nestedWaiter) {
|
||||
this.nestedWaiter = nestedWaiter;
|
||||
return this;
|
||||
}
|
||||
|
||||
Builder nanoTime(LongSupplier nanoTime) {
|
||||
this.nanoTime = nanoTime;
|
||||
return this;
|
||||
@@ -294,7 +300,7 @@ final class AslExecutorFixture {
|
||||
jsonataEvaluator != null ? jsonataEvaluator : new JsonataEvaluator(objectMapper),
|
||||
sfnService, config, vertx, customResourceLiveness, clock, sleeper, maxWaitSeconds,
|
||||
redshiftDataHandler, serviceRegistry, null, lambdaTaskAuthorizer, expressMaxExecutionTime,
|
||||
nanoTime, null, emrTaskInvoker, emrServerlessTaskInvoker);
|
||||
nanoTime, null, emrTaskInvoker, emrServerlessTaskInvoker, nestedWaiter);
|
||||
}
|
||||
}
|
||||
}
|
||||
+246
-22
@@ -3,25 +3,39 @@ package io.github.hectorvent.floci.services.stepfunctions;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.ExecutionStatusSubscription;
|
||||
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 org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.LongSupplier;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
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.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -48,6 +62,7 @@ class AslExecutorNestedSyncTimeoutTest {
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private StepFunctionsService sfnService;
|
||||
private List<HistoryEvent> history;
|
||||
private AslExecutor.NestedWaiter nestedWaiter;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -86,23 +101,24 @@ class AslExecutorNestedSyncTimeoutTest {
|
||||
verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void syncIsNotCappedByAPollCountWhenNoTimeoutSecondsIsDeclared() throws Exception {
|
||||
AtomicInteger polls = new AtomicInteger();
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {".sync", ".sync:2"})
|
||||
void syncCompletionDoesNotDependOnPolling(String mode) throws Exception {
|
||||
AtomicLong nanos = new AtomicLong();
|
||||
when(sfnService.describeExecution(CHILD_ARN)).thenAnswer(invocation -> {
|
||||
if (polls.incrementAndGet() < 700) {
|
||||
return child("RUNNING");
|
||||
}
|
||||
nanos.addAndGet(TimeUnit.MILLISECONDS.toNanos(350));
|
||||
Execution done = child("SUCCEEDED");
|
||||
done.setOutput("{\"answer\":42}");
|
||||
return done;
|
||||
});
|
||||
|
||||
Execution execution = run(newExecutor(nanos -> { }), ".sync", 0, false);
|
||||
Execution execution = run(newExecutor(pause -> {
|
||||
throw new AssertionError("Nested execution completion must not use a polling sleep");
|
||||
}, nanos::get), mode, 0, false, 0, true);
|
||||
|
||||
assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause());
|
||||
assertEquals(700, polls.get());
|
||||
assertTrue(objectMapper.readTree(execution.getOutput()).path("Output").asText().contains("42"));
|
||||
assertEquals(TimeUnit.MILLISECONDS.toNanos(350), nanos.get());
|
||||
assertTrue(objectMapper.readTree(execution.getOutput()).path("Output").toString().contains("42"));
|
||||
verify(sfnService, never()).stopExecution(any(), any(), any());
|
||||
}
|
||||
|
||||
@@ -120,18 +136,19 @@ class AslExecutorNestedSyncTimeoutTest {
|
||||
|
||||
@Test
|
||||
void stopExecutionOnTheParentEndsTheWaitAndAbortsTheChild() {
|
||||
AtomicInteger parentReads = new AtomicInteger();
|
||||
when(sfnService.describeExecution(PARENT_ARN))
|
||||
.thenAnswer(invocation -> parent(parentReads.incrementAndGet() < 3 ? "RUNNING" : "ABORTED"));
|
||||
Execution parent = parent("RUNNING");
|
||||
when(sfnService.describeExecution(PARENT_ARN)).thenReturn(parent);
|
||||
AtomicInteger childPolls = new AtomicInteger();
|
||||
when(sfnService.describeExecution(CHILD_ARN)).thenAnswer(invocation -> {
|
||||
childPolls.incrementAndGet();
|
||||
parent.setStatus("ABORTED");
|
||||
return child("RUNNING");
|
||||
});
|
||||
|
||||
run(newExecutor(nanos -> { }), ".sync", 0, false);
|
||||
run(newExecutor(nanos -> { throw new AssertionError("Parent cancellation must notify the wait"); }),
|
||||
".sync", 0, false);
|
||||
|
||||
assertEquals(2, childPolls.get(), "polling stops as soon as the parent reads ABORTED");
|
||||
assertEquals(1, childPolls.get(), "the parent cancellation wakes the wait without rereading its child");
|
||||
verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
|
||||
List<String> types = history.stream().map(HistoryEvent::getType).toList();
|
||||
assertTrue(types.stream().noneMatch(type -> type.equals("TaskTimedOut")
|
||||
@@ -139,6 +156,186 @@ class AslExecutorNestedSyncTimeoutTest {
|
||||
&& !type.equals("ExecutionStarted")), "an aborted execution gets no terminal event from the worker: " + types);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {".sync", ".sync:2"})
|
||||
void childCompletionWakesAParkedParentWithoutPolling(String mode) throws Exception {
|
||||
Execution live = child("RUNNING");
|
||||
when(sfnService.startExecution(any(), any(), any(), any())).thenReturn(live);
|
||||
CountDownLatch firstRead = new CountDownLatch(1);
|
||||
AtomicReference<Thread> waitingThread = new AtomicReference<>();
|
||||
when(sfnService.describeExecution(CHILD_ARN)).thenAnswer(invocation -> {
|
||||
waitingThread.set(Thread.currentThread());
|
||||
firstRead.countDown();
|
||||
return live;
|
||||
});
|
||||
AslExecutor executor = newExecutor(nanos -> {
|
||||
throw new AssertionError("Nested completion must not use the polling sleeper");
|
||||
});
|
||||
CompletableFuture<Execution> result = CompletableFuture.supplyAsync(
|
||||
() -> run(executor, mode, 60, false));
|
||||
try {
|
||||
assertTrue(firstRead.await(2, TimeUnit.SECONDS));
|
||||
await().atMost(Duration.ofSeconds(2))
|
||||
.until(() -> waitingThread.get().getState() == Thread.State.TIMED_WAITING);
|
||||
verify(sfnService, times(1)).describeExecution(CHILD_ARN);
|
||||
synchronized (live) {
|
||||
live.setOutput("{\"answer\":42}");
|
||||
live.setStopDate(2.0);
|
||||
live.setStatus("SUCCEEDED");
|
||||
}
|
||||
|
||||
Execution execution = result.get(2, TimeUnit.SECONDS);
|
||||
assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause());
|
||||
assertTrue(objectMapper.readTree(execution.getOutput()).path("Output").toString().contains("42"));
|
||||
verify(sfnService, times(2)).describeExecution(CHILD_ARN);
|
||||
verify(sfnService, never()).stopExecution(any(), any(), any());
|
||||
} finally {
|
||||
if (!result.isDone() && waitingThread.get() != null) {
|
||||
waitingThread.get().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearCancelsAnActiveNestedWaitAndAbortsItsChild() {
|
||||
AslExecutor executor = newExecutor(nanos -> {
|
||||
throw new AssertionError("Reset must notify the wait");
|
||||
});
|
||||
when(sfnService.describeExecution(CHILD_ARN)).thenAnswer(invocation -> {
|
||||
executor.clearNestedExecutionWaits();
|
||||
return child("RUNNING");
|
||||
});
|
||||
|
||||
Execution execution = run(executor, ".sync", 0, false);
|
||||
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
assertEquals("States.TaskFailed", execution.getError());
|
||||
verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clearDuringChildStartCannotLeaveAnUnregisteredWait() {
|
||||
AslExecutor executor = newExecutor(nanos -> {
|
||||
throw new AssertionError("Reset during submission must not start polling");
|
||||
});
|
||||
when(sfnService.startExecution(any(), any(), any(), any())).thenAnswer(invocation -> {
|
||||
executor.clearNestedExecutionWaits();
|
||||
return child("RUNNING");
|
||||
});
|
||||
|
||||
Execution execution = run(executor, ".sync:2", 0, false);
|
||||
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
assertEquals("States.TaskFailed", execution.getError());
|
||||
verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {".sync", ".sync:2"})
|
||||
void clearDuringInputEncodingCancelsTheNestedWait(String mode) throws Exception {
|
||||
ObjectMapper mapper = spy(objectMapper);
|
||||
AslExecutor executor = newExecutor(nanos -> {
|
||||
throw new AssertionError("Reset during input encoding must not start polling");
|
||||
}, System::nanoTime, mapper);
|
||||
AtomicInteger resets = new AtomicInteger();
|
||||
JsonNode childInput = objectMapper.readTree("{\"resetDuringEncoding\":true}");
|
||||
doAnswer(invocation -> {
|
||||
resets.incrementAndGet();
|
||||
executor.clearNestedExecutionWaits();
|
||||
return invocation.callRealMethod();
|
||||
}).when(mapper).writeValueAsString(eq(childInput));
|
||||
when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child("SUCCEEDED"));
|
||||
|
||||
Execution execution = run(executor, mode, 0, false, 0, false,
|
||||
", \"Input\": {\"resetDuringEncoding\":true}");
|
||||
|
||||
assertEquals(1, resets.get(), "reset occurs while encoding the child's input");
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
assertEquals("States.TaskFailed", execution.getError());
|
||||
verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {".sync", ".sync:2"})
|
||||
@Timeout(5)
|
||||
void injectedClockReachesNestedTaskDeadline(String mode) {
|
||||
AtomicLong nanos = new AtomicLong();
|
||||
AtomicInteger waits = new AtomicInteger();
|
||||
nestedWaiter = (subscription, observed, remaining) -> {
|
||||
assertEquals(TimeUnit.SECONDS.toNanos(60), remaining);
|
||||
waits.incrementAndGet();
|
||||
nanos.addAndGet(remaining);
|
||||
};
|
||||
when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child("RUNNING"));
|
||||
|
||||
Execution execution = run(newExecutor(pause -> {
|
||||
throw new AssertionError("Nested waits must not poll through the sleeper");
|
||||
}, nanos::get), mode, 60, true);
|
||||
|
||||
assertEquals(1, waits.get());
|
||||
assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause());
|
||||
assertTrue(history.stream().anyMatch(event -> "TaskTimedOut".equals(event.getType())));
|
||||
verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {".sync", ".sync:2"})
|
||||
@Timeout(5)
|
||||
void injectedClockReachesParentDeadlineBeforeNestedTaskDeadline(String mode) {
|
||||
AtomicLong nanos = new AtomicLong();
|
||||
AtomicInteger waits = new AtomicInteger();
|
||||
nestedWaiter = (subscription, observed, remaining) -> {
|
||||
assertEquals(TimeUnit.SECONDS.toNanos(30), remaining);
|
||||
waits.incrementAndGet();
|
||||
nanos.addAndGet(remaining);
|
||||
};
|
||||
when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child("RUNNING"));
|
||||
|
||||
Execution execution = run(newExecutor(pause -> {
|
||||
throw new AssertionError("Nested waits must not poll through the sleeper");
|
||||
}, nanos::get), mode, 60, false, 30);
|
||||
|
||||
assertEquals(1, waits.get());
|
||||
assertEquals("TIMED_OUT", execution.getStatus());
|
||||
assertTrue(history.stream().noneMatch(event -> "TaskTimedOut".equals(event.getType())));
|
||||
verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {".sync", ".sync:2"})
|
||||
void clockAdvanceOnAParkedWaitIsCheckedAfterWake(String mode) throws Exception {
|
||||
AtomicLong nanos = new AtomicLong();
|
||||
AtomicReference<ExecutionStatusSubscription> parked = new AtomicReference<>();
|
||||
AtomicReference<Thread> waiter = new AtomicReference<>();
|
||||
nestedWaiter = (subscription, observed, remaining) -> {
|
||||
parked.set(subscription);
|
||||
waiter.set(Thread.currentThread());
|
||||
subscription.awaitChange(observed, remaining);
|
||||
};
|
||||
when(sfnService.describeExecution(CHILD_ARN)).thenReturn(child("RUNNING"));
|
||||
AslExecutor executor = newExecutor(pause -> {
|
||||
throw new AssertionError("Nested waits must not poll through the sleeper");
|
||||
}, nanos::get);
|
||||
CompletableFuture<Execution> result = CompletableFuture.supplyAsync(
|
||||
() -> run(executor, mode, 60, true));
|
||||
try {
|
||||
await().atMost(Duration.ofSeconds(2)).until(() -> waiter.get() != null
|
||||
&& waiter.get().getState() == Thread.State.TIMED_WAITING);
|
||||
ExecutionStatusSubscription subscription = parked.get();
|
||||
synchronized (subscription) {
|
||||
nanos.set(TimeUnit.SECONDS.toNanos(60));
|
||||
subscription.notifyAll();
|
||||
}
|
||||
Execution execution = result.get(2, TimeUnit.SECONDS);
|
||||
assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause());
|
||||
assertTrue(history.stream().anyMatch(event -> "TaskTimedOut".equals(event.getType())));
|
||||
verify(sfnService).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
|
||||
} finally {
|
||||
executor.clearNestedExecutionWaits();
|
||||
result.get(2, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
private static Execution child(String status) {
|
||||
Execution current = new Execution();
|
||||
current.setExecutionArn(CHILD_ARN);
|
||||
@@ -156,15 +353,25 @@ class AslExecutorNestedSyncTimeoutTest {
|
||||
return current;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private AslExecutor newExecutor(AslExecutor.Sleeper sleeper) {
|
||||
return newExecutor(sleeper, System::nanoTime);
|
||||
}
|
||||
|
||||
private AslExecutor newExecutor(AslExecutor.Sleeper sleeper, LongSupplier nanoTime) {
|
||||
return newExecutor(sleeper, nanoTime, objectMapper);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private AslExecutor newExecutor(AslExecutor.Sleeper sleeper, LongSupplier nanoTime, ObjectMapper mapper) {
|
||||
Instance<StepFunctionsService> instance = mock(Instance.class);
|
||||
when(instance.get()).thenReturn(sfnService);
|
||||
return AslExecutorFixture.builder()
|
||||
.objectMapper(objectMapper)
|
||||
.objectMapper(mapper)
|
||||
.sfnService(instance)
|
||||
.customResourceLiveness(null)
|
||||
.sleeper(sleeper)
|
||||
.nanoTime(nanoTime)
|
||||
.nestedWaiter(nestedWaiter)
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -173,7 +380,17 @@ class AslExecutorNestedSyncTimeoutTest {
|
||||
}
|
||||
|
||||
private Execution run(AslExecutor executor, String mode, int timeoutSeconds, boolean catchTimeout,
|
||||
int executionTimeoutSeconds) {
|
||||
int executionTimeoutSeconds) {
|
||||
return run(executor, mode, timeoutSeconds, catchTimeout, executionTimeoutSeconds, false);
|
||||
}
|
||||
|
||||
private Execution run(AslExecutor executor, String mode, int timeoutSeconds, boolean catchTimeout,
|
||||
int executionTimeoutSeconds, boolean asynchronous) {
|
||||
return run(executor, mode, timeoutSeconds, catchTimeout, executionTimeoutSeconds, asynchronous, "");
|
||||
}
|
||||
|
||||
private Execution run(AslExecutor executor, String mode, int timeoutSeconds, boolean catchTimeout,
|
||||
int executionTimeoutSeconds, boolean asynchronous, String additionalParameters) {
|
||||
String timeout = timeoutSeconds > 0 ? "\"TimeoutSeconds\": %d,".formatted(timeoutSeconds) : "";
|
||||
String catcher = catchTimeout
|
||||
? "\"Catch\": [{\"ErrorEquals\": [\"States.Timeout\"], \"Next\": \"Recover\"}],"
|
||||
@@ -191,13 +408,13 @@ class AslExecutorNestedSyncTimeoutTest {
|
||||
"Resource": "arn:aws:states:::states:startExecution%s",
|
||||
%s
|
||||
%s
|
||||
"Parameters": { "StateMachineArn": "%s" },
|
||||
"Parameters": { "StateMachineArn": "%s"%s },
|
||||
"End": true
|
||||
},
|
||||
"Recover": { "Type": "Pass", "End": true }
|
||||
}
|
||||
}
|
||||
""".formatted(budget, mode, timeout, catcher, CHILD_SM_ARN);
|
||||
""".formatted(budget, mode, timeout, catcher, CHILD_SM_ARN, additionalParameters);
|
||||
|
||||
StateMachine stateMachine = new StateMachine();
|
||||
stateMachine.setName("parent");
|
||||
@@ -211,8 +428,15 @@ class AslExecutorNestedSyncTimeoutTest {
|
||||
execution.setStateMachineArn(stateMachine.getStateMachineArn());
|
||||
execution.setInput("{}");
|
||||
|
||||
history = new ArrayList<>();
|
||||
executor.executeSync(stateMachine, execution, history, (updated, events) -> { });
|
||||
history = new CopyOnWriteArrayList<>();
|
||||
if (asynchronous) {
|
||||
executor.executeAsync(stateMachine, execution, history, (updated, events) -> { });
|
||||
await().atMost(Duration.ofSeconds(10))
|
||||
.until(() -> history.stream().anyMatch(event -> event.getType().startsWith("Execution")
|
||||
&& !event.getType().equals("ExecutionStarted")));
|
||||
} else {
|
||||
executor.executeSync(stateMachine, execution, history, (updated, events) -> { });
|
||||
}
|
||||
return execution;
|
||||
}
|
||||
}
|
||||
+16
-7
@@ -46,6 +46,7 @@ import static org.mockito.Mockito.when;
|
||||
* <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.
|
||||
*/
|
||||
@Timeout(20)
|
||||
class AslExecutorParallelCutTest {
|
||||
|
||||
private static final String REGION = "us-east-2";
|
||||
@@ -105,6 +106,7 @@ class AslExecutorParallelCutTest {
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private StepFunctionsService sfnService;
|
||||
private List<HistoryEvent> history;
|
||||
private Runnable nestedWaitStarted = () -> { };
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -376,20 +378,23 @@ class AslExecutorParallelCutTest {
|
||||
|
||||
/**
|
||||
* 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
|
||||
* threads have entered a nested status wait or a longer Wait; every
|
||||
* other sleep is real, so the cut interrupts it.
|
||||
*/
|
||||
private static AslExecutor.Sleeper sleeper(int waitingBranches) {
|
||||
private AslExecutor.Sleeper sleeper(int waitingBranches) {
|
||||
CountDownLatch othersWaiting = new CountDownLatch(waitingBranches);
|
||||
Set<Thread> seen = ConcurrentHashMap.newKeySet();
|
||||
return nanos -> {
|
||||
if (nanos == PAUSE_NANOS) {
|
||||
othersWaiting.await();
|
||||
return;
|
||||
}
|
||||
nestedWaitStarted = () -> {
|
||||
if (seen.add(Thread.currentThread())) {
|
||||
othersWaiting.countDown();
|
||||
}
|
||||
};
|
||||
return nanos -> {
|
||||
if (nanos == PAUSE_NANOS) {
|
||||
assertTrue(othersWaiting.await(5, TimeUnit.SECONDS), "other branches must enter their waits");
|
||||
return;
|
||||
}
|
||||
nestedWaitStarted.run();
|
||||
TimeUnit.NANOSECONDS.sleep(nanos);
|
||||
};
|
||||
}
|
||||
@@ -403,6 +408,10 @@ class AslExecutorParallelCutTest {
|
||||
.sfnService(instance)
|
||||
.customResourceLiveness(null)
|
||||
.sleeper(sleeper)
|
||||
.nestedWaiter((subscription, observed, nanos) -> {
|
||||
nestedWaitStarted.run();
|
||||
subscription.awaitChange(observed, nanos);
|
||||
})
|
||||
.maxWaitSeconds(30)
|
||||
.build();
|
||||
}
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions.model;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ExecutionStatusSubscriptionTest {
|
||||
@Test
|
||||
void completionBeforeRegistrationDoesNotPark() throws Exception {
|
||||
Execution child = new Execution();
|
||||
child.setStatus("SUCCEEDED");
|
||||
try (ExecutionStatusSubscription subscription = new ExecutionStatusSubscription(child, null)) {
|
||||
assertTrue(subscription.version() > 0);
|
||||
assertNull(registrations(child));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void completionBetweenStateReadAndParkingCannotBeLost() throws Exception {
|
||||
Execution child = new Execution();
|
||||
try (ExecutionStatusSubscription subscription = new ExecutionStatusSubscription(child, null)) {
|
||||
long observed = subscription.version();
|
||||
child.setOutput("{\"answer\":42}");
|
||||
child.setStatus("SUCCEEDED");
|
||||
assertTimeoutPreemptively(Duration.ofSeconds(1),
|
||||
() -> assertTrue(subscription.awaitChange(observed, TimeUnit.MINUTES.toNanos(1))));
|
||||
assertEquals("{\"answer\":42}", child.getOutput());
|
||||
assertNull(registrations(child));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void parentTerminationWakesTheWaitAndCloseReleasesBothRegistrations() throws Exception {
|
||||
Execution child = new Execution();
|
||||
Execution parent = new Execution();
|
||||
try (ExecutionStatusSubscription subscription = new ExecutionStatusSubscription(child, parent);
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor()) {
|
||||
long observed = subscription.version();
|
||||
CountDownLatch entered = new CountDownLatch(1);
|
||||
CompletableFuture<Boolean> result = CompletableFuture.supplyAsync(() -> {
|
||||
entered.countDown();
|
||||
try {
|
||||
return subscription.awaitChange(observed, TimeUnit.SECONDS.toNanos(5));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}, executor);
|
||||
assertTrue(entered.await(1, TimeUnit.SECONDS));
|
||||
parent.setStatus("ABORTED");
|
||||
assertTrue(result.get(1, TimeUnit.SECONDS));
|
||||
assertEquals("RUNNING", child.getStatus());
|
||||
}
|
||||
assertNull(registrations(child));
|
||||
assertNull(registrations(parent));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unrelatedExecutionDoesNotChangeTheObservedVersion() throws Exception {
|
||||
Execution child = new Execution();
|
||||
Execution parent = new Execution();
|
||||
try (ExecutionStatusSubscription subscription = new ExecutionStatusSubscription(child, parent)) {
|
||||
long observed = subscription.version();
|
||||
new Execution().setStatus("SUCCEEDED");
|
||||
assertEquals(observed, subscription.version());
|
||||
assertFalse(subscription.awaitChange(observed, 0));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void timeoutAndCancellationDoNotManufactureTerminalStatus() throws Exception {
|
||||
Execution child = new Execution();
|
||||
Execution parent = new Execution();
|
||||
try (ExecutionStatusSubscription subscription = new ExecutionStatusSubscription(child, parent)) {
|
||||
long observed = subscription.version();
|
||||
assertFalse(subscription.awaitChange(observed, TimeUnit.MILLISECONDS.toNanos(1)));
|
||||
subscription.cancel();
|
||||
assertTrue(subscription.cancelled());
|
||||
assertTrue(subscription.awaitChange(observed, TimeUnit.MINUTES.toNanos(1)));
|
||||
assertEquals("RUNNING", child.getStatus());
|
||||
assertEquals("RUNNING", parent.getStatus());
|
||||
}
|
||||
assertNull(registrations(child));
|
||||
assertNull(registrations(parent));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wakeWithoutStatusChangeReturnsToTheExecutorsDeadlineClock() throws Exception {
|
||||
Execution child = new Execution();
|
||||
try (ExecutionStatusSubscription subscription = new ExecutionStatusSubscription(child, null);
|
||||
ExecutorService executor = Executors.newSingleThreadExecutor()) {
|
||||
AtomicReference<Thread> waiter = new AtomicReference<>();
|
||||
CompletableFuture<Boolean> result = CompletableFuture.supplyAsync(() -> {
|
||||
waiter.set(Thread.currentThread());
|
||||
try {
|
||||
return subscription.awaitChange(subscription.version(), TimeUnit.MINUTES.toNanos(1));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}, executor);
|
||||
try {
|
||||
await().atMost(Duration.ofSeconds(2)).until(() -> waiter.get() != null
|
||||
&& waiter.get().getState() == Thread.State.TIMED_WAITING);
|
||||
synchronized (subscription) {
|
||||
subscription.notifyAll();
|
||||
}
|
||||
assertFalse(result.get(1, TimeUnit.SECONDS));
|
||||
assertEquals("RUNNING", child.getStatus());
|
||||
} finally {
|
||||
subscription.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateTargetsAndRepeatedCloseLeaveNoRegistration() throws Exception {
|
||||
Execution child = new Execution();
|
||||
ExecutionStatusSubscription subscription = new ExecutionStatusSubscription(child, child);
|
||||
subscription.close();
|
||||
subscription.close();
|
||||
assertNull(registrations(child));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ephemeralRegistrationsAreAbsentFromPersistedExecution() throws Exception {
|
||||
Execution child = new Execution();
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
String before = mapper.writeValueAsString(child);
|
||||
try (ExecutionStatusSubscription subscription = new ExecutionStatusSubscription(child, null)) {
|
||||
assertEquals(before, mapper.writeValueAsString(child));
|
||||
Execution restored = mapper.readValue(before, Execution.class);
|
||||
assertNull(registrations(restored));
|
||||
assertEquals("RUNNING", restored.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private static Object registrations(Execution execution) throws Exception {
|
||||
Field field = Execution.class.getDeclaredField("statusSubscriptions");
|
||||
field.setAccessible(true);
|
||||
return field.get(execution);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user