mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(stepfunctions): paginate ListExecutions (#6727)
* fix(stepfunctions): paginate ListExecutions Honor maxResults and nextToken after applying statusFilter, with newest-first scoped cursors. Add regression coverage for continuation pages and token isolation. * fix(stepfunctions): snapshot ListExecutions status * fix(stepfunctions): order terminal executions by stop time * fix(stepfunctions): expire signed ListExecutions tokens * fix(stepfunctions): compact ListExecutions continuation scope * fix(stepfunctions): reuse expiring history pagination * fix(stepfunctions): validate history token before execution lookup
This commit is contained in:
1 parent
41717057c5
commit
a8151ff56b
9 files changed
+578
-77
No files matched your search
@@ -2,9 +2,12 @@ package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -75,6 +78,33 @@ public final class Pagination {
|
||||
prefix, Pagination::encodeToken);
|
||||
}
|
||||
|
||||
/** Paginates namespaced cursors that are invalid after the supplied lifetime. */
|
||||
public static <T> PaginatedResult<T> paginateExpiring(List<T> all, Function<T, String> cursorOf,
|
||||
int limit, String nextToken, String namespace,
|
||||
Clock clock, Duration lifetime, SignedMarkers markers,
|
||||
Function<String, AwsException> invalidToken) {
|
||||
return paginateExpiring(() -> all, cursorOf, limit, nextToken, namespace, clock, lifetime,
|
||||
markers, invalidToken);
|
||||
}
|
||||
|
||||
/** Decodes the token before loading items whose lookup can fail independently. */
|
||||
public static <T> PaginatedResult<T> paginateExpiring(Supplier<List<T>> all, Function<T, String> cursorOf,
|
||||
int limit, String nextToken, String namespace,
|
||||
Clock clock, Duration lifetime, SignedMarkers markers,
|
||||
Function<String, AwsException> invalidToken) {
|
||||
if (limit < 1) {
|
||||
throw new IllegalArgumentException("limit must be at least 1, was " + limit);
|
||||
}
|
||||
if (lifetime.isNegative()) {
|
||||
throw new IllegalArgumentException("lifetime must not be negative, was " + lifetime);
|
||||
}
|
||||
String prefix = namespace + ":";
|
||||
long nowMillis = clock.millis();
|
||||
String after = decodeExpiringCursor(nextToken, prefix, nowMillis, lifetime.toMillis(), markers, invalidToken);
|
||||
String tokenPrefix = prefix + nowMillis + ":";
|
||||
return slice(all.get(), cursorOf, limit, after, tokenPrefix, markers::issue);
|
||||
}
|
||||
|
||||
/** Paginates with instance-signed markers, optionally scoped by a prefix within the signed cursor. */
|
||||
public static <T> PaginatedResult<T> paginate(List<T> all, Function<T, String> cursorOf,
|
||||
int limit, String marker, SignedMarkers markers,
|
||||
@@ -197,6 +227,26 @@ public final class Pagination {
|
||||
return decoded.substring(prefix.length());
|
||||
}
|
||||
|
||||
private static String decodeExpiringCursor(String token, String prefix, long nowMillis,
|
||||
long lifetimeMillis, SignedMarkers markers,
|
||||
Function<String, AwsException> invalidToken) {
|
||||
if (token == null || token.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String decoded = markers.cursorOf(token);
|
||||
if (decoded == null || !decoded.startsWith(prefix)) {
|
||||
throw invalidToken.apply(token);
|
||||
}
|
||||
String issuedAndCursor = decoded.substring(prefix.length());
|
||||
int separator = issuedAndCursor.indexOf(':');
|
||||
long issuedMillis = Long.parseLong(issuedAndCursor.substring(0, separator));
|
||||
long ageMillis = nowMillis - issuedMillis;
|
||||
if (issuedMillis > nowMillis || ageMillis > lifetimeMillis) {
|
||||
throw invalidToken.apply(token);
|
||||
}
|
||||
return issuedAndCursor.substring(separator + 1);
|
||||
}
|
||||
|
||||
private static String decodeToken(String token) {
|
||||
if (token == null || token.isEmpty()) {
|
||||
return null;
|
||||
|
||||
+28
-56
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.Digests;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.SignedMarkers;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.Activity;
|
||||
@@ -26,7 +27,6 @@ import jakarta.ws.rs.core.Response;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
@@ -482,14 +482,15 @@ public class StepFunctionsJsonHandler {
|
||||
throw new AwsException("ValidationException",
|
||||
"PENDING_REDRIVE execution listing is not supported.", 400);
|
||||
}
|
||||
List<Execution> list = service.listExecutions(request.path("stateMachineArn").asText());
|
||||
String stateMachineArn = request.path("stateMachineArn").asText();
|
||||
Integer maxResults = parseOptionalInt(request, "maxResults");
|
||||
String nextToken = optionalText(request, "nextToken");
|
||||
PaginatedResult<StepFunctionsService.ExecutionSnapshot> page = service.listExecutions(
|
||||
stateMachineArn, statusFilter, maxResults, nextToken);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode array = response.putArray("executions");
|
||||
for (Execution e : list) {
|
||||
String status = e.getStatus();
|
||||
if (statusFilter != null && !statusFilter.equals(status)) {
|
||||
continue;
|
||||
}
|
||||
for (StepFunctionsService.ExecutionSnapshot snapshot : page.items()) {
|
||||
Execution e = snapshot.execution();
|
||||
ObjectNode item = array.addObject();
|
||||
item.put("executionArn", e.getExecutionArn());
|
||||
item.put("stateMachineArn", e.getStateMachineArn());
|
||||
@@ -500,10 +501,13 @@ public class StepFunctionsJsonHandler {
|
||||
item.put("stateMachineAliasArn", e.getStateMachineAliasArn());
|
||||
}
|
||||
item.put("name", e.getName());
|
||||
item.put("status", status);
|
||||
item.put("status", snapshot.status());
|
||||
item.put("startDate", e.getStartDate());
|
||||
if (e.getStopDate() != null) item.put("stopDate", e.getStopDate());
|
||||
}
|
||||
if (page.nextToken() != null) {
|
||||
response.put("nextToken", page.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
@@ -525,28 +529,20 @@ public class StepFunctionsJsonHandler {
|
||||
Integer maxResults = parseOptionalInt(request, "maxResults");
|
||||
String nextToken = optionalText(request, "nextToken");
|
||||
int pageSize = StepFunctionsPaging.pageSize(maxResults, nextToken);
|
||||
Long lastReturnedId = nextToken == null ? null : historyTokenPosition(nextToken, arn, reverseOrder);
|
||||
|
||||
List<HistoryEvent> live = service.getExecutionHistory(arn);
|
||||
List<HistoryEvent> events;
|
||||
// Branch and iteration threads append under the history's own monitor while a client reads.
|
||||
synchronized (live) {
|
||||
events = new ArrayList<>(live);
|
||||
}
|
||||
if (reverseOrder) {
|
||||
Collections.reverse(events);
|
||||
}
|
||||
// Ids rise in the order events were recorded, so a page starts at the first event listed
|
||||
// after the last one the previous page returned, however many were recorded in between.
|
||||
int start = 0;
|
||||
while (lastReturnedId != null && start < events.size()
|
||||
&& !listedAfter(events.get(start), lastReturnedId, reverseOrder)) {
|
||||
start++;
|
||||
}
|
||||
int end = Math.min(events.size(), start + pageSize);
|
||||
PaginatedResult<HistoryEvent> page = Pagination.paginateExpiring(() -> {
|
||||
List<HistoryEvent> live = service.getExecutionHistory(arn);
|
||||
// Branch and iteration threads append under the history's own monitor while a client reads.
|
||||
synchronized (live) {
|
||||
return new ArrayList<>(live);
|
||||
}
|
||||
},
|
||||
event -> historyEventCursor(event, reverseOrder), pageSize, nextToken,
|
||||
historyTokenScope(arn, reverseOrder), clock, HISTORY_TOKEN_LIFETIME, historyTokens,
|
||||
token -> invalidHistoryToken());
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode array = response.putArray("events");
|
||||
for (HistoryEvent e : events.subList(start, end)) {
|
||||
for (HistoryEvent e : page.items()) {
|
||||
ObjectNode item = array.addObject();
|
||||
item.put("id", e.getId());
|
||||
item.put("timestamp", e.getTimestamp());
|
||||
@@ -562,39 +558,15 @@ public class StepFunctionsJsonHandler {
|
||||
item.set(historyEventDetailsField(e.getType()), objectMapper.valueToTree(details));
|
||||
}
|
||||
}
|
||||
if (end < events.size()) {
|
||||
response.put("nextToken", issueHistoryToken(arn, reverseOrder, events.get(end - 1).getId()));
|
||||
if (page.nextToken() != null) {
|
||||
response.put("nextToken", page.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private static boolean listedAfter(HistoryEvent event, long id, boolean reverseOrder) {
|
||||
return reverseOrder ? event.getId() < id : event.getId() > id;
|
||||
}
|
||||
|
||||
/**
|
||||
* A history token names its execution, its order and the last event its page returned, and
|
||||
* may be used with any page size and includeExecutionData. The execution is named by the
|
||||
* SHA-256 of its ARN, so the token stays far below the 1,024 characters AWS allows however long
|
||||
* the ARN is. Tokens are signed, so an edited one, or one issued before a restart, is refused,
|
||||
* and each expires 24 hours after it was issued, as on AWS.
|
||||
*/
|
||||
private String issueHistoryToken(String arn, boolean reverseOrder, long lastReturnedId) {
|
||||
return historyTokens.issue(
|
||||
clock.millis() + ":" + historyTokenScope(arn, reverseOrder) + ":" + lastReturnedId);
|
||||
}
|
||||
|
||||
private long historyTokenPosition(String nextToken, String arn, boolean reverseOrder) {
|
||||
String issued = historyTokens.cursorOf(nextToken);
|
||||
if (issued == null) {
|
||||
throw invalidHistoryToken();
|
||||
}
|
||||
String[] fields = issued.split(":");
|
||||
if (!fields[1].equals(historyTokenScope(arn, reverseOrder))
|
||||
|| clock.millis() - Long.parseLong(fields[0]) > HISTORY_TOKEN_LIFETIME.toMillis()) {
|
||||
throw invalidHistoryToken();
|
||||
}
|
||||
return Long.parseLong(fields[2]);
|
||||
private static String historyEventCursor(HistoryEvent event, boolean reverseOrder) {
|
||||
long position = reverseOrder ? Long.MAX_VALUE - event.getId() : event.getId();
|
||||
return String.format("%019d", position);
|
||||
}
|
||||
|
||||
private static String historyTokenScope(String arn, boolean reverseOrder) {
|
||||
|
||||
+13
-5
@@ -3,9 +3,11 @@ package io.github.hectorvent.floci.services.stepfunctions;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
|
||||
/**
|
||||
* The page request ListActivities, ListStateMachines and GetExecutionHistory check: a {@code maxResults} of 0 to 1000,
|
||||
* where 0 or none means 100, and a {@code nextToken} of 1 to 1024 characters. Callers read both
|
||||
* fields before calling it, so a wrongly typed field is reported before either bound.
|
||||
* The page requests ListActivities, ListStateMachines, GetExecutionHistory, and ListExecutions
|
||||
* check a {@code maxResults} of 0 to 1000, where 0 or none means 100. ListActivities,
|
||||
* ListStateMachines, and GetExecutionHistory accept a {@code nextToken} of 1 to 1024 characters;
|
||||
* ListExecutions accepts up to 3096 characters. Callers read both fields before calling it, so a
|
||||
* wrongly typed field is reported before either bound.
|
||||
*/
|
||||
final class StepFunctionsPaging {
|
||||
|
||||
@@ -18,11 +20,17 @@ final class StepFunctionsPaging {
|
||||
|
||||
/** Validates the pair and returns the number of items a page holds. */
|
||||
static int pageSize(Integer maxResults, String nextToken) {
|
||||
return pageSize(maxResults, nextToken, MAX_TOKEN_LENGTH);
|
||||
}
|
||||
|
||||
/** Validates the pair using the operation's modeled token length. */
|
||||
static int pageSize(Integer maxResults, String nextToken, int maxTokenLength) {
|
||||
if (maxResults != null && (maxResults < 0 || maxResults > MAX_PAGE_SIZE)) {
|
||||
throw new AwsException("ValidationException", "maxResults must be between 0 and 1000.", 400);
|
||||
}
|
||||
if (nextToken != null && (nextToken.isEmpty() || nextToken.length() > MAX_TOKEN_LENGTH)) {
|
||||
throw new AwsException("ValidationException", "nextToken length must be between 1 and 1024.", 400);
|
||||
if (nextToken != null && (nextToken.isEmpty() || nextToken.length() > maxTokenLength)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"nextToken length must be between 1 and " + maxTokenLength + ".", 400);
|
||||
}
|
||||
return maxResults == null || maxResults == 0 ? DEFAULT_PAGE_SIZE : maxResults;
|
||||
}
|
||||
|
||||
+50
-1
@@ -9,10 +9,13 @@ import io.github.hectorvent.floci.core.common.AwsArnShapes;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.Base64Url;
|
||||
import io.github.hectorvent.floci.core.common.Digests;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.common.SignedMarkers;
|
||||
import io.github.hectorvent.floci.core.resource.ExplorerResource;
|
||||
import io.github.hectorvent.floci.core.resource.ResourceProvider;
|
||||
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
|
||||
@@ -34,6 +37,9 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
@@ -50,9 +56,11 @@ import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
private static final int LIST_EXECUTIONS_MAX_TOKEN_LENGTH = 3096;
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(StepFunctionsService.class);
|
||||
private static final int HISTORY_PERSIST_CHECKPOINT = 100;
|
||||
private static final Duration LIST_EXECUTIONS_TOKEN_LIFETIME = Duration.ofHours(24);
|
||||
|
||||
private final StorageBackend<String, StateMachine> stateMachineStore;
|
||||
private final StorageBackend<String, StateMachineAlias> stateMachineAliasStore;
|
||||
@@ -102,6 +110,8 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final SfnMockLoader mockLoader;
|
||||
private final StepFunctionsEventPublisher eventPublisher;
|
||||
private final Clock clock;
|
||||
private final SignedMarkers listExecutionTokens = new SignedMarkers();
|
||||
|
||||
// Fields that are valid only in JSONPath mode. Validated against real AWS:
|
||||
// creating a JSONata state machine with any of these fields returns SCHEMA_VALIDATION_FAILED.
|
||||
@@ -151,10 +161,18 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
new FieldStateTypeRule("Catch", Set.of("Task", "Parallel", "Map")),
|
||||
new FieldStateTypeRule("Retry", Set.of("Task", "Parallel", "Map")));
|
||||
|
||||
@Inject
|
||||
public StepFunctionsService(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
AslExecutor aslExecutor, ObjectMapper objectMapper,
|
||||
SfnMockLoader mockLoader, StepFunctionsEventPublisher eventPublisher) {
|
||||
this(storageFactory, regionResolver, aslExecutor, objectMapper, mockLoader, eventPublisher,
|
||||
Clock.systemUTC());
|
||||
}
|
||||
|
||||
@Inject
|
||||
public StepFunctionsService(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
AslExecutor aslExecutor, ObjectMapper objectMapper,
|
||||
SfnMockLoader mockLoader, StepFunctionsEventPublisher eventPublisher,
|
||||
Clock clock) {
|
||||
this.stateMachineStore = storageFactory.create("stepfunctions", "sfn-state-machines.json",
|
||||
new TypeReference<Map<String, StateMachine>>() {});
|
||||
this.executionStore = storageFactory.create("stepfunctions", "sfn-executions.json",
|
||||
@@ -173,6 +191,7 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
this.objectMapper = objectMapper;
|
||||
this.mockLoader = mockLoader;
|
||||
this.eventPublisher = eventPublisher;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
@@ -1019,6 +1038,36 @@ public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
}).orElse(false));
|
||||
}
|
||||
|
||||
/** Returns a filtered, newest-first page of executions for the ListExecutions API. */
|
||||
public PaginatedResult<ExecutionSnapshot> listExecutions(String stateMachineArn, String statusFilter,
|
||||
Integer maxResults, String nextToken) {
|
||||
int pageSize = StepFunctionsPaging.pageSize(maxResults, nextToken, LIST_EXECUTIONS_MAX_TOKEN_LENGTH);
|
||||
List<ExecutionSnapshot> matching = listExecutions(stateMachineArn).stream()
|
||||
.map(execution -> new ExecutionSnapshot(execution, execution.getStatus()))
|
||||
.filter(snapshot -> statusFilter == null || statusFilter.equals(snapshot.status()))
|
||||
.toList();
|
||||
String scope = "states:executions:" + regionResolver.getAccountId() + ":" + stateMachineArn + ":"
|
||||
+ (statusFilter == null ? "*" : statusFilter);
|
||||
String namespace = "states:executions:" + Base64Url.encode(
|
||||
Digests.sha256(scope.getBytes(StandardCharsets.UTF_8)));
|
||||
return Pagination.paginateExpiring(matching, StepFunctionsService::executionPaginationCursor,
|
||||
pageSize, nextToken, namespace, clock, LIST_EXECUTIONS_TOKEN_LIFETIME, listExecutionTokens,
|
||||
token -> new AwsException("InvalidToken", "Invalid nextToken.", 400));
|
||||
}
|
||||
|
||||
public record ExecutionSnapshot(Execution execution, String status) {
|
||||
}
|
||||
|
||||
/** Sorts newest executions first while keeping equal timestamps deterministic. */
|
||||
private static String executionPaginationCursor(ExecutionSnapshot snapshot) {
|
||||
Execution execution = snapshot.execution();
|
||||
Double stopDate = execution.getStopDate();
|
||||
double sortDate = "RUNNING".equals(snapshot.status()) || stopDate == null
|
||||
? execution.getStartDate() : stopDate;
|
||||
long sortMillis = Math.round(sortDate * 1000.0);
|
||||
return String.format("%019d:%s", Long.MAX_VALUE - sortMillis, execution.getExecutionArn());
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
|
||||
Reference in new issue
Block a user