Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(bcm-data-exports): paginate exports and executions (#6604)

Aniket Shukla935922933f5a
diff --git a/docs/services/bcm-data-exports.md b/docs/services/bcm-data-exports.md
index 81bc4f5bbb..809dd6ac69 100644
--- a/docs/services/bcm-data-exports.md
+++ b/docs/services/bcm-data-exports.md
@@ -15,12 +15,20 @@ management surfaces over one underlying export pipeline.
|-----------|-------|
| `CreateExport` | Creates an export; rejects duplicate `Name` with `ValidationException` |
| `GetExport` | Returns one export by ARN; missing ARN returns `ResourceNotFoundException` |
-| `ListExports` | Returns every export owned by the calling account |
+| `ListExports` | Returns a page of exports owned by the calling account |
| `UpdateExport` | Replaces mutable fields on an existing export |
| `DeleteExport` | Idempotent; deletes orphan executions too |
-| `ListExecutions` | Returns all execution records for an export |
+| `ListExecutions` | Returns a page of execution records for an export |
| `GetExecution` | Returns one execution record |
+`ListExports` and `ListExecutions` accept `MaxResults` from 1 to 300 and an optional
+`NextToken` of up to 8192 characters. Floci defaults to 300 results per page. It
+returns `NextToken` only when more results remain. Cursors use stable export ARN
+or execution ID order and can resume after a previously returned item is deleted.
+Tokens are scoped to the action and calling account, and execution tokens also
+belong to the requested export. Invalid pagination fields return
+`ValidationException` (400).
+
## Validation rules
- `Export.Name`: alphanumerics + `-_`, max 128 chars
diff --git a/pom.xml b/pom.xml
index ac51810f64..83fe5b954c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -390,6 +390,12 @@
<version>${aws.sdk.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>bcmdataexports</artifactId>
+ <version>${aws.sdk.version}</version>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>redshift</artifactId>
diff --git a/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsJsonHandler.java
index 43c1ec240c..e14ff389c5 100644
--- a/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsJsonHandler.java
@@ -6,6 +6,7 @@ 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.services.bcmdataexports.model.DataQuery;
import io.github.hectorvent.floci.services.bcmdataexports.model.DestinationConfiguration;
import io.github.hectorvent.floci.services.bcmdataexports.model.Export;
@@ -20,7 +21,6 @@ import java.time.Instant;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
-import java.util.List;
import java.util.Map;
/**
@@ -51,7 +51,7 @@ public class BcmDataExportsJsonHandler {
return switch (action) {
case "CreateExport" -> handleCreate(request, region);
case "GetExport" -> handleGet(request);
- case "ListExports" -> handleList();
+ case "ListExports" -> handleList(request);
case "UpdateExport" -> handleUpdate(request);
case "DeleteExport" -> handleDelete(request);
case "ListExecutions" -> handleListExecutions(request);
@@ -85,13 +85,16 @@ public class BcmDataExportsJsonHandler {
return Response.ok(response).build();
}
- private Response handleList() {
- List<Export> exports = service.listExports();
+ private Response handleList(JsonNode request) {
+ PaginatedResult<Export> page = service.listExports(maxResults(request), nextToken(request));
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = response.putArray("Exports");
- for (Export export : exports) {
+ for (Export export : page.items()) {
arr.add(serializeExportReference(export));
}
+ if (page.nextToken() != null) {
+ response.put("NextToken", page.nextToken());
+ }
return Response.ok(response).build();
}
@@ -119,15 +122,40 @@ public class BcmDataExportsJsonHandler {
private Response handleListExecutions(JsonNode request) {
String arn = stringOrNull(request, "ExportArn");
- List<ExportExecution> executions = service.listExecutions(arn);
+ PaginatedResult<ExportExecution> page = service.listExecutions(arn, maxResults(request), nextToken(request));
ObjectNode response = objectMapper.createObjectNode();
ArrayNode arr = response.putArray("Executions");
- for (ExportExecution exec : executions) {
+ for (ExportExecution exec : page.items()) {
arr.add(serializeExecution(exec));
}
+ if (page.nextToken() != null) {
+ response.put("NextToken", page.nextToken());
+ }
return Response.ok(response).build();
}
+ private static Integer maxResults(JsonNode request) {
+ JsonNode value = request.get("MaxResults");
+ if (value == null || value.isNull()) {
+ return null;
+ }
+ if (!value.isIntegralNumber() || !value.canConvertToInt()) {
+ throw new AwsException("ValidationException", "MaxResults must be an integer between 1 and 300.", 400);
+ }
+ return value.intValue();
+ }
+
+ private static String nextToken(JsonNode request) {
+ JsonNode value = request.get("NextToken");
+ if (value == null || value.isNull()) {
+ return null;
+ }
+ if (!value.isTextual()) {
+ throw new AwsException("ValidationException", "NextToken must be a string.", 400);
+ }
+ return value.textValue();
+ }
+
private Response handleGetExecution(JsonNode request) {
String arn = stringOrNull(request, "ExportArn");
String executionId = stringOrNull(request, "ExecutionId");
diff --git a/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsService.java b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsService.java
index 6282c8800e..6510923f0f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsService.java
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.bcmdataexports;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+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.S3DestinationValidation;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
@@ -24,6 +26,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
+import java.util.function.Function;
import java.util.regex.Pattern;
/**
@@ -43,6 +46,7 @@ import java.util.regex.Pattern;
public class BcmDataExportsService {
private static final Logger LOG = Logger.getLogger(BcmDataExportsService.class);
+ private static final int MAX_PAGE_SIZE = 300;
private static final Pattern EXPORT_NAME_PATTERN = Pattern.compile("[A-Za-z0-9_-]+");
private static final Set<String> ALLOWED_FREQUENCY = Set.of("SYNCHRONOUS");
@@ -112,9 +116,10 @@ public class BcmDataExportsService {
"Export " + exportArn + " not found.", 400));
}
- /** {@code ListExports} — returns every export owned by the calling account. */
- public List<Export> listExports() {
- return new ArrayList<>(exportStore.scan(key -> true));
+ /** Returns one account-scoped page for {@code ListExports}. */
+ public PaginatedResult<Export> listExports(Integer maxResults, String nextToken) {
+ return paginate(exportStore.scan(key -> true), Export::getExportArn, maxResults, nextToken,
+ "ListExports:" + regionResolver.getAccountId());
}
/**
@@ -186,15 +191,29 @@ public class BcmDataExportsService {
return existing;
}
- /** {@code ListExecutions} — returns every recorded execution for the export. */
- public List<ExportExecution> listExecutions(String exportArn) {
+ /** Returns one page of recorded executions for the export. */
+ public PaginatedResult<ExportExecution> listExecutions(String exportArn, Integer maxResults, String nextToken) {
requireNonEmpty(exportArn, "ExportArn");
if (exportStore.get(exportKey(exportArn)).isEmpty()) {
throw new AwsException("ResourceNotFoundException",
"Export " + exportArn + " not found.", 400);
}
String prefix = exportArn + "::";
- return new ArrayList<>(executionStore.scan(key -> key.startsWith(prefix)));
+ return paginate(executionStore.scan(key -> key.startsWith(prefix)), ExportExecution::getExecutionId,
+ maxResults, nextToken, "ListExecutions:" + regionResolver.getAccountId() + ":" + exportArn);
+ }
+
+ private static <T> PaginatedResult<T> paginate(List<T> items, Function<T, String> cursorOf,
+ Integer maxResults, String nextToken, String namespace) {
+ int limit = maxResults != null ? maxResults : MAX_PAGE_SIZE;
+ if (limit < 1 || limit > MAX_PAGE_SIZE) {
+ throw new AwsException("ValidationException", "MaxResults must be between 1 and 300.", 400);
+ }
+ if (nextToken != null && nextToken.length() > 8192) {
+ throw new AwsException("ValidationException", "NextToken must not exceed 8192 characters.", 400);
+ }
+ return Pagination.paginate(items, cursorOf, limit, nextToken, namespace,
+ token -> new AwsException("ValidationException", "Invalid NextToken.", 400));
}
/** {@code GetExecution} — returns one execution record. */
diff --git a/src/test/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsPaginationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsPaginationIntegrationTest.java
new file mode 100644
index 0000000000..7774d990ca
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/bcmdataexports/BcmDataExportsPaginationIntegrationTest.java
@@ -0,0 +1,258 @@
+package io.github.hectorvent.floci.services.bcmdataexports;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.bcmdataexports.model.Export;
+import io.github.hectorvent.floci.services.bcmdataexports.model.ExportExecution;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.common.http.TestHTTPResource;
+import io.quarkus.test.junit.QuarkusTest;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
+import software.amazon.awssdk.regions.Region;
+import software.amazon.awssdk.services.bcmdataexports.BcmDataExportsClient;
+import software.amazon.awssdk.services.bcmdataexports.model.ListExecutionsResponse;
+import software.amazon.awssdk.services.bcmdataexports.model.ListExportsRequest;
+import software.amazon.awssdk.services.bcmdataexports.model.ListExportsResponse;
+import software.amazon.awssdk.services.bcmdataexports.model.ValidationException;
+
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+@QuarkusTest
+class BcmDataExportsPaginationIntegrationTest {
+
+ private static final String ACCOUNT = "741660000001";
+ private static final String OTHER_ACCOUNT = "741660000002";
+ private static final String TARGET = "AWSBillingAndCostManagementDataExports.";
+
+ @Inject
+ StorageFactory storageFactory;
+
+ @TestHTTPResource
+ URI endpoint;
+
+ private final List<StoredKey> storedKeys = new ArrayList<>();
+ private AccountAwareStorageBackend<Export> exports;
+ private AccountAwareStorageBackend<ExportExecution> executions;
+ private BcmDataExportsClient client;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @BeforeEach
+ void setUp() {
+ exports = storageFactory.create("bcmdataexports", "bcm-exports.json",
+ new TypeReference<Map<String, Export>>() {});
+ executions = storageFactory.create("bcmdataexports", "bcm-executions.json",
+ new TypeReference<Map<String, ExportExecution>>() {});
+ client = client(ACCOUNT);
+ }
+
+ @AfterEach
+ void cleanUp() {
+ client.close();
+ for (StoredKey key : storedKeys) {
+ if (key.execution()) {
+ executions.deleteForAccount(key.account(), key.key());
+ } else {
+ exports.deleteForAccount(key.account(), key.key());
+ }
+ }
+ }
+
+ @Test
+ void sdkPaginatesExportsWithoutRepeatingOrLosingItems() {
+ List<String> expected = List.of(export(ACCOUNT, "a"), export(ACCOUNT, "b"), export(ACCOUNT, "c"));
+ ListExportsResponse first = client.listExports(request -> request.maxResults(1));
+ assertEquals(1, first.exports().size());
+ assertNotNull(first.nextToken());
+ List<String> actual = client.listExportsPaginator(request -> request.maxResults(1)).stream()
+ .flatMap(page -> page.exports().stream()).map(item -> item.exportArn()).toList();
+ assertEquals(expected, actual);
+ ListExportsResponse last = client.listExports(request -> request.maxResults(300).nextToken(first.nextToken()));
+ assertEquals(2, last.exports().size());
+ assertNull(last.nextToken());
+ }
+
+ @Test
+ void sdkPaginatesExecutionsWithinTheRequestedExport() {
+ String arn = export(ACCOUNT, "executions");
+ List<String> expected = List.of(execution(arn, "a"), execution(arn, "b"), execution(arn, "c"));
+ execution(export(ACCOUNT, "other"), "unrelated");
+ ListExecutionsResponse first = client.listExecutions(request -> request.exportArn(arn).maxResults(1));
+ assertEquals(1, first.executions().size());
+ assertNotNull(first.nextToken());
+ List<String> actual = client.listExecutionsPaginator(request -> request.exportArn(arn).maxResults(1)).stream()
+ .flatMap(page -> page.executions().stream()).map(item -> item.executionId()).toList();
+ assertEquals(expected, actual);
+ assertNull(client.listExecutions(request -> request.exportArn(arn).maxResults(300)
+ .nextToken(first.nextToken())).nextToken());
+ }
+
+ @Test
+ void omittedAndMaximumPageSizesAreBoundedAt300() {
+ String arn = export(ACCOUNT, "defaults");
+ for (int i = 0; i < 300; i++) {
+ export(ACCOUNT, "bulk-" + i);
+ }
+ for (int i = 0; i < 301; i++) {
+ execution(arn, "exec-" + i);
+ }
+ ListExportsResponse exportPage = client.listExports(ListExportsRequest.builder().build());
+ assertEquals(300, exportPage.exports().size());
+ assertNotNull(exportPage.nextToken());
+ assertEquals(1, client.listExports(request -> request.maxResults(300).nextToken(exportPage.nextToken())).exports().size());
+ ListExecutionsResponse executionPage = client.listExecutions(request -> request.exportArn(arn));
+ assertEquals(300, executionPage.executions().size());
+ assertNotNull(executionPage.nextToken());
+ assertEquals(1, client.listExecutions(request -> request.exportArn(arn).maxResults(300)
+ .nextToken(executionPage.nextToken())).executions().size());
+ }
+
+ @ParameterizedTest
+ @ValueSource(ints = {-1, 0, 301})
+ void sdkRejectsOutOfRangeLimitsForBothActions(int limit) {
+ String arn = export(ACCOUNT, "limits");
+ assertEquals(400, assertThrows(ValidationException.class,
+ () -> client.listExports(request -> request.maxResults(limit))).statusCode());
+ assertEquals(400, assertThrows(ValidationException.class,
+ () -> client.listExecutions(request -> request.exportArn(arn).maxResults(limit))).statusCode());
+ }
+
+ @Test
+ void tokensCannotCrossAccountsActionsOrExports() {
+ String arn = export(ACCOUNT, "a");
+ String otherArn = export(ACCOUNT, "b");
+ execution(arn, "a");
+ execution(arn, "b");
+ execution(otherArn, "a");
+ String exportToken = client.listExports(request -> request.maxResults(1)).nextToken();
+ assertNotNull(exportToken);
+ assertThrows(ValidationException.class, () -> client.listExecutions(request -> request.exportArn(arn).nextToken(exportToken)));
+ export(OTHER_ACCOUNT, "other-account");
+ try (BcmDataExportsClient other = client(OTHER_ACCOUNT)) {
+ assertThrows(ValidationException.class, () -> other.listExports(request -> request.nextToken(exportToken)));
+ }
+ String executionToken = client.listExecutions(request -> request.exportArn(arn).maxResults(1)).nextToken();
+ assertNotNull(executionToken);
+ assertThrows(ValidationException.class, () -> client.listExecutions(request -> request.exportArn(otherArn).nextToken(executionToken)));
+ }
+
+ @Test
+ void deletedCursorItemsDoNotPreventResumingEitherList() {
+ String firstArn = export(ACCOUNT, "a");
+ String secondArn = export(ACCOUNT, "b");
+ ListExportsResponse first = client.listExports(request -> request.maxResults(1));
+ assertNotNull(first.nextToken());
+ exports.deleteForAccount(ACCOUNT, firstArn);
+ assertEquals(secondArn, client.listExports(request -> request.nextToken(first.nextToken())).exports().getFirst().exportArn());
+ execution(secondArn, "a");
+ execution(secondArn, "b");
+ ListExecutionsResponse executionPage = client.listExecutions(request -> request.exportArn(secondArn).maxResults(1));
+ assertNotNull(executionPage.nextToken());
+ executions.deleteForAccount(ACCOUNT, secondArn + "::a");
+ assertEquals("b", client.listExecutions(request -> request.exportArn(secondArn)
+ .nextToken(executionPage.nextToken())).executions().getFirst().executionId());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"4294967297", "1.5", "\"1\"", "{}", "[]"})
+ void malformedLimitShapesAreRejectedBeforeCoercion(String value) {
+ String arn = export(ACCOUNT, "shape");
+ raw("ListExports", "{\"MaxResults\":" + value + "}", 400);
+ raw("ListExecutions", "{\"ExportArn\":\"" + arn + "\",\"MaxResults\":" + value + "}", 400);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"\"%%%%\"", "17", "{}", "[]"})
+ void invalidTokenValuesAreRejected(String value) {
+ String arn = export(ACCOUNT, "token");
+ raw("ListExports", "{\"NextToken\":" + value + "}", 400);
+ raw("ListExecutions", "{\"ExportArn\":\"" + arn + "\",\"NextToken\":" + value + "}", 400);
+ }
+
+ @Test
+ void oversizedTokensAreRejectedEvenWhenTheirDecodedScopeMatches() {
+ String arn = export(ACCOUNT, "long-token");
+ String exportToken = Base64.getUrlEncoder().withoutPadding().encodeToString(
+ ("ListExports:" + ACCOUNT + ":" + "x".repeat(7000)).getBytes(StandardCharsets.UTF_8));
+ String executionToken = Base64.getUrlEncoder().withoutPadding().encodeToString(
+ ("ListExecutions:" + ACCOUNT + ":" + arn + ":" + "x".repeat(7000)).getBytes(StandardCharsets.UTF_8));
+ raw("ListExports", "{\"NextToken\":\"" + exportToken + "\"}", 400);
+ raw("ListExecutions", "{\"ExportArn\":\"" + arn + "\",\"NextToken\":\"" + executionToken + "\"}", 400);
+ }
+
+ @Test
+ void emptyAndFinalPagesOmitNextTokenAndAcceptAnEmptyInputToken() {
+ assertFalse(raw("ListExports", "{\"NextToken\":\"\"}", 200).containsKey("NextToken"));
+ String arn = export(ACCOUNT, "final");
+ assertFalse(raw("ListExports", "{}", 200).containsKey("NextToken"));
+ assertFalse(raw("ListExecutions", "{\"ExportArn\":\"" + arn + "\"}", 200).containsKey("NextToken"));
+ }
+
+ private Map<String, Object> raw(String action, String body, int status) {
+ Map<String, Object> response = given().contentType("application/x-amz-json-1.1")
+ .header("X-Amz-Target", TARGET + action)
+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + ACCOUNT + "/20260101/us-east-1/bcm-data-exports/aws4_request")
+ .body(body).when().post("/").then().statusCode(status).extract().jsonPath().getMap("");
+ if (status == 400) {
+ assertEquals("ValidationException", response.get("__type"));
+ }
+ return response;
+ }
+
+ private String export(String account, String name) {
+ String arn = "arn:aws:bcm-data-exports:us-east-1:" + account + ":export/" + name + "-" + UUID.randomUUID();
+ Export export = new Export();
+ export.setExportArn(arn);
+ export.setName(name);
+ export.setOwnerAccountId(account);
+ export.setExportStatus("HEALTHY");
+ export.setCreatedAt(1_700_000_000_000L);
+ export.setLastUpdatedAt(1_700_000_000_000L);
+ exports.putForAccount(account, arn, export);
+ storedKeys.add(new StoredKey(account, arn, false));
+ return arn;
+ }
+
+ private String execution(String arn, String id) {
+ ExportExecution execution = new ExportExecution();
+ execution.setExportArn(arn);
+ execution.setExecutionId(id);
+ execution.setCreatedAt(1_700_000_000_000L);
+ execution.setExportStatus("DELIVERY_SUCCESS");
+ executions.putForAccount(ACCOUNT, arn + "::" + id, execution);
+ storedKeys.add(new StoredKey(ACCOUNT, arn + "::" + id, true));
+ return id;
+ }
+
+ private BcmDataExportsClient client(String account) {
+ return BcmDataExportsClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
+ .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test"))).build();
+ }
+
+ private record StoredKey(String account, String key, boolean execution) {}
+}