fix(scheduler): honor MaxResults and NextToken in ListScheduleGroups and ListSchedules (#7187)

Both list operations now page through the shared Pagination helper, return NextToken only while items remain, and answer an out-of-range MaxResults or a foreign or malformed NextToken with ValidationException. NamePrefix, State and ScheduleGroup filtering apply before paging.

Fixes #6720

Let the namespaced Pagination overload take the reject-empty-token flag that
paginateUnencoded already uses, and drop SchedulerService.requireNonEmptyToken.
Explain why the compatibility test's best-effort cleanup ignores failures.
This commit is contained in:
Daniël van Ziel authored and GitHub committed 2026-11-09 01:53:04 -04:00
1 parent b93afa9e89
commit 4e5c60cd58
8 files changed
+340 -11

No files matched your search

@@ -595,4 +595,67 @@ class SchedulerTest {
} catch (Exception ignored) {}
}
}
@Test
@Order(31)
@DisplayName("ListScheduleGroups / ListSchedules - paginators follow NextToken")
void listOperationsPaginate() {
String prefix = "sdk-paging-" + System.currentTimeMillis();
String groupA = prefix + "-a";
String groupB = prefix + "-b";
try {
for (String group : new String[]{groupA, groupB}) {
scheduler.createScheduleGroup(CreateScheduleGroupRequest.builder().name(group).build());
}
for (String name : new String[]{"s-1", "s-2"}) {
scheduler.createSchedule(CreateScheduleRequest.builder()
.name(name)
.groupName(groupA)
.scheduleExpression("rate(1 hour)")
.flexibleTimeWindow(FlexibleTimeWindow.builder().mode(FlexibleTimeWindowMode.OFF).build())
.target(Target.builder()
.arn("arn:aws:sqs:us-east-1:000000000000:queue")
.roleArn("arn:aws:iam::000000000000:role/scheduler-role")
.build())
.build());
}
ListScheduleGroupsResponse firstGroups = scheduler.listScheduleGroups(
ListScheduleGroupsRequest.builder().namePrefix(prefix).maxResults(1).build());
assertThat(firstGroups.scheduleGroups()).extracting(ScheduleGroupSummary::name).containsExactly(groupA);
assertThat(firstGroups.nextToken()).isNotNull();
assertThat(scheduler.listScheduleGroupsPaginator(
ListScheduleGroupsRequest.builder().namePrefix(prefix).maxResults(1).build())
.scheduleGroups())
.extracting(ScheduleGroupSummary::name)
.containsExactly(groupA, groupB);
assertThat(scheduler.listSchedulesPaginator(
ListSchedulesRequest.builder().groupName(groupA).maxResults(1).build())
.schedules())
.extracting(ScheduleSummary::name)
.containsExactly("s-1", "s-2");
assertThatThrownBy(() -> scheduler.listSchedules(
ListSchedulesRequest.builder().nextToken("bogus-token").build()))
.isInstanceOf(ValidationException.class);
} finally {
for (String name : new String[]{"s-1", "s-2"}) {
try {
scheduler.deleteSchedule(DeleteScheduleRequest.builder().name(name).groupName(groupA).build());
} catch (Exception ignored) {
// Best-effort cleanup: the schedule is absent when the test failed before creating it,
// and a cleanup error must not mask that original failure.
}
}
for (String group : new String[]{groupA, groupB}) {
try {
scheduler.deleteScheduleGroup(DeleteScheduleGroupRequest.builder().name(group).build());
} catch (Exception ignored) {
// Best-effort cleanup, as above: the group may never have been created.
}
}
}
}
}
+2 -3
View File
@@ -10,12 +10,12 @@
| `CreateScheduleGroup` | `POST` | `/schedule-groups/{Name}` | Create a schedule group |
| `GetScheduleGroup` | `GET` | `/schedule-groups/{Name}` | Get schedule group details |
| `DeleteScheduleGroup` | `DELETE` | `/schedule-groups/{Name}` | Delete a schedule group and its schedules |
| `ListScheduleGroups` | `GET` | `/schedule-groups` | List schedule groups |
| `ListScheduleGroups` | `GET` | `/schedule-groups` | List schedule groups, paged with `MaxResults` (1-100) and `NextToken` |
| `CreateSchedule` | `POST` | `/schedules/{Name}` | Create a schedule |
| `GetSchedule` | `GET` | `/schedules/{Name}` | Get schedule details |
| `UpdateSchedule` | `PUT` | `/schedules/{Name}` | Update a schedule |
| `DeleteSchedule` | `DELETE` | `/schedules/{Name}` | Delete a schedule |
| `ListSchedules` | `GET` | `/schedules` | List schedules |
| `ListSchedules` | `GET` | `/schedules` | List schedules, paged with `MaxResults` (1-100) and `NextToken` |
| `TagResource` | `POST` | `/tags/{ResourceArn}` | Add tags to a schedule group |
| `UntagResource` | `DELETE` | `/tags/{ResourceArn}?TagKeys=...` | Remove tags from a schedule group |
| `ListTagsForResource` | `GET` | `/tags/{ResourceArn}` | List tags on a schedule group |
@@ -163,7 +163,6 @@ Invocation support and time-window limitations are the same as the Scheduler API
## Not Yet Supported
- `FlexibleTimeWindow` jitter (fires deterministically at the scheduled time)
- `NextToken`-based pagination for List operations
## Examples
@@ -142,8 +142,22 @@ public final class Pagination {
Integer maxResults, String nextToken,
int defaultPageSize, int maxResultsLimit, int maxTokenLength,
String errorCode, String namespace) {
return paginate(all, cursorOf, maxResults, nextToken, defaultPageSize, maxResultsLimit, maxTokenLength,
errorCode, namespace, false);
}
/**
* As above; when {@code tokenMustBeNonEmpty} is set, an empty token is refused instead of being
* read as the first page, for operations whose model gives the token a minimum length of 1.
*/
public static <T> PaginatedResult<T> paginate(List<T> all, Function<T, String> cursorOf,
Integer maxResults, String nextToken,
int defaultPageSize, int maxResultsLimit, int maxTokenLength,
String errorCode, String namespace, boolean tokenMustBeNonEmpty) {
validatePageSizeAndToken(maxResults, nextToken, maxResultsLimit, maxTokenLength, errorCode,
false, "Pagination token must not exceed " + maxTokenLength + " characters.");
tokenMustBeNonEmpty, nextToken != null && nextToken.isEmpty()
? tokenRangeMessage(maxTokenLength)
: "Pagination token must not exceed " + maxTokenLength + " characters.");
return paginate(all, cursorOf, maxResults == null ? defaultPageSize : maxResults, nextToken, namespace,
token -> new AwsException(errorCode, "Invalid pagination token.", 400));
}
@@ -158,7 +172,7 @@ public final class Pagination {
int defaultPageSize, int maxResultsLimit,
int maxTokenLength, String errorCode) {
validatePageSizeAndToken(maxResults, nextToken, maxResultsLimit, maxTokenLength, errorCode,
true, "Pagination token must be between 1 and " + maxTokenLength + " characters.");
true, tokenRangeMessage(maxTokenLength));
int limit = maxResults == null ? defaultPageSize : maxResults;
return slice(all, cursorOf, limit, nextToken, "", Function.identity());
}
@@ -176,6 +190,10 @@ public final class Pagination {
}
}
private static String tokenRangeMessage(int maxTokenLength) {
return "Pagination token must be between 1 and " + maxTokenLength + " characters.";
}
/** Reads an optional JSON page size without coercing strings, fractions, or overflowing integers. */
public static Integer parseMaxResults(JsonNode request, String field, String errorCode) {
JsonNode value = request.get(field);
@@ -6,6 +6,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.scheduler.model.AwsVpcConfiguration;
import io.floci.aws.services.scheduler.model.DeadLetterConfig;
@@ -33,6 +35,7 @@ import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import java.time.Instant;
import java.util.HashMap;
@@ -109,14 +112,20 @@ public class SchedulerController {
@GET
@Path("/schedule-groups")
public Response listScheduleGroups(@Context HttpHeaders headers,
@QueryParam("NamePrefix") String namePrefix) {
@QueryParam("NamePrefix") String namePrefix,
@QueryParam("MaxResults") String maxResults,
@Context UriInfo uriInfo) {
String region = regionResolver.resolveRegion(headers);
List<ScheduleGroup> groups = schedulerService.listScheduleGroups(namePrefix, region);
PaginatedResult<ScheduleGroup> page = schedulerService.listScheduleGroups(namePrefix,
Pagination.parseMaxResults(maxResults, "ValidationException"), rawNextToken(uriInfo), region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode items = response.putArray("ScheduleGroups");
for (ScheduleGroup group : groups) {
for (ScheduleGroup group : page.items()) {
items.add(objectMapper.valueToTree(buildGroupResponse(group)));
}
if (page.nextToken() != null) {
response.put("NextToken", page.nextToken());
}
return Response.ok(response).build();
}
@@ -197,19 +206,39 @@ public class SchedulerController {
public Response listSchedules(@Context HttpHeaders headers,
@QueryParam("ScheduleGroup") String groupName,
@QueryParam("NamePrefix") String namePrefix,
@QueryParam("State") String state) {
@QueryParam("State") String state,
@QueryParam("MaxResults") String maxResults,
@Context UriInfo uriInfo) {
String region = regionResolver.resolveRegion(headers);
List<Schedule> schedules = schedulerService.listSchedules(groupName, namePrefix, state, region);
PaginatedResult<Schedule> page = schedulerService.listSchedules(groupName, namePrefix, state,
Pagination.parseMaxResults(maxResults, "ValidationException"), rawNextToken(uriInfo), region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode items = response.putArray("Schedules");
for (Schedule schedule : schedules) {
for (Schedule schedule : page.items()) {
items.add(objectMapper.valueToTree(buildScheduleSummary(schedule)));
}
if (page.nextToken() != null) {
response.put("NextToken", page.nextToken());
}
return Response.ok(response).build();
}
// ──────────────────────────── Helpers ────────────────────────────
/**
* Reads {@code NextToken} from the raw query so an explicit empty value stays {@code ""}:
* a {@code @QueryParam} binding reports it as absent, which would serve the first page
* instead of the ValidationException the modeled minimum length of 1 calls for.
*/
private static String rawNextToken(UriInfo uriInfo) {
List<String> values = uriInfo.getQueryParameters().get("NextToken");
if (values == null || values.isEmpty()) {
return null;
}
String value = values.getFirst();
return value == null ? "" : value;
}
private Map<String, Object> buildGroupResponse(ScheduleGroup group) {
Map<String, Object> response = new HashMap<>();
response.put("Name", group.getName());
@@ -8,6 +8,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
@@ -37,6 +39,9 @@ public class SchedulerService {
"arn:(?:" + AwsArnUtils.PARTITION_REGEX + "):iam::\\d{12}:role/[\\w+=,.@/-]+");
private static final String ROLE_ARN_MODEL_PATTERN = "^arn:aws(-[a-z]+)?:iam::\\d{12}:role\\/[\\w+=,.@\\/-]+$"; // partition-literal: the Scheduler model's RoleArn pattern, quoted verbatim in the error message
private static final String DEFAULT_GROUP = "default";
// ListScheduleGroups and ListSchedules model MaxResults as 1-100 and NextToken as 1-2048 chars.
private static final int MAX_PAGE_SIZE = 100;
private static final int MAX_TOKEN_LENGTH = 2048;
// FAIL_ON_TRAILING_TOKENS matters here: without it an Input of "{} garbage" parses as the
// leading object and the rest is silently dropped, so a value AWS rejects would be stored.
private static final ObjectReader JSON = new ObjectMapper()
@@ -185,6 +190,13 @@ public class SchedulerService {
});
}
public PaginatedResult<ScheduleGroup> listScheduleGroups(String namePrefix, Integer maxResults,
String nextToken, String region) {
return Pagination.paginate(listScheduleGroups(namePrefix, region), ScheduleGroup::getName,
maxResults, nextToken, MAX_PAGE_SIZE, MAX_PAGE_SIZE, MAX_TOKEN_LENGTH,
"ValidationException", pageNamespace("ListScheduleGroups", region), true);
}
// ──────────────────────────── Schedules ────────────────────────────
public Schedule createSchedule(ScheduleRequest req, String region) {
@@ -324,6 +336,18 @@ public class SchedulerService {
}).toList();
}
public PaginatedResult<Schedule> listSchedules(String groupName, String namePrefix, String state,
Integer maxResults, String nextToken, String region) {
return Pagination.paginate(listSchedules(groupName, namePrefix, state, region),
schedule -> schedule.getGroupName() + ":" + schedule.getName(),
maxResults, nextToken, MAX_PAGE_SIZE, MAX_PAGE_SIZE, MAX_TOKEN_LENGTH,
"ValidationException", pageNamespace("ListSchedules", region), true);
}
private String pageNamespace(String operation, String region) {
return "scheduler:" + operation + ":" + regionResolver.getAccountId() + ":" + region;
}
// ──────────────────────────── Helpers ────────────────────────────
public static boolean isValidName(String name) {
@@ -219,6 +219,22 @@ class PaginationTest {
assertThat(bounded(1, "").items(), contains("a"));
}
@Test
void boundedNamespacedPaging_refusesEmptyAndLongTokensWhenTokenMustBeNonEmpty() {
String longToken = Base64.getUrlEncoder().withoutPadding()
.encodeToString(("ns:" + "a".repeat(100)).getBytes(StandardCharsets.UTF_8));
AwsException empty = assertInvalid(() -> Pagination.paginate(ITEMS, Function.identity(), 1, "",
2, 3, 32, "InvalidInput", "ns", true));
assertEquals("Pagination token must be between 1 and 32 characters.", empty.getMessage());
AwsException tooLong = assertInvalid(() -> Pagination.paginate(ITEMS, Function.identity(), 1, longToken,
2, 3, 32, "InvalidInput", "ns", true));
assertEquals("Pagination token must not exceed 32 characters.", tooLong.getMessage());
PaginatedResult<String> first = Pagination.paginate(ITEMS, Function.identity(), 1, null,
2, 3, 32, "InvalidInput", "ns", true);
assertThat(Pagination.paginate(ITEMS, Function.identity(), 1, first.nextToken(),
2, 3, 32, "InvalidInput", "ns", true).items(), contains("b"));
}
@Test
void boundedNamespacedPaging_refusesMalformedAndForeignTokens() {
assertInvalid(() -> bounded(1, "!!!"));
@@ -1195,4 +1195,77 @@ class SchedulerIntegrationTest {
.body("__type", containsString("SerializationException"));
}
}
@Test
@Order(45)
void listScheduleGroupsPagesWithMaxResultsAndNextToken() {
for (String name : List.of("paging-group-a", "paging-group-b")) {
given().contentType("application/json").body("{}")
.when().post("/schedule-groups/" + name)
.then().statusCode(200);
}
String token = given().queryParam("NamePrefix", "paging-group-").queryParam("MaxResults", 1)
.when().get("/schedule-groups")
.then().statusCode(200)
.body("ScheduleGroups.Name", contains("paging-group-a"))
.body("NextToken", notNullValue())
.extract().path("NextToken");
given().queryParam("NamePrefix", "paging-group-").queryParam("MaxResults", 1)
.queryParam("NextToken", token)
.when().get("/schedule-groups")
.then().statusCode(200)
.body("ScheduleGroups.Name", contains("paging-group-b"))
.body("$", not(hasKey("NextToken")));
}
@Test
@Order(46)
void listSchedulesPagesWithMaxResultsAndNextToken() {
String body = """
{"ScheduleExpression":"rate(1 hour)","FlexibleTimeWindow":{"Mode":"OFF"},
"GroupName":"paging-group-a",
"Target":{"Arn":"arn:aws:sqs:us-east-1:000000000000:queue",
"RoleArn":"arn:aws:iam::000000000000:role/scheduler-role"}}
""";
for (String name : List.of("paging-1", "paging-2")) {
given().contentType("application/json").body(body)
.when().post("/schedules/" + name)
.then().statusCode(200);
}
String token = given().queryParam("ScheduleGroup", "paging-group-a").queryParam("MaxResults", 1)
.when().get("/schedules")
.then().statusCode(200)
.body("Schedules.Name", contains("paging-1"))
.body("NextToken", notNullValue())
.extract().path("NextToken");
given().queryParam("ScheduleGroup", "paging-group-a").queryParam("MaxResults", 1)
.queryParam("NextToken", token)
.when().get("/schedules")
.then().statusCode(200)
.body("Schedules.Name", contains("paging-2"))
.body("$", not(hasKey("NextToken")));
}
@Test
@Order(47)
void listOperationsRejectInvalidMaxResultsAndNextToken() {
for (String path : List.of("/schedule-groups", "/schedules")) {
for (String maxResults : List.of("0", "101", "abc")) {
given().queryParam("MaxResults", maxResults)
.when().get(path)
.then().statusCode(400)
.body("__type", containsString("ValidationException"));
}
for (String nextToken : List.of("bogus-token", "")) {
given().queryParam("NextToken", nextToken)
.when().get(path)
.then().statusCode(400)
.body("__type", containsString("ValidationException"));
}
}
}
}
@@ -1,6 +1,7 @@
package io.floci.aws.services.scheduler;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.services.scheduler.model.DeadLetterConfig;
@@ -726,6 +727,112 @@ class SchedulerServiceTest {
assertEquals("disabled-1", result.get(0).getName());
}
@Test
void listScheduleGroupsPagesWithNextToken() {
service.createScheduleGroup("page-a", null, REGION);
service.createScheduleGroup("page-b", null, REGION);
PaginatedResult<ScheduleGroup> first = service.listScheduleGroups("page-", 1, null, REGION);
assertEquals(List.of("page-a"), first.items().stream().map(ScheduleGroup::getName).toList());
assertNotNull(first.nextToken());
PaginatedResult<ScheduleGroup> second = service.listScheduleGroups("page-", 1, first.nextToken(), REGION);
assertEquals(List.of("page-b"), second.items().stream().map(ScheduleGroup::getName).toList());
assertNull(second.nextToken());
}
@Test
void listSchedulesPagesWithinGroupAndState() {
service.createScheduleGroup("paged", null, REGION);
for (String name : List.of("p-1", "p-2", "p-3")) {
ScheduleRequest req = newRequest(name, "paged", "rate(1 hour)",
new FlexibleTimeWindow("OFF", null),
new Target("arn:t", "arn:aws:iam::000000000000:role/r", null, null));
req.setState("p-2".equals(name) ? "DISABLED" : "ENABLED");
service.createSchedule(req, REGION);
}
PaginatedResult<Schedule> first = service.listSchedules("paged", "p-", "ENABLED", 1, null, REGION);
assertEquals(List.of("p-1"), first.items().stream().map(Schedule::getName).toList());
assertNotNull(first.nextToken());
PaginatedResult<Schedule> second = service.listSchedules("paged", "p-", "ENABLED", 1,
first.nextToken(), REGION);
assertEquals(List.of("p-3"), second.items().stream().map(Schedule::getName).toList());
assertNull(second.nextToken());
}
@Test
void listSchedulesPagesAcrossGroups() {
service.createScheduleGroup("g-a", null, REGION);
service.createScheduleGroup("g-b", null, REGION);
for (String group : List.of("g-a", "g-b")) {
service.createSchedule(newRequest("same", group, "rate(1 hour)",
new FlexibleTimeWindow("OFF", null),
new Target("arn:t", "arn:aws:iam::000000000000:role/r", null, null)), REGION);
}
PaginatedResult<Schedule> first = service.listSchedules(null, null, null, 1, null, REGION);
PaginatedResult<Schedule> second = service.listSchedules(null, null, null, 1, first.nextToken(), REGION);
assertEquals("g-a", first.items().get(0).getGroupName());
assertEquals("g-b", second.items().get(0).getGroupName());
assertNull(second.nextToken());
}
@Test
void listOperationsRejectOutOfRangeMaxResults() {
for (Integer maxResults : List.of(0, 101)) {
AwsException groups = assertThrows(AwsException.class, () ->
service.listScheduleGroups(null, maxResults, null, REGION));
assertEquals("ValidationException", groups.getErrorCode());
assertEquals(400, groups.getHttpStatus());
AwsException schedules = assertThrows(AwsException.class, () ->
service.listSchedules(null, null, null, maxResults, null, REGION));
assertEquals("ValidationException", schedules.getErrorCode());
}
}
@Test
void listOperationsRejectForeignOrBogusNextToken() {
service.createScheduleGroup("tok-a", null, REGION);
service.createScheduleGroup("tok-b", null, REGION);
String groupToken = service.listScheduleGroups(null, 1, null, REGION).nextToken();
AwsException bogus = assertThrows(AwsException.class, () ->
service.listScheduleGroups(null, 1, "not-a-token", REGION));
assertEquals("ValidationException", bogus.getErrorCode());
assertEquals(400, bogus.getHttpStatus());
AwsException foreign = assertThrows(AwsException.class, () ->
service.listSchedules(null, null, null, 1, groupToken, REGION));
assertEquals("ValidationException", foreign.getErrorCode());
AwsException emptyGroups = assertThrows(AwsException.class, () ->
service.listScheduleGroups(null, 1, "", REGION));
assertEquals("ValidationException", emptyGroups.getErrorCode());
assertEquals(400, emptyGroups.getHttpStatus());
assertEquals("Pagination token must be between 1 and 2048 characters.", emptyGroups.getMessage());
AwsException emptySchedules = assertThrows(AwsException.class, () ->
service.listSchedules(null, null, null, 1, "", REGION));
assertEquals("ValidationException", emptySchedules.getErrorCode());
assertEquals(400, emptySchedules.getHttpStatus());
assertEquals("Pagination token must be between 1 and 2048 characters.", emptySchedules.getMessage());
}
@Test
void listOperationsRejectOverLengthNextToken() {
String overLength = "x".repeat(2049);
AwsException groups = assertThrows(AwsException.class, () ->
service.listScheduleGroups(null, 1, overLength, REGION));
assertEquals("ValidationException", groups.getErrorCode());
assertEquals(400, groups.getHttpStatus());
assertEquals("Pagination token must not exceed 2048 characters.", groups.getMessage());
AwsException schedules = assertThrows(AwsException.class, () ->
service.listSchedules(null, null, null, 1, overLength, REGION));
assertEquals("ValidationException", schedules.getErrorCode());
assertEquals(400, schedules.getHttpStatus());
assertEquals("Pagination token must not exceed 2048 characters.", schedules.getMessage());
}
@Test
void createScheduleWithDeadLetterConfig() {
Target target = new Target("arn:aws:lambda:us-east-1:000000000000:function:my-func",