diff --git a/compatibility-tests/sdk-test-awscli/test/glue-data-quality.bats b/compatibility-tests/sdk-test-awscli/test/glue-data-quality.bats new file mode 100644 index 0000000000..491518a89b --- /dev/null +++ b/compatibility-tests/sdk-test-awscli/test/glue-data-quality.bats @@ -0,0 +1,51 @@ +#!/usr/bin/env bats + +setup() { + load 'test_helper/common-setup' + RULESET_NAME="$(unique_name glue-dq-ruleset)" +} + +teardown() { + aws_cmd glue delete-data-quality-ruleset --name "$RULESET_NAME" >/dev/null 2>&1 || true +} + +@test "Glue data quality: ruleset lifecycle" { + run aws_cmd glue create-data-quality-ruleset \ + --name "$RULESET_NAME" \ + --description "orders checks" \ + --ruleset 'Rules = [ RowCount > 0, IsComplete "id" ]' \ + --target-table TableName=orders,DatabaseName=sales \ + --tags team=data + assert_success + [ "$(json_get "$output" '.Name')" = "$RULESET_NAME" ] + + run aws_cmd glue create-data-quality-ruleset \ + --name "$RULESET_NAME" \ + --ruleset 'Rules = [ RowCount > 0 ]' + assert_failure + [[ "$output" == *"AlreadyExistsException"* ]] + + run aws_cmd glue get-data-quality-ruleset --name "$RULESET_NAME" + assert_success + [ "$(json_get "$output" '.TargetTable.DatabaseName')" = "sales" ] + [ "$(json_get "$output" '.Ruleset')" = 'Rules = [ RowCount > 0, IsComplete "id" ]' ] + + run aws_cmd glue update-data-quality-ruleset \ + --name "$RULESET_NAME" \ + --description "orders, nightly" + assert_success + [ "$(json_get "$output" '.Description')" = "orders, nightly" ] + + run aws_cmd glue list-data-quality-rulesets --tags team=data \ + --filter 'TargetTable={TableName=orders,DatabaseName=sales}' + assert_success + count=$(echo "$output" | jq -r --arg n "$RULESET_NAME" '.Rulesets[] | select(.Name == $n) | .RuleCount') + [ "$count" = "2" ] + + run aws_cmd glue delete-data-quality-ruleset --name "$RULESET_NAME" + assert_success + + run aws_cmd glue get-data-quality-ruleset --name "$RULESET_NAME" + assert_failure + [[ "$output" == *"EntityNotFoundException"* ]] +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/GlueDataQualityRulesetTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/GlueDataQualityRulesetTest.java new file mode 100644 index 0000000000..b94830ca68 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/GlueDataQualityRulesetTest.java @@ -0,0 +1,81 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.glue.GlueClient; +import software.amazon.awssdk.services.glue.model.AlreadyExistsException; +import software.amazon.awssdk.services.glue.model.DataQualityRulesetListDetails; +import software.amazon.awssdk.services.glue.model.EntityNotFoundException; +import software.amazon.awssdk.services.glue.model.GetDataQualityRulesetResponse; +import software.amazon.awssdk.services.glue.model.UpdateDataQualityRulesetResponse; + +import java.time.Instant; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("Glue data quality rulesets") +class GlueDataQualityRulesetTest { + + private static final String NAME = TestFixtures.uniqueName("dq_ruleset"); + private static final String RULESET = "Rules = [ RowCount > 0, IsComplete \"id\" ]"; + + private static GlueClient glue; + + @BeforeAll + static void setup() { + glue = TestFixtures.glueClient(); + } + + @AfterAll + static void cleanup() { + if (glue == null) { + return; + } + try { + glue.deleteDataQualityRuleset(r -> r.name(NAME)); + } + catch (Exception ignored) { + // Cleanup is best effort: the name is unique to this run and the emulator is disposable. + } + } + + @Test + void sdkRoundTripsADataQualityRuleset() { + Instant before = Instant.now().minusSeconds(60); + assertThat(glue.createDataQualityRuleset(r -> r.name(NAME).description("orders checks").ruleset(RULESET) + .targetTable(t -> t.tableName("orders").databaseName("sales")) + .tags(Map.of("team", "data"))).name()).isEqualTo(NAME); + assertThatThrownBy(() -> glue.createDataQualityRuleset(r -> r.name(NAME).ruleset(RULESET))) + .isInstanceOf(AlreadyExistsException.class); + + GetDataQualityRulesetResponse got = glue.getDataQualityRuleset(r -> r.name(NAME)); + assertThat(got.ruleset()).isEqualTo(RULESET); + assertThat(got.targetTable().databaseName()).isEqualTo("sales"); + assertThat(got.createdOn()).isAfter(before); + assertThat(got.lastModifiedOn()).isEqualTo(got.createdOn()); + + UpdateDataQualityRulesetResponse updated = glue.updateDataQualityRuleset(r -> r.name(NAME) + .description("orders, nightly")); + assertThat(updated.ruleset()).isEqualTo(RULESET); + assertThat(updated.description()).isEqualTo("orders, nightly"); + + List listed = glue.listDataQualityRulesets(r -> r + .filter(f -> f.targetTable(t -> t.tableName("orders").databaseName("sales")) + .createdAfter(before)) + .tags(Map.of("team", "data"))).rulesets(); + assertThat(listed).extracting(DataQualityRulesetListDetails::name).contains(NAME); + DataQualityRulesetListDetails item = listed.stream().filter(d -> d.name().equals(NAME)).findFirst() + .orElseThrow(); + assertThat(item.ruleCount()).isEqualTo(2); + assertThat(item.createdOn()).isEqualTo(got.createdOn()); + + glue.deleteDataQualityRuleset(r -> r.name(NAME)); + assertThatThrownBy(() -> glue.getDataQualityRuleset(r -> r.name(NAME))) + .isInstanceOf(EntityNotFoundException.class); + } +} diff --git a/docs/services/glue.md b/docs/services/glue.md index c78ef213b7..d83e82c830 100644 --- a/docs/services/glue.md +++ b/docs/services/glue.md @@ -254,6 +254,21 @@ Blueprints are not emulated. | UpdateClassifier | Partially updates a classifier without changing its type. | | DeleteClassifier | Deletes a classifier by name. | +#### Data quality rulesets + +| Action | Description | +|--------|-------------| +| CreateDataQualityRuleset | Stores a named DQDL ruleset, optionally with a `TargetTable` and tags. | +| GetDataQualityRuleset | Returns a ruleset with its `CreatedOn` and `LastModifiedOn`. | +| UpdateDataQualityRuleset | Replaces the `Description` or `Ruleset` the request sets and keeps the rest. | +| DeleteDataQualityRuleset | Deletes a ruleset and its tags. | +| ListDataQualityRulesets | Lists rulesets in name order with `RuleCount`, filtered by `Filter` (name, description, target table, created and last modified times) and `Tags`, paged by `MaxResults` (1 to 1000) and `NextToken`. | + +Rulesets are stored, not evaluated: there are no recommendation or evaluation runs, so +`RecommendationRunId` is never set. `RuleCount` is the number of entries in the ruleset's +top level `Rules = [ ... ]` list, with a composite rule counted once. Rulesets are tagged by +ARN `arn:aws:glue:::dataQualityRuleset/`. + ### Schema Registry #### Registries diff --git a/docs/services/index.md b/docs/services/index.md index 63656c5143..a45f54038c 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -71,7 +71,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Amazon MQ](amazonmq.md) | `/v1/brokers/...` + RabbitMQ broker | REST JSON + AMQP | 5 | | [MWAA](mwaa.md) | `/` REST paths for environments + CLI/web proxy | REST JSON | 10 | | [Athena](athena.md) | `POST /` + `X-Amz-Target: AmazonAthena.*` | JSON 1.1 | 21 | -| [Glue](glue.md) | `POST /` + `X-Amz-Target: AWSGlue.*` | JSON 1.1 | 131 | +| [Glue](glue.md) | `POST /` + `X-Amz-Target: AWSGlue.*` | JSON 1.1 | 135 | | [Lake Formation](lakeformation.md) | `POST /` | REST JSON | 16 | | [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 14 | | [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 13 | diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/GlueJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/glue/GlueJsonHandler.java index 0e442fe31e..2a58998429 100644 --- a/src/main/java/io/github/hectorvent/floci/services/glue/GlueJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/glue/GlueJsonHandler.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsJsonTimestamp; import io.github.hectorvent.floci.services.glue.model.*; import io.github.hectorvent.floci.services.glue.schemaregistry.GlueSchemaRegistryService; import io.github.hectorvent.floci.services.glue.schemaregistry.model.Registry; @@ -460,10 +461,42 @@ public class GlueJsonHandler { region, readMaxResults(request), readNextToken(request)); yield Response.ok(pageResponse("SecurityConfigurations", page.items(), page.nextToken())).build(); } - // Read-only Glue actions for resources the emulator does not model. The AWS SDK - // expects each to return a 200 with its result key present (empty), so we emit the - // documented empty shape rather than an InvalidAction 400 that callers can't read. - case "ListDataQualityRulesets" -> Response.ok(Map.of("Rulesets", List.of())).build(); + case "CreateDataQualityRuleset" -> { + Map tags = request.hasNonNull("Tags") + ? mapper.convertValue(request.get("Tags"), STRING_MAP) + : null; + DataQualityRuleset created = glueService.createDataQualityRuleset( + request.path("Name").asText(null), request.path("Description").asText(null), + request.path("Ruleset").asText(null), readTargetTable(request.get("TargetTable")), + request.path("DataQualitySecurityConfiguration").asText(null), tags, region); + yield Response.ok(Map.of("Name", created.getName())).build(); + } + case "GetDataQualityRuleset" -> + Response.ok(glueService.getDataQualityRuleset(request.path("Name").asText(null), region)).build(); + case "UpdateDataQualityRuleset" -> { + DataQualityRuleset updated = glueService.updateDataQualityRuleset(request.path("Name").asText(null), + request.path("Description").asText(null), request.path("Ruleset").asText(null), region); + Map response = new LinkedHashMap<>(); + response.put("Name", updated.getName()); + putIfNotNull(response, "Description", updated.getDescription()); + response.put("Ruleset", updated.getRuleset()); + yield Response.ok(response).build(); + } + case "DeleteDataQualityRuleset" -> { + glueService.deleteDataQualityRuleset(request.path("Name").asText(null), region); + yield Response.ok(Map.of()).build(); + } + case "ListDataQualityRulesets" -> { + Map tags = request.hasNonNull("Tags") + ? mapper.convertValue(request.get("Tags"), STRING_MAP) + : null; + GlueService.Page page = glueService.listDataQualityRulesets( + readDataQualityFilter(request.get("Filter")), tags, + readMaxResults(request), readNextToken(request), region); + yield Response.ok(pageResponse("Rulesets", + page.items().stream().map(GlueJsonHandler::dataQualityListItem).toList(), + page.nextToken())).build(); + } case "CreateTrigger" -> { Trigger trigger = toTrigger(request); trigger.setName(request.path("Name").asText(null)); @@ -1113,6 +1146,42 @@ public class GlueJsonHandler { } } + private static DataQualityRuleset.TargetTable readTargetTable(JsonNode node) { + if (node == null || node.isNull()) { + return null; + } + return new DataQualityRuleset.TargetTable(node.path("TableName").asText(null), + node.path("DatabaseName").asText(null), node.path("CatalogId").asText(null)); + } + + private static GlueService.DataQualityRulesetFilter readDataQualityFilter(JsonNode node) { + if (node == null || node.isNull()) { + return null; + } + return new GlueService.DataQualityRulesetFilter(node.path("Name").asText(null), + node.path("Description").asText(null), + AwsJsonTimestamp.epochSeconds(node, "CreatedBefore", "InvalidInputException"), + AwsJsonTimestamp.epochSeconds(node, "CreatedAfter", "InvalidInputException"), + AwsJsonTimestamp.epochSeconds(node, "LastModifiedBefore", "InvalidInputException"), + AwsJsonTimestamp.epochSeconds(node, "LastModifiedAfter", "InvalidInputException"), + readTargetTable(node.get("TargetTable"))); + } + + private static Map dataQualityListItem(DataQualityRuleset ruleset) { + Map item = new LinkedHashMap<>(); + item.put("Name", ruleset.getName()); + putIfNotNull(item, "Description", ruleset.getDescription()); + item.put("CreatedOn", epochSeconds(ruleset.getCreatedOn())); + item.put("LastModifiedOn", epochSeconds(ruleset.getLastModifiedOn())); + putIfNotNull(item, "TargetTable", ruleset.getTargetTable()); + putIfNotNull(item, "RuleCount", GlueService.dataQualityRuleCount(ruleset.getRuleset())); + return item; + } + + private static double epochSeconds(Instant instant) { + return instant.toEpochMilli() / 1000.0; + } + private static String iso(Instant instant) { return instant != null ? instant.toString() : null; } diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java b/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java index 4075dc3cd4..e7c5c6d287 100644 --- a/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java +++ b/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java @@ -19,6 +19,7 @@ import io.github.hectorvent.floci.services.glue.model.ConnectionPasswordEncrypti import io.github.hectorvent.floci.services.glue.model.Crawler; import io.github.hectorvent.floci.services.glue.model.CrawlerTargets; import io.github.hectorvent.floci.services.glue.model.DataCatalogEncryptionSettings; +import io.github.hectorvent.floci.services.glue.model.DataQualityRuleset; import io.github.hectorvent.floci.services.glue.model.Database; import io.github.hectorvent.floci.services.glue.model.EncryptionAtRest; import io.github.hectorvent.floci.services.glue.model.GluePolicy; @@ -56,6 +57,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.time.format.DateTimeParseException; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Base64; import java.util.Comparator; @@ -78,6 +80,10 @@ public class GlueService { private static final int MAX_FUNCTION_PATTERN_LENGTH = 255; private static final int MAX_FUNCTION_RESULTS = 100; private static final int MAX_SECURITY_CONFIGURATION_NAME_LENGTH = 255; + private static final int MAX_DATA_QUALITY_NAME_LENGTH = 255; + private static final int MAX_DATA_QUALITY_DESCRIPTION_LENGTH = 2048; + private static final int MAX_DATA_QUALITY_RULESET_LENGTH = 65536; + private static final int MAX_TAGS = 50; private static final Set CSV_HEADER_VALUES = Set.of("UNKNOWN", "PRESENT", "ABSENT"); private static final Set CSV_SERDE_VALUES = Set.of("OpenCSVSerDe", "LazySimpleSerDe", "None"); private static final Set CSV_CUSTOM_DATATYPES = Set.of( @@ -198,6 +204,7 @@ public class GlueService { private final StorageBackend resourcePolicyStore; private final StorageBackend encryptionSettingsStore; private final StorageBackend securityConfigurationStore; + private final StorageBackend dataQualityRulesetStore; private final StorageBackend triggerStore; private final StorageBackend workflowStore; private final GlueSchemaRegistryService schemaRegistryService; @@ -230,6 +237,8 @@ public class GlueService { "glue", "catalog_encryption_settings.json", new TypeReference<>() {}); this.securityConfigurationStore = storageFactory.create( "glue", "security_configurations.json", new TypeReference<>() {}); + this.dataQualityRulesetStore = storageFactory.create( + "glue", "data_quality_rulesets.json", new TypeReference<>() {}); this.triggerStore = storageFactory.create("glue", "triggers.json", new TypeReference<>() {}); this.workflowStore = storageFactory.create("glue", "workflows.json", new TypeReference<>() {}); this.schemaRegistryService = schemaRegistryService; @@ -253,6 +262,7 @@ public class GlueService { StorageBackend resourcePolicyStore, StorageBackend encryptionSettingsStore, StorageBackend securityConfigurationStore, + StorageBackend dataQualityRulesetStore, StorageBackend triggerStore, StorageBackend workflowStore, GlueSchemaRegistryService schemaRegistryService, @@ -274,6 +284,7 @@ public class GlueService { this.resourcePolicyStore = resourcePolicyStore; this.encryptionSettingsStore = encryptionSettingsStore; this.securityConfigurationStore = securityConfigurationStore; + this.dataQualityRulesetStore = dataQualityRulesetStore; this.triggerStore = triggerStore; this.workflowStore = workflowStore; this.schemaRegistryService = schemaRegistryService; @@ -2992,6 +3003,10 @@ public class GlueService { } else if (resource.startsWith("connection/")) { getConnection(resource.substring(11), false); return; + } else if (resource.startsWith("dataQualityRuleset/")) { + getDataQualityRuleset(resource.substring("dataQualityRuleset/".length()), + AwsArnUtils.parse(arn).region()); + return; } else if (resource.startsWith("database/")) { getDatabase(resource.substring(9)); return; @@ -3012,6 +3027,220 @@ public class GlueService { throw new AwsException("EntityNotFoundException", "Resource " + arn + " not found or not supported.", 400); } + // ── Data quality rulesets ───────────────────────────────────────────────── + + /** The filters ListDataQualityRulesets takes; each one left null matches every ruleset. */ + public record DataQualityRulesetFilter(String name, String description, Instant createdBefore, + Instant createdAfter, Instant lastModifiedBefore, + Instant lastModifiedAfter, DataQualityRuleset.TargetTable targetTable) {} + + public DataQualityRuleset createDataQualityRuleset(String name, String description, String ruleset, + DataQualityRuleset.TargetTable targetTable, + String securityConfiguration, Map tags, + String region) { + validateDataQualityName(name, "Name"); + validateDataQualityRulesetText(ruleset); + validateDataQualityDescription(description); + if (targetTable != null) { + validateDataQualityName(targetTable.tableName(), "TargetTable.TableName"); + validateDataQualityName(targetTable.databaseName(), "TargetTable.DatabaseName"); + } + if (securityConfiguration != null) { + validateDataQualityName(securityConfiguration, "DataQualitySecurityConfiguration"); + } + if (tags != null && tags.size() > MAX_TAGS) { + throw new AwsException("InvalidInputException", "Tags must have at most " + MAX_TAGS + " entries.", 400); + } + String key = dataQualityRulesetKey(region, name); + synchronized (dataQualityRulesetStore) { + if (dataQualityRulesetStore.get(key).isPresent()) { + throw new AwsException("AlreadyExistsException", "Data quality ruleset already exists: " + name, 400); + } + Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS); + DataQualityRuleset created = new DataQualityRuleset(); + created.setName(name); + created.setDescription(description); + created.setRuleset(ruleset); + created.setTargetTable(targetTable); + created.setDataQualitySecurityConfiguration(securityConfiguration); + created.setCreatedOn(now); + created.setLastModifiedOn(now); + dataQualityRulesetStore.put(key, created); + if (tags != null && !tags.isEmpty()) { + resourceGroupsTaggingService.tagResources(List.of(dataQualityRulesetArn(region, name)), tags, region); + } + LOG.infov("Created Glue data quality ruleset: {0}", name); + return created; + } + } + + public DataQualityRuleset getDataQualityRuleset(String name, String region) { + validateDataQualityName(name, "Name"); + return dataQualityRulesetStore.get(dataQualityRulesetKey(region, name)) + .orElseThrow(() -> dataQualityRulesetNotFound(name)); + } + + /** Replaces the description and ruleset the request sets; a member left out keeps its value. */ + public DataQualityRuleset updateDataQualityRuleset(String name, String description, String ruleset, String region) { + validateDataQualityName(name, "Name"); + if (ruleset != null) { + validateDataQualityRulesetText(ruleset); + } + validateDataQualityDescription(description); + String key = dataQualityRulesetKey(region, name); + synchronized (dataQualityRulesetStore) { + DataQualityRuleset existing = dataQualityRulesetStore.get(key) + .orElseThrow(() -> dataQualityRulesetNotFound(name)); + if (description != null) { + existing.setDescription(description); + } + if (ruleset != null) { + existing.setRuleset(ruleset); + } + existing.setLastModifiedOn(Instant.now().truncatedTo(ChronoUnit.MILLIS)); + dataQualityRulesetStore.put(key, existing); + return existing; + } + } + + public void deleteDataQualityRuleset(String name, String region) { + validateDataQualityName(name, "Name"); + String key = dataQualityRulesetKey(region, name); + synchronized (dataQualityRulesetStore) { + if (dataQualityRulesetStore.get(key).isEmpty()) { + throw dataQualityRulesetNotFound(name); + } + dataQualityRulesetStore.delete(key); + resourceGroupsTaggingService.deleteResources(List.of(dataQualityRulesetArn(region, name)), region); + } + LOG.infov("Deleted Glue data quality ruleset: {0}", name); + } + + /** The Region's rulesets in name order, narrowed by the filter and by tags they all carry. */ + public Page listDataQualityRulesets(DataQualityRulesetFilter filter, Map tags, + Integer maxResults, String nextToken, String region) { + return paginate(() -> { + String prefix = region + ":"; + String accountId = regionResolver.getAccountId(); + List matching = new ArrayList<>(); + for (DataQualityRuleset candidate : dataQualityRulesetStore.scan(key -> key.startsWith(prefix))) { + if (matchesDataQualityFilter(candidate, filter, accountId) && (tags == null || tags.isEmpty() + || hasTags(dataQualityRulesetArn(region, candidate.getName()), tags, region))) { + matching.add(candidate); + } + } + matching.sort(Comparator.comparing(DataQualityRuleset::getName)); + return matching; + }, maxResults, nextToken, 1000); + } + + /** + * The number of rules in a DQDL ruleset: the entries of its top-level {@code Rules = [ ... ]} + * list, where a composite rule in parentheses counts as one. Null when the text has no such list. + */ + public static Integer dataQualityRuleCount(String ruleset) { + if (ruleset == null) { + return null; + } + int start = ruleset.indexOf('[', Math.max(ruleset.indexOf("Rules"), 0)); + if (start < 0) { + return null; + } + int depth = 0; + int count = 0; + boolean inEntry = false; + boolean quoted = false; + for (int i = start; i < ruleset.length(); i++) { + char c = ruleset.charAt(i); + if (quoted) { + if (c == '\\') { + i++; + } else if (c == '"') { + quoted = false; + } + continue; + } + switch (c) { + case '"' -> quoted = true; + case '[', '(' -> depth++; + case ']', ')' -> depth--; + default -> { } + } + if (depth == 0) { + return inEntry ? count + 1 : count; + } + if (depth == 1 && c == ',') { + count++; + inEntry = false; + } else if (!Character.isWhitespace(c) && !(depth == 1 && c == '[' && i == start)) { + inEntry = true; + } + } + return null; + } + + /** A target table without a CatalogId is in the caller's own catalog, the account. */ + private static boolean matchesDataQualityFilter(DataQualityRuleset ruleset, DataQualityRulesetFilter filter, + String accountId) { + if (filter == null) { + return true; + } + DataQualityRuleset.TargetTable table = ruleset.getTargetTable(); + return (filter.name() == null || filter.name().equals(ruleset.getName())) + && (filter.description() == null || filter.description().equals(ruleset.getDescription())) + && (filter.createdBefore() == null || ruleset.getCreatedOn().isBefore(filter.createdBefore())) + && (filter.createdAfter() == null || ruleset.getCreatedOn().isAfter(filter.createdAfter())) + && (filter.lastModifiedBefore() == null + || ruleset.getLastModifiedOn().isBefore(filter.lastModifiedBefore())) + && (filter.lastModifiedAfter() == null + || ruleset.getLastModifiedOn().isAfter(filter.lastModifiedAfter())) + && (filter.targetTable() == null || (table != null + && Objects.equals(filter.targetTable().tableName(), table.tableName()) + && Objects.equals(filter.targetTable().databaseName(), table.databaseName()) + && (filter.targetTable().catalogId() == null + || filter.targetTable().catalogId().equals( + table.catalogId() != null ? table.catalogId() : accountId)))); + } + + private String dataQualityRulesetArn(String region, String name) { + return regionResolver.buildArn("glue", region, "dataQualityRuleset/" + name); + } + + private static String dataQualityRulesetKey(String region, String name) { + return region + ":" + name; + } + + private static AwsException dataQualityRulesetNotFound(String name) { + return new AwsException("EntityNotFoundException", "Data quality ruleset not found: " + name, 400); + } + + private static void validateDataQualityName(String value, String field) { + if (value == null || value.isBlank()) { + throw new AwsException("InvalidInputException", field + " is required.", 400); + } + if (value.length() > MAX_DATA_QUALITY_NAME_LENGTH) { + throw new AwsException("InvalidInputException", + field + " must be between 1 and " + MAX_DATA_QUALITY_NAME_LENGTH + " characters.", 400); + } + } + + private static void validateDataQualityRulesetText(String ruleset) { + if (ruleset == null || ruleset.isEmpty()) { + throw new AwsException("InvalidInputException", "Ruleset is required.", 400); + } + if (ruleset.length() > MAX_DATA_QUALITY_RULESET_LENGTH) { + throw new AwsException("InvalidInputException", + "Ruleset must be at most " + MAX_DATA_QUALITY_RULESET_LENGTH + " characters.", 400); + } + } + + private static void validateDataQualityDescription(String description) { + if (description != null && description.length() > MAX_DATA_QUALITY_DESCRIPTION_LENGTH) { + throw new AwsException("InvalidInputException", + "Description must be at most " + MAX_DATA_QUALITY_DESCRIPTION_LENGTH + " characters.", 400); + } + } + public record Page(List items, String nextToken) {} Page paginate(List all, Integer maxResults, String nextToken) { diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/model/DataQualityRuleset.java b/src/main/java/io/github/hectorvent/floci/services/glue/model/DataQualityRuleset.java new file mode 100644 index 0000000000..f4d31be5e9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/glue/model/DataQualityRuleset.java @@ -0,0 +1,64 @@ +package io.github.hectorvent.floci.services.glue.model; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** + * A data quality ruleset as GetDataQualityRuleset reports it: a named DQDL ruleset, optionally + * bound to a table. Floci stores rulesets; it does not evaluate them. + */ +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class DataQualityRuleset { + + /** The table a ruleset is written for. */ + @RegisterForReflection + @JsonInclude(JsonInclude.Include.NON_NULL) + public record TargetTable(@JsonProperty("TableName") String tableName, + @JsonProperty("DatabaseName") String databaseName, + @JsonProperty("CatalogId") String catalogId) {} + + private String name; + private String description; + private String ruleset; + private TargetTable targetTable; + private String dataQualitySecurityConfiguration; + @JsonFormat(shape = JsonFormat.Shape.NUMBER) + private Instant createdOn; + @JsonFormat(shape = JsonFormat.Shape.NUMBER) + private Instant lastModifiedOn; + + public DataQualityRuleset() {} + + @JsonProperty("Name") + public String getName() { return name; } + public void setName(String name) { this.name = name; } + + @JsonProperty("Description") + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + + @JsonProperty("Ruleset") + public String getRuleset() { return ruleset; } + public void setRuleset(String ruleset) { this.ruleset = ruleset; } + + @JsonProperty("TargetTable") + public TargetTable getTargetTable() { return targetTable; } + public void setTargetTable(TargetTable targetTable) { this.targetTable = targetTable; } + + @JsonProperty("DataQualitySecurityConfiguration") + public String getDataQualitySecurityConfiguration() { return dataQualitySecurityConfiguration; } + public void setDataQualitySecurityConfiguration(String name) { this.dataQualitySecurityConfiguration = name; } + + @JsonProperty("CreatedOn") + public Instant getCreatedOn() { return createdOn; } + public void setCreatedOn(Instant createdOn) { this.createdOn = createdOn; } + + @JsonProperty("LastModifiedOn") + public Instant getLastModifiedOn() { return lastModifiedOn; } + public void setLastModifiedOn(Instant lastModifiedOn) { this.lastModifiedOn = lastModifiedOn; } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueDataQualityRulesetIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueDataQualityRulesetIntegrationTest.java new file mode 100644 index 0000000000..3f59acd408 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueDataQualityRulesetIntegrationTest.java @@ -0,0 +1,277 @@ +package io.github.hectorvent.floci.services.glue; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Glue data quality rulesets: create, read, update, list and delete, the list filters, tags and + * paging, the errors the model names, and isolation by account and Region. Each test works in an + * account of its own, so a listing sees only the rulesets that test created. + */ +@QuarkusTest +class GlueDataQualityRulesetIntegrationTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String REGION = "us-east-1"; + private static final String RULESET = "Rules = [ RowCount > 0, IsComplete \"id\", " + + "(ColumnValues \"age\" > 0) and (ColumnValues \"age\" < 150) ]"; + + @BeforeAll + static void setup() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aRulesetRoundTripsThroughCreateGetUpdateListAndDelete() { + String account = "000000000071"; + String name = unique("orders"); + call("CreateDataQualityRuleset", account, REGION, """ + {"Name":"%s","Description":"orders checks","Ruleset":%s, + "TargetTable":{"TableName":"orders","DatabaseName":"sales"}, + "Tags":{"team":"data"}} + """.formatted(name, json(RULESET))) + .statusCode(200) + .body("Name", equalTo(name)); + + call("GetDataQualityRuleset", account, REGION, "{\"Name\":\"" + name + "\"}") + .statusCode(200) + .body("Name", equalTo(name)) + .body("Description", equalTo("orders checks")) + .body("Ruleset", equalTo(RULESET)) + .body("TargetTable.TableName", equalTo("orders")) + .body("TargetTable.DatabaseName", equalTo("sales")) + .body("CreatedOn", instanceOf(Number.class)) + .body("LastModifiedOn", instanceOf(Number.class)); + + call("UpdateDataQualityRuleset", account, REGION, + "{\"Name\":\"" + name + "\",\"Description\":\"orders, nightly\"}") + .statusCode(200) + .body("Name", equalTo(name)) + .body("Description", equalTo("orders, nightly")) + .body("Ruleset", equalTo(RULESET)); + call("UpdateDataQualityRuleset", account, REGION, + "{\"Name\":\"" + name + "\",\"Ruleset\":\"Rules = [ RowCount > 10 ]\"}") + .statusCode(200) + .body("Description", equalTo("orders, nightly")) + .body("Ruleset", equalTo("Rules = [ RowCount > 10 ]")); + + call("ListDataQualityRulesets", account, REGION, "{}") + .statusCode(200) + .body("Rulesets", hasSize(1)) + .body("Rulesets[0].Name", equalTo(name)) + .body("Rulesets[0].Description", equalTo("orders, nightly")) + .body("Rulesets[0].RuleCount", equalTo(1)) + .body("Rulesets[0].TargetTable.TableName", equalTo("orders")) + .body("Rulesets[0].CreatedOn", instanceOf(Number.class)) + .body("Rulesets[0].Ruleset", nullValue()) + .body("NextToken", nullValue()); + + String arn = "arn:aws:glue:" + REGION + ":" + account + ":dataQualityRuleset/" + name; + call("GetTags", account, REGION, "{\"ResourceArn\":\"" + arn + "\"}") + .statusCode(200) + .body("Tags.team", equalTo("data")); + + call("DeleteDataQualityRuleset", account, REGION, "{\"Name\":\"" + name + "\"}") + .statusCode(200); + call("GetDataQualityRuleset", account, REGION, "{\"Name\":\"" + name + "\"}") + .statusCode(400) + .body("__type", equalTo("EntityNotFoundException")); + call("GetTags", account, REGION, "{\"ResourceArn\":\"" + arn + "\"}") + .statusCode(400) + .body("__type", equalTo("EntityNotFoundException")); + + create(account, REGION, name, RULESET, null, null); + call("GetTags", account, REGION, "{\"ResourceArn\":\"" + arn + "\"}") + .statusCode(200) + .body("Tags.team", nullValue()); + call("DeleteDataQualityRuleset", account, REGION, "{\"Name\":\"" + name + "\"}") + .statusCode(200); + } + + @Test + void theListCountsTopLevelRulesWithACompositeRuleAsOne() { + String account = "000000000072"; + String name = unique("composite"); + create(account, REGION, name, "Rules = [ (ColumnValues \"code\" in [1, 2]) or (IsComplete \"id\"), " + + "RowCount > 0, IsComplete \"name\" ]", null, null); + + call("ListDataQualityRulesets", account, REGION, "{}") + .statusCode(200) + .body("Rulesets[0].RuleCount", equalTo(3)); + } + + @Test + void theListFiltersByTableTagsAndTime() throws Exception { + String account = "000000000073"; + String first = "a-" + unique("first"); + String second = "b-" + unique("second"); + create(account, REGION, first, RULESET, "{\"TableName\":\"orders\",\"DatabaseName\":\"sales\"}", + "{\"team\":\"data\"}"); + String firstBody = call("GetDataQualityRuleset", account, REGION, "{\"Name\":\"" + first + "\"}") + .statusCode(200) + .extract().asString(); + create(account, REGION, second, RULESET, "{\"TableName\":\"items\",\"DatabaseName\":\"sales\"}", + "{\"team\":\"ops\"}"); + + assertEquals(List.of(first), listNames(account, + "{\"Filter\":{\"TargetTable\":{\"TableName\":\"orders\",\"DatabaseName\":\"sales\"}}}")); + assertEquals(List.of(second), listNames(account, "{\"Tags\":{\"team\":\"ops\"}}")); + assertEquals(List.of(second), listNames(account, "{\"Filter\":{\"Name\":\"" + second + "\"}}")); + // RestAssured reads JSON numbers as Float, too coarse for epoch seconds. + double created = MAPPER.readTree(firstBody).get("CreatedOn").asDouble(); + assertEquals(List.of(first, second), listNames(account, + "{\"Filter\":{\"CreatedAfter\":" + (created - 1) + ",\"CreatedBefore\":" + (created + 3600) + "}}")); + assertEquals(List.of(), listNames(account, "{\"Filter\":{\"CreatedAfter\":" + (created + 3600) + "}}")); + assertEquals(List.of(), listNames(account, "{\"Filter\":{\"CreatedBefore\":" + (created - 1) + "}}")); + assertEquals(List.of(), listNames(account, "{\"Filter\":{\"LastModifiedAfter\":" + (created + 3600) + "}}")); + assertEquals(List.of(first, second), listNames(account, + "{\"Filter\":{\"LastModifiedBefore\":" + (created + 3600) + "}}")); + call("ListDataQualityRulesets", account, REGION, + "{\"Filter\":{\"CreatedAfter\":\"" + created + "\"}}") + .statusCode(400) + .body("__type", equalTo("InvalidInputException")); + + String token = call("ListDataQualityRulesets", account, REGION, "{\"MaxResults\":1}") + .statusCode(200) + .body("Rulesets.Name", contains(first)) + .body("NextToken", notNullValue()) + .extract().path("NextToken"); + call("ListDataQualityRulesets", account, REGION, "{\"MaxResults\":1,\"NextToken\":\"" + token + "\"}") + .statusCode(200) + .body("Rulesets.Name", contains(second)) + .body("NextToken", nullValue()); + call("ListDataQualityRulesets", account, REGION, "{\"MaxResults\":0}") + .statusCode(400) + .body("__type", equalTo("InvalidInputException")); + } + + @Test + void theTargetTableFilterMatchesTheCatalogWhenOneIsGiven() { + String account = "000000000077"; + String own = "a-" + unique("own"); + String shared = "b-" + unique("shared"); + create(account, REGION, own, RULESET, "{\"TableName\":\"orders\",\"DatabaseName\":\"sales\"}", null); + create(account, REGION, shared, RULESET, + "{\"TableName\":\"orders\",\"DatabaseName\":\"sales\",\"CatalogId\":\"111111111111\"}", null); + + assertEquals(List.of(own, shared), listNames(account, + "{\"Filter\":{\"TargetTable\":{\"TableName\":\"orders\",\"DatabaseName\":\"sales\"}}}")); + assertEquals(List.of(own), listNames(account, "{\"Filter\":{\"TargetTable\":" + + "{\"TableName\":\"orders\",\"DatabaseName\":\"sales\",\"CatalogId\":\"" + account + "\"}}}")); + assertEquals(List.of(shared), listNames(account, "{\"Filter\":{\"TargetTable\":" + + "{\"TableName\":\"orders\",\"DatabaseName\":\"sales\",\"CatalogId\":\"111111111111\"}}}")); + } + + @Test + void requestsTheModelRefusesUseItsErrors() { + String account = "000000000074"; + String name = unique("errors"); + create(account, REGION, name, RULESET, null, null); + + call("CreateDataQualityRuleset", account, REGION, + "{\"Name\":\"" + name + "\",\"Ruleset\":" + json(RULESET) + "}") + .statusCode(400) + .body("__type", equalTo("AlreadyExistsException")); + call("CreateDataQualityRuleset", account, REGION, "{\"Name\":\"" + unique("no-rules") + "\"}") + .statusCode(400) + .body("__type", equalTo("InvalidInputException")); + call("CreateDataQualityRuleset", account, REGION, "{\"Name\":\"" + unique("no-db") + "\",\"Ruleset\":" + + json(RULESET) + ",\"TargetTable\":{\"TableName\":\"orders\"}}") + .statusCode(400) + .body("__type", equalTo("InvalidInputException")); + call("CreateDataQualityRuleset", account, REGION, + "{\"Name\":\"" + "n".repeat(256) + "\",\"Ruleset\":" + json(RULESET) + "}") + .statusCode(400) + .body("__type", equalTo("InvalidInputException")); + call("UpdateDataQualityRuleset", account, REGION, "{\"Name\":\"" + unique("missing") + "\"}") + .statusCode(400) + .body("__type", equalTo("EntityNotFoundException")); + call("DeleteDataQualityRuleset", account, REGION, "{\"Name\":\"" + unique("missing") + "\"}") + .statusCode(400) + .body("__type", equalTo("EntityNotFoundException")); + call("UpdateDataQualityRuleset", account, REGION, + "{\"Name\":\"" + name + "\",\"Ruleset\":\"\"}") + .statusCode(400) + .body("__type", equalTo("InvalidInputException")); + call("GetDataQualityRuleset", account, REGION, "{\"Name\":\"" + name + "\"}") + .statusCode(200) + .body("Ruleset", equalTo(RULESET)); + } + + @Test + void rulesetsAreIsolatedByAccountAndRegion() { + String name = unique("isolated"); + create("000000000075", REGION, name, RULESET, null, null); + + call("GetDataQualityRuleset", "000000000076", REGION, "{\"Name\":\"" + name + "\"}") + .statusCode(400) + .body("__type", equalTo("EntityNotFoundException")); + call("GetDataQualityRuleset", "000000000075", "us-west-2", "{\"Name\":\"" + name + "\"}") + .statusCode(400) + .body("__type", equalTo("EntityNotFoundException")); + assertTrue(listNames("000000000076", "{}").isEmpty()); + + create("000000000076", REGION, name, "Rules = [ RowCount > 1 ]", null, null); + call("GetDataQualityRuleset", "000000000075", REGION, "{\"Name\":\"" + name + "\"}") + .statusCode(200) + .body("Ruleset", equalTo(RULESET)); + } + + private static void create(String account, String region, String name, String ruleset, String targetTable, + String tags) { + StringBuilder body = new StringBuilder("{\"Name\":\"" + name + "\",\"Ruleset\":" + json(ruleset)); + if (targetTable != null) { + body.append(",\"TargetTable\":").append(targetTable); + } + if (tags != null) { + body.append(",\"Tags\":").append(tags); + } + call("CreateDataQualityRuleset", account, region, body.append('}').toString()).statusCode(200); + } + + private static List listNames(String account, String body) { + return call("ListDataQualityRulesets", account, REGION, body) + .statusCode(200) + .extract().jsonPath().getList("Rulesets.Name", String.class); + } + + private static ValidatableResponse call(String action, String account, String region, String body) { + return given().contentType(CONTENT_TYPE) + .header("X-Amz-Target", "AWSGlue." + action) + .header("Authorization", authorization(account, region)) + .body(body) + .when().post("/") + .then(); + } + + private static String json(String text) { + return "\"" + text.replace("\\", "\\\\").replace("\"", "\\\"") + "\""; + } + + private static String unique(String prefix) { + return prefix + "-" + UUID.randomUUID().toString().substring(0, 8); + } + + private static String authorization(String account, String region) { + return "AWS4-HMAC-SHA256 Credential=" + account + + "/20260918/" + region + "/glue/aws4_request, SignedHeaders=host, Signature=abc"; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerEmptyListTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerEmptyListTest.java index 93adf66c31..9ab7295e35 100644 --- a/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerEmptyListTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerEmptyListTest.java @@ -23,9 +23,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** - * Verifies the wire-accurate empty-list responses for an unmodeled Glue action and an - * empty newly modeled resource collection. Each must return HTTP 200, an empty list - * under its result key, and omit NextToken. + * Verifies the wire-accurate empty-list responses for empty Glue resource collections. + * Each must return HTTP 200, an empty list under its result key, and omit NextToken. */ class GlueJsonHandlerEmptyListTest { diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java index 9978d64649..d0177d0569 100644 --- a/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java @@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.glue.model.ConnectionPasswordEncrypti import io.github.hectorvent.floci.services.glue.model.Crawler; import io.github.hectorvent.floci.services.glue.model.CrawlerTargets; import io.github.hectorvent.floci.services.glue.model.DataCatalogEncryptionSettings; +import io.github.hectorvent.floci.services.glue.model.DataQualityRuleset; import io.github.hectorvent.floci.services.glue.model.Database; import io.github.hectorvent.floci.services.glue.model.EncryptionAtRest; import io.github.hectorvent.floci.services.glue.model.GluePolicy; @@ -112,6 +113,7 @@ class GlueServiceTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), schemaRegistryService, regionResolver, new ResourceGroupsTaggingService(null), kmsService);