mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(stepfunctions): preserve callback token ownership (#6271)
Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
1 parent
efc693ad17
commit
d3359662e5
6 files changed
+281
-53
No files matched your search
@@ -943,7 +943,8 @@ public class AslExecutor {
|
||||
String credentialsRoleArn = credentials == null ? null : credentials.path("RoleArn").asText(null);
|
||||
|
||||
// Registered after the input template resolved, so a template failure leaves no token behind.
|
||||
CompletableFuture<JsonNode> tokenFuture = needsToken ? sfnService.get().registerPendingToken(taskToken) : null;
|
||||
CompletableFuture<JsonNode> tokenFuture = needsToken ? sfnService.get().registerPendingToken(taskToken,
|
||||
AwsArnUtils.parse(sm.getStateMachineArn()).accountId()) : null;
|
||||
TaskEventProfile profile = taskEventProfile(resource, isActivity);
|
||||
JsonNode taskResult;
|
||||
// Read before the scheduled event is built, so a large input or a slow history callback
|
||||
@@ -1726,8 +1727,10 @@ public class AslExecutor {
|
||||
*/
|
||||
private JsonNode invokeAwsSdkSfnSendTaskSuccess(JsonNode input) throws Exception {
|
||||
String taskToken = input.path("TaskToken").asText(null);
|
||||
if (!sfnService.get().sendTaskSuccess(taskToken, sdkPayload(input.path("Output")))) {
|
||||
throw new FailStateException("Sfn.InvalidTokenException", "Invalid Token: 'Invalid token'");
|
||||
try {
|
||||
sfnService.get().sendTaskSuccess(taskToken, sdkPayload(input.path("Output")));
|
||||
} catch (AwsException e) {
|
||||
throw new FailStateException(sdkExceptionName("Sfn", e.getErrorCode()), e.getMessage());
|
||||
}
|
||||
return objectMapper.createObjectNode();
|
||||
}
|
||||
@@ -1735,9 +1738,11 @@ public class AslExecutor {
|
||||
/** AWS SDK integration for {@code sfn:sendTaskFailure}, token semantics as in SendTaskSuccess. */
|
||||
private JsonNode invokeAwsSdkSfnSendTaskFailure(JsonNode input) {
|
||||
String taskToken = input.path("TaskToken").asText(null);
|
||||
if (!sfnService.get().sendTaskFailure(taskToken, input.path("Cause").asText(null),
|
||||
input.path("Error").asText(null))) {
|
||||
throw new FailStateException("Sfn.InvalidTokenException", "Invalid Token: 'Invalid token'");
|
||||
try {
|
||||
sfnService.get().sendTaskFailure(taskToken, input.path("Cause").asText(null),
|
||||
input.path("Error").asText(null));
|
||||
} catch (AwsException e) {
|
||||
throw new FailStateException(sdkExceptionName("Sfn", e.getErrorCode()), e.getMessage());
|
||||
}
|
||||
return objectMapper.createObjectNode();
|
||||
}
|
||||
|
||||
+82
-44
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -60,7 +61,15 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
private final StorageBackend<String, MapRun> mapRunStore;
|
||||
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<>();
|
||||
private final Map<String, PendingTask> pendingTaskTokens = new ConcurrentHashMap<>();
|
||||
// Only recent closures are classified as TaskTimedOut: five minutes, at most 1,024 tokens.
|
||||
// Evicted/older tokens remain InvalidToken. No task payloads are retained.
|
||||
private final Map<String, ClosedTask> closedTaskTokens = new LinkedHashMap<>();
|
||||
private static final long CLOSED_TOKEN_RETENTION_NANOS = TimeUnit.MINUTES.toNanos(5);
|
||||
private static final int MAX_CLOSED_TOKENS = 1024;
|
||||
|
||||
private record PendingTask(String accountId, CompletableFuture<JsonNode> future) {}
|
||||
private record ClosedTask(String accountId, long closedAtNanos) {}
|
||||
// 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<>();
|
||||
@@ -148,8 +157,11 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
public void clear() {
|
||||
historyCache.clear();
|
||||
activityQueues.clear();
|
||||
pendingTaskTokens.values().forEach(f -> f.completeExceptionally(new RuntimeException("StepFunctionsService cleared")));
|
||||
pendingTaskTokens.values().forEach(f -> f.future().completeExceptionally(new RuntimeException("StepFunctionsService cleared")));
|
||||
pendingTaskTokens.clear();
|
||||
synchronized (this) {
|
||||
closedTaskTokens.clear();
|
||||
}
|
||||
taskHeartbeatNanos.clear();
|
||||
}
|
||||
|
||||
@@ -1184,9 +1196,9 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
queue.add(new ActivityTask(taskToken, input));
|
||||
}
|
||||
|
||||
public CompletableFuture<JsonNode> registerPendingToken(String token) {
|
||||
public synchronized CompletableFuture<JsonNode> registerPendingToken(String token, String accountId) {
|
||||
CompletableFuture<JsonNode> future = new CompletableFuture<>();
|
||||
pendingTaskTokens.put(token, future);
|
||||
pendingTaskTokens.put(token, new PendingTask(Objects.requireNonNull(accountId), future));
|
||||
taskHeartbeatNanos.put(token, System.nanoTime());
|
||||
return future;
|
||||
}
|
||||
@@ -1201,62 +1213,88 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
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;
|
||||
/** Retires a token when its task stops waiting, including timeout and resource failure. */
|
||||
public synchronized void discardPendingToken(String taskToken) {
|
||||
if (taskToken != null) {
|
||||
PendingTask pending = pendingTaskTokens.remove(taskToken);
|
||||
taskHeartbeatNanos.remove(taskToken);
|
||||
if (pending != null) {
|
||||
rememberClosed(taskToken, pending.accountId());
|
||||
}
|
||||
}
|
||||
pendingTaskTokens.remove(taskToken);
|
||||
taskHeartbeatNanos.remove(taskToken);
|
||||
}
|
||||
|
||||
// ──────────────────────────── Tasks ────────────────────────────
|
||||
private void rememberClosed(String token, String accountId) {
|
||||
long now = System.nanoTime();
|
||||
closedTaskTokens.entrySet().removeIf(entry -> now - entry.getValue().closedAtNanos()
|
||||
>= CLOSED_TOKEN_RETENTION_NANOS);
|
||||
closedTaskTokens.put(token, new ClosedTask(accountId, now));
|
||||
while (closedTaskTokens.size() > MAX_CLOSED_TOKENS) {
|
||||
closedTaskTokens.remove(closedTaskTokens.keySet().iterator().next());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return whether the token named a task that was waiting for it. The
|
||||
* {@code aws-sdk:sfn:sendTaskSuccess} Task integration fails the calling state when it
|
||||
* did not, the way AWS answers an unknown token with {@code InvalidToken}.
|
||||
*/
|
||||
private PendingTask requirePendingTask(String token) {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
PendingTask pending = token == null ? null : pendingTaskTokens.get(token);
|
||||
if (pending != null) {
|
||||
requireTokenOwner(pending.accountId(), accountId);
|
||||
return pending;
|
||||
}
|
||||
ClosedTask closed = token == null ? null : closedTaskTokens.get(token);
|
||||
if (closed != null && System.nanoTime() - closed.closedAtNanos() >= CLOSED_TOKEN_RETENTION_NANOS) {
|
||||
closedTaskTokens.remove(token);
|
||||
closed = null;
|
||||
}
|
||||
if (closed != null) {
|
||||
requireTokenOwner(closed.accountId(), accountId);
|
||||
throw new AwsException("TaskTimedOut", "The associated task has already been closed.", 400);
|
||||
}
|
||||
throw new AwsException("InvalidToken", "Invalid Token: 'Invalid token'", 400);
|
||||
}
|
||||
|
||||
private void requireTokenOwner(String owner, String caller) {
|
||||
if (!owner.equals(caller)) {
|
||||
throw new AwsException("AccessDeniedException", "Not authorized to access this resource.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized CompletableFuture<JsonNode> claimPendingTask(String token) {
|
||||
PendingTask pending = requirePendingTask(token);
|
||||
pendingTaskTokens.remove(token);
|
||||
taskHeartbeatNanos.remove(token);
|
||||
rememberClosed(token, pending.accountId());
|
||||
return pending.future();
|
||||
}
|
||||
|
||||
/** Claims an owned callback exactly once; completion runs outside the token lock. */
|
||||
public boolean sendTaskSuccess(String taskToken, String output) {
|
||||
CompletableFuture<JsonNode> future = taskToken != null ? pendingTaskTokens.remove(taskToken) : null;
|
||||
if (future == null) {
|
||||
LOG.warnv("SendTaskSuccess: no pending task for token {0}", taskToken);
|
||||
return false;
|
||||
JsonNode result;
|
||||
synchronized (this) {
|
||||
requirePendingTask(taskToken);
|
||||
}
|
||||
try {
|
||||
future.complete(objectMapper.readTree(output));
|
||||
} catch (Exception e) {
|
||||
future.completeExceptionally(new RuntimeException("Invalid JSON output: " + e.getMessage()));
|
||||
result = objectMapper.readTree(output);
|
||||
} catch (JsonProcessingException | IllegalArgumentException e) {
|
||||
throw new AwsException("InvalidOutput", "Output is not valid JSON.", 400);
|
||||
}
|
||||
if (result == null || result.isMissingNode()) {
|
||||
throw new AwsException("InvalidOutput", "Output is not valid JSON.", 400);
|
||||
}
|
||||
CompletableFuture<JsonNode> future = claimPendingTask(taskToken);
|
||||
future.complete(result);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return whether the token named a task that was waiting for it, as in
|
||||
* {@link #sendTaskSuccess(String, String)}.
|
||||
*/
|
||||
public boolean sendTaskFailure(String taskToken, String cause, String error) {
|
||||
CompletableFuture<JsonNode> future = taskToken != null ? pendingTaskTokens.remove(taskToken) : null;
|
||||
if (future == null) {
|
||||
LOG.warnv("SendTaskFailure: no pending task for token {0}", taskToken);
|
||||
return false;
|
||||
}
|
||||
CompletableFuture<JsonNode> future = claimPendingTask(taskToken);
|
||||
future.completeExceptionally(new AslExecutor.FailStateException(error, cause));
|
||||
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) {
|
||||
if (taskToken == null || !pendingTaskTokens.containsKey(taskToken)) {
|
||||
LOG.warnv("SendTaskHeartbeat: no pending task for token {0}", taskToken);
|
||||
return;
|
||||
}
|
||||
/** A foreign, closed or unknown token cannot refresh a task's heartbeat. */
|
||||
public synchronized void sendTaskHeartbeat(String taskToken) {
|
||||
requirePendingTask(taskToken);
|
||||
taskHeartbeatNanos.put(taskToken, System.nanoTime());
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user