feat(glue): data quality rulesets (#7035)

* feat(glue): data quality rulesets

CreateDataQualityRuleset, GetDataQualityRuleset, UpdateDataQualityRuleset
and DeleteDataQualityRuleset answered InvalidAction, and
ListDataQualityRulesets always returned an empty list, so Terraform's
aws_glue_data_quality_ruleset failed at its first apply.

Rulesets are now stored per account and Region by name, with their
description, DQDL text, target table, security configuration and created
and last modified times, and tagged through the shared tag store by their
dataQualityRuleset ARN. Update replaces only the members the request sets.
List returns them in name order with RuleCount, filtered by name,
description, target table, created and last modified times and tags, and
paged by MaxResults and NextToken. Errors follow the model:
AlreadyExistsException for a duplicate, EntityNotFoundException for an
unknown name, InvalidInputException for a missing or oversized member.

Rulesets are stored, not evaluated.

Closes #6830

* fix(glue): match a ruleset's catalog and take its store from the caller

The ListDataQualityRulesets target table filter compared only TableName and
DatabaseName, so filtering for one catalog also returned a ruleset on the
same table in another. A CatalogId in the filter now has to match too, with
a target table that names no catalog in the account's own.

The package-private GlueService constructor built the ruleset store itself;
it now takes it as an argument, as it does every other store.

* fix(glue): reuse hasTags and AwsJsonTimestamp for ruleset listing

The ruleset tag filter now goes through hasTags, as jobs, crawlers and
triggers do, and the list filter's timestamps through
AwsJsonTimestamp.epochSeconds, so a timestamp sent as a string is refused
with InvalidInputException as the SDKs never send one.

---------

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
This commit is contained in:
DavidandPriamo Germosen authored and GitHub committed 2026-10-30 22:36:13 -04:00
1 parent 3a941bc450
commit 6db78b8ef4
10 files changed
+795 -8

No files matched your search

@@ -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"* ]]
}
@@ -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<DataQualityRulesetListDetails> 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);
}
}
+15
View File
@@ -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:<region>:<account>:dataQualityRuleset/<name>`.
### Schema Registry
#### Registries
+1 -1
View File
@@ -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 /<Action>` | 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 |
@@ -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<String, String> 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<String, Object> 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<String, String> tags = request.hasNonNull("Tags")
? mapper.convertValue(request.get("Tags"), STRING_MAP)
: null;
GlueService.Page<DataQualityRuleset> 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<String, Object> dataQualityListItem(DataQualityRuleset ruleset) {
Map<String, Object> 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;
}
@@ -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<String> CSV_HEADER_VALUES = Set.of("UNKNOWN", "PRESENT", "ABSENT");
private static final Set<String> CSV_SERDE_VALUES = Set.of("OpenCSVSerDe", "LazySimpleSerDe", "None");
private static final Set<String> CSV_CUSTOM_DATATYPES = Set.of(
@@ -198,6 +204,7 @@ public class GlueService {
private final StorageBackend<String, GluePolicy> resourcePolicyStore;
private final StorageBackend<String, DataCatalogEncryptionSettings> encryptionSettingsStore;
private final StorageBackend<String, SecurityConfiguration> securityConfigurationStore;
private final StorageBackend<String, DataQualityRuleset> dataQualityRulesetStore;
private final StorageBackend<String, Trigger> triggerStore;
private final StorageBackend<String, Workflow> 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<String, GluePolicy> resourcePolicyStore,
StorageBackend<String, DataCatalogEncryptionSettings> encryptionSettingsStore,
StorageBackend<String, SecurityConfiguration> securityConfigurationStore,
StorageBackend<String, DataQualityRuleset> dataQualityRulesetStore,
StorageBackend<String, Trigger> triggerStore,
StorageBackend<String, Workflow> 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<String, String> 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<DataQualityRuleset> listDataQualityRulesets(DataQualityRulesetFilter filter, Map<String, String> tags,
Integer maxResults, String nextToken, String region) {
return paginate(() -> {
String prefix = region + ":";
String accountId = regionResolver.getAccountId();
List<DataQualityRuleset> 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<T>(List<T> items, String nextToken) {}
<T> Page<T> paginate(List<T> all, Integer maxResults, String nextToken) {
@@ -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; }
}
@@ -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<String> 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";
}
}
@@ -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 {
@@ -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<String, GluePolicy>(),
new InMemoryStorage<String, DataCatalogEncryptionSettings>(),
new InMemoryStorage<String, SecurityConfiguration>(),
new InMemoryStorage<String, DataQualityRuleset>(),
new InMemoryStorage<String, Trigger>(),
new InMemoryStorage<String, Workflow>(),
schemaRegistryService, regionResolver, new ResourceGroupsTaggingService(null), kmsService);