diff --git a/docs/services/glue.md b/docs/services/glue.md index 9b058277ac..4a39e5b675 100644 --- a/docs/services/glue.md +++ b/docs/services/glue.md @@ -31,7 +31,7 @@ descriptor keeps the `AdditionalLocations`, `BucketColumns`, `SortColumns`, `Ske |--------|-------------| | CreateDatabase | Creates a database in the local Glue Data Catalog. | | GetDatabase | Returns a stored Data Catalog database. | -| GetDatabases | Lists databases in the local Glue Data Catalog. | +| GetDatabases | Lists databases in pages using `MaxResults` and `NextToken`. | | DeleteDatabase | Deletes a database from the local Glue Data Catalog. | #### Tables @@ -40,11 +40,11 @@ descriptor keeps the `AdditionalLocations`, `BucketColumns`, `SortColumns`, `Ske |--------|-------------| | CreateTable | Creates a table definition in the local Glue Data Catalog. | | GetTable | Returns a stored table definition and resolves schema references when possible. | -| GetTables | Lists table definitions for a database. | +| GetTables | Lists table definitions for a database in pages using `MaxResults` and `NextToken`. | | UpdateTable | Replaces a table definition; the previous version is archived unless `SkipArchive` is set. | | DeleteTable | Deletes a table definition from a database. | | BatchDeleteTable | Deletes several tables of a database, reporting the missing ones in `Errors`. | -| GetTableVersions | Lists the current and archived versions of a table, newest first. | +| GetTableVersions | Lists the current and archived versions of a table, newest first, in pages using `MaxResults` and `NextToken`. | | GetTableVersion | Returns one version by `VersionId`, or the current version when none is given. | | DeleteTableVersion | Deletes an archived version; the current version cannot be deleted, as on AWS. | | BatchDeleteTableVersion | Deletes several archived versions, reporting the ones not deleted in `Errors`. | @@ -55,7 +55,7 @@ descriptor keeps the `AdditionalLocations`, `BucketColumns`, `SortColumns`, `Ske | Action | Description | |--------|-------------| | CreatePartition | Creates a partition for a Data Catalog table. | -| GetPartitions | Lists partitions stored for a Data Catalog table. With a `Segment`, returns that segment's share of them: each partition is in exactly one of `TotalSegments` (1 to 10) segments; a `Segment` member that is not an integer is a `SerializationException`. AWS documents `SegmentNumber` values from 0 through `TotalSegments` minus 1 and not what a larger one returns, so a `SegmentNumber` of `TotalSegments` or more returning no partitions is Floci's reading. | +| GetPartitions | Lists partitions stored for a Data Catalog table in pages using `MaxResults` and `NextToken`. With a `Segment`, returns that segment's share of them: each partition is in exactly one of `TotalSegments` (1 to 10) segments; a `Segment` member that is not an integer is a `SerializationException`. AWS documents `SegmentNumber` values from 0 through `TotalSegments` minus 1 and not what a larger one returns, so a `SegmentNumber` of `TotalSegments` or more returning no partitions is Floci's reading. | | BatchDeletePartition | Deletes up to 25 partitions, reporting the ones not found in `Errors`. | | CreatePartitionIndex | Registers a partition index on a table. Keys must name partition columns, and a table holds at most 3 indexes. The index reports `CREATING` before `ACTIVE`. | | GetPartitionIndexes | Lists a table's partition indexes, each with its keys resolved to name and type. | @@ -437,3 +437,5 @@ aws glue list-schema-versions \ --schema-id RegistryName=local-registry,SchemaName=orders \ --endpoint-url $AWS_ENDPOINT_URL ``` + +Catalog pagination for GetDatabases, GetTables, GetPartitions and GetTableVersions uses opaque continuation cursors ordered by database name, table name, partition values and descending version number respectively. Removing the last returned item or inserting items before its cursor does not invalidate continuation. Table schema references are resolved for the selected page. diff --git a/src/main/java/io/floci/aws/services/glue/GlueJsonHandler.java b/src/main/java/io/floci/aws/services/glue/GlueJsonHandler.java index d315087af7..f323c7dafa 100644 --- a/src/main/java/io/floci/aws/services/glue/GlueJsonHandler.java +++ b/src/main/java/io/floci/aws/services/glue/GlueJsonHandler.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsJsonTimestamp; import io.floci.aws.core.common.EpochSeconds; +import io.floci.aws.core.common.Pagination; import io.floci.aws.services.glue.model.*; import io.floci.aws.services.glue.schemaregistry.GlueSchemaRegistryService; import io.floci.aws.services.glue.schemaregistry.model.Registry; @@ -90,9 +91,7 @@ public class GlueJsonHandler { Database db = glueService.getDatabase(name); yield Response.ok(Map.of("Database", db)).build(); } - case "GetDatabases" -> { - yield Response.ok(Map.of("DatabaseList", glueService.getDatabases())).build(); - } + case "GetDatabases" -> handleGetDatabases(request); case "DeleteDatabase" -> { String name = request.get("Name").asText(); glueService.deleteDatabase(name, region); @@ -141,9 +140,13 @@ public class GlueJsonHandler { glueService.getPartitionIndexes(dbName, tableName))).build(); } case "GetTables" -> { + Integer maxResults = Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException"); + String nextToken = Pagination.parseNextToken(request, "NextToken", "InvalidInputException"); String dbName = request.get("DatabaseName").asText(); - List tables = glueService.getTables(dbName).stream().map(GlueService::withReadDefaults).toList(); - yield Response.ok(Map.of("TableList", tables)).build(); + GlueService.Page
page = glueService.getTables( + dbName, maxResults, nextToken); + List
tables = page.items().stream().map(GlueService::withReadDefaults).toList(); + yield Response.ok(pageResponse("TableList", tables, page.nextToken())).build(); } case "UpdateTable" -> { String dbName = request.get("DatabaseName").asText(); @@ -153,9 +156,13 @@ public class GlueJsonHandler { yield Response.ok().build(); } case "GetTableVersions" -> { + Integer maxResults = Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException"); + String nextToken = Pagination.parseNextToken(request, "NextToken", "InvalidInputException"); String dbName = request.get("DatabaseName").asText(); String tableName = request.get("TableName").asText(); - yield Response.ok(Map.of("TableVersions", glueService.getTableVersions(dbName, tableName))).build(); + GlueService.Page> page = glueService.getTableVersions( + dbName, tableName, maxResults, nextToken); + yield Response.ok(pageResponse("TableVersions", page.items(), page.nextToken())).build(); } case "GetTableVersion" -> { String dbName = request.get("DatabaseName").asText(); @@ -203,13 +210,16 @@ public class GlueJsonHandler { case "GetPartition" -> handleGetPartition(request); case "BatchGetPartition" -> handleBatchGetPartition(request); case "GetPartitions" -> { + Integer maxResults = Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException"); + String nextToken = Pagination.parseNextToken(request, "NextToken", "InvalidInputException"); String dbName = request.get("DatabaseName").asText(); String tableName = request.get("TableName").asText(); String expression = request.path("Expression").asText(null); GlueService.Segment segment = request.hasNonNull("Segment") ? segment(request.get("Segment")) : null; - List partitions = glueService.getPartitions(dbName, tableName, expression, segment).stream() - .map(GlueService::withReadDefaults).toList(); - yield Response.ok(Map.of("Partitions", partitions)).build(); + GlueService.Page page = glueService.getPartitions(dbName, tableName, expression, segment, + maxResults, nextToken); + List partitions = page.items().stream().map(GlueService::withReadDefaults).toList(); + yield Response.ok(pageResponse("Partitions", partitions, page.nextToken())).build(); } case "DeletePartition" -> handleDeletePartition(request); case "BatchDeletePartition" -> handleBatchDeletePartition(request); @@ -1102,6 +1112,13 @@ public class GlueJsonHandler { return vn.asLong(); } + private Response handleGetDatabases(JsonNode request) { + GlueService.Page page = glueService.getDatabases( + Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException"), + Pagination.parseNextToken(request, "NextToken", "InvalidInputException")); + return Response.ok(pageResponse("DatabaseList", page.items(), page.nextToken())).build(); + } + private Integer readMaxResults(JsonNode request) { JsonNode node = request.get("MaxResults"); if (node == null || node.isNull()) { diff --git a/src/main/java/io/floci/aws/services/glue/GlueService.java b/src/main/java/io/floci/aws/services/glue/GlueService.java index 4f0d95664d..4fdd1680fd 100644 --- a/src/main/java/io/floci/aws/services/glue/GlueService.java +++ b/src/main/java/io/floci/aws/services/glue/GlueService.java @@ -10,6 +10,8 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.Base64Url; import io.floci.aws.core.common.Digests; import io.floci.aws.core.common.EpochSeconds; +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.StorageBackend; @@ -62,6 +64,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Base64; import java.util.Comparator; +import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; @@ -69,6 +72,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -388,6 +392,12 @@ public class GlueService { return databases; } + public Page getDatabases(Integer maxResults, String nextToken) { + return paginate(() -> getDatabases().stream() + .sorted(Comparator.comparing(Database::getName)).toList(), maxResults, nextToken, 100, + Database::getName, "glue-databases"); + } + /** * Heals a database persisted before CatalogId was modelled. The store is namespaced by * account, so the reader is always the owning account and the healed value is stable — @@ -466,6 +476,13 @@ public class GlueService { return resolved; } + public Page
getTables(String databaseName, Integer maxResults, String nextToken) { + String prefix = normalizeName(databaseName) + ":"; + Page
page = paginate(() -> tableStore.scan(key -> key.startsWith(prefix)), + maxResults, nextToken, 100, Table::getName, "glue-tables:" + prefix); + return new Page<>(page.items().stream().map(this::withResolvedSchemaReference).toList(), page.nextToken()); + } + /** * SearchTables over every table of the catalog. SearchText matches a substring of the name, * database, description, owner, column names and comments and parameter values, or the whole @@ -698,6 +715,13 @@ public class GlueService { .toList(); } + public Page> getTableVersions(String databaseName, String tableName, + Integer maxResults, String nextToken) { + return paginate(() -> getTableVersions(databaseName, tableName), maxResults, nextToken, 100, + version -> String.format("%019d", Long.MAX_VALUE - versionIdAsLong((Table) version.get("Table"))), + "glue-versions:" + tableKey(databaseName, tableName)); + } + /** One archived version, or the current table when no VersionId is given, as AWS answers. */ public Map getTableVersion(String databaseName, String tableName, String versionId) { Table current = getTable(databaseName, tableName); @@ -953,6 +977,29 @@ public class GlueService { .toList(); } + public Page getPartitions(String databaseName, String tableName, String expression, + Segment segment, Integer maxResults, String nextToken) { + return paginate(() -> getPartitions(databaseName, tableName, expression, segment), + maxResults, nextToken, 1000, GlueService::partitionCursor, + "glue-partitions:" + tableKey(databaseName, tableName)); + } + + /** Fixed-width UTF-16 digits and terminators preserve the null-first tuple ordering. */ + private static String partitionCursor(Partition partition) { + StringBuilder cursor = new StringBuilder(); + List values = partition.getValues() == null ? List.of() : partition.getValues(); + for (String value : values) { + cursor.append(value == null ? '0' : '1'); + if (value != null) { + for (int index = 0; index < value.length(); index++) { + cursor.append(HexFormat.of().toHexDigits(value.charAt(index))); + } + } + cursor.append('/'); + } + return cursor.toString(); + } + private static void validateSegment(Segment segment) { if (segment == null) { return; @@ -3430,12 +3477,18 @@ public class GlueService { return paginate(() -> all, maxResults, nextToken, 1000); } + private Page paginate(Supplier> items, Integer maxResults, String nextToken, int maximum, + Function cursorOf, String namespace) { + int limit = pageLimit(maxResults, maximum); + PaginatedResult page = Pagination.paginate(items.get(), cursorOf, + limit, nextToken, namespace, + token -> new AwsException("InvalidInputException", "Invalid NextToken", 400)); + return new Page<>(page.items(), page.nextToken()); + } + private Page paginate(Supplier> items, Integer maxResults, String nextToken, int maximum) { - if (maxResults != null && (maxResults < 1 || maxResults > maximum)) { - throw new AwsException("InvalidInputException", "MaxResults must be between 1 and " + maximum, 400); - } + int limit = pageLimit(maxResults, maximum); List all = items.get(); - int limit = maxResults == null ? 100 : maxResults; int start = 0; if (nextToken != null && !nextToken.isBlank()) { try { @@ -3451,4 +3504,11 @@ public class GlueService { String newToken = end < all.size() ? String.valueOf(end) : null; return new Page<>(List.copyOf(all.subList(start, end)), newToken); } + + private static int pageLimit(Integer maxResults, int maximum) { + if (maxResults != null && (maxResults < 1 || maxResults > maximum)) { + throw new AwsException("InvalidInputException", "MaxResults must be between 1 and " + maximum, 400); + } + return maxResults == null ? 100 : maxResults; + } } diff --git a/src/test/java/io/floci/aws/services/glue/GlueCatalogPaginationTestSupport.java b/src/test/java/io/floci/aws/services/glue/GlueCatalogPaginationTestSupport.java new file mode 100644 index 0000000000..8e1f1c5fee --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/GlueCatalogPaginationTestSupport.java @@ -0,0 +1,29 @@ +package io.floci.aws.services.glue; + +import io.floci.aws.testing.AwsTestClients; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.glue.GlueClient; + +import java.util.UUID; +import java.util.function.BiConsumer; + +final class GlueCatalogPaginationTestSupport { + + private GlueCatalogPaginationTestSupport() { + } + + static void withCatalog(String account, String prefix, BiConsumer action) { + String database = prefix + UUID.randomUUID().toString().replace("-", ""); + try (GlueClient client = AwsTestClients.create(GlueClient.builder(), account, Region.US_EAST_1)) { + client.createDatabase(request -> request.databaseInput(input -> input.name(database))); + try { + action.accept(client, database); + } finally { + client.getTablesPaginator(request -> request.databaseName(database)).stream() + .flatMap(page -> page.tableList().stream()).forEach(table -> client.deleteTable(request -> request + .databaseName(database).name(table.name()))); + client.deleteDatabase(request -> request.name(database)); + } + } + } +} diff --git a/src/test/java/io/floci/aws/services/glue/GlueCatalogPaginationValidationIntegrationTest.java b/src/test/java/io/floci/aws/services/glue/GlueCatalogPaginationValidationIntegrationTest.java new file mode 100644 index 0000000000..6de0944db4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/GlueCatalogPaginationValidationIntegrationTest.java @@ -0,0 +1,69 @@ +package io.floci.aws.services.glue; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import software.amazon.awssdk.services.glue.GlueClient; +import software.amazon.awssdk.services.glue.model.InvalidInputException; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@QuarkusTest +class GlueCatalogPaginationValidationIntegrationTest { + + enum Operation { + DATABASES(100), TABLES(100), VERSIONS(100), PARTITIONS(1000); + + final int maximum; + + Operation(int maximum) { + this.maximum = maximum; + } + + void call(GlueClient client, String database, Integer size, String token) { + switch (this) { + case DATABASES -> client.getDatabases(request -> request.maxResults(size).nextToken(token)); + case TABLES -> client.getTables(request -> request.databaseName(database).maxResults(size).nextToken(token)); + case VERSIONS -> client.getTableVersions(request -> request.databaseName(database).tableName("example") + .maxResults(size).nextToken(token)); + case PARTITIONS -> client.getPartitions(request -> request.databaseName(database).tableName("example") + .maxResults(size).nextToken(token)); + } + } + } + + static Stream invalidSizes() { + return Stream.of(Operation.values()).flatMap(operation -> Stream.of(-1, 0, operation.maximum + 1) + .map(size -> Arguments.of(operation, size))); + } + + static Stream invalidTokens() { + return Stream.of(Operation.values()).flatMap(operation -> Stream.of("not-a-token", "-1", "2147483647") + .map(token -> Arguments.of(operation, token))); + } + + @ParameterizedTest + @MethodSource("invalidSizes") + void rejectsSizesOutsideEachOperationsRange(Operation operation, int size) { + assertInvalid(operation, size, null); + } + + @ParameterizedTest + @MethodSource("invalidTokens") + void rejectsMalformedTokensForEachOperation(Operation operation, String token) { + assertInvalid(operation, null, token); + } + + private static void assertInvalid(Operation operation, Integer size, String token) { + GlueCatalogPaginationTestSupport.withCatalog("741648700614", "validation_", (client, database) -> { + client.createTable(request -> request.databaseName(database).tableInput(input -> input.name("example"))); + InvalidInputException failure = assertThrows(InvalidInputException.class, + () -> operation.call(client, database, size, token)); + assertEquals(400, failure.statusCode()); + }); + } +} diff --git a/src/test/java/io/floci/aws/services/glue/GlueDatabasesPaginationIntegrationTest.java b/src/test/java/io/floci/aws/services/glue/GlueDatabasesPaginationIntegrationTest.java new file mode 100644 index 0000000000..42994538c2 --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/GlueDatabasesPaginationIntegrationTest.java @@ -0,0 +1,69 @@ +package io.floci.aws.services.glue; + +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.glue.GlueClient; +import software.amazon.awssdk.services.glue.model.Database; +import software.amazon.awssdk.services.glue.model.GetDatabasesResponse; + +import java.util.List; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class GlueDatabasesPaginationIntegrationTest { + + @Test + void sdkPagesDatabasesWithoutLosingFieldsOrCrossingAccounts() { + String prefix = "page-" + UUID.randomUUID(); + List names = List.of(prefix + "-a", prefix + "-b", prefix + "-c"); + try (GlueClient client = AwsTestClients.create(GlueClient.builder(), "741648700611", Region.US_EAST_1); + GlueClient foreignAccount = AwsTestClients.create(GlueClient.builder(), "741648700612", Region.US_EAST_1)) { + for (String name : names.reversed()) { + client.createDatabase(request -> request.databaseInput(builder -> builder + .name(name).description("details-" + name))); + } + foreignAccount.createDatabase(request -> request.databaseInput(builder -> builder.name(prefix + "-0"))); + try { + assertEquals(names, client.getDatabases(request -> {}).databaseList().stream() + .map(Database::name).sorted().toList()); + GetDatabasesResponse first = client.getDatabases(request -> request.maxResults(1)); + assertEquals(List.of(names.get(0)), first.databaseList().stream() + .map(Database::name).toList()); + assertNotNull(first.nextToken()); + assertEquals("details-" + names.getFirst(), first.databaseList().getFirst().description()); + assertEquals("741648700611", first.databaseList().getFirst().catalogId()); + GetDatabasesResponse second = client.getDatabases(request -> request + .maxResults(1).nextToken(first.nextToken())); + assertEquals(List.of(names.get(1)), second.databaseList().stream() + .map(Database::name).toList()); + assertNotNull(second.nextToken()); + GetDatabasesResponse last = client.getDatabases(request -> request + .maxResults(1).nextToken(second.nextToken())); + assertEquals(List.of(names.get(2)), last.databaseList().stream() + .map(Database::name).toList()); + assertNull(last.nextToken()); + assertEquals(names, client.getDatabasesPaginator(request -> request.maxResults(2)) + .stream().flatMap(page -> page.databaseList().stream()).map(Database::name).toList()); + } finally { + names.forEach(name -> client.deleteDatabase(request -> request.name(name))); + foreignAccount.deleteDatabase(request -> request.name(prefix + "-0")); + } + } + } + + @Test + void sdkReadsAnEmptyPageAtTheMaximumPageSizeWithoutAToken() { + try (GlueClient client = AwsTestClients.create(GlueClient.builder(), "741648700613", Region.US_EAST_1)) { + GetDatabasesResponse response = client.getDatabases(request -> request.maxResults(100)); + assertTrue(response.databaseList().isEmpty()); + assertNull(response.nextToken()); + } + } +} diff --git a/src/test/java/io/floci/aws/services/glue/GlueJsonHandlerTest.java b/src/test/java/io/floci/aws/services/glue/GlueJsonHandlerTest.java index 9ba4ebe4c0..9b6010633c 100644 --- a/src/test/java/io/floci/aws/services/glue/GlueJsonHandlerTest.java +++ b/src/test/java/io/floci/aws/services/glue/GlueJsonHandlerTest.java @@ -58,6 +58,79 @@ class GlueJsonHandlerTest { schemaRegistryService, mapper); } + @Test + void databasesPageAcrossResultsAndPreserveMetadata() throws Exception { + for (String name : List.of("third", "first", "second")) { + ObjectNode create = mapper.createObjectNode(); + create.putObject("DatabaseInput").put("Name", name).put("Description", "description-" + name); + handler.handle("CreateDatabase", create, REGION); + } + JsonNode first = mapper.valueToTree(body(handler.handle("GetDatabases", + mapper.createObjectNode().put("MaxResults", 2), REGION))); + assertEquals(2, first.get("DatabaseList").size()); + assertEquals("first", first.get("DatabaseList").get(0).get("Name").asText()); + assertEquals("description-first", first.get("DatabaseList").get(0).get("Description").asText()); + assertEquals(ACCOUNT_ID, first.get("DatabaseList").get(0).get("CatalogId").asText()); + JsonNode last = mapper.valueToTree(body(handler.handle("GetDatabases", + mapper.createObjectNode().put("MaxResults", 2) + .put("NextToken", first.get("NextToken").asText()), REGION))); + assertEquals(1, last.get("DatabaseList").size()); + assertEquals("third", last.get("DatabaseList").get(0).get("Name").asText()); + assertFalse(last.has("NextToken")); + } + + @Test + void databasesUseHundredRowDefault() throws Exception { + for (int index = 0; index < 101; index++) { + ObjectNode create = mapper.createObjectNode(); + create.putObject("DatabaseInput").put("Name", "database-%03d".formatted(index)); + handler.handle("CreateDatabase", create, REGION); + } + JsonNode first = mapper.valueToTree(body(handler.handle("GetDatabases", mapper.createObjectNode(), REGION))); + assertEquals(100, first.get("DatabaseList").size()); + JsonNode last = mapper.valueToTree(body(handler.handle("GetDatabases", + mapper.createObjectNode().put("NextToken", first.get("NextToken").asText()), REGION))); + assertEquals(1, last.get("DatabaseList").size()); + assertFalse(last.has("NextToken")); + } + + @Test + void databasesRejectInvalidPageSizesAndTokens() { + for (int limit : List.of(-1, 0, 101)) { + AwsException error = assertThrows(AwsException.class, () -> handler.handle("GetDatabases", + mapper.createObjectNode().put("MaxResults", limit), REGION)); + assertEquals("InvalidInputException", error.getErrorCode()); + } + for (String token : List.of("invalid", "-1", "1")) { + AwsException error = assertThrows(AwsException.class, () -> handler.handle("GetDatabases", + mapper.createObjectNode().put("NextToken", token), REGION)); + assertEquals("InvalidInputException", error.getErrorCode()); + } + } + + @Test + void catalogListsRejectNonIntegerPageSizesAndNonStringTokens() { + for (String action : List.of("GetDatabases", "GetTables", "GetPartitions", "GetTableVersions")) { + for (JsonNode value : List.of(mapper.getNodeFactory().textNode("1"), + mapper.getNodeFactory().numberNode(1.5), mapper.getNodeFactory().numberNode(Long.MAX_VALUE))) { + ObjectNode request = mapper.createObjectNode().put("DatabaseName", "catalog-db").put("TableName", "catalog-table"); + request.set("MaxResults", value); + assertEquals("InvalidInputException", assertThrows(AwsException.class, + () -> handler.handle(action, request, REGION)).getErrorCode()); + } + assertEquals("InvalidInputException", assertThrows(AwsException.class, () -> handler.handle(action, + mapper.createObjectNode().put("DatabaseName", "catalog-db").put("TableName", "catalog-table").put("NextToken", 0), REGION)).getErrorCode()); + } + } + + @Test + void databasesReturnEmptyTerminalPage() throws Exception { + JsonNode empty = mapper.valueToTree(body(handler.handle("GetDatabases", + mapper.createObjectNode().put("MaxResults", 100), REGION))); + assertEquals(0, empty.get("DatabaseList").size()); + assertFalse(empty.has("NextToken")); + } + private void createDatabaseAndTable(String dbName, String tableName) throws Exception { ObjectNode createDb = mapper.createObjectNode(); createDb.putObject("DatabaseInput").put("Name", dbName); diff --git a/src/test/java/io/floci/aws/services/glue/GluePartitionsPaginationIntegrationTest.java b/src/test/java/io/floci/aws/services/glue/GluePartitionsPaginationIntegrationTest.java new file mode 100644 index 0000000000..116aea5b72 --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/GluePartitionsPaginationIntegrationTest.java @@ -0,0 +1,89 @@ +package io.floci.aws.services.glue; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.glue.GlueClient; +import software.amazon.awssdk.services.glue.model.GetPartitionsResponse; +import software.amazon.awssdk.services.glue.model.Partition; + +import java.util.List; +import java.util.function.BiConsumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +@QuarkusTest +class GluePartitionsPaginationIntegrationTest { + + @Test + void sdkTraversesAllSelectedPartitionsWithoutDuplicates() { + withPartitions((client, database) -> { + List> all = client.getPartitions(request -> request.databaseName(database).tableName("example")) + .partitions().stream().map(Partition::values).toList(); + assertEquals(3, all.size()); + GetPartitionsResponse first = client.getPartitions(request -> request + .databaseName(database).tableName("example").maxResults(1)); + assertEquals(all.subList(0, 1), first.partitions().stream().map(Partition::values).toList()); + assertNotNull(first.nextToken()); + GetPartitionsResponse second = client.getPartitions(request -> request + .databaseName(database).tableName("example").maxResults(1).nextToken(first.nextToken())); + assertEquals(all.subList(1, 2), second.partitions().stream().map(Partition::values).toList()); + assertNotNull(second.nextToken()); + GetPartitionsResponse last = client.getPartitions(request -> request + .databaseName(database).tableName("example").maxResults(1).nextToken(second.nextToken())); + assertEquals(all.subList(2, 3), last.partitions().stream().map(Partition::values).toList()); + assertNull(last.nextToken()); + assertEquals(all, client.getPartitionsPaginator(request -> request + .databaseName(database).tableName("example").maxResults(2)).stream().flatMap(page -> page.partitions().stream()) + .map(Partition::values).toList()); + GetPartitionsResponse maximum = client.getPartitions(request -> request + .databaseName(database).tableName("example").maxResults(1000)); + assertEquals(all, maximum.partitions().stream().map(Partition::values).toList()); + assertNull(maximum.nextToken()); + }); + } + + @Test + void expressionSelectionPrecedesPaging() { + withPartitions((client, database) -> { + GetPartitionsResponse response = client.getPartitions(request -> request.databaseName(database) + .tableName("example").expression("day = 'second'").maxResults(1)); + assertEquals(List.of(List.of("second")), response.partitions().stream().map(Partition::values).toList()); + assertNull(response.nextToken()); + }); + } + + @Test + void segmentSelectionPrecedesPaging() { + withPartitions((client, database) -> { + List> all = client.getPartitions(request -> request.databaseName(database) + .tableName("example").segment(segment -> segment.segmentNumber(1).totalSegments(2))) + .partitions().stream().map(Partition::values).toList(); + assertEquals(2, all.size()); + GetPartitionsResponse first = client.getPartitions(request -> request.databaseName(database) + .tableName("example").segment(segment -> segment.segmentNumber(1).totalSegments(2)).maxResults(1)); + assertEquals(all.subList(0, 1), first.partitions().stream().map(Partition::values).toList()); + assertNotNull(first.nextToken()); + GetPartitionsResponse last = client.getPartitions(request -> request.databaseName(database) + .tableName("example").segment(segment -> segment.segmentNumber(1).totalSegments(2)) + .maxResults(1).nextToken(first.nextToken())); + assertEquals(all.subList(1, 2), last.partitions().stream().map(Partition::values).toList()); + assertNull(last.nextToken()); + }); + } + + private static void withPartitions(BiConsumer action) { + GlueCatalogPaginationTestSupport.withCatalog("741648700007", "partitions_", (client, database) -> { + client.createTable(request -> request.databaseName(database).tableInput(input -> input.name("example") + .partitionKeys(key -> key.name("day").type("string")) + .storageDescriptor(sd -> sd.columns(column -> column.name("id").type("string"))))); + for (String value : List.of("first", "second", "third")) { + client.createPartition(request -> request.databaseName(database).tableName("example") + .partitionInput(input -> input.values(value) + .storageDescriptor(sd -> sd.columns(column -> column.name("id").type("string"))))); + } + action.accept(client, database); + }); + } +} diff --git a/src/test/java/io/floci/aws/services/glue/GlueServiceTest.java b/src/test/java/io/floci/aws/services/glue/GlueServiceTest.java index c28eb28850..f6b099c4bf 100644 --- a/src/test/java/io/floci/aws/services/glue/GlueServiceTest.java +++ b/src/test/java/io/floci/aws/services/glue/GlueServiceTest.java @@ -62,6 +62,12 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; class GlueServiceTest { @@ -90,7 +96,7 @@ class GlueServiceTest { void setUp() { RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT_ID); StorageFactory storageFactory = new InMemoryStorageFactory(); - schemaRegistryService = new GlueSchemaRegistryService(storageFactory, regionResolver); + schemaRegistryService = spy(new GlueSchemaRegistryService(storageFactory, regionResolver)); kmsService = new KmsService(storageFactory, regionResolver); databaseStore = new InMemoryStorage<>(); tableStore = new InMemoryStorage<>(); @@ -225,6 +231,99 @@ class GlueServiceTest { assertEquals("Database cannot be renamed", exception.getMessage()); } + private static Table paginationTable(String name) { + Table table = new Table(); + table.setName(name); + return table; + } + + @Test + void catalogDatabaseCursorSurvivesDeletionAndShrinking() { + glueService.createDatabase(new Database("db2")); + glueService.createDatabase(new Database("db3")); + GlueService.Page first = glueService.getDatabases(2, null); + glueService.deleteDatabase("db1"); + glueService.deleteDatabase("db2"); + GlueService.Page last = glueService.getDatabases(2, first.nextToken()); + assertEquals(List.of("db3"), last.items().stream().map(Database::getName).toList()); + assertNull(last.nextToken()); + glueService.deleteDatabase("db3"); + assertTrue(glueService.getDatabases(2, first.nextToken()).items().isEmpty()); + } + + @Test + void tableCursorIgnoresInsertionsBeforeAndDeletionOfItsItem() { + for (String name : List.of("alpha", "charlie", "echo")) { + glueService.createTable("db1", paginationTable(name)); + } + GlueService.Page
first = glueService.getTables("db1", 2, null); + assertEquals(List.of("alpha", "charlie"), first.items().stream().map(Table::getName).toList()); + glueService.deleteTable("db1", "charlie"); + glueService.createTable("db1", paginationTable("bravo")); + glueService.createTable("db1", paginationTable("delta")); + GlueService.Page
last = glueService.getTables("db1", 2, first.nextToken()); + assertEquals(List.of("delta", "echo"), last.items().stream().map(Table::getName).toList()); + assertNull(last.nextToken()); + } + + @Test + void tableVersionCursorPreservesDescendingOrderAfterAnUpdate() { + glueService.createTable("db1", paginationTable("versioned")); + glueService.updateTable("db1", paginationTable("versioned"), null, false); + glueService.updateTable("db1", paginationTable("versioned"), null, false); + GlueService.Page> first = glueService.getTableVersions("db1", "versioned", 1, null); + assertEquals("2", first.items().getFirst().get("VersionId")); + glueService.updateTable("db1", paginationTable("versioned"), null, false); + GlueService.Page> second = glueService.getTableVersions("db1", "versioned", 1, + first.nextToken()); + assertEquals("1", second.items().getFirst().get("VersionId")); + } + + @Test + void partitionCursorPreservesTupleOrderAfterItsPrefixShrinks() { + Table table = paginationTable("partitioned"); + table.setPartitionKeys(List.of(new Column("group", "string"), new Column("value", "string"))); + glueService.createTable("db1", table); + for (List values : List.of(List.of("a", "first"), List.of("a", "second"), + List.of("a0", "x"), List.of("aa", "y"), List.of("é", "z"))) { + Partition partition = new Partition(); + partition.setValues(values); + glueService.createPartition("db1", "partitioned", partition); + } + GlueService.Page first = glueService.getPartitions("db1", "partitioned", null, null, 2, null); + assertEquals(List.of(List.of("a", "first"), List.of("a", "second")), + first.items().stream().map(Partition::getValues).toList()); + glueService.deletePartition("db1", "partitioned", List.of("a", "first")); + glueService.deletePartition("db1", "partitioned", List.of("a", "second")); + for (String value : List.of("middle", "third")) { + Partition partition = new Partition(); + partition.setValues(List.of("a", value)); + glueService.createPartition("db1", "partitioned", partition); + } + GlueService.Page last = glueService.getPartitions("db1", "partitioned", null, null, 100, + first.nextToken()); + assertEquals(List.of(List.of("a", "third"), List.of("a0", "x"), List.of("aa", "y"), List.of("é", "z")), + last.items().stream().map(Partition::getValues).toList()); + assertNull(last.nextToken()); + } + + @Test + void tablePagingResolvesOnlyTheReturnedSchemas() { + schemaRegistryService.createRegistry("r1", null, null, REGION); + schemaRegistryService.createSchema(new RegistryId("r1", null), + "users", "AVRO", "BACKWARD", null, AVRO_V1, null, REGION); + for (String name : List.of("alpha", "bravo", "charlie")) { + Table table = tableReferencing("r1", "users", null, null); + table.setName(name); + glueService.createTable("db1", table); + } + clearInvocations(schemaRegistryService); + GlueService.Page
first = glueService.getTables("db1", 1, null); + assertEquals("alpha", first.items().getFirst().getName()); + assertEquals("id", first.items().getFirst().getStorageDescriptor().getColumns().getFirst().getName()); + verify(schemaRegistryService, times(1)).getSchemaVersion(any(), any(), any(), anyBoolean(), any()); + } + @Test void getTableWithValidSchemaReferenceReturnsDerivedColumns() { schemaRegistryService.createRegistry("r1", null, null, REGION); diff --git a/src/test/java/io/floci/aws/services/glue/GlueTableVersionsPaginationIntegrationTest.java b/src/test/java/io/floci/aws/services/glue/GlueTableVersionsPaginationIntegrationTest.java new file mode 100644 index 0000000000..ebd446df1f --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/GlueTableVersionsPaginationIntegrationTest.java @@ -0,0 +1,58 @@ +package io.floci.aws.services.glue; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.glue.GlueClient; +import software.amazon.awssdk.services.glue.model.GetTableVersionsResponse; +import software.amazon.awssdk.services.glue.model.TableVersion; + +import java.util.List; +import java.util.function.BiConsumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +@QuarkusTest +class GlueTableVersionsPaginationIntegrationTest { + + @Test + void sdkTraversesCurrentAndArchivedVersionsWithoutDuplicates() { + withVersions((client, database) -> { + List all = client.getTableVersions(request -> request.databaseName(database).tableName("example")) + .tableVersions().stream().map(TableVersion::versionId).toList(); + assertEquals(3, all.size()); + GetTableVersionsResponse first = client.getTableVersions(request -> request + .databaseName(database).tableName("example").maxResults(1)); + assertEquals(all.subList(0, 1), first.tableVersions().stream().map(TableVersion::versionId).toList()); + assertNotNull(first.nextToken()); + GetTableVersionsResponse second = client.getTableVersions(request -> request + .databaseName(database).tableName("example").maxResults(1).nextToken(first.nextToken())); + assertEquals(all.subList(1, 2), second.tableVersions().stream().map(TableVersion::versionId).toList()); + assertNotNull(second.nextToken()); + GetTableVersionsResponse last = client.getTableVersions(request -> request + .databaseName(database).tableName("example").maxResults(1).nextToken(second.nextToken())); + assertEquals(all.subList(2, 3), last.tableVersions().stream().map(TableVersion::versionId).toList()); + assertNull(last.nextToken()); + assertEquals(all, client.getTableVersionsPaginator(request -> request + .databaseName(database).tableName("example").maxResults(2)).stream().flatMap(page -> page.tableVersions().stream()) + .map(TableVersion::versionId).toList()); + GetTableVersionsResponse maximum = client.getTableVersions(request -> request + .databaseName(database).tableName("example").maxResults(100)); + assertEquals(all, maximum.tableVersions().stream().map(TableVersion::versionId).toList()); + assertNull(maximum.nextToken()); + }); + } + + private static void withVersions(BiConsumer action) { + GlueCatalogPaginationTestSupport.withCatalog("741648700005", "versions_", (client, database) -> { + client.createTable(request -> request.databaseName(database) + .tableInput(input -> input.name("example").description("first"))); + client.updateTable(request -> request.databaseName(database) + .tableInput(input -> input.name("example").description("second"))); + client.updateTable(request -> request.databaseName(database) + .tableInput(input -> input.name("example").description("third"))); + action.accept(client, database); + }); + } +} diff --git a/src/test/java/io/floci/aws/services/glue/GlueTablesPaginationIntegrationTest.java b/src/test/java/io/floci/aws/services/glue/GlueTablesPaginationIntegrationTest.java new file mode 100644 index 0000000000..551844c346 --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/GlueTablesPaginationIntegrationTest.java @@ -0,0 +1,56 @@ +package io.floci.aws.services.glue; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.glue.GlueClient; +import software.amazon.awssdk.services.glue.model.GetTablesResponse; +import software.amazon.awssdk.services.glue.model.Table; + +import java.util.List; +import java.util.function.BiConsumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +@QuarkusTest +class GlueTablesPaginationIntegrationTest { + + @Test + void sdkTraversesAllTablesWithoutDuplicates() { + withTables((client, database) -> { + List all = client.getTables(request -> request.databaseName(database)) + .tableList().stream().map(Table::name).toList(); + assertEquals(3, all.size()); + GetTablesResponse first = client.getTables(request -> request + .databaseName(database).maxResults(1)); + assertEquals(all.subList(0, 1), first.tableList().stream().map(Table::name).toList()); + assertNotNull(first.nextToken()); + GetTablesResponse second = client.getTables(request -> request + .databaseName(database).maxResults(1).nextToken(first.nextToken())); + assertEquals(all.subList(1, 2), second.tableList().stream().map(Table::name).toList()); + assertNotNull(second.nextToken()); + GetTablesResponse last = client.getTables(request -> request + .databaseName(database).maxResults(1).nextToken(second.nextToken())); + assertEquals(all.subList(2, 3), last.tableList().stream().map(Table::name).toList()); + assertNull(last.nextToken()); + assertEquals(all, client.getTablesPaginator(request -> request + .databaseName(database).maxResults(2)).stream().flatMap(page -> page.tableList().stream()) + .map(Table::name).toList()); + GetTablesResponse maximum = client.getTables(request -> request + .databaseName(database).maxResults(100)); + assertEquals(all, maximum.tableList().stream().map(Table::name).toList()); + assertNull(maximum.nextToken()); + }); + } + + private static void withTables(BiConsumer action) { + GlueCatalogPaginationTestSupport.withCatalog("741648700006", "tables_", (client, database) -> { + for (String name : List.of("first", "second", "third")) { + client.createTable(request -> request.databaseName(database) + .tableInput(input -> input.name(name))); + } + action.accept(client, database); + }); + } +}