mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(stepfunctions): record the iterations a failing Map iteration cuts, and the state each was in (#4724)
* fix(stepfunctions): record the iterations a failing Map iteration cuts, and the state each was in AWS records, for each iteration an inline Map failure cuts, a MapIterationAborted and then the TaskStateAborted or WaitStateAborted of the state it was in, all chained to the failing iteration's last event and ahead of MapIterationFailed and MapStateFailed. Floci cancelled the iterations and recorded nothing for them. MapIterationScheduler cancelled the in-flight iterations without knowing their chains, so the Map saw them only after they had left their states. It now calls back with each in-flight index before cancelling, and the Map reads and cuts each one in one step through abandonInState, as the Parallel does. The failing iteration's MapIterationFailed is recorded by the Map after the cut, so the aborted events come first; its previousEventId is unchanged. Closes #4722 * fix(stepfunctions): never report a Map iteration both ended and cut The scheduler names every iteration it has not yet taken off its queue, so an iteration that finished after the failing one was dequeued was cut as well and recorded MapIterationAborted after its own MapIterationSucceeded. The iteration's end event is now published under the chain's lock together with an ended marker, and the cut reads that marker in the same step it reads the state, so an iteration is reported either ended or cut, never both. * fix(stepfunctions): record the iterations a Map failure cut only with its MapIterationFailed A States.Runtime failure records no MapIterationFailed. When it was a declared tolerance that failure exceeded, the Map ended with States.ExceedToleratedFailureThreshold instead, which passed the check for the cut iterations, so they were recorded aborted without the MapIterationFailed of the iteration that cut them. Both now follow the one condition. * fix(stepfunctions): record a cut Map iteration by the rule of the event it accompanies The cut iterations are recorded right before MapStateFailed and now follow its rule, that the failure ending the Map is not States.Runtime, while MapIterationFailed keeps the iteration's own. Tying both to the iteration's condition had dropped the cut iterations for an ItemSelector that fails before its iteration starts, which has nothing to report itself but still cuts the others and still records MapStateFailed. An iteration is also reported cut only when its MapIterationStarted is recorded: the start is published under the chain's lock with a started marker, read by the cut in the same step, so an iteration cut while its ItemSelector was still being evaluated records neither a start nor an abort. --------- Co-authored-by: mitsukado-shinagawa <mitsukado-shinagawa@users.noreply.github.com>
This commit is contained in:
1 parent
fd094aee05
commit
955c11dc56
8 files changed
+574
-27
No files matched your search
+134
-2
@@ -27,6 +27,7 @@ import org.junit.jupiter.api.Timeout;
|
||||
import java.time.Clock;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
@@ -87,14 +88,21 @@ class AslExecutorParallelCutTest {
|
||||
{"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}}}""";
|
||||
/** An inline Map whose "fail" item runs the failing branch and whose other items run the nested one. */
|
||||
/**
|
||||
* An inline Map whose "fail" item runs the failing branch, whose "wait" item runs the long Wait,
|
||||
* whose "done" item is a Pass, and whose other items run the nested Task.
|
||||
*/
|
||||
private static final String MAP_WITH_A_FAILING_ITERATION = """
|
||||
{"Type":"Map","End":true,"ItemProcessor":{"ProcessorConfig":{"Mode":"INLINE"},
|
||||
"StartAt":"Route","States":{
|
||||
"Route":{"Type":"Choice","Default":"Nest",
|
||||
"Choices":[{"Variable":"$.kind","StringEquals":"fail","Next":"Pause"}]},
|
||||
"Choices":[{"Variable":"$.kind","StringEquals":"fail","Next":"Pause"},
|
||||
{"Variable":"$.kind","StringEquals":"wait","Next":"Long"},
|
||||
{"Variable":"$.kind","StringEquals":"done","Next":"Done"}]},
|
||||
"Pause":{"Type":"Wait","Seconds":1,"Next":"Boom"},
|
||||
"Boom":{"Type":"Fail","Error":"Boom","Cause":"sibling failed"},
|
||||
"Long":{"Type":"Wait","Seconds":20,"End":true},
|
||||
"Done":{"Type":"Pass","End":true},
|
||||
"Nest":{"Type":"Task","Resource":"arn:aws:states:::states:startExecution.sync:2",
|
||||
"Parameters":{"StateMachineArn":"%s"},"End":true}}}}""".formatted(CHILD_SM_ARN);
|
||||
private static final String SLOW_RESULT_BRANCH = """
|
||||
@@ -225,6 +233,130 @@ class AslExecutorParallelCutTest {
|
||||
verify(sfnService, timeout(5_000)).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
|
||||
}
|
||||
|
||||
/**
|
||||
* Measured on AWS: a failing iteration records, for each iteration it cuts, MapIterationAborted
|
||||
* and then the *StateAborted of the state it was in, all chained to the failing iteration's last
|
||||
* event and ahead of MapIterationFailed and MapStateFailed, which point at that same event.
|
||||
*/
|
||||
@Test
|
||||
void aMapIterationCutInsideItsTaskRecordsMapIterationAbortedAndTaskStateAborted() {
|
||||
Execution execution = run(MAP_WITH_A_FAILING_ITERATION, sleeper(1), 0,
|
||||
"[{\"kind\":\"nest\"},{\"kind\":\"fail\"}]");
|
||||
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
HistoryEvent failure = eventOfType("FailStateEntered");
|
||||
List<HistoryEvent> tail = history.subList(history.indexOf(failure) + 1, history.size());
|
||||
assertEquals(List.of("MapIterationAborted", "TaskStateAborted", "MapIterationFailed", "MapStateFailed",
|
||||
"ExecutionFailed"), tail.stream().map(HistoryEvent::getType).toList(), types().toString());
|
||||
for (HistoryEvent event : tail.subList(0, 4)) {
|
||||
assertEquals(failure.getId(), event.getPreviousEventId().longValue(), event.getType());
|
||||
}
|
||||
assertEquals(Map.of("name", "P", "index", 0), tail.get(0).getDetails());
|
||||
assertNull(tail.get(1).getDetails());
|
||||
assertEquals(Map.of("name", "P", "index", 1), tail.get(2).getDetails());
|
||||
assertEquals(tail.get(3).getId(), tail.get(4).getPreviousEventId().longValue());
|
||||
verify(sfnService, timeout(5_000)).stopExecution(eq(CHILD_ARN), eq(ABORT_CAUSE), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMapIterationCutInsideItsWaitRecordsMapIterationAbortedAndWaitStateAborted() {
|
||||
Execution execution = run(MAP_WITH_A_FAILING_ITERATION, sleeper(1), 0,
|
||||
"[{\"kind\":\"fail\"},{\"kind\":\"wait\"}]");
|
||||
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
long failure = eventOfType("FailStateEntered").getId();
|
||||
HistoryEvent aborted = eventOfType("MapIterationAborted");
|
||||
assertEquals(Map.of("name", "P", "index", 1), aborted.getDetails());
|
||||
assertEquals(failure, aborted.getPreviousEventId().longValue());
|
||||
HistoryEvent waitAborted = eventOfType("WaitStateAborted");
|
||||
assertEquals(failure, waitAborted.getPreviousEventId().longValue());
|
||||
assertTrue(aborted.getId() < waitAborted.getId());
|
||||
assertTrue(waitAborted.getId() < eventOfType("MapIterationFailed").getId());
|
||||
assertEquals(List.of("Pause"), eventsOfType("WaitStateExited").stream()
|
||||
.map(event -> String.valueOf(event.getDetails().get("name"))).toList(), types().toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Each event follows the rule of the one it accompanies. A States.Runtime failure in an
|
||||
* iteration records no MapIterationFailed; when what ends the Map is the tolerance it exceeded,
|
||||
* MapStateFailed is recorded, and so are the iterations that failure cut, right before it.
|
||||
*/
|
||||
@Test
|
||||
void aRuntimeFailureThatExceedsTheToleranceRecordsTheOnesItCutButNotItself() {
|
||||
String map = MAP_WITH_A_FAILING_ITERATION.replace("\"Type\":\"Map\",", "\"Type\":\"Map\",\"ToleratedFailureCount\":0,")
|
||||
.replace("\"Default\":\"Nest\",", "");
|
||||
Execution execution = run(map, sleeper(1), 0, "[{\"kind\":\"wait\"},{\"kind\":\"nomatch\"}]");
|
||||
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
assertEquals("States.ExceedToleratedFailureThreshold", execution.getError());
|
||||
assertTrue(types().stream().noneMatch("MapIterationFailed"::equals), types().toString());
|
||||
int stateFailed = types().indexOf("MapStateFailed");
|
||||
assertEquals(List.of("MapIterationAborted", "WaitStateAborted"), types().subList(stateFailed - 2, stateFailed),
|
||||
types().toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* A States.Runtime failure that ends the Map records no MapStateFailed, and nothing for the
|
||||
* iterations it cut either.
|
||||
*/
|
||||
@Test
|
||||
void aRuntimeFailureThatEndsTheMapRecordsNothingForTheOnesItCut() {
|
||||
String map = MAP_WITH_A_FAILING_ITERATION.replace("\"Default\":\"Nest\",", "");
|
||||
Execution execution = run(map, sleeper(1), 0, "[{\"kind\":\"wait\"},{\"kind\":\"nomatch\"}]");
|
||||
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
assertEquals("States.Runtime", execution.getError());
|
||||
assertTrue(types().stream().noneMatch(type -> type.contains("Aborted") || type.endsWith("Failed")
|
||||
&& !type.equals("ExecutionFailed")), types().toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* An ItemSelector that fails does so before its iteration starts, so there is no
|
||||
* MapIterationFailed to record, but the Map fails with the expression's error and the
|
||||
* iterations it cut are recorded before MapStateFailed. Which state the other iteration had
|
||||
* reached by then is a race the test does not fix, so it asserts the invariant over many runs:
|
||||
* an iteration is recorded cut exactly when its start is recorded and its end is not.
|
||||
*/
|
||||
@Test
|
||||
void anItemSelectorFailureRecordsTheIterationsItCutOnlyOnceTheyStarted() {
|
||||
String map = """
|
||||
{"Type":"Map","End":true,"QueryLanguage":"JSONata","Items":"{% $states.input %}",
|
||||
"ItemSelector":{"kind":"{% $states.context.Map.Item.Value.kind %}",
|
||||
"v":"{% $states.context.Map.Item.Value.v %}"},
|
||||
"ItemProcessor":{"ProcessorConfig":{"Mode":"INLINE"},"StartAt":"Long","States":{
|
||||
"Long":{"Type":"Wait","Seconds":20,"End":true}}}}""";
|
||||
for (int round = 0; round < 40; round++) {
|
||||
Execution execution = run(map, nanos -> TimeUnit.NANOSECONDS.sleep(nanos), 0,
|
||||
"[{\"kind\":\"wait\",\"v\":1},{\"kind\":\"selector\"}]");
|
||||
|
||||
assertEquals("FAILED", execution.getStatus(), types().toString());
|
||||
assertEquals("States.QueryEvaluationError", execution.getError(), types().toString());
|
||||
assertTrue(types().contains("MapStateFailed"), types().toString());
|
||||
assertTrue(types().stream().noneMatch("MapIterationFailed"::equals), types().toString());
|
||||
boolean started = types().contains("MapIterationStarted");
|
||||
boolean ended = types().contains("MapIterationSucceeded");
|
||||
assertEquals(started && !ended, types().contains("MapIterationAborted"), "round " + round + ": " + types());
|
||||
boolean inWait = types().contains("WaitStateEntered") && !types().contains("WaitStateExited");
|
||||
assertEquals(started && !ended && inWait, types().contains("WaitStateAborted"), "round " + round + ": " + types());
|
||||
if (types().contains("MapIterationAborted")) {
|
||||
assertTrue(types().indexOf("MapIterationAborted") < types().indexOf("MapStateFailed"), types().toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMapIterationThatFinishedBeforeTheFailureRecordsNoAbortedEvent() {
|
||||
AslExecutor.Sleeper sleeper = nanos -> TimeUnit.MILLISECONDS.sleep(200);
|
||||
Execution execution = run(MAP_WITH_A_FAILING_ITERATION, sleeper, 0,
|
||||
"[{\"kind\":\"done\"},{\"kind\":\"fail\"}]");
|
||||
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
assertEquals(1, eventsOfType("MapIterationSucceeded").size(), types().toString());
|
||||
assertTrue(types().stream().noneMatch(type -> type.contains("Aborted")), types().toString());
|
||||
assertEquals(eventOfType("FailStateEntered").getId(),
|
||||
eventOfType("MapIterationFailed").getPreviousEventId().longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void executionBudgetCuttingTheParallelAbortsTheChildAndRecordsNoAbortedState() {
|
||||
Execution execution = run(parallel(NESTED_SYNC_BRANCH), 0, 1);
|
||||
|
||||
@@ -11,7 +11,9 @@ 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.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class HistoryChainTest {
|
||||
|
||||
@@ -95,6 +97,87 @@ class HistoryChainTest {
|
||||
assertEquals(List.of("TaskStateEntered"), typesOf(history));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIterationThatEndedBeforeTheCutIsReportedEndedAndNotCut() {
|
||||
List<HistoryEvent> history = new ArrayList<>();
|
||||
HistoryChain iteration = HistoryChain.of(history).fork();
|
||||
iteration.publishIterationStart("MapIterationStarted", null);
|
||||
iteration.publishStateEntered("Task", "TaskStateEntered", null);
|
||||
iteration.publishStateExited("TaskStateExited", null);
|
||||
iteration.publishIterationEnd("MapIterationSucceeded", null);
|
||||
|
||||
HistoryChain.IterationCut cut = iteration.abandonIteration();
|
||||
|
||||
assertTrue(cut.started());
|
||||
assertTrue(cut.ended());
|
||||
assertFalse(cut.recorded());
|
||||
assertNull(cut.stateType());
|
||||
assertEquals(List.of("MapIterationStarted", "TaskStateEntered", "TaskStateExited", "MapIterationSucceeded"),
|
||||
typesOf(history));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIterationCutBeforeItEndsIsReportedInItsStateAndRecordsNoEnd() {
|
||||
List<HistoryEvent> history = new ArrayList<>();
|
||||
HistoryChain iteration = HistoryChain.of(history).fork();
|
||||
iteration.publishIterationStart("MapIterationStarted", null);
|
||||
iteration.publishStateEntered("Task", "TaskStateEntered", null);
|
||||
|
||||
HistoryChain.IterationCut cut = iteration.abandonIteration();
|
||||
iteration.publishStateExited("TaskStateExited", null);
|
||||
iteration.publishIterationEnd("MapIterationSucceeded", null);
|
||||
|
||||
assertTrue(cut.recorded());
|
||||
assertFalse(cut.ended());
|
||||
assertEquals("Task", cut.stateType());
|
||||
assertEquals(List.of("MapIterationStarted", "TaskStateEntered"), typesOf(history));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIterationCutBeforeItStartsIsNotReportedAndRecordsNoStart() {
|
||||
List<HistoryEvent> history = new ArrayList<>();
|
||||
HistoryChain iteration = HistoryChain.of(history).fork();
|
||||
|
||||
HistoryChain.IterationCut cut = iteration.abandonIteration();
|
||||
iteration.publishIterationStart("MapIterationStarted", null);
|
||||
iteration.publishStateEntered("Task", "TaskStateEntered", null);
|
||||
|
||||
assertFalse(cut.started());
|
||||
assertFalse(cut.recorded());
|
||||
assertEquals(List.of(), typesOf(history));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCutRacingAnIterationNeverDisagreesWithItsRecordedStartAndEnd() throws Exception {
|
||||
for (int round = 0; round < 2_000; round++) {
|
||||
List<HistoryEvent> history = Collections.synchronizedList(new ArrayList<>());
|
||||
HistoryChain iteration = HistoryChain.of(history).fork();
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
Thread worker = new Thread(() -> {
|
||||
try {
|
||||
start.await();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
iteration.publishIterationStart("MapIterationStarted", null);
|
||||
iteration.publishStateEntered("Task", "TaskStateEntered", null);
|
||||
iteration.publishStateExited("TaskStateExited", null);
|
||||
iteration.publishIterationEnd("MapIterationSucceeded", null);
|
||||
});
|
||||
worker.start();
|
||||
start.countDown();
|
||||
HistoryChain.IterationCut cut = iteration.abandonIteration();
|
||||
worker.join();
|
||||
|
||||
List<String> types = typesOf(history);
|
||||
assertEquals(types.contains("MapIterationStarted"), cut.started(), "round " + round + ": " + cut + " with " + types);
|
||||
assertEquals(types.contains("MapIterationSucceeded"), cut.ended(), "round " + round + ": " + cut + " with " + types);
|
||||
boolean cutMidState = types.contains("TaskStateEntered") && !types.contains("TaskStateExited");
|
||||
assertEquals(cutMidState, "Task".equals(cut.stateType()), "round " + round + ": " + cut + " with " + types);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCutRacingAStateNeverDisagreesWithTheRecordedEvents() throws Exception {
|
||||
for (int round = 0; round < 2_000; round++) {
|
||||
|
||||
+59
@@ -5,6 +5,7 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -226,4 +227,62 @@ class MapIterationSchedulerTest {
|
||||
"the iterations still running should be interrupted once the deadline passes");
|
||||
}
|
||||
}
|
||||
@Test
|
||||
void namesEachInFlightIterationBeforeCancellingItOnFailure() throws Exception {
|
||||
CountDownLatch othersStarted = new CountDownLatch(2);
|
||||
CountDownLatch neverRelease = new CountDownLatch(1);
|
||||
CountDownLatch othersInterrupted = new CountDownLatch(2);
|
||||
List<Integer> cut = new CopyOnWriteArrayList<>();
|
||||
List<Integer> namedWhenInterrupted = new CopyOnWriteArrayList<>();
|
||||
|
||||
try (ExecutorService driver = Executors.newSingleThreadExecutor()) {
|
||||
Future<List<Integer>> execution = driver.submit(() -> MapIterationScheduler.execute(
|
||||
3, 3, index -> () -> {
|
||||
if (index == 1) {
|
||||
if (!othersStarted.await(2, TimeUnit.SECONDS)) {
|
||||
fail("the other iterations did not start");
|
||||
}
|
||||
throw new IllegalStateException("middle iteration failed");
|
||||
}
|
||||
othersStarted.countDown();
|
||||
try {
|
||||
neverRelease.await();
|
||||
return index;
|
||||
} catch (InterruptedException e) {
|
||||
if (cut.contains(index)) {
|
||||
namedWhenInterrupted.add(index);
|
||||
}
|
||||
othersInterrupted.countDown();
|
||||
throw e;
|
||||
}
|
||||
}, Long.MAX_VALUE, cut::add));
|
||||
|
||||
assertThrows(ExecutionException.class, () -> execution.get(2, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
assertEquals(List.of(0, 2), cut, "every in-flight iteration, in start order, never the failed one");
|
||||
assertTrue(othersInterrupted.await(2, TimeUnit.SECONDS));
|
||||
assertEquals(List.of(0, 2), namedWhenInterrupted.stream().sorted().toList(),
|
||||
"each was named before it was cancelled");
|
||||
}
|
||||
|
||||
@Test
|
||||
void namesNoIterationWhenTheDeadlineEndsTheRun() throws Exception {
|
||||
CountDownLatch neverRelease = new CountDownLatch(1);
|
||||
List<Integer> cut = new CopyOnWriteArrayList<>();
|
||||
|
||||
try (ExecutorService driver = Executors.newSingleThreadExecutor()) {
|
||||
Future<List<Integer>> execution = driver.submit(() -> MapIterationScheduler.execute(
|
||||
2, 2, index -> () -> {
|
||||
neverRelease.await();
|
||||
return index;
|
||||
}, System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(100), cut::add));
|
||||
|
||||
ExecutionException failure = assertThrows(ExecutionException.class,
|
||||
() -> execution.get(2, TimeUnit.SECONDS));
|
||||
assertEquals(TimeoutException.class, failure.getCause().getClass());
|
||||
}
|
||||
|
||||
assertEquals(List.of(), cut);
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* An inline {@code Map} iteration that fails cuts the other iterations, and the history records what
|
||||
* it cut the way AWS does (measured in ap-northeast-1 on 2026-09-30): a {@code MapIterationAborted}
|
||||
* and then the {@code *StateAborted} of the state each cut iteration was in, all chained to the
|
||||
* failing iteration's last event, ahead of {@code MapIterationFailed} and {@code MapStateFailed}.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class StepFunctionsMapIterationFailureIntegrationTest {
|
||||
|
||||
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 ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailingIterationRecordsTheIterationItCutAndTheWaitItWasIn() throws Exception {
|
||||
String smArn = createStateMachine("map-iteration-cut", """
|
||||
{
|
||||
"StartAt": "M",
|
||||
"States": {
|
||||
"M": {
|
||||
"Type": "Map",
|
||||
"End": true,
|
||||
"ItemsPath": "$.items",
|
||||
"ItemProcessor": {
|
||||
"ProcessorConfig": {"Mode": "INLINE"},
|
||||
"StartAt": "Route",
|
||||
"States": {
|
||||
"Route": {"Type": "Choice", "Default": "Long",
|
||||
"Choices": [{"Variable": "$.kind", "StringEquals": "fail", "Next": "Pause"}]},
|
||||
"Long": {"Type": "Wait", "Seconds": 15, "End": true},
|
||||
"Pause": {"Type": "Wait", "Seconds": 1, "Next": "Boom"},
|
||||
"Boom": {"Type": "Fail", "Error": "Boom", "Cause": "sibling failed"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""");
|
||||
String execArn = startExecution(smArn, "{\"items\": [{\"kind\": \"long\"}, {\"kind\": \"fail\"}]}");
|
||||
|
||||
Response failed = waitForTerminalExecution(execArn, 8_000);
|
||||
|
||||
assertEquals("FAILED", failed.jsonPath().getString("status"), failed.body().asString());
|
||||
assertEquals("Boom", failed.jsonPath().getString("error"));
|
||||
JsonNode events = MAPPER.readTree(getExecutionHistory(execArn).body().asString()).path("events");
|
||||
List<String> types = new ArrayList<>();
|
||||
events.forEach(event -> types.add(event.path("type").asText()));
|
||||
int failure = types.indexOf("FailStateEntered");
|
||||
assertTrue(failure > 0, types.toString());
|
||||
assertEquals(List.of("MapIterationAborted", "WaitStateAborted", "MapIterationFailed", "MapStateFailed",
|
||||
"ExecutionFailed"), types.subList(failure + 1, types.size()), types.toString());
|
||||
long failureId = events.get(failure).path("id").asLong();
|
||||
for (int i = failure + 1; i <= failure + 4; i++) {
|
||||
assertEquals(failureId, events.get(i).path("previousEventId").asLong(), types.get(i));
|
||||
}
|
||||
JsonNode aborted = events.get(failure + 1).path("mapIterationAbortedEventDetails");
|
||||
assertEquals("M", aborted.path("name").asText());
|
||||
assertEquals(0, aborted.path("index").asInt());
|
||||
assertEquals(1, events.get(failure + 3).path("mapIterationFailedEventDetails").path("index").asInt());
|
||||
}
|
||||
|
||||
private static String createStateMachine(String name, String definition) {
|
||||
Response resp = given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"name": "%s-%d", "definition": %s, "roleArn": "%s"}
|
||||
""".formatted(name, System.currentTimeMillis(), quote(definition), ROLE_ARN))
|
||||
.when()
|
||||
.post("/");
|
||||
resp.then().statusCode(200);
|
||||
return resp.jsonPath().getString("stateMachineArn");
|
||||
}
|
||||
|
||||
private static String startExecution(String smArn, String input) {
|
||||
Response resp = given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.StartExecution")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"stateMachineArn": "%s", "input": %s}
|
||||
""".formatted(smArn, quote(input)))
|
||||
.when()
|
||||
.post("/");
|
||||
resp.then().statusCode(200);
|
||||
return resp.jsonPath().getString("executionArn");
|
||||
}
|
||||
|
||||
private static Response describeExecution(String execArn) {
|
||||
return given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"executionArn": "%s"}
|
||||
""".formatted(execArn))
|
||||
.when()
|
||||
.post("/");
|
||||
}
|
||||
|
||||
private static Response getExecutionHistory(String execArn) {
|
||||
Response resp = given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.GetExecutionHistory")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"executionArn": "%s"}
|
||||
""".formatted(execArn))
|
||||
.when()
|
||||
.post("/");
|
||||
resp.then().statusCode(200);
|
||||
return resp;
|
||||
}
|
||||
|
||||
private static Response waitForTerminalExecution(String execArn, long limitMillis) throws InterruptedException {
|
||||
long deadline = System.currentTimeMillis() + limitMillis;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
Response resp = describeExecution(execArn);
|
||||
if (!"RUNNING".equals(resp.jsonPath().getString("status"))) {
|
||||
return resp;
|
||||
}
|
||||
Thread.sleep(100);
|
||||
}
|
||||
fail("Execution " + execArn + " was still RUNNING after " + limitMillis + " ms");
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String quote(String raw) {
|
||||
return "\"" + raw
|
||||
.replace("\\", "\\\\")
|
||||
.replace("\"", "\\\"")
|
||||
.replace("\n", "\\n")
|
||||
.replace("\r", "\\r")
|
||||
.replace("\t", "\\t")
|
||||
+ "\"";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user