mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(stepfunctions): bound a running execution the four ways AWS does (#2782)
* fix(stepfunctions): enforce both TimeoutSeconds clocks The state machine's top-level TimeoutSeconds was read back by DescribeStateMachine and copied into activityScheduledEventDetails but never used as a deadline, so an execution ran to completion however long it took. Compute the budget once in doExecute, check it before every state and inside the Wait sleep, and end the execution TIMED_OUT with stopDate set, no error, no cause, and one ExecutionTimedOut event carrying States.Timeout and previousEventId 0. A Task's two bounds were swapped: HeartbeatSeconds acted as the total wait and TimeoutSeconds was decorative, so "TimeoutSeconds": 5, "HeartbeatSeconds": 60 failed at 60 seconds instead of 5. awaitToken now bounds the whole wait with TimeoutSeconds and the gap between heartbeats with HeartbeatSeconds. SendTaskHeartbeat only logged, so the gap bound needed a per-token timestamp: the service now records one when the token is registered and again on every heartbeat, and forgets it when the waiting task stops listening. Either clock ends the state as a TaskTimedOutException, which is what us-east-1 answers for a heartbeat expiry: an ActivityTimedOut event carrying error States.Timeout and no cause, then an execution reading FAILED with error States.Timeout and no cause key, over the six-event history ExecutionStarted, TaskStateEntered, ActivityScheduled, ActivityStarted, ActivityTimedOut, ExecutionFailed. A Catch still matches a heartbeat expiry under States.HeartbeatTimeout, so ErrorEquals matching now asks the failure which names it answers to rather than comparing one string. The Wait sleep stops at the execution deadline instead of sleeping its full duration first, which would have reported the timeout as many seconds late as the Wait outlasts the budget and left a WaitStateExited behind for a state AWS never finished. awaitToken discards its token on the way out; without that the token would stay pending for the life of the process and a later SendTaskSuccess would be answered as if someone were still waiting. Neither timeout carries a cause, so failExecution now reads a null cause as the failure having none and leaves the key out of both DescribeExecution and the ExecutionFailed event. The two other failures that reach it without a cause -- a Fail state with no Cause, and SendTaskFailure with no cause -- keep reporting an empty one, since AWS's shape for those is unmeasured. Refs #2733 * fix(stepfunctions): bound an execution's history and make StopExecution stop it AWS puts two bounds on a running execution that floci did not: it ends one that reaches 25,000 history events with States.Runtime, event 25,000 being the ExecutionFailed event itself, and StopExecution stops the worker rather than relabelling an execution that goes on to overwrite the status it wrote. Counting an event against that limit and numbering it in the published history are two meanings that one AtomicLong was carrying. They are separated here. producedEventCount counts every event the execution produces, the top-level flow's and those of its Parallel branches and inline Map iterations alike, and is what the limit judges. The published history numbers its own events: an event's id is its position in the list, which makes the list the only authority for the next id, where the counter and the seal in StepFunctionsService used to be a second one that agreed with it only at rest. A branch's events are counted and never built, so executeBranch no longer assembles HistoryEvent objects with full input and output JSON into a list it throws away. A Distributed Map runs each item as a child execution on AWS, and a child execution has a history of its own, so its items are counted against their own limit rather than the parent's: a Distributed Map over 13,000 items no longer fails the parent partway through with States.Runtime. The count is taken before it is judged. Reading it and then taking it let 40 concurrent inline Map iterations through the same check and spent more events than the execution had. StopExecution records its abort against a history that need not be in memory. Executions are stored and histories are not, so a restart in persistent mode brings a RUNNING execution back with nothing behind it, and the same window opens between a reset emptying the cache and emptying the store; the abort was written to the store and then thrown away as a 500. * fix(stepfunctions): end an execution that spends its budget waiting A state machine's TimeoutSeconds budget was read only between states and around the two pauses a definition asks for, a Wait and a Retry backoff. Every other way a state blocks outlasted it: a Task waiting for its token, a states:startExecution.sync or ecs:runTask.sync poll, and a Parallel or Map waiting for its branches. Those executions ended past their budget, and ended FAILED or SUCCEEDED rather than TIMED_OUT. Each of those waits now stops at the budget, and the Task path publishes no failure event for the state it cuts. Measured against us-east-1: a state machine with TimeoutSeconds 5 over an activity Task whose own TimeoutSeconds is 60 stops at exactly 5.000 s with status TIMED_OUT, and its history is ExecutionStarted, TaskStateEntered, ActivityScheduled, ExecutionTimedOut, with no ActivityTimedOut and no ExecutionFailed. --------- Co-authored-by: Facundo Paredes <naranjax@MAC-69786.local>
This commit is contained in:
1 parent
2480daaa09
commit
9288769607
11 files changed
+1985
-173
No files matched your search
+485
-138
@@ -108,6 +108,19 @@ public class AslExecutor {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AslExecutor.class);
|
||||
private static final int MAX_WAIT_SECONDS = 30;
|
||||
// How long a Task waits for its token when the state declares no TimeoutSeconds. AWS lets it
|
||||
// run for a year; the emulator would rather free the worker thread.
|
||||
private static final int DEFAULT_TASK_TOKEN_TIMEOUT_SECONDS = 300;
|
||||
|
||||
/**
|
||||
* AWS ends an execution once its history reaches this many events. The count is neither reset
|
||||
* nor offset: the event that ends the execution is number 25,000 itself, so the last event the
|
||||
* state machine produced is 24,999.
|
||||
*/
|
||||
private static final int MAX_HISTORY_EVENTS = 25_000;
|
||||
private static final String HISTORY_EVENT_LIMIT_CAUSE =
|
||||
"The execution reached the maximum number of history events (" + MAX_HISTORY_EVENTS + ").";
|
||||
|
||||
private static final int INLINE_MAP_MAX_CONCURRENCY = 40;
|
||||
private static final int DISTRIBUTED_MAP_MAX_CONCURRENCY = 10_000;
|
||||
|
||||
@@ -354,9 +367,10 @@ public class AslExecutor {
|
||||
|
||||
private void doExecute(StateMachine sm, Execution exec, List<HistoryEvent> history,
|
||||
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
|
||||
// Declared outside the try so the terminal handlers below can keep numbering the history
|
||||
// where the execution left it.
|
||||
AtomicLong eventId = new AtomicLong(history.size());
|
||||
// Shared with every Parallel branch and every inline Map iteration of this execution: the
|
||||
// 25,000-event limit is the execution's, not the thread's. It starts where the history
|
||||
// already is, because ExecutionStarted is an event of this execution too.
|
||||
AtomicLong producedEventCount = new AtomicLong(history.size());
|
||||
var firstState = true;
|
||||
try {
|
||||
JsonNode definition = objectMapper.readTree(sm.getDefinition());
|
||||
@@ -364,20 +378,30 @@ public class AslExecutor {
|
||||
String startAt = definition.path("StartAt").asText();
|
||||
String topLevelQueryLanguage = definition.path("QueryLanguage").asText("JSONPath");
|
||||
JsonNode currentInput = parseInput(exec.getInput());
|
||||
// The state machine's total budget, computed once so every state measures against the
|
||||
// same instant. Long.MAX_VALUE stands for a definition with no TimeoutSeconds.
|
||||
int timeoutSeconds = definition.path("TimeoutSeconds").asInt(0);
|
||||
long executionDeadlineNanos = timeoutSeconds > 0
|
||||
? System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds)
|
||||
: Long.MAX_VALUE;
|
||||
JsonNode execContext = buildContext(exec, sm);
|
||||
// Execution-scoped JSONata variables (the Assign field). Mutated in place as states
|
||||
// assign, so later states observe earlier assignments.
|
||||
ObjectNode variables = objectMapper.createObjectNode();
|
||||
|
||||
String currentStateName = startAt;
|
||||
while (currentStateName != null) {
|
||||
while (currentStateName != null && !abortedByCaller(exec)) {
|
||||
if (System.nanoTime() >= executionDeadlineNanos) {
|
||||
throw new ExecutionTimedOutException();
|
||||
}
|
||||
JsonNode stateDef = states.path(currentStateName);
|
||||
if (stateDef.isMissingNode()) {
|
||||
throw new RuntimeException("State not found: " + currentStateName);
|
||||
}
|
||||
|
||||
String type = stateDef.path("Type").asText();
|
||||
addEvent(history, eventId, stateEnteredEventType(type), firstState ? 0L : eventId.get(),
|
||||
publishStateEnteredEvent(history, producedEventCount, stateEnteredEventType(type),
|
||||
firstState ? 0L : history.size(),
|
||||
Map.of("name", currentStateName, "input", currentInput.toString(),
|
||||
"inputDetails", Map.of("truncated", false)));
|
||||
firstState = false;
|
||||
@@ -388,8 +412,9 @@ public class AslExecutor {
|
||||
var jsonata = isJsonata(stateDef, topLevelQueryLanguage);
|
||||
try {
|
||||
var stateResult = executeStateWithRetry(currentStateName, type, stateDef, currentInput,
|
||||
history, eventId, sm, jsonata, topLevelQueryLanguage, execContext, variables);
|
||||
addEvent(history, eventId, stateExitedEventType(type),
|
||||
history, producedEventCount, sm, jsonata, topLevelQueryLanguage, execContext,
|
||||
variables, executionDeadlineNanos);
|
||||
publishEvent(history, producedEventCount, stateExitedEventType(type),
|
||||
Map.of("name", currentStateName, "output", stateResult.output().toString(),
|
||||
"outputDetails", Map.of("truncated", false)));
|
||||
|
||||
@@ -411,35 +436,36 @@ public class AslExecutor {
|
||||
failure = catchClauseFailure;
|
||||
}
|
||||
if (caught != null) {
|
||||
addEvent(history, eventId, stateExitedEventType(type),
|
||||
publishEvent(history, producedEventCount, stateExitedEventType(type),
|
||||
Map.of("name", currentStateName, "output", caught.output().toString(),
|
||||
"outputDetails", Map.of("truncated", false)));
|
||||
currentInput = caught.output();
|
||||
currentStateName = caught.nextState();
|
||||
continue;
|
||||
}
|
||||
failExecution(exec, history, eventId, failure);
|
||||
failExecution(exec, history, failure);
|
||||
onUpdate.accept(exec, history);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Status is the publication point, so it is set last. describeExecution hands out this
|
||||
// same live Execution, so a client polling for SUCCEEDED between setStatus and setOutput
|
||||
// would read a terminal execution with a null output, which real Step Functions never
|
||||
// returns. The same ordering applies to every terminal path below.
|
||||
exec.setOutput(currentInput.toString());
|
||||
exec.setStopDate(System.currentTimeMillis() / 1000.0);
|
||||
exec.setStatus("SUCCEEDED");
|
||||
addEvent(history, eventId, "ExecutionSucceeded",
|
||||
Map.of("output", currentInput.toString(), "outputDetails", Map.of("truncated", false)));
|
||||
succeedExecution(exec, history, currentInput);
|
||||
onUpdate.accept(exec, history);
|
||||
|
||||
} catch (ExecutionTimedOutException e) {
|
||||
timeOutExecution(exec, history);
|
||||
onUpdate.accept(exec, history);
|
||||
} catch (FailStateException e) {
|
||||
// A state's own failure is handled inside the loop, where its Catch clauses apply. What
|
||||
// reaches here is a failure raised while recording a state's entered event, outside the
|
||||
// per-state try: the execution hit the history-event limit.
|
||||
failExecution(exec, history, e);
|
||||
onUpdate.accept(exec, history);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("ASL execution failed for {0}: {1}", exec.getExecutionArn(), e.getMessage());
|
||||
// This path previously set only the status, leaving error and cause null forever on an
|
||||
// execution DescribeExecution reports as FAILED.
|
||||
failExecution(exec, history, eventId, "States.Runtime",
|
||||
failExecution(exec, history, "States.Runtime",
|
||||
e.getMessage() != null ? e.getMessage() : "Unknown error");
|
||||
onUpdate.accept(exec, history);
|
||||
} catch (Error e) {
|
||||
@@ -449,7 +475,7 @@ public class AslExecutor {
|
||||
// and the rethrow keeps the Error itself from being swallowed here. The cause carries
|
||||
// toString() rather than getMessage(), because an Error's message is often null and
|
||||
// the type name is the whole diagnostic.
|
||||
failExecution(exec, history, eventId, "States.Runtime", e.toString());
|
||||
failExecution(exec, history, "States.Runtime", e.toString());
|
||||
onUpdate.accept(exec, history);
|
||||
throw e;
|
||||
} finally {
|
||||
@@ -470,16 +496,17 @@ public class AslExecutor {
|
||||
* caller's Catch handling, preserving Retry-before-Catch order.
|
||||
*/
|
||||
private StateResult executeStateWithRetry(String name, String type, JsonNode stateDef, JsonNode input,
|
||||
List<HistoryEvent> history, AtomicLong eventId, StateMachine sm,
|
||||
boolean jsonata, String topLevelQueryLanguage, JsonNode context,
|
||||
ObjectNode variables) throws Exception {
|
||||
List<HistoryEvent> history, AtomicLong producedEventCount,
|
||||
StateMachine sm, boolean jsonata, String topLevelQueryLanguage,
|
||||
JsonNode context, ObjectNode variables,
|
||||
long executionDeadlineNanos) throws Exception {
|
||||
var retriers = stateDef.path("Retry");
|
||||
var attemptsPerRetrier = new HashMap<Integer, Integer>();
|
||||
var attempt = 0;
|
||||
while (true) {
|
||||
try {
|
||||
return executeState(name, type, stateDef, input, history, eventId, sm, jsonata,
|
||||
topLevelQueryLanguage, context, variables, attempt);
|
||||
return executeState(name, type, stateDef, input, history, producedEventCount, sm, jsonata,
|
||||
topLevelQueryLanguage, context, variables, attempt, executionDeadlineNanos);
|
||||
} catch (FailStateException e) {
|
||||
var retrierIndex = findMatchingRetrier(retriers, e);
|
||||
if (retrierIndex < 0) {
|
||||
@@ -490,7 +517,7 @@ public class AslExecutor {
|
||||
if (attemptsUsed > retrier.path("MaxAttempts").asInt(3)) {
|
||||
throw e;
|
||||
}
|
||||
sleepBeforeRetry(retrier, attemptsUsed);
|
||||
sleepBeforeRetry(retrier, attemptsUsed, executionDeadlineNanos);
|
||||
attempt++;
|
||||
updateRetryCount(context, attempt);
|
||||
}
|
||||
@@ -501,20 +528,25 @@ public class AslExecutor {
|
||||
if (!retriers.isArray()) {
|
||||
return -1;
|
||||
}
|
||||
var error = failure.error != null ? failure.error : "States.Runtime";
|
||||
for (var i = 0; i < retriers.size(); i++) {
|
||||
if (catchMatches(retriers.get(i), error)) {
|
||||
if (catchMatches(retriers.get(i), failure)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private void sleepBeforeRetry(JsonNode retrier, int attemptsUsed) throws InterruptedException {
|
||||
/**
|
||||
* Backs off before the next attempt. The backoff is a pause inside the state, so a retrier
|
||||
* whose interval outlasts the state machine's {@code TimeoutSeconds} budget ends the execution
|
||||
* where the budget runs out rather than attempting again past it, which is what AWS does. The
|
||||
* deadline is read even when the delay is zero, so a state that already spent the budget stops
|
||||
* instead of retrying instantly.
|
||||
*/
|
||||
private void sleepBeforeRetry(JsonNode retrier, int attemptsUsed, long executionDeadlineNanos)
|
||||
throws InterruptedException {
|
||||
var delaySeconds = retryDelaySeconds(retrier, attemptsUsed, ThreadLocalRandom.current().nextDouble());
|
||||
if (delaySeconds > 0) {
|
||||
Thread.sleep((long) (delaySeconds * 1000));
|
||||
}
|
||||
sleepOrTimeOutExecution((long) (delaySeconds * 1_000_000_000L), executionDeadlineNanos);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -542,19 +574,22 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
private StateResult executeState(String name, String type, JsonNode stateDef, JsonNode input,
|
||||
List<HistoryEvent> history, AtomicLong eventId, StateMachine sm,
|
||||
boolean jsonata, String topLevelQueryLanguage, JsonNode context,
|
||||
ObjectNode variables, int attempt) throws Exception {
|
||||
List<HistoryEvent> history, AtomicLong producedEventCount,
|
||||
StateMachine sm, boolean jsonata, String topLevelQueryLanguage,
|
||||
JsonNode context, ObjectNode variables, int attempt,
|
||||
long executionDeadlineNanos) throws Exception {
|
||||
return switch (type) {
|
||||
case "Pass" -> executePassState(stateDef, input, jsonata, context, variables);
|
||||
case "Task" -> executeTaskState(name, stateDef, input, history, eventId, sm, jsonata, context,
|
||||
variables, attempt);
|
||||
case "Task" -> executeTaskState(name, stateDef, input, history, producedEventCount, sm,
|
||||
jsonata, context, variables, attempt, executionDeadlineNanos);
|
||||
case "Choice" -> executeChoiceState(stateDef, input, jsonata, context, variables);
|
||||
case "Wait" -> executeWaitState(stateDef, input, jsonata, context, variables);
|
||||
case "Wait" -> executeWaitState(stateDef, input, jsonata, context, variables, executionDeadlineNanos);
|
||||
case "Succeed" -> executeSucceedState(stateDef, input, jsonata, context, variables);
|
||||
case "Fail" -> executeFail(stateDef, input, jsonata, context, variables);
|
||||
case "Parallel" -> executeParallelState(name, stateDef, input, sm, jsonata, topLevelQueryLanguage, context, variables);
|
||||
case "Map" -> executeMapState(name, stateDef, input, sm, jsonata, topLevelQueryLanguage, context, variables);
|
||||
case "Parallel" -> executeParallelState(name, stateDef, input, producedEventCount, sm, jsonata,
|
||||
topLevelQueryLanguage, context, variables, executionDeadlineNanos);
|
||||
case "Map" -> executeMapState(name, stateDef, input, producedEventCount, sm, jsonata,
|
||||
topLevelQueryLanguage, context, variables, executionDeadlineNanos);
|
||||
default -> new StateResult(input, stateDef.path("Next").asText(null));
|
||||
};
|
||||
}
|
||||
@@ -585,9 +620,10 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
private StateResult executeTaskState(String stateName, JsonNode stateDef, JsonNode input,
|
||||
List<HistoryEvent> history, AtomicLong eventId, StateMachine sm,
|
||||
boolean jsonata, JsonNode context, ObjectNode variables,
|
||||
int attempt) throws Exception {
|
||||
List<HistoryEvent> history, AtomicLong producedEventCount,
|
||||
StateMachine sm, boolean jsonata, JsonNode context,
|
||||
ObjectNode variables, int attempt,
|
||||
long executionDeadlineNanos) throws Exception {
|
||||
var resource = stateDef.path("Resource").asText();
|
||||
var isWaitForToken = resource.endsWith(".waitForTaskToken");
|
||||
var effectiveResource = isWaitForToken
|
||||
@@ -623,25 +659,44 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
var profile = taskEventProfile(resource, isActivity);
|
||||
addTaskScheduledEvent(history, eventId, profile, stateDef, effectiveInput, sm);
|
||||
addTaskStartedEvent(history, eventId, profile);
|
||||
|
||||
JsonNode taskResult;
|
||||
try {
|
||||
taskResult = mockedSteps != null
|
||||
? mockedTaskResult(mockedSteps, stateName, attempt)
|
||||
: invokeResource(effectiveResource, effectiveInput, sm, taskToken);
|
||||
if (tokenFuture != null) {
|
||||
taskResult = awaitToken(tokenFuture, stateDef);
|
||||
addTaskScheduledEvent(history, producedEventCount, profile, stateDef, effectiveInput, sm);
|
||||
addTaskStartedEvent(history, producedEventCount, profile);
|
||||
try {
|
||||
taskResult = mockedSteps != null
|
||||
? mockedTaskResult(mockedSteps, stateName, attempt)
|
||||
: invokeResource(effectiveResource, effectiveInput, sm, taskToken, executionDeadlineNanos);
|
||||
if (tokenFuture != null) {
|
||||
taskResult = awaitToken(tokenFuture, stateDef, taskToken, executionDeadlineNanos);
|
||||
}
|
||||
} catch (ExecutionTimedOutException e) {
|
||||
// The state machine's TimeoutSeconds budget ran out while this task was waiting. AWS
|
||||
// ends the execution there and writes nothing about the state it cut: the history of
|
||||
// a task still waiting on its token is ExecutionStarted, TaskStateEntered,
|
||||
// ActivityScheduled, ExecutionTimedOut, with no TaskFailed and no TaskTimedOut.
|
||||
throw e;
|
||||
} catch (TaskTimedOutException e) {
|
||||
addTaskTimedOutEvent(history, producedEventCount, profile);
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
var failure = e instanceof FailStateException f ? f : null;
|
||||
addTaskFailedEvent(history, producedEventCount, profile,
|
||||
failure != null && failure.error != null ? failure.error : "States.Runtime",
|
||||
failure != null ? failure.cause : e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
var failure = e instanceof FailStateException f ? f : null;
|
||||
addTaskFailedEvent(history, eventId, profile,
|
||||
failure != null && failure.error != null ? failure.error : "States.Runtime",
|
||||
failure != null ? failure.cause : e.getMessage());
|
||||
// A token registered above is normally discarded by awaitToken's own finally. Anything
|
||||
// that throws before awaitToken runs — the scheduled/started events themselves, or the
|
||||
// resource invocation — would otherwise leave it pending forever; the discard here is a
|
||||
// no-op once awaitToken already ran it.
|
||||
if (needsToken) {
|
||||
sfnService.get().discardPendingToken(taskToken);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
addTaskSucceededEvent(history, eventId, profile, taskResult);
|
||||
addTaskSucceededEvent(history, producedEventCount, profile, taskResult);
|
||||
|
||||
if (jsonata) {
|
||||
JsonNode output = applyJsonataOutput(stateDef, input, taskResult, context, variables);
|
||||
@@ -685,17 +740,51 @@ public class AslExecutor {
|
||||
"No mocked response defined for attempt " + attempt + " of state '" + stateName + "'");
|
||||
}
|
||||
|
||||
private JsonNode awaitToken(CompletableFuture<JsonNode> future, JsonNode stateDef) throws Exception {
|
||||
int timeout = stateDef.path("HeartbeatSeconds").asInt(0);
|
||||
if (timeout <= 0) {
|
||||
timeout = 300;
|
||||
/**
|
||||
* Waits for the worker to answer the task token under the two independent bounds AWS enforces:
|
||||
* {@code TimeoutSeconds} is the whole wait, and {@code HeartbeatSeconds} is the longest gap
|
||||
* allowed between two SendTaskHeartbeat calls, each of which pushes that gap forward. Either
|
||||
* clock ends the state as a {@link TaskTimedOutException}: the error is {@code States.Timeout}
|
||||
* and there is no cause.
|
||||
*
|
||||
* <p>Both clocks start when the task is scheduled. AWS starts TimeoutSeconds when a worker
|
||||
* picks the task up, which is the instant it emits ActivityStarted; Floci emits that event at
|
||||
* schedule time, so there is no later instant to anchor on here.
|
||||
*/
|
||||
private JsonNode awaitToken(CompletableFuture<JsonNode> future, JsonNode stateDef, String taskToken,
|
||||
long executionDeadlineNanos) throws Exception {
|
||||
int timeoutSeconds = stateDef.path("TimeoutSeconds").asInt(0);
|
||||
if (timeoutSeconds <= 0) {
|
||||
timeoutSeconds = DEFAULT_TASK_TOKEN_TIMEOUT_SECONDS;
|
||||
}
|
||||
int heartbeatSeconds = stateDef.path("HeartbeatSeconds").asInt(0);
|
||||
long timeoutDeadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds);
|
||||
try {
|
||||
return future.get(timeout, TimeUnit.SECONDS);
|
||||
} catch (java.util.concurrent.TimeoutException e) {
|
||||
future.cancel(true);
|
||||
throw new FailStateException("States.HeartbeatTimeout",
|
||||
"Task timed out after " + timeout + " seconds");
|
||||
while (true) {
|
||||
long wakeAtNanos = Math.min(executionDeadlineNanos, Math.min(timeoutDeadlineNanos,
|
||||
heartbeatDeadlineNanos(taskToken, heartbeatSeconds)));
|
||||
try {
|
||||
return future.get(wakeAtNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
|
||||
} catch (java.util.concurrent.TimeoutException e) {
|
||||
// The execution's budget is read first: when it is the clock that ran out, the
|
||||
// execution ends as TIMED_OUT and the task's own timeout never applies.
|
||||
if (System.nanoTime() >= executionDeadlineNanos) {
|
||||
future.cancel(true);
|
||||
throw new ExecutionTimedOutException();
|
||||
}
|
||||
if (System.nanoTime() >= timeoutDeadlineNanos) {
|
||||
future.cancel(true);
|
||||
throw new TaskTimedOutException("States.Timeout");
|
||||
}
|
||||
// Read the gap again rather than trusting the one this thread parked on: a
|
||||
// heartbeat that landed meanwhile has already moved it past now, and the task
|
||||
// goes back to waiting on the later deadline.
|
||||
if (System.nanoTime() >= heartbeatDeadlineNanos(taskToken, heartbeatSeconds)) {
|
||||
future.cancel(true);
|
||||
throw new TaskTimedOutException("States.HeartbeatTimeout");
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (ExecutionException e) {
|
||||
Throwable cause = e.getCause();
|
||||
if (cause instanceof FailStateException fse) {
|
||||
@@ -703,9 +792,21 @@ public class AslExecutor {
|
||||
}
|
||||
throw new FailStateException("States.TaskFailed",
|
||||
cause != null ? cause.getMessage() : "Task failed");
|
||||
} finally {
|
||||
sfnService.get().discardPendingToken(taskToken);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* When the worker's silence becomes too long: its last heartbeat plus the state's
|
||||
* {@code HeartbeatSeconds}, or never for a state that declares none.
|
||||
*/
|
||||
private long heartbeatDeadlineNanos(String taskToken, int heartbeatSeconds) {
|
||||
return heartbeatSeconds > 0
|
||||
? sfnService.get().lastTaskHeartbeatNanos(taskToken) + TimeUnit.SECONDS.toNanos(heartbeatSeconds)
|
||||
: Long.MAX_VALUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the Lambda function name from a reference that may be a bare name, a name with a
|
||||
* version/alias qualifier (e.g. "name:$LATEST"), or a full/partial function ARN
|
||||
@@ -745,7 +846,8 @@ public class AslExecutor {
|
||||
CustomResourceLiveness.tokenIn(payload).ifPresent(customResourceLiveness::touch);
|
||||
}
|
||||
|
||||
private JsonNode invokeResource(String resource, JsonNode input, StateMachine sm, String taskToken) throws Exception {
|
||||
private JsonNode invokeResource(String resource, JsonNode input, StateMachine sm, String taskToken,
|
||||
long executionDeadlineNanos) throws Exception {
|
||||
// Support Lambda resources: direct ARN or optimized integration
|
||||
String functionName = null;
|
||||
JsonNode lambdaPayload = input;
|
||||
@@ -869,7 +971,7 @@ public class AslExecutor {
|
||||
? ".waitForTaskToken"
|
||||
: resource.substring("arn:aws:states:::ecs:runTask".length());
|
||||
String region = extractRegionFromArn(sm.getStateMachineArn());
|
||||
return invokeEcsRunTask(mode, input, region);
|
||||
return invokeEcsRunTask(mode, input, region, executionDeadlineNanos);
|
||||
}
|
||||
|
||||
// AWS SDK service integrations: Step Functions
|
||||
@@ -896,7 +998,7 @@ public class AslExecutor {
|
||||
if (resource.startsWith("arn:aws:states:::states:startExecution")) {
|
||||
String mode = resource.substring("arn:aws:states:::states:startExecution".length());
|
||||
String region = extractRegionFromArn(sm.getStateMachineArn());
|
||||
return invokeNestedStateMachine(mode, input, region);
|
||||
return invokeNestedStateMachine(mode, input, region, executionDeadlineNanos);
|
||||
}
|
||||
|
||||
// Activity resource: arn:aws:states:{region}:{account}:activity:{name}
|
||||
@@ -1229,7 +1331,8 @@ public class AslExecutor {
|
||||
return envelope;
|
||||
}
|
||||
|
||||
private JsonNode invokeNestedStateMachine(String mode, JsonNode input, String region) throws Exception {
|
||||
private JsonNode invokeNestedStateMachine(String mode, JsonNode input, String region,
|
||||
long executionDeadlineNanos) throws Exception {
|
||||
String smArn = input.path("StateMachineArn").asText(null);
|
||||
if (smArn == null || smArn.isBlank()) {
|
||||
throw new FailStateException("States.TaskFailed",
|
||||
@@ -1250,9 +1353,10 @@ public class AslExecutor {
|
||||
return result;
|
||||
}
|
||||
|
||||
// .sync or .sync:2 — poll until terminal
|
||||
// .sync or .sync:2 — poll until terminal, or until the parent execution's TimeoutSeconds
|
||||
// budget runs out, which ends the parent as TIMED_OUT and leaves the child running.
|
||||
for (int i = 0; i < 600; i++) {
|
||||
Thread.sleep(100);
|
||||
sleepOrTimeOutExecution(TimeUnit.MILLISECONDS.toNanos(100), executionDeadlineNanos);
|
||||
io.github.hectorvent.floci.services.stepfunctions.model.Execution current =
|
||||
sfnService.get().describeExecution(execArn);
|
||||
String status = current.getStatus();
|
||||
@@ -1302,7 +1406,8 @@ public class AslExecutor {
|
||||
* STOPPED, or ".waitForTaskToken" to launch and let the token future carry the result
|
||||
* (both ".sync" and ".waitForTaskToken" fail the state on a placement failure).
|
||||
*/
|
||||
private JsonNode invokeEcsRunTask(String mode, JsonNode input, String region) throws Exception {
|
||||
private JsonNode invokeEcsRunTask(String mode, JsonNode input, String region,
|
||||
long executionDeadlineNanos) throws Exception {
|
||||
String taskDefinition = input.path("TaskDefinition").asText(null);
|
||||
if (taskDefinition == null || taskDefinition.isBlank()) {
|
||||
throw new FailStateException("States.TaskFailed",
|
||||
@@ -1374,7 +1479,8 @@ public class AslExecutor {
|
||||
// fail the state, otherwise tasks beyond the first would run unmonitored.
|
||||
List<String> taskArns = launched.stream().map(EcsTask::getTaskArn).toList();
|
||||
for (int i = 0; i < ECS_SYNC_POLL_ATTEMPTS; i++) {
|
||||
Thread.sleep(ECS_SYNC_POLL_INTERVAL_MS);
|
||||
sleepOrTimeOutExecution(TimeUnit.MILLISECONDS.toNanos(ECS_SYNC_POLL_INTERVAL_MS),
|
||||
executionDeadlineNanos);
|
||||
List<EcsTask> described = ecsService.describeTasks(cluster, taskArns, region);
|
||||
boolean allStopped = described.size() == taskArns.size()
|
||||
&& described.stream().allMatch(t -> "STOPPED".equals(t.getLastStatus()));
|
||||
@@ -1845,7 +1951,8 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
private StateResult executeWaitState(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context,
|
||||
ObjectNode variables) throws InterruptedException {
|
||||
ObjectNode variables, long executionDeadlineNanos)
|
||||
throws InterruptedException {
|
||||
int seconds = 0;
|
||||
if (jsonata) {
|
||||
if (stateDef.has("Seconds")) {
|
||||
@@ -1869,7 +1976,7 @@ public class AslExecutor {
|
||||
}
|
||||
// Timestamp and TimestampPath: wait until that time or now, whichever is sooner
|
||||
if (seconds > 0) {
|
||||
TimeUnit.SECONDS.sleep(seconds);
|
||||
sleepOrTimeOutExecution(TimeUnit.SECONDS.toNanos(seconds), executionDeadlineNanos);
|
||||
}
|
||||
if (jsonata) {
|
||||
JsonNode output = applyJsonataOutput(stateDef, input, null, context, variables);
|
||||
@@ -1878,6 +1985,23 @@ public class AslExecutor {
|
||||
return new StateResult(input, stateDef.path("Next").asText(null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sleeps out a pause the definition asked for, ending the execution instead when the state
|
||||
* machine's {@code TimeoutSeconds} budget runs out first. The two pauses long enough to
|
||||
* outlast that budget are a Wait and a Retry's backoff, and both leave the state they cut
|
||||
* without its Exited event, the same way AWS does.
|
||||
*/
|
||||
private void sleepOrTimeOutExecution(long pauseNanos, long executionDeadlineNanos)
|
||||
throws InterruptedException {
|
||||
long remainingNanos = executionDeadlineNanos - System.nanoTime();
|
||||
if (pauseNanos < remainingNanos) {
|
||||
TimeUnit.NANOSECONDS.sleep(pauseNanos);
|
||||
return;
|
||||
}
|
||||
TimeUnit.NANOSECONDS.sleep(Math.max(remainingNanos, 0));
|
||||
throw new ExecutionTimedOutException();
|
||||
}
|
||||
|
||||
private StateResult executeSucceedState(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context,
|
||||
ObjectNode variables) {
|
||||
if (jsonata) {
|
||||
@@ -1890,7 +2014,9 @@ public class AslExecutor {
|
||||
private StateResult executeFail(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context,
|
||||
ObjectNode variables) {
|
||||
String error = stateDef.path("Error").asText(null);
|
||||
String cause = stateDef.path("Cause").asText(null);
|
||||
// A Fail state that declares no Cause reports an empty one, not a missing key. A task that
|
||||
// ran out of one of its clocks is the only failure that omits the key.
|
||||
String cause = stateDef.path("Cause").asText("");
|
||||
if (jsonata) {
|
||||
JsonNode statesVar = buildStatesVar(input, null, context);
|
||||
if (error != null && JsonataEvaluator.isExpression(error)) {
|
||||
@@ -1903,9 +2029,11 @@ public class AslExecutor {
|
||||
throw new FailStateException(error, cause);
|
||||
}
|
||||
|
||||
private StateResult executeParallelState(String name, JsonNode stateDef, JsonNode input, StateMachine sm,
|
||||
boolean jsonata, String topLevelQueryLanguage, JsonNode context,
|
||||
ObjectNode variables) throws Exception {
|
||||
private StateResult executeParallelState(String name, JsonNode stateDef, JsonNode input,
|
||||
AtomicLong producedEventCount, StateMachine sm, boolean jsonata,
|
||||
String topLevelQueryLanguage, JsonNode context,
|
||||
ObjectNode variables, long executionDeadlineNanos)
|
||||
throws Exception {
|
||||
JsonNode branches = stateDef.path("Branches");
|
||||
List<Future<JsonNode>> futures = new ArrayList<>();
|
||||
|
||||
@@ -1924,28 +2052,29 @@ public class AslExecutor {
|
||||
// scope is thread-bound, so without this a branch's Task integrations would resolve to
|
||||
// the default account rather than the execution's.
|
||||
futures.add(executor.submit(() -> callUnderExecutionAccount(sm,
|
||||
() -> executeBranch(startAt, branchStates, capturedInput, sm, topLevelQueryLanguage,
|
||||
branchContext, branchVariables))));
|
||||
() -> executeBranch(startAt, branchStates, capturedInput, producedEventCount, sm,
|
||||
topLevelQueryLanguage, branchContext, branchVariables))));
|
||||
}
|
||||
|
||||
int timeoutSeconds = stateDef.path("TimeoutSeconds").asInt(0);
|
||||
long deadlineNanos = timeoutSeconds > 0
|
||||
long stateDeadlineNanos = timeoutSeconds > 0
|
||||
? System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds)
|
||||
: Long.MAX_VALUE;
|
||||
// Two clocks can end this wait, and the join stops at whichever comes first: the state's
|
||||
// own TimeoutSeconds, and the state machine's budget for the whole execution.
|
||||
long joinDeadlineNanos = Math.min(stateDeadlineNanos, executionDeadlineNanos);
|
||||
|
||||
ArrayNode results = objectMapper.createArrayNode();
|
||||
try {
|
||||
for (Future<JsonNode> future : futures) {
|
||||
long remainingNanos = deadlineNanos - System.nanoTime();
|
||||
long remainingNanos = joinDeadlineNanos - System.nanoTime();
|
||||
if (remainingNanos <= 0) {
|
||||
throw new FailStateException("States.Timeout",
|
||||
"Parallel state timed out after " + timeoutSeconds + " seconds");
|
||||
throw parallelJoinExpired(stateDeadlineNanos, timeoutSeconds);
|
||||
}
|
||||
try {
|
||||
results.add(future.get(remainingNanos, TimeUnit.NANOSECONDS));
|
||||
} catch (java.util.concurrent.TimeoutException e) {
|
||||
throw new FailStateException("States.Timeout",
|
||||
"Parallel state timed out after " + timeoutSeconds + " seconds");
|
||||
throw parallelJoinExpired(stateDeadlineNanos, timeoutSeconds);
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
@@ -1986,9 +2115,24 @@ public class AslExecutor {
|
||||
return new StateResult(output, stateDef.path("Next").asText(null));
|
||||
}
|
||||
|
||||
private StateResult executeMapState(String name, JsonNode stateDef, JsonNode input, StateMachine sm,
|
||||
boolean jsonata, String topLevelQueryLanguage, JsonNode context,
|
||||
ObjectNode variables) throws Exception {
|
||||
/**
|
||||
* Names the clock that ended a Parallel's join. The state's own {@code TimeoutSeconds} fails
|
||||
* the state, so its Retry and Catch still apply; the state machine's budget ends the whole
|
||||
* execution and no Catch sees it.
|
||||
*/
|
||||
private RuntimeException parallelJoinExpired(long stateDeadlineNanos, int timeoutSeconds) {
|
||||
if (System.nanoTime() < stateDeadlineNanos) {
|
||||
return new ExecutionTimedOutException();
|
||||
}
|
||||
return new FailStateException("States.Timeout",
|
||||
"Parallel state timed out after " + timeoutSeconds + " seconds");
|
||||
}
|
||||
|
||||
private StateResult executeMapState(String name, JsonNode stateDef, JsonNode input,
|
||||
AtomicLong producedEventCount, StateMachine sm, boolean jsonata,
|
||||
String topLevelQueryLanguage, JsonNode context,
|
||||
ObjectNode variables, long executionDeadlineNanos)
|
||||
throws Exception {
|
||||
String processorMode = stateDef.path("ItemProcessor").path("ProcessorConfig")
|
||||
.path("Mode").asText("INLINE");
|
||||
boolean distributed = "DISTRIBUTED".equals(processorMode);
|
||||
@@ -2055,8 +2199,13 @@ public class AslExecutor {
|
||||
if (hasResultWriter) {
|
||||
childInputsByIndex[i] = iterInput;
|
||||
}
|
||||
JsonNode branchOutput = executeBranch(startAt, iteratorStates, iterInput, sm,
|
||||
topLevelQueryLanguage, iterContext, variables.deepCopy());
|
||||
// A Distributed Map runs each item as a child execution, and a child execution has a
|
||||
// history of its own: the item's events count against its own limit, not the parent's.
|
||||
// An inline Map's iterations are part of this execution and count here.
|
||||
AtomicLong childExecutionEventCount = distributed ? new AtomicLong() : producedEventCount;
|
||||
JsonNode branchOutput = executeBranch(startAt, iteratorStates, iterInput,
|
||||
childExecutionEventCount, sm, topLevelQueryLanguage, iterContext,
|
||||
variables.deepCopy());
|
||||
if (hasResultWriter) {
|
||||
childTimingsByIndex[i] = new long[]{startMs, System.currentTimeMillis()};
|
||||
}
|
||||
@@ -2064,9 +2213,17 @@ public class AslExecutor {
|
||||
};
|
||||
|
||||
if (itemCount > 0) {
|
||||
List<JsonNode> itemOutputs = MapIterationScheduler.execute(
|
||||
itemCount, Math.max(1, effectiveConcurrency),
|
||||
i -> () -> callUnderExecutionAccount(sm, makeTask.apply(i)));
|
||||
List<JsonNode> itemOutputs;
|
||||
try {
|
||||
itemOutputs = MapIterationScheduler.execute(
|
||||
itemCount, Math.max(1, effectiveConcurrency),
|
||||
i -> () -> callUnderExecutionAccount(sm, makeTask.apply(i)),
|
||||
executionDeadlineNanos);
|
||||
} catch (java.util.concurrent.TimeoutException e) {
|
||||
// The only deadline the scheduler is given is the state machine's budget, so its
|
||||
// expiry ends the execution rather than failing the Map state.
|
||||
throw new ExecutionTimedOutException();
|
||||
}
|
||||
results.addAll(itemOutputs);
|
||||
}
|
||||
|
||||
@@ -2499,10 +2656,17 @@ public class AslExecutor {
|
||||
return limited;
|
||||
}
|
||||
|
||||
private JsonNode executeBranch(String startAt, JsonNode states, JsonNode input, StateMachine sm,
|
||||
String topLevelQueryLanguage, JsonNode context, ObjectNode variables) throws Exception {
|
||||
List<HistoryEvent> ignored = new ArrayList<>();
|
||||
AtomicLong eventId = new AtomicLong(0);
|
||||
/**
|
||||
* Runs the states of one Parallel branch or one Map iteration. floci does not publish their
|
||||
* events, but they are events of the execution all the same, so each one is counted against its
|
||||
* history-event limit: a branch that never reaches a terminal state ends the whole execution at
|
||||
* event 25,000, exactly as one in the top-level flow does. A null history is what tells the
|
||||
* states below they are running inside a branch.
|
||||
*/
|
||||
private JsonNode executeBranch(String startAt, JsonNode states, JsonNode input,
|
||||
AtomicLong producedEventCount, StateMachine sm,
|
||||
String topLevelQueryLanguage, JsonNode context,
|
||||
ObjectNode variables) throws Exception {
|
||||
JsonNode currentInput = input;
|
||||
String currentState = startAt;
|
||||
|
||||
@@ -2517,10 +2681,15 @@ public class AslExecutor {
|
||||
String type = stateDef.path("Type").asText();
|
||||
boolean stateJsonata = isJsonata(stateDef, topLevelQueryLanguage);
|
||||
updateStateContext(context, currentState);
|
||||
countTowardsHistoryEventLimit(producedEventCount);
|
||||
StateResult result;
|
||||
try {
|
||||
result = executeStateWithRetry(currentState, type, stateDef, currentInput, ignored, eventId, sm,
|
||||
stateJsonata, topLevelQueryLanguage, context, variables);
|
||||
// A Parallel or Map branch runs on its own thread and is not cut mid-state by the
|
||||
// execution's TimeoutSeconds: the state loop that resumes once the branch returns
|
||||
// is where the budget is enforced.
|
||||
result = executeStateWithRetry(currentState, type, stateDef, currentInput,
|
||||
null, producedEventCount, sm, stateJsonata, topLevelQueryLanguage, context,
|
||||
variables, Long.MAX_VALUE);
|
||||
} catch (FailStateException e) {
|
||||
StateResult caught = handleCatch(stateDef, currentInput, e, stateJsonata, context, variables);
|
||||
if (caught == null) {
|
||||
@@ -2528,6 +2697,7 @@ public class AslExecutor {
|
||||
}
|
||||
result = caught;
|
||||
}
|
||||
countTowardsHistoryEventLimit(producedEventCount);
|
||||
currentInput = result.output();
|
||||
currentState = result.nextState();
|
||||
if ("Succeed".equals(type) || stateDef.path("End").asBoolean(false)) {
|
||||
@@ -3458,18 +3628,76 @@ public class AslExecutor {
|
||||
|
||||
// ──────────────────────────── History helpers ────────────────────────────
|
||||
|
||||
private void addEvent(List<HistoryEvent> history, AtomicLong counter, String type, Map<String, Object> details) {
|
||||
addEvent(history, counter, type, counter.get(), details);
|
||||
/**
|
||||
* Counts one event towards the limit AWS puts on an execution's history, leaving the last slot
|
||||
* free: it belongs to the event that ends the execution. The count is taken before it is
|
||||
* judged, so however many branches and Map iterations are producing events at once, exactly one
|
||||
* of them takes event 24,999 and every other one finds the limit reached.
|
||||
*
|
||||
* <p>Reaching it raises {@code States.Runtime} at the state that produced the event, and that
|
||||
* ends the whole execution: {@link #catchMatches} refuses {@code States.Runtime} before it
|
||||
* reads {@code ErrorEquals}, so a Retry and a Catch the state declares for it both stand down.
|
||||
*/
|
||||
static void countTowardsHistoryEventLimit(AtomicLong producedEventCount) {
|
||||
if (producedEventCount.incrementAndGet() >= MAX_HISTORY_EVENTS) {
|
||||
throw new FailStateException("States.Runtime", HISTORY_EVENT_LIMIT_CAUSE);
|
||||
}
|
||||
}
|
||||
|
||||
private void addEvent(List<HistoryEvent> history, AtomicLong counter, String type, long previousEventId,
|
||||
Map<String, Object> details) {
|
||||
var event = new HistoryEvent();
|
||||
event.setId(counter.incrementAndGet());
|
||||
event.setPreviousEventId(previousEventId);
|
||||
event.setType(type);
|
||||
event.setDetails(details);
|
||||
history.add(event);
|
||||
/**
|
||||
* Records an event the state machine produced: counted against the history-event limit, then
|
||||
* published.
|
||||
*
|
||||
* <p>{@code history} is null inside a Parallel branch or a Map iteration. Their states are
|
||||
* states of this execution and their events count against its limit, but floci does not publish
|
||||
* them, so there is nothing to build for them beyond the count.
|
||||
*/
|
||||
private void publishEvent(List<HistoryEvent> history, AtomicLong producedEventCount, String type,
|
||||
Map<String, Object> details) {
|
||||
countTowardsHistoryEventLimit(producedEventCount);
|
||||
if (history == null) {
|
||||
return;
|
||||
}
|
||||
appendEvent(history, type, history.size(), details);
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a state's Entered event with the previousEventId the top-level flow works out: AWS
|
||||
* leaves the Entered event of the state an execution starts in unchained, at previousEventId 0,
|
||||
* rather than pointing it at the ExecutionStarted event before it. Only the top-level flow
|
||||
* publishes these, so its history is never null.
|
||||
*/
|
||||
private void publishStateEnteredEvent(List<HistoryEvent> history, AtomicLong producedEventCount,
|
||||
String type, long previousEventId,
|
||||
Map<String, Object> details) {
|
||||
countTowardsHistoryEventLimit(producedEventCount);
|
||||
appendEvent(history, type, previousEventId, details);
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the event that ends the execution. It does not count towards the history-event limit:
|
||||
* an execution always gets to say how it ended, in the slot {@link #publishEvent} leaves free.
|
||||
*/
|
||||
private void publishTerminalEvent(List<HistoryEvent> history, String type, Map<String, Object> details) {
|
||||
appendEvent(history, type, history.size(), details);
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends an event and numbers it from the end of the history: the published history is the one
|
||||
* authority for an event's id, so an event's id is its position in the list. Held under the
|
||||
* history's own monitor, because StopExecution appends the terminal event of an aborted
|
||||
* execution from another thread and seals the history against anything after it.
|
||||
*/
|
||||
private void appendEvent(List<HistoryEvent> history, String type, long previousEventId,
|
||||
Map<String, Object> details) {
|
||||
synchronized (history) {
|
||||
var event = new HistoryEvent();
|
||||
event.setId(history.size() + 1L);
|
||||
event.setPreviousEventId(previousEventId);
|
||||
event.setType(type);
|
||||
event.setDetails(details);
|
||||
history.add(event);
|
||||
}
|
||||
}
|
||||
|
||||
private record TaskEventProfile(String prefix, String resourceType, String resource) {}
|
||||
@@ -3492,8 +3720,9 @@ public class AslExecutor {
|
||||
return new TaskEventProfile("Task", resource, resource);
|
||||
}
|
||||
|
||||
private void addTaskScheduledEvent(List<HistoryEvent> history, AtomicLong eventId, TaskEventProfile profile,
|
||||
JsonNode stateDef, JsonNode effectiveInput, StateMachine sm) {
|
||||
private void addTaskScheduledEvent(List<HistoryEvent> history, AtomicLong producedEventCount,
|
||||
TaskEventProfile profile, JsonNode stateDef, JsonNode effectiveInput,
|
||||
StateMachine sm) {
|
||||
var details = new LinkedHashMap<String, Object>();
|
||||
if (profile.resourceType() != null) {
|
||||
details.put("resourceType", profile.resourceType());
|
||||
@@ -3512,33 +3741,34 @@ public class AslExecutor {
|
||||
if (stateDef.path("HeartbeatSeconds").isNumber()) {
|
||||
details.put("heartbeatInSeconds", stateDef.path("HeartbeatSeconds").asLong());
|
||||
}
|
||||
addEvent(history, eventId, profile.prefix() + "Scheduled", details);
|
||||
publishEvent(history, producedEventCount, profile.prefix() + "Scheduled", details);
|
||||
}
|
||||
|
||||
private void addTaskStartedEvent(List<HistoryEvent> history, AtomicLong eventId, TaskEventProfile profile) {
|
||||
private void addTaskStartedEvent(List<HistoryEvent> history, AtomicLong producedEventCount,
|
||||
TaskEventProfile profile) {
|
||||
if ("Task".equals(profile.prefix())) {
|
||||
addEvent(history, eventId, profile.prefix() + "Started",
|
||||
publishEvent(history, producedEventCount, profile.prefix() + "Started",
|
||||
Map.of("resourceType", profile.resourceType(), "resource", profile.resource()));
|
||||
} else {
|
||||
addEvent(history, eventId, profile.prefix() + "Started", null);
|
||||
publishEvent(history, producedEventCount, profile.prefix() + "Started", null);
|
||||
}
|
||||
}
|
||||
|
||||
private void addTaskSucceededEvent(List<HistoryEvent> history, AtomicLong eventId, TaskEventProfile profile,
|
||||
JsonNode taskResult) {
|
||||
private void addTaskSucceededEvent(List<HistoryEvent> history, AtomicLong producedEventCount,
|
||||
TaskEventProfile profile, JsonNode taskResult) {
|
||||
var output = taskResult.toString();
|
||||
if ("Task".equals(profile.prefix())) {
|
||||
addEvent(history, eventId, profile.prefix() + "Succeeded",
|
||||
publishEvent(history, producedEventCount, profile.prefix() + "Succeeded",
|
||||
Map.of("resourceType", profile.resourceType(), "resource", profile.resource(),
|
||||
"output", output, "outputDetails", Map.of("truncated", false)));
|
||||
} else {
|
||||
addEvent(history, eventId, profile.prefix() + "Succeeded",
|
||||
publishEvent(history, producedEventCount, profile.prefix() + "Succeeded",
|
||||
Map.of("output", output, "outputDetails", Map.of("truncated", false)));
|
||||
}
|
||||
}
|
||||
|
||||
private void addTaskFailedEvent(List<HistoryEvent> history, AtomicLong eventId, TaskEventProfile profile,
|
||||
String error, String cause) {
|
||||
private void addTaskFailedEvent(List<HistoryEvent> history, AtomicLong producedEventCount,
|
||||
TaskEventProfile profile, String error, String cause) {
|
||||
var details = new LinkedHashMap<String, Object>();
|
||||
if ("Task".equals(profile.prefix())) {
|
||||
details.put("resourceType", profile.resourceType());
|
||||
@@ -3550,27 +3780,103 @@ public class AslExecutor {
|
||||
if (cause != null) {
|
||||
details.put("cause", cause);
|
||||
}
|
||||
addEvent(history, eventId, profile.prefix() + "Failed", details);
|
||||
publishEvent(history, producedEventCount, profile.prefix() + "Failed", details);
|
||||
}
|
||||
|
||||
private void failExecution(Execution exec, List<HistoryEvent> history, AtomicLong eventId, FailStateException e) {
|
||||
failExecution(exec, history, eventId, e.error != null ? e.error : "States.Runtime",
|
||||
e.cause != null ? e.cause : "");
|
||||
/**
|
||||
* The event a Task leaves when one of its clocks runs out. It names {@code States.Timeout} for
|
||||
* both {@code TimeoutSeconds} and {@code HeartbeatSeconds}, and carries no cause.
|
||||
*/
|
||||
private void addTaskTimedOutEvent(List<HistoryEvent> history, AtomicLong producedEventCount,
|
||||
TaskEventProfile profile) {
|
||||
var details = new LinkedHashMap<String, Object>();
|
||||
if ("Task".equals(profile.prefix())) {
|
||||
details.put("resourceType", profile.resourceType());
|
||||
details.put("resource", profile.resource());
|
||||
}
|
||||
details.put("error", "States.Timeout");
|
||||
publishEvent(history, producedEventCount, profile.prefix() + "TimedOut", details);
|
||||
}
|
||||
|
||||
private void failExecution(Execution exec, List<HistoryEvent> history, FailStateException e) {
|
||||
failExecution(exec, history, e.error != null ? e.error : "States.Runtime", e.cause);
|
||||
}
|
||||
|
||||
/**
|
||||
* The single terminal-failure write: every way an execution can fail leaves the same
|
||||
* {@code error}, {@code cause} and {@code ExecutionFailed} event behind, so a client cannot
|
||||
* tell a Fail state from a state that threw from a runtime Error by what it reads back.
|
||||
*
|
||||
* <p>A null {@code cause} is the failure saying it has none, and both DescribeExecution and the
|
||||
* ExecutionFailed event leave the key out rather than reporting it empty. Only a task that ran
|
||||
* out of its TimeoutSeconds or HeartbeatSeconds budget arrives here without one.
|
||||
*/
|
||||
private void failExecution(Execution exec, List<HistoryEvent> history, AtomicLong eventId,
|
||||
String error, String cause) {
|
||||
exec.setError(error);
|
||||
exec.setCause(cause);
|
||||
exec.setStopDate(System.currentTimeMillis() / 1000.0);
|
||||
exec.setStatus("FAILED");
|
||||
addEvent(history, eventId, "ExecutionFailed",
|
||||
Map.of("error", error, "cause", cause));
|
||||
private void failExecution(Execution exec, List<HistoryEvent> history, String error, String cause) {
|
||||
synchronized (exec) {
|
||||
if (abortedByCaller(exec)) {
|
||||
return;
|
||||
}
|
||||
exec.setError(error);
|
||||
exec.setCause(cause);
|
||||
exec.setStopDate(System.currentTimeMillis() / 1000.0);
|
||||
exec.setStatus("FAILED");
|
||||
}
|
||||
var details = new LinkedHashMap<String, Object>();
|
||||
details.put("error", error);
|
||||
if (cause != null) {
|
||||
details.put("cause", cause);
|
||||
}
|
||||
publishTerminalEvent(history, "ExecutionFailed", details);
|
||||
}
|
||||
|
||||
/**
|
||||
* The third terminal write. A timed out execution carries neither error nor cause:
|
||||
* DescribeExecution leaves both keys out, and States.Timeout is named only inside the
|
||||
* ExecutionTimedOut event, which points at the start of the execution rather than at the state
|
||||
* it cut. The event is appended rather than published, because it is what ends the execution
|
||||
* and the history-event limit leaves the last slot free for exactly that.
|
||||
*/
|
||||
private void timeOutExecution(Execution exec, List<HistoryEvent> history) {
|
||||
synchronized (exec) {
|
||||
if (abortedByCaller(exec)) {
|
||||
return;
|
||||
}
|
||||
exec.setStopDate(System.currentTimeMillis() / 1000.0);
|
||||
exec.setStatus("TIMED_OUT");
|
||||
}
|
||||
appendEvent(history, "ExecutionTimedOut", 0L, Map.of("error", "States.Timeout"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The single terminal-success write, the mirror of {@link #failExecution}.
|
||||
*
|
||||
* <p>Status is the publication point, so it is set last. describeExecution hands out this same
|
||||
* live Execution, so a client polling for SUCCEEDED between setStatus and setOutput would read
|
||||
* a terminal execution with a null output, which real Step Functions never returns.
|
||||
*/
|
||||
private void succeedExecution(Execution exec, List<HistoryEvent> history, JsonNode output) {
|
||||
synchronized (exec) {
|
||||
if (abortedByCaller(exec)) {
|
||||
return;
|
||||
}
|
||||
exec.setOutput(output.toString());
|
||||
exec.setStopDate(System.currentTimeMillis() / 1000.0);
|
||||
exec.setStatus("SUCCEEDED");
|
||||
}
|
||||
publishTerminalEvent(history, "ExecutionSucceeded",
|
||||
Map.of("output", output.toString(), "outputDetails", Map.of("truncated", false)));
|
||||
}
|
||||
|
||||
/**
|
||||
* True once StopExecution published ABORTED on this execution. The state loop reads it between
|
||||
* states and every terminal write here reads it before publishing, so the worker's own status
|
||||
* loses the race against a stop that arrived while it was still stepping: what a caller has
|
||||
* already read back from DescribeExecution is what stands.
|
||||
*/
|
||||
private static boolean abortedByCaller(Execution exec) {
|
||||
synchronized (exec) {
|
||||
return "ABORTED".equals(exec.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
private StateResult handleCatch(JsonNode stateDef, JsonNode input, FailStateException failure,
|
||||
@@ -3583,7 +3889,7 @@ public class AslExecutor {
|
||||
String cause = failure.cause != null ? failure.cause : "";
|
||||
for (int i = 0; i < catchers.size(); i++) {
|
||||
JsonNode catcher = catchers.get(i);
|
||||
if (!catchMatches(catcher, error)) {
|
||||
if (!catchMatches(catcher, failure)) {
|
||||
continue;
|
||||
}
|
||||
String next = catcher.path("Next").asText(null);
|
||||
@@ -3607,11 +3913,12 @@ public class AslExecutor {
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean catchMatches(JsonNode catcher, String error) {
|
||||
private boolean catchMatches(JsonNode catcher, FailStateException failure) {
|
||||
var errors = catcher.path("ErrorEquals");
|
||||
if (!errors.isArray()) {
|
||||
return false;
|
||||
}
|
||||
var error = failure.error != null ? failure.error : "States.Runtime";
|
||||
// States.Runtime is never retried or caught, even when named explicitly in
|
||||
// ErrorEquals. Verified against real AWS: the execution fails immediately.
|
||||
if ("States.Runtime".equals(error)) {
|
||||
@@ -3619,7 +3926,7 @@ public class AslExecutor {
|
||||
}
|
||||
for (JsonNode candidate : errors) {
|
||||
var expected = candidate.asText();
|
||||
if (expected.equals(error)) {
|
||||
if (failure.isNamedBy(expected)) {
|
||||
return true;
|
||||
}
|
||||
if ("States.TaskFailed".equals(expected)
|
||||
@@ -3663,6 +3970,17 @@ public class AslExecutor {
|
||||
|
||||
record StateResult(JsonNode output, String nextState) {}
|
||||
|
||||
/**
|
||||
* Thrown when the state machine's top-level {@code TimeoutSeconds} budget runs out. It is not a
|
||||
* {@link FailStateException} on purpose: a Catch clause never sees it, no Retry re-runs the
|
||||
* state it cut, and the execution ends TIMED_OUT rather than FAILED.
|
||||
*/
|
||||
static class ExecutionTimedOutException extends RuntimeException {
|
||||
ExecutionTimedOutException() {
|
||||
super("States.Timeout");
|
||||
}
|
||||
}
|
||||
|
||||
static class FailStateException extends RuntimeException {
|
||||
final String error;
|
||||
final String cause;
|
||||
@@ -3672,5 +3990,34 @@ public class AslExecutor {
|
||||
this.error = error;
|
||||
this.cause = cause;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an {@code ErrorEquals} entry spelling {@code errorName} names this failure. A
|
||||
* failure answers to the error it reports, and a task timeout answers to the name of the
|
||||
* clock that ran out as well.
|
||||
*/
|
||||
boolean isNamedBy(String errorName) {
|
||||
return errorName.equals(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when a Task ran out of one of the two clocks bounding its wait for a task token. Both
|
||||
* report {@code States.Timeout} with no cause and emit a {@code TimedOut} history event; a
|
||||
* {@code HeartbeatSeconds} expiry is also caught by an {@code ErrorEquals} naming
|
||||
* {@code States.HeartbeatTimeout}.
|
||||
*/
|
||||
static class TaskTimedOutException extends FailStateException {
|
||||
private final String expiredClockError;
|
||||
|
||||
TaskTimedOutException(String expiredClockError) {
|
||||
super("States.Timeout", null);
|
||||
this.expiredClockError = expiredClockError;
|
||||
}
|
||||
|
||||
@Override
|
||||
boolean isNamedBy(String errorName) {
|
||||
return super.isNamedBy(errorName) || errorName.equals(expiredClockError);
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
-8
@@ -12,6 +12,8 @@ import java.util.concurrent.ExecutorCompletionService;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.function.IntFunction;
|
||||
|
||||
/** Runs Map iterations with a bounded in-flight window while preserving input order. */
|
||||
@@ -20,8 +22,15 @@ final class MapIterationScheduler {
|
||||
private MapIterationScheduler() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param deadlineNanos a {@link System#nanoTime()} reading the iterations must all finish
|
||||
* before, or {@link Long#MAX_VALUE} for no deadline. Reaching it throws
|
||||
* {@link TimeoutException}, leaving the caller to say what the expiry
|
||||
* means for the state it belongs to.
|
||||
*/
|
||||
static <T> List<T> execute(int itemCount, int maxConcurrency,
|
||||
IntFunction<Callable<T>> taskFactory) throws Exception {
|
||||
IntFunction<Callable<T>> taskFactory, long deadlineNanos)
|
||||
throws Exception {
|
||||
if (itemCount < 0) {
|
||||
throw new IllegalArgumentException("itemCount must not be negative");
|
||||
}
|
||||
@@ -31,12 +40,8 @@ final class MapIterationScheduler {
|
||||
if (itemCount == 0) {
|
||||
return List.of();
|
||||
}
|
||||
if (itemCount == 1 || maxConcurrency == 1) {
|
||||
List<T> results = new ArrayList<>(itemCount);
|
||||
for (int i = 0; i < itemCount; i++) {
|
||||
results.add(taskFactory.apply(i).call());
|
||||
}
|
||||
return results;
|
||||
if (System.nanoTime() >= deadlineNanos) {
|
||||
throw new TimeoutException();
|
||||
}
|
||||
|
||||
int inFlightLimit = Math.min(itemCount, maxConcurrency);
|
||||
@@ -53,7 +58,12 @@ final class MapIterationScheduler {
|
||||
inFlight.add(submit(completions, taskFactory, nextIndex++));
|
||||
}
|
||||
while (completed < itemCount) {
|
||||
Future<IndexedResult<T>> future = completions.take();
|
||||
Future<IndexedResult<T>> future =
|
||||
completions.poll(deadlineNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
|
||||
if (future == null) {
|
||||
cancel(inFlight);
|
||||
throw new TimeoutException();
|
||||
}
|
||||
inFlight.remove(future);
|
||||
IndexedResult<T> result = future.get();
|
||||
results.set(result.index(), result.value());
|
||||
|
||||
+3
-1
@@ -410,7 +410,9 @@ public class StepFunctionsJsonHandler {
|
||||
private Response handleSendTaskFailure(JsonNode request) {
|
||||
service.sendTaskFailure(
|
||||
request.path("taskToken").asText(),
|
||||
request.path("cause").asText(null),
|
||||
// A SendTaskFailure that names no cause fails the task with an empty one, not with
|
||||
// a missing key.
|
||||
request.path("cause").asText(""),
|
||||
request.path("error").asText(null)
|
||||
);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
|
||||
+102
-16
@@ -46,9 +46,12 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
private final StorageBackend<String, Execution> executionStore;
|
||||
private final StorageBackend<String, Activity> activityStore;
|
||||
private final StorageBackend<String, MapRun> mapRunStore;
|
||||
private final Map<String, List<HistoryEvent>> historyCache = new ConcurrentHashMap<>();
|
||||
private final Map<String, ExecutionHistory> historyCache = new ConcurrentHashMap<>();
|
||||
private final Map<String, BlockingQueue<ActivityTask>> activityQueues = new ConcurrentHashMap<>();
|
||||
private final Map<String, CompletableFuture<JsonNode>> pendingTaskTokens = new ConcurrentHashMap<>();
|
||||
// When each pending token last showed progress, so a Task's HeartbeatSeconds can bound the gap
|
||||
// between heartbeats instead of the whole wait.
|
||||
private final Map<String, Long> taskHeartbeatNanos = new ConcurrentHashMap<>();
|
||||
private final RegionResolver regionResolver;
|
||||
private final AslExecutor aslExecutor;
|
||||
private final ObjectMapper objectMapper;
|
||||
@@ -104,6 +107,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
activityQueues.clear();
|
||||
pendingTaskTokens.values().forEach(f -> f.completeExceptionally(new RuntimeException("StepFunctionsService cleared")));
|
||||
pendingTaskTokens.clear();
|
||||
taskHeartbeatNanos.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -524,7 +528,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
|
||||
executionStore.put(arn, exec);
|
||||
|
||||
var history = new ArrayList<HistoryEvent>();
|
||||
var history = new ExecutionHistory();
|
||||
var startEvent = new HistoryEvent();
|
||||
startEvent.setId(1L);
|
||||
startEvent.setPreviousEventId(0L);
|
||||
@@ -537,9 +541,10 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
|
||||
LOG.infov("Started execution: {0}", arn);
|
||||
|
||||
// The executor appends to this same history, so the cache entry put above is already the
|
||||
// finished history by the time this runs.
|
||||
aslExecutor.executeAsync(sm, exec, history, mockedTestCase, (updatedExec, updatedHistory) -> {
|
||||
executionStore.put(updatedExec.getExecutionArn(), updatedExec);
|
||||
historyCache.put(updatedExec.getExecutionArn(), updatedHistory);
|
||||
LOG.infov("Execution {0} completed with status {1}", updatedExec.getExecutionArn(), updatedExec.getStatus());
|
||||
});
|
||||
|
||||
@@ -660,30 +665,80 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
.map(e -> e.getStateMachineArn().equals(stateMachineArn)).orElse(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* Aborts a running execution. The caller's {@code error} and {@code cause} land on the
|
||||
* Execution itself, not only on the history event, so DescribeExecution reports them.
|
||||
*
|
||||
* <p>The worker thread may still be inside a state when this runs. It shares this Execution
|
||||
* instance and reads the status it publishes here, so the writes are made under the same
|
||||
* monitor the worker's terminal write takes: ABORTED is the status that stands.
|
||||
*
|
||||
* <p>ExecutionAborted seals the history for the same reason: the worker still has the state it
|
||||
* is inside left to record, and those events belong to an execution the caller has already
|
||||
* been told is finished.
|
||||
*/
|
||||
public void stopExecution(String arn, String cause, String error) {
|
||||
Execution exec = describeExecution(arn);
|
||||
if (!"RUNNING".equals(exec.getStatus())) {
|
||||
return;
|
||||
synchronized (exec) {
|
||||
if (!"RUNNING".equals(exec.getStatus())) {
|
||||
return;
|
||||
}
|
||||
exec.setError(error);
|
||||
exec.setCause(cause);
|
||||
exec.setStopDate(System.currentTimeMillis() / 1000.0);
|
||||
exec.setStatus("ABORTED");
|
||||
}
|
||||
exec.setStopDate(System.currentTimeMillis() / 1000.0);
|
||||
exec.setStatus("ABORTED");
|
||||
executionStore.put(arn, exec);
|
||||
|
||||
List<HistoryEvent> history = historyCache.getOrDefault(arn, new ArrayList<>());
|
||||
HistoryEvent event = new HistoryEvent();
|
||||
event.setId(history.size() + 1L);
|
||||
event.setPreviousEventId((long) history.size());
|
||||
event.setType("ExecutionAborted");
|
||||
Map<String, Object> details = new HashMap<>();
|
||||
if (error != null) details.put("error", error);
|
||||
if (cause != null) details.put("cause", cause);
|
||||
event.setDetails(details);
|
||||
history.add(event);
|
||||
// An execution can outlive its history: the executions are stored, the histories are held in
|
||||
// memory only, so a restart in persistent mode brings a RUNNING execution back with nothing
|
||||
// behind it. The abort still gets recorded, against a history that starts here.
|
||||
historyCache.computeIfAbsent(arn, key -> new ExecutionHistory())
|
||||
.sealWith("ExecutionAborted", details);
|
||||
}
|
||||
|
||||
public List<HistoryEvent> getExecutionHistory(String arn) {
|
||||
describeExecution(arn);
|
||||
return historyCache.getOrDefault(arn, Collections.emptyList());
|
||||
ExecutionHistory history = historyCache.get(arn);
|
||||
return history != null ? history : Collections.emptyList();
|
||||
}
|
||||
|
||||
/**
|
||||
* The history of one execution, appended to by the worker thread running the state machine and
|
||||
* by the thread serving StopExecution. Sealing it with the terminal event is what makes that
|
||||
* event the last one: the worker is still inside a state when the abort lands, and the events
|
||||
* it has left to record belong to an execution the caller has already been told is finished.
|
||||
*
|
||||
* <p>The seal is enforced in {@link #add}, the one way the worker appends. {@code addAll} does
|
||||
* not route through it, so a bulk append would write past the seal; nothing does one today.
|
||||
*/
|
||||
static final class ExecutionHistory extends ArrayList<HistoryEvent> {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private boolean sealed;
|
||||
|
||||
@Override
|
||||
public synchronized boolean add(HistoryEvent event) {
|
||||
if (sealed) {
|
||||
return false;
|
||||
}
|
||||
return super.add(event);
|
||||
}
|
||||
|
||||
/** Appends the terminal event, numbered from the end of the history, and takes no more. */
|
||||
synchronized void sealWith(String terminalEventType, Map<String, Object> details) {
|
||||
HistoryEvent terminalEvent = new HistoryEvent();
|
||||
terminalEvent.setId(size() + 1L);
|
||||
terminalEvent.setPreviousEventId((long) size());
|
||||
terminalEvent.setType(terminalEventType);
|
||||
terminalEvent.setDetails(details);
|
||||
add(terminalEvent);
|
||||
sealed = true;
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── Activities ────────────────────────────
|
||||
@@ -744,9 +799,32 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
public CompletableFuture<JsonNode> registerPendingToken(String token) {
|
||||
CompletableFuture<JsonNode> future = new CompletableFuture<>();
|
||||
pendingTaskTokens.put(token, future);
|
||||
taskHeartbeatNanos.put(token, System.nanoTime());
|
||||
return future;
|
||||
}
|
||||
|
||||
/**
|
||||
* When the token last showed progress: the moment its task was scheduled, then every
|
||||
* SendTaskHeartbeat that named it. A token that is no longer pending reads as having just
|
||||
* reported, so a task whose result already arrived is never failed on a heartbeat gap.
|
||||
*/
|
||||
public long lastTaskHeartbeatNanos(String taskToken) {
|
||||
Long reportedAt = taskToken != null ? taskHeartbeatNanos.get(taskToken) : null;
|
||||
return reportedAt != null ? reportedAt : System.nanoTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* Forgets a token the waiting task has stopped listening for, so a later SendTaskSuccess,
|
||||
* SendTaskFailure or SendTaskHeartbeat naming it reports no pending task.
|
||||
*/
|
||||
public void discardPendingToken(String taskToken) {
|
||||
if (taskToken == null) {
|
||||
return;
|
||||
}
|
||||
pendingTaskTokens.remove(taskToken);
|
||||
taskHeartbeatNanos.remove(taskToken);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Tasks ────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -782,8 +860,16 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the gap a Task's {@code HeartbeatSeconds} allows. A heartbeat for a token nobody is
|
||||
* waiting for is logged and changes nothing, as in {@link #sendTaskSuccess(String, String)}.
|
||||
*/
|
||||
public void sendTaskHeartbeat(String taskToken) {
|
||||
LOG.debugv("Task heartbeat for token {0}", taskToken);
|
||||
if (taskToken == null || !pendingTaskTokens.containsKey(taskToken)) {
|
||||
LOG.warnv("SendTaskHeartbeat: no pending task for token {0}", taskToken);
|
||||
return;
|
||||
}
|
||||
taskHeartbeatNanos.put(taskToken, System.nanoTime());
|
||||
}
|
||||
|
||||
// ──────────────────────────── Map runs ────────────────────────────
|
||||
|
||||
Reference in new issue
Block a user