fix(core): extract shared pagination helper, reject maxResults=0 (#2343)

Closes #2339, #2340.

ListResult<T> and its paginate()/encode()/decode() helpers existed as
five near-identical private copies (BedrockAgentCoreGatewayService,
BedrockAgentCoreIdentityService, BedrockAgentCoreMemoryService,
BedrockAgentCoreControlService's three list methods, and MskService),
not the two originally scoped in #2340 - the ListResult<T> record was
already shared within bedrockagentcorecontrol, which is what earlier
scoping missed. Extracts core.common.Pagination + PaginatedResult<T>
and migrates every one of them, deleting both now-unused per-service
ListResult model classes.

Every duplicate collapsed "maxResults omitted" and "maxResults=0"
onto the same primitive int, defaulting both to the full page instead
of rejecting the explicit zero the way AWS's MaxResults min:1
constraint requires (confirmed against botocore's real kafka and
verified live: botocore itself refuses to send MaxResults=0
client-side). Pagination.paginate/parseMaxResults take a boxed
Integer so the two cases are distinguishable, and every migrated
service now rejects 0 with its own existing error code
(ValidationException for the bedrockagentcorecontrol services,
BadRequestException for MSK) - the fix lands once, not five times.

Also carries over the MskController fix from #2336: an
Integer-typed @QueryParam converts before the resource method runs,
so a non-numeric maxResults was a bare 404 instead of an AWS-shaped
400. Every migrated REST controller now binds maxResults as a String
and calls Pagination.parseMaxResults, closing the same gap in
BedrockAgentCoreGatewayController/ControlController/MemoryController
that MSK already had fixed.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-08-17 00:01:48 -05:00
1 parent 1cc97d57c1
commit 25b46e28ad
18 files changed
+215 -338

No files matched your search

@@ -0,0 +1,10 @@
package io.github.hectorvent.floci.core.common;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
/** A page of list results plus an optional pagination token. */
@RegisterForReflection
public record PaginatedResult<T>(List<T> items, String nextToken) {
}
@@ -0,0 +1,87 @@
package io.github.hectorvent.floci.core.common;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Opaque-cursor pagination shared by list endpoints that model AWS's {@code maxResults}/
* {@code nextToken} pair. The cursor is the last returned item's sort key, base64
* URL-encoded - not a raw offset, so a page stays resumable even if items are inserted or
* removed elsewhere in the collection between requests.
*
* <p>{@code maxResults} is a boxed {@link Integer} deliberately: {@code null} means the
* caller omitted it (falls back to {@code maxPage}), while {@code 0} is a real, out-of-range
* value a caller explicitly sent and must be rejected the same as a value above {@code maxPage}
* - AWS's own models declare {@code MaxResults} with a minimum of 1. Collapsing "omitted" and
* "explicitly zero" onto the same primitive {@code int} sentinel is what let that distinction
* get lost in every service that inlined this logic before this class existed.
*/
public final class Pagination {
private Pagination() {}
public static <T> PaginatedResult<T> paginate(List<T> all, Function<T, String> cursorOf,
Integer maxResults, String nextToken,
int maxPage, String errorCode) {
if (maxResults != null && (maxResults < 1 || maxResults > maxPage)) {
throw new AwsException(errorCode, "maxResults must be between 1 and " + maxPage, 400);
}
int limit = maxResults != null ? maxResults : maxPage;
List<T> sorted = all.stream().sorted(Comparator.comparing(cursorOf)).collect(Collectors.toList());
String after = decodeToken(nextToken, errorCode);
int start = 0;
if (after != null) {
for (int i = 0; i < sorted.size(); i++) {
if (cursorOf.apply(sorted.get(i)).compareTo(after) > 0) {
start = i;
break;
}
start = i + 1;
}
}
List<T> page = sorted.stream().skip(start).limit(limit).collect(Collectors.toList());
String token = null;
if (start + limit < sorted.size() && !page.isEmpty()) {
token = encodeToken(cursorOf.apply(page.get(page.size() - 1)));
}
return new PaginatedResult<>(page, token);
}
/**
* Parses a raw {@code maxResults} query-string value. Bind the JAX-RS {@code @QueryParam}
* as {@code String}, not {@code Integer}: RESTEasy Reactive's default handling of a
* non-numeric value for an {@code Integer}-typed {@code @QueryParam} is a 404 (the request
* never reaches the resource method at all), not the AWS-shaped 400 a malformed parameter
* should produce.
*/
public static Integer parseMaxResults(String value, String errorCode) {
if (value == null || value.isBlank()) {
return null;
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new AwsException(errorCode, "maxResults must be an integer.", 400);
}
}
private static String encodeToken(String cursor) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(cursor.getBytes(StandardCharsets.UTF_8));
}
private static String decodeToken(String token, String errorCode) {
if (token == null || token.isEmpty()) {
return null;
}
try {
return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
throw new AwsException(errorCode, "Invalid nextToken.", 400);
}
}
}
@@ -6,11 +6,12 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntime;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeEndpoint;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeVersion;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
@@ -97,12 +98,12 @@ public class BedrockAgentCoreControlController {
@POST
@Path("/runtimes/")
public Response listAgentRuntimes(@Context HttpHeaders headers,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("maxResults") String maxResultsParam,
@QueryParam("nextToken") String nextToken) {
String region = regionResolver.resolveRegion(headers);
try {
ListResult<AgentRuntime> result =
service.listAgentRuntimes(maxResults != null ? maxResults : 0, nextToken, region);
Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException");
PaginatedResult<AgentRuntime> result = service.listAgentRuntimes(maxResults, nextToken, region);
ObjectNode out = objectMapper.createObjectNode();
ArrayNode arr = out.putArray("agentRuntimes");
for (AgentRuntime runtime : result.items()) {
@@ -202,13 +203,14 @@ public class BedrockAgentCoreControlController {
@Path("/runtimes/{agentRuntimeId}/versions/")
public Response listAgentRuntimeVersions(@Context HttpHeaders headers,
@PathParam("agentRuntimeId") String id,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("maxResults") String maxResultsParam,
@QueryParam("nextToken") String nextToken) {
String region = regionResolver.resolveRegion(headers);
try {
Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException");
AgentRuntime runtime = service.getAgentRuntime(id, region);
ListResult<AgentRuntimeVersion> result =
service.listAgentRuntimeVersions(id, maxResults != null ? maxResults : 0, nextToken, region);
PaginatedResult<AgentRuntimeVersion> result =
service.listAgentRuntimeVersions(id, maxResults, nextToken, region);
ObjectNode out = objectMapper.createObjectNode();
ArrayNode arr = out.putArray("agentRuntimes");
for (AgentRuntimeVersion snap : result.items()) {
@@ -315,13 +317,14 @@ public class BedrockAgentCoreControlController {
@Path("/runtimes/{agentRuntimeId}/runtime-endpoints/")
public Response listEndpoints(@Context HttpHeaders headers,
@PathParam("agentRuntimeId") String id,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("maxResults") String maxResultsParam,
@QueryParam("nextToken") String nextToken) {
String region = regionResolver.resolveRegion(headers);
try {
Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException");
AgentRuntime runtime = service.getAgentRuntime(id, region);
ListResult<AgentRuntimeEndpoint> result =
service.listEndpoints(id, maxResults != null ? maxResults : 0, nextToken, region);
PaginatedResult<AgentRuntimeEndpoint> result =
service.listEndpoints(id, maxResults, nextToken, region);
ObjectNode out = objectMapper.createObjectNode();
ArrayNode arr = out.putArray("runtimeEndpoints");
for (AgentRuntimeEndpoint endpoint : result.items()) {
@@ -3,21 +3,19 @@ package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntime;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeEndpoint;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeVersion;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -26,9 +24,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Business logic for the Amazon Bedrock AgentCore control plane (runtime registry).
@@ -48,7 +44,6 @@ public class BedrockAgentCoreControlService {
private static final String ID_ALPHABET =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final int MAX_PAGE = 100;
private static final int DEFAULT_PAGE = 100;
private final StorageBackend<String, AgentRuntime> storage;
private final RegionResolver regionResolver;
@@ -220,20 +215,20 @@ public class BedrockAgentCoreControlService {
return region + "" + clientToken;
}
public ListResult<AgentRuntime> listAgentRuntimes(int maxResults, String nextToken, String region) {
public PaginatedResult<AgentRuntime> listAgentRuntimes(Integer maxResults, String nextToken, String region) {
String prefix = keyPrefix(region);
List<AgentRuntime> all = storage.scan(k -> k.startsWith(prefix)).stream()
.sorted(Comparator.comparing(AgentRuntime::getAgentRuntimeId))
.collect(Collectors.toList());
return paginate(all, AgentRuntime::getAgentRuntimeId, maxResults, nextToken);
List<AgentRuntime> all = storage.scan(k -> k.startsWith(prefix));
return Pagination.paginate(all, AgentRuntime::getAgentRuntimeId, maxResults, nextToken,
MAX_PAGE, "ValidationException");
}
public ListResult<AgentRuntimeVersion> listAgentRuntimeVersions(String id, int maxResults, String nextToken,
public PaginatedResult<AgentRuntimeVersion> listAgentRuntimeVersions(String id, Integer maxResults, String nextToken,
String region) {
AgentRuntime runtime = getAgentRuntime(id, region);
// Cursor must be zero-padded so lexicographic order matches numeric version order;
// paginate() sorts by the cursor, keeping sort order and resume order consistent.
return paginate(runtime.getVersions(), v -> pad(v.getVersion()), maxResults, nextToken);
// Pagination.paginate() sorts by the cursor, keeping sort order and resume order consistent.
return Pagination.paginate(runtime.getVersions(), v -> pad(v.getVersion()), maxResults, nextToken,
MAX_PAGE, "ValidationException");
}
private static String pad(String version) {
@@ -393,13 +388,11 @@ public class BedrockAgentCoreControlService {
return endpoint;
}
public ListResult<AgentRuntimeEndpoint> listEndpoints(String runtimeId, int maxResults, String nextToken,
public PaginatedResult<AgentRuntimeEndpoint> listEndpoints(String runtimeId, Integer maxResults, String nextToken,
String region) {
AgentRuntime runtime = getAgentRuntime(runtimeId, region);
List<AgentRuntimeEndpoint> all = runtime.getEndpoints().stream()
.sorted(Comparator.comparing(AgentRuntimeEndpoint::getName))
.collect(Collectors.toList());
return paginate(all, AgentRuntimeEndpoint::getName, maxResults, nextToken);
return Pagination.paginate(runtime.getEndpoints(), AgentRuntimeEndpoint::getName, maxResults, nextToken,
MAX_PAGE, "ValidationException");
}
private AgentRuntimeEndpoint findEndpoint(AgentRuntime runtime, String name) {
@@ -438,49 +431,6 @@ public class BedrockAgentCoreControlService {
return snap;
}
private <T> ListResult<T> paginate(List<T> all, Function<T, String> cursorOf,
int maxResults, String nextToken) {
if (maxResults < 0 || maxResults > MAX_PAGE) {
throw new AwsException("ValidationException",
"maxResults must be between 1 and " + MAX_PAGE, 400);
}
int limit = maxResults > 0 ? maxResults : DEFAULT_PAGE;
// Sort by the same key used as the pagination cursor so resume order always matches.
List<T> sorted = all.stream().sorted(Comparator.comparing(cursorOf)).collect(Collectors.toList());
String after = decodeToken(nextToken);
int start = 0;
if (after != null) {
for (int i = 0; i < sorted.size(); i++) {
if (cursorOf.apply(sorted.get(i)).compareTo(after) > 0) {
start = i;
break;
}
start = i + 1;
}
}
List<T> page = sorted.stream().skip(start).limit(limit).collect(Collectors.toList());
String outToken = null;
if (start + limit < sorted.size() && !page.isEmpty()) {
outToken = encodeToken(cursorOf.apply(page.get(page.size() - 1)));
}
return new ListResult<>(page, outToken);
}
private static String encodeToken(String cursor) {
return Base64.getUrlEncoder().withoutPadding()
.encodeToString(cursor.getBytes(StandardCharsets.UTF_8));
}
private static String decodeToken(String token) {
if (token == null || token.isEmpty()) {
return null;
}
try {
return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
throw new AwsException("ValidationException", "Invalid nextToken", 400);
}
}
private static String key(String region, String id) {
return keyPrefix(region) + id;
@@ -6,10 +6,11 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Gateway;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.GatewayTarget;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
@@ -115,11 +116,12 @@ public class BedrockAgentCoreGatewayController {
@GET
@Path("/")
public Response listGateways(@Context HttpHeaders headers,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("maxResults") String maxResultsParam,
@QueryParam("nextToken") String nextToken) {
String region = regionResolver.resolveRegion(headers);
try {
ListResult<Gateway> result = service.list(maxResults != null ? maxResults : 0, nextToken, region);
Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException");
PaginatedResult<Gateway> result = service.list(maxResults, nextToken, region);
ObjectNode out = objectMapper.createObjectNode();
ArrayNode arr = out.putArray("items");
for (Gateway gateway : result.items()) {
@@ -211,12 +213,12 @@ public class BedrockAgentCoreGatewayController {
@GET
@Path("/{gatewayIdentifier}/targets/")
public Response listTargets(@Context HttpHeaders headers, @PathParam("gatewayIdentifier") String id,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("maxResults") String maxResultsParam,
@QueryParam("nextToken") String nextToken) {
String region = regionResolver.resolveRegion(headers);
try {
ListResult<GatewayTarget> result =
service.listTargets(id, maxResults != null ? maxResults : 0, nextToken, region);
Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException");
PaginatedResult<GatewayTarget> result = service.listTargets(id, maxResults, nextToken, region);
ObjectNode out = objectMapper.createObjectNode();
ArrayNode arr = out.putArray("items");
for (GatewayTarget target : result.items()) {
@@ -3,25 +3,21 @@ package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Gateway;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.GatewayTarget;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import java.util.stream.Collectors;
/** CRUD for AgentCore gateways and their targets. Metadata registry only. */
@ApplicationScoped
@@ -141,12 +137,10 @@ public class BedrockAgentCoreGatewayService {
return gateway;
}
public ListResult<Gateway> list(int maxResults, String nextToken, String region) {
public PaginatedResult<Gateway> list(Integer maxResults, String nextToken, String region) {
String prefix = keyPrefix(region);
List<Gateway> all = storage.scan(k -> k.startsWith(prefix)).stream()
.sorted(Comparator.comparing(Gateway::getGatewayId))
.collect(Collectors.toList());
return paginate(all, Gateway::getGatewayId, maxResults, nextToken);
List<Gateway> all = storage.scan(k -> k.startsWith(prefix));
return Pagination.paginate(all, Gateway::getGatewayId, maxResults, nextToken, MAX_PAGE, "ValidationException");
}
public String gatewayArn(Gateway gateway, String region) {
@@ -203,12 +197,10 @@ public class BedrockAgentCoreGatewayService {
return target;
}
public ListResult<GatewayTarget> listTargets(String gatewayId, int maxResults, String nextToken, String region) {
public PaginatedResult<GatewayTarget> listTargets(String gatewayId, Integer maxResults, String nextToken, String region) {
Gateway gateway = get(gatewayId, region);
List<GatewayTarget> all = gateway.getTargets().stream()
.sorted(Comparator.comparing(GatewayTarget::getTargetId))
.collect(Collectors.toList());
return paginate(all, GatewayTarget::getTargetId, maxResults, nextToken);
return Pagination.paginate(gateway.getTargets(), GatewayTarget::getTargetId, maxResults, nextToken,
MAX_PAGE, "ValidationException");
}
private GatewayTarget findTarget(Gateway gateway, String targetId) {
@@ -219,31 +211,6 @@ public class BedrockAgentCoreGatewayService {
"Gateway target not found: " + targetId, 404));
}
private <T> ListResult<T> paginate(List<T> all, Function<T, String> cursorOf, int maxResults, String nextToken) {
if (maxResults < 0 || maxResults > MAX_PAGE) {
throw new AwsException("ValidationException",
"maxResults must be between 1 and " + MAX_PAGE, 400);
}
int limit = maxResults > 0 ? maxResults : MAX_PAGE;
String after = decode(nextToken);
int start = 0;
if (after != null) {
for (int i = 0; i < all.size(); i++) {
if (cursorOf.apply(all.get(i)).compareTo(after) > 0) {
start = i;
break;
}
start = i + 1;
}
}
List<T> page = all.stream().skip(start).limit(limit).collect(Collectors.toList());
String token = null;
if (start + limit < all.size() && !page.isEmpty()) {
token = encode(cursorOf.apply(page.get(page.size() - 1)));
}
return new ListResult<>(page, token);
}
private static String sanitize(String name) {
String s = name.toLowerCase().replaceAll("[^a-z0-9]", "");
if (s.isEmpty()) {
@@ -267,19 +234,4 @@ public class BedrockAgentCoreGatewayService {
private static String keyPrefix(String region) {
return "gateway:" + region + ":";
}
private static String encode(String cursor) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(cursor.getBytes(StandardCharsets.UTF_8));
}
private static String decode(String token) {
if (token == null || token.isEmpty()) {
return null;
}
try {
return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
throw new AwsException("ValidationException", "Invalid nextToken", 400);
}
}
}
@@ -6,8 +6,8 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.WorkloadIdentity;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
@@ -109,9 +109,9 @@ public class BedrockAgentCoreIdentityController {
String region = regionResolver.resolveRegion(headers);
try {
JsonNode req = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}");
int maxResults = req.hasNonNull("maxResults") ? req.get("maxResults").asInt() : 0;
Integer maxResults = req.hasNonNull("maxResults") ? req.get("maxResults").asInt() : null;
String nextToken = text(req, "nextToken");
ListResult<WorkloadIdentity> result = service.list(maxResults, nextToken, region);
PaginatedResult<WorkloadIdentity> result = service.list(maxResults, nextToken, region);
ObjectNode out = objectMapper.createObjectNode();
ArrayNode arr = out.putArray("workloadIdentities");
for (WorkloadIdentity identity : result.items()) {
@@ -2,22 +2,19 @@ package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.WorkloadIdentity;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Workload identity registry for the AgentCore control plane. Exposed via the
@@ -94,51 +91,14 @@ public class BedrockAgentCoreIdentityService {
storage.delete(key(region, name));
}
public ListResult<WorkloadIdentity> list(int maxResults, String nextToken, String region) {
if (maxResults < 0 || maxResults > MAX_PAGE) {
throw new AwsException("ValidationException",
"maxResults must be between 1 and " + MAX_PAGE, 400);
}
public PaginatedResult<WorkloadIdentity> list(Integer maxResults, String nextToken, String region) {
String prefix = "identity:" + region + ":";
List<WorkloadIdentity> all = storage.scan(k -> k.startsWith(prefix)).stream()
.sorted(Comparator.comparing(WorkloadIdentity::getName))
.collect(Collectors.toList());
int limit = maxResults > 0 ? maxResults : MAX_PAGE;
String after = decode(nextToken);
int start = 0;
if (after != null) {
for (int i = 0; i < all.size(); i++) {
if (all.get(i).getName().compareTo(after) > 0) {
start = i;
break;
}
start = i + 1;
}
}
List<WorkloadIdentity> page = all.stream().skip(start).limit(limit).collect(Collectors.toList());
String token = null;
if (start + limit < all.size() && !page.isEmpty()) {
token = encode(page.get(page.size() - 1).getName());
}
return new ListResult<>(page, token);
List<WorkloadIdentity> all = storage.scan(k -> k.startsWith(prefix));
return Pagination.paginate(all, WorkloadIdentity::getName, maxResults, nextToken,
MAX_PAGE, "ValidationException");
}
private static String key(String region, String name) {
return "identity:" + region + ":" + name;
}
private static String encode(String cursor) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(cursor.getBytes(StandardCharsets.UTF_8));
}
private static String decode(String token) {
if (token == null || token.isEmpty()) {
return null;
}
try {
return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
throw new AwsException("ValidationException", "Invalid nextToken", 400);
}
}
}
@@ -6,8 +6,9 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Memory;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
@@ -109,11 +110,12 @@ public class BedrockAgentCoreMemoryController {
@POST
@Path("/")
public Response listMemories(@Context HttpHeaders headers,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("maxResults") String maxResultsParam,
@QueryParam("nextToken") String nextToken) {
String region = regionResolver.resolveRegion(headers);
try {
ListResult<Memory> result = service.list(maxResults != null ? maxResults : 0, nextToken, region);
Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException");
PaginatedResult<Memory> result = service.list(maxResults, nextToken, region);
ObjectNode out = objectMapper.createObjectNode();
ArrayNode arr = out.putArray("memories");
for (Memory memory : result.items()) {
@@ -2,25 +2,22 @@ package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Memory;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
/** CRUD for AgentCore memory resources. Metadata registry only. */
@ApplicationScoped
@@ -118,33 +115,10 @@ public class BedrockAgentCoreMemoryService {
return memory;
}
public ListResult<Memory> list(int maxResults, String nextToken, String region) {
if (maxResults < 0 || maxResults > MAX_PAGE) {
throw new AwsException("ValidationException",
"maxResults must be between 1 and " + MAX_PAGE, 400);
}
public PaginatedResult<Memory> list(Integer maxResults, String nextToken, String region) {
String prefix = keyPrefix(region);
List<Memory> all = storage.scan(k -> k.startsWith(prefix)).stream()
.sorted(Comparator.comparing(Memory::getMemoryId))
.collect(Collectors.toList());
int limit = maxResults > 0 ? maxResults : MAX_PAGE;
String after = decode(nextToken);
int start = 0;
if (after != null) {
for (int i = 0; i < all.size(); i++) {
if (all.get(i).getMemoryId().compareTo(after) > 0) {
start = i;
break;
}
start = i + 1;
}
}
List<Memory> page = all.stream().skip(start).limit(limit).collect(Collectors.toList());
String token = null;
if (start + limit < all.size() && !page.isEmpty()) {
token = encode(page.get(page.size() - 1).getMemoryId());
}
return new ListResult<>(page, token);
List<Memory> all = storage.scan(k -> k.startsWith(prefix));
return Pagination.paginate(all, Memory::getMemoryId, maxResults, nextToken, MAX_PAGE, "ValidationException");
}
public String arn(Memory memory, String region) {
@@ -174,19 +148,4 @@ public class BedrockAgentCoreMemoryService {
private static String keyPrefix(String region) {
return "memory:" + region + ":";
}
private static String encode(String cursor) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(cursor.getBytes(StandardCharsets.UTF_8));
}
private static String decode(String token) {
if (token == null || token.isEmpty()) {
return null;
}
try {
return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
throw new AwsException("ValidationException", "Invalid nextToken", 400);
}
}
}
@@ -1,12 +0,0 @@
package io.github.hectorvent.floci.services.bedrockagentcorecontrol.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
/**
* A page of list results plus an optional pagination token.
*/
@RegisterForReflection
public record ListResult<T>(List<T> items, String nextToken) {
}
@@ -1,7 +1,8 @@
package io.github.hectorvent.floci.services.msk;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.msk.model.ListResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.services.msk.model.MskCluster;
import io.github.hectorvent.floci.services.msk.model.MskConfiguration;
import jakarta.inject.Inject;
@@ -113,8 +114,8 @@ public class MskController {
@Path("/v1/configurations")
public Response listConfigurations(@QueryParam("maxResults") String maxResultsParam,
@QueryParam("nextToken") String nextToken) {
ListResult<MskConfiguration> result = mskService.listConfigurations(
parseMaxResults(maxResultsParam), nextToken);
PaginatedResult<MskConfiguration> result = mskService.listConfigurations(
Pagination.parseMaxResults(maxResultsParam, "BadRequestException"), nextToken);
var configurations = result.items().stream()
.map(this::toConfigurationView)
.toList();
@@ -167,20 +168,6 @@ public class MskController {
}
}
// Bound as String rather than @QueryParam Integer: RESTEasy Reactive's default handling
// of a non-numeric value for an Integer-typed @QueryParam is a 404, not a 400 - the
// request never reaches this method at all in that case, so it must be parsed here.
private int parseMaxResults(String value) {
if (value == null || value.isBlank()) {
return 0;
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new AwsException("BadRequestException", "maxResults must be an integer.", 400);
}
}
private String asString(Object value, String fieldName) {
if (value == null) {
return null;
@@ -3,13 +3,14 @@ package io.github.hectorvent.floci.services.msk;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.msk.model.ClusterState;
import io.github.hectorvent.floci.services.msk.model.ConfigurationState;
import io.github.hectorvent.floci.services.msk.model.ListResult;
import io.github.hectorvent.floci.services.msk.model.MskCluster;
import io.github.hectorvent.floci.services.msk.model.MskConfiguration;
import com.fasterxml.jackson.core.type.TypeReference;
@@ -19,18 +20,13 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
@ApplicationScoped
public class MskService {
@@ -158,50 +154,9 @@ public class MskService {
.orElseThrow(() -> new AwsException("NotFoundException", "Configuration not found: " + arn, 404));
}
public ListResult<MskConfiguration> listConfigurations(int maxResults, String nextToken) {
List<MskConfiguration> all = configurationStorage.scan(k -> true).stream()
.sorted(Comparator.comparing(MskConfiguration::getArn))
.collect(Collectors.toList());
return paginate(all, MskConfiguration::getArn, maxResults, nextToken);
}
private <T> ListResult<T> paginate(List<T> all, Function<T, String> cursorOf, int maxResults, String nextToken) {
if (maxResults < 0 || maxResults > MAX_PAGE) {
throw new AwsException("BadRequestException", "maxResults must be between 1 and " + MAX_PAGE, 400);
}
int limit = maxResults > 0 ? maxResults : MAX_PAGE;
String after = decodeToken(nextToken);
int start = 0;
if (after != null) {
for (int i = 0; i < all.size(); i++) {
if (cursorOf.apply(all.get(i)).compareTo(after) > 0) {
start = i;
break;
}
start = i + 1;
}
}
List<T> page = all.stream().skip(start).limit(limit).collect(Collectors.toList());
String token = null;
if (start + limit < all.size() && !page.isEmpty()) {
token = encodeToken(cursorOf.apply(page.get(page.size() - 1)));
}
return new ListResult<>(page, token);
}
private static String encodeToken(String cursor) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(cursor.getBytes(StandardCharsets.UTF_8));
}
private static String decodeToken(String token) {
if (token == null || token.isEmpty()) {
return null;
}
try {
return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
throw new AwsException("BadRequestException", "Invalid nextToken.", 400);
}
public PaginatedResult<MskConfiguration> listConfigurations(Integer maxResults, String nextToken) {
List<MskConfiguration> all = configurationStorage.scan(k -> true);
return Pagination.paginate(all, MskConfiguration::getArn, maxResults, nextToken, MAX_PAGE, "BadRequestException");
}
public MskConfiguration deleteConfiguration(String arn) {
@@ -1,12 +0,0 @@
package io.github.hectorvent.floci.services.msk.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
/**
* A page of list results plus an optional pagination token.
*/
@RegisterForReflection
public record ListResult<T>(List<T> items, String nextToken) {
}
@@ -3,12 +3,12 @@ package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntime;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeEndpoint;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeVersion;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.ListResult;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -109,7 +109,7 @@ class BedrockAgentCoreControlServiceTest {
void listReturnsCreatedRuntimes() {
create("agentA");
create("agentB");
ListResult<AgentRuntime> result = service.listAgentRuntimes(0, null, REGION);
PaginatedResult<AgentRuntime> result = service.listAgentRuntimes(null, null, REGION);
assertEquals(2, result.items().size());
assertNull(result.nextToken());
}
@@ -119,10 +119,10 @@ class BedrockAgentCoreControlServiceTest {
create("agentA");
create("agentB");
create("agentC");
ListResult<AgentRuntime> page1 = service.listAgentRuntimes(2, null, REGION);
PaginatedResult<AgentRuntime> page1 = service.listAgentRuntimes(2, null, REGION);
assertEquals(2, page1.items().size());
assertTrue(page1.nextToken() != null);
ListResult<AgentRuntime> page2 = service.listAgentRuntimes(2, page1.nextToken(), REGION);
PaginatedResult<AgentRuntime> page2 = service.listAgentRuntimes(2, page1.nextToken(), REGION);
assertEquals(1, page2.items().size());
assertNull(page2.nextToken());
}
@@ -141,7 +141,7 @@ class BedrockAgentCoreControlServiceTest {
String token = null;
int pages = 0;
do {
ListResult<AgentRuntimeVersion> page = service.listAgentRuntimeVersions(id, 5, token, REGION);
PaginatedResult<AgentRuntimeVersion> page = service.listAgentRuntimeVersions(id, 5, token, REGION);
page.items().forEach(v -> seen.add(v.getVersion()));
token = page.nextToken();
assertTrue(++pages <= 5, "pagination did not terminate (cycled)");
@@ -183,7 +183,15 @@ class BedrockAgentCoreControlServiceTest {
@Test
void listRejectsMalformedNextToken() {
assertEquals(400, assertThrows(AwsException.class,
() -> service.listAgentRuntimes(0, "!!!not-base64!!!", REGION)).getHttpStatus());
() -> service.listAgentRuntimes(null, "!!!not-base64!!!", REGION)).getHttpStatus());
}
@Test
void listRejectsZeroMaxResults() {
// AWS declares MaxResults with a minimum of 1; 0 is a real out-of-range value, not a
// synonym for "omitted" (that's represented by null instead).
assertEquals(400, assertThrows(AwsException.class,
() -> service.listAgentRuntimes(0, null, REGION)).getHttpStatus());
}
@Test
@@ -194,7 +202,7 @@ class BedrockAgentCoreControlServiceTest {
AgentRuntime b = service.createAgentRuntime("myAgent", artifact(), network(),
"arn:aws:iam::000000000000:role/agent", "d", null, null, null, "tok-1", REGION);
assertEquals(a.getAgentRuntimeId(), b.getAgentRuntimeId());
assertEquals(1, service.listAgentRuntimes(0, null, REGION).items().size());
assertEquals(1, service.listAgentRuntimes(null, null, REGION).items().size());
}
@Test
@@ -223,7 +231,7 @@ class BedrockAgentCoreControlServiceTest {
AgentRuntime rt = create("myAgent");
String id = rt.getAgentRuntimeId();
// Not visible or gettable from a different region.
assertTrue(service.listAgentRuntimes(0, null, "us-west-2").items().isEmpty());
assertTrue(service.listAgentRuntimes(null, null, "us-west-2").items().isEmpty());
assertEquals(404, assertThrows(AwsException.class,
() -> service.getAgentRuntime(id, "us-west-2")).getHttpStatus());
// Same id resolves in its own region.
@@ -61,4 +61,13 @@ class BedrockAgentCorePaginationIntegrationTest {
assertEquals(collected.size(), new HashSet<>(collected).size(), "duplicate items across pages");
assertTrue(collected.containsAll(mine), "a created runtime was dropped by pagination");
}
// AWS declares MaxResults with a minimum of 1; 0 is real out-of-range input, not a
// synonym for "omitted" (an absent query param instead).
@Test
void listRuntimesRejectsZeroMaxResults() {
given().contentType("application/json").queryParam("maxResults", 0)
.when().post("/runtimes/")
.then().statusCode(400);
}
}
@@ -270,6 +270,15 @@ class MskControllerIntegrationTest {
.then().statusCode(400);
}
// AWS declares MaxResults with a minimum of 1; 0 is real out-of-range input, not a
// synonym for "omitted" (that's an absent query param instead).
@Test
void listConfigurationsRejectsZeroMaxResults() {
given()
.when().get("/v1/configurations?maxResults=0")
.then().statusCode(400);
}
// maxResults is bound as a raw String and parsed by hand rather than @QueryParam
// Integer specifically because a non-numeric value for an Integer-typed @QueryParam
// fails RESTEasy Reactive's own conversion before the method body runs, and its
@@ -6,9 +6,9 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.services.msk.model.ClusterState;
import io.github.hectorvent.floci.services.msk.model.ConfigurationState;
import io.github.hectorvent.floci.services.msk.model.ListResult;
import io.github.hectorvent.floci.services.msk.model.MskCluster;
import io.github.hectorvent.floci.services.msk.model.MskConfiguration;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -153,7 +153,7 @@ class MskServiceTest {
void listConfigurations() {
mskService.createConfiguration("config-1", "desc", List.of("3.6.0"), "props");
mskService.createConfiguration("config-2", "desc", List.of("3.6.0"), "props");
List<MskConfiguration> configurations = mskService.listConfigurations(0, null).items();
List<MskConfiguration> configurations = mskService.listConfigurations(null, null).items();
assertEquals(2, configurations.size());
}
@@ -163,11 +163,11 @@ class MskServiceTest {
mskService.createConfiguration("config-2", "desc", List.of("3.6.0"), "props");
mskService.createConfiguration("config-3", "desc", List.of("3.6.0"), "props");
ListResult<MskConfiguration> firstPage = mskService.listConfigurations(2, null);
PaginatedResult<MskConfiguration> firstPage = mskService.listConfigurations(2, null);
assertEquals(2, firstPage.items().size());
assertNotNull(firstPage.nextToken());
ListResult<MskConfiguration> secondPage = mskService.listConfigurations(2, firstPage.nextToken());
PaginatedResult<MskConfiguration> secondPage = mskService.listConfigurations(2, firstPage.nextToken());
assertEquals(1, secondPage.items().size());
assertNull(secondPage.nextToken());
}
@@ -177,9 +177,17 @@ class MskServiceTest {
assertThrows(AwsException.class, () -> mskService.listConfigurations(101, null));
}
@Test
void listConfigurationsRejectsZeroMaxResults() {
// AWS declares MaxResults with a minimum of 1; 0 is a real out-of-range value, not a
// synonym for "omitted" (that's represented by null instead).
AwsException ex = assertThrows(AwsException.class, () -> mskService.listConfigurations(0, null));
assertEquals("BadRequestException", ex.getErrorCode());
}
@Test
void listConfigurationsRejectsInvalidNextToken() {
assertThrows(AwsException.class, () -> mskService.listConfigurations(0, "not-a-valid-token!!"));
assertThrows(AwsException.class, () -> mskService.listConfigurations(null, "not-a-valid-token!!"));
}
@Test
@@ -187,7 +195,7 @@ class MskServiceTest {
MskConfiguration configuration = mskService.createConfiguration(
"test-config", "desc", List.of("3.6.0"), "props");
mskService.deleteConfiguration(configuration.getArn());
assertTrue(mskService.listConfigurations(0, null).items().isEmpty());
assertTrue(mskService.listConfigurations(null, null).items().isEmpty());
}
// StorageBackend persists this model via plain Jackson serialization (PersistentStorage,