diff --git a/docs/services/glue.md b/docs/services/glue.md index 12618b6929..f323578538 100644 --- a/docs/services/glue.md +++ b/docs/services/glue.md @@ -84,6 +84,16 @@ only arises from a backfill failure. | UpdateCrawler | Updates a crawler. | | DeleteCrawler | Removes a specified crawler from the AWS Glue Data Catalog. | +#### Classifiers + +| Action | Description | +|--------|-------------| +| CreateClassifier | Creates a Grok, XML, JSON, or CSV classifier. | +| GetClassifier | Retrieves a classifier by name. | +| GetClassifiers | Lists classifiers, paged by `MaxResults` and `NextToken`. | +| UpdateClassifier | Partially updates a classifier without changing its type. | +| DeleteClassifier | Deletes a classifier by name. | + ### Schema Registry #### Registries 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 4694a53a49..e0216f8317 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 @@ -235,6 +235,27 @@ public class GlueJsonHandler { glueService.deleteJob(req.getJobName(), region); yield Response.ok(new DeleteJobResponse(req.getJobName())).build(); } + case "CreateClassifier" -> { + Classifier classifier = mapper.treeToValue(request, Classifier.class); + glueService.createClassifier(classifier); + yield Response.ok().build(); + } + case "GetClassifier" -> Response.ok(Map.of( + "Classifier", glueService.getClassifier(request.path("Name").asText(null)))).build(); + case "GetClassifiers" -> { + GlueService.Page page = glueService.getClassifiers( + readMaxResults(request), readNextToken(request)); + yield Response.ok(pageResponse("Classifiers", page.items(), page.nextToken())).build(); + } + case "UpdateClassifier" -> { + Classifier classifier = mapper.treeToValue(request, Classifier.class); + glueService.updateClassifier(classifier); + yield Response.ok().build(); + } + case "DeleteClassifier" -> { + glueService.deleteClassifier(request.path("Name").asText(null)); + yield Response.ok().build(); + } case "CreateCrawler" -> { CreateCrawlerRequest req = mapper.treeToValue(request, CreateCrawlerRequest.class); Crawler crawler = toDomain(req); 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 36c2781a8f..619cb1d9d4 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 @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.glue.model.Classifier; import io.github.hectorvent.floci.services.glue.model.Column; import io.github.hectorvent.floci.services.glue.model.Crawler; import io.github.hectorvent.floci.services.glue.model.CrawlerTargets; @@ -41,6 +42,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; @@ -51,6 +53,11 @@ public class GlueService { private static final Logger LOG = Logger.getLogger(GlueService.class); private static final int MAX_FUNCTION_PATTERN_LENGTH = 255; private static final int MAX_FUNCTION_RESULTS = 100; + 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( + "BINARY", "BOOLEAN", "DATE", "DECIMAL", "DOUBLE", "FLOAT", + "INT", "LONG", "SHORT", "STRING", "TIMESTAMP"); static final String COLUMN_NAME = "ColumnName"; static final String COLUMN_TYPE = "ColumnType"; static final String ANALYZED_TIME = "AnalyzedTime"; @@ -81,6 +88,7 @@ public class GlueService { private final StorageBackend functionStore; private final StorageBackend jobStore; private final StorageBackend crawlerStore; + private final StorageBackend classifierStore; private final GlueSchemaRegistryService schemaRegistryService; private final RegionResolver regionResolver; private final ResourceGroupsTaggingService resourceGroupsTaggingService; @@ -102,6 +110,7 @@ public class GlueService { this.functionStore = storageFactory.create("glue", "functions.json", new TypeReference<>() {}); this.jobStore = storageFactory.create("glue", "jobs.json", new TypeReference<>() {}); this.crawlerStore = storageFactory.create("glue", "crawlers.json", new TypeReference<>() {}); + this.classifierStore = storageFactory.create("glue", "classifiers.json", new TypeReference<>() {}); this.schemaRegistryService = schemaRegistryService; this.regionResolver = regionResolver; this.resourceGroupsTaggingService = resourceGroupsTaggingService; @@ -117,6 +126,7 @@ public class GlueService { StorageBackend functionStore, StorageBackend jobStore, StorageBackend crawlerStore, + StorageBackend classifierStore, GlueSchemaRegistryService schemaRegistryService, RegionResolver regionResolver, ResourceGroupsTaggingService resourceGroupsTaggingService) { @@ -130,6 +140,7 @@ public class GlueService { this.functionStore = functionStore; this.jobStore = jobStore; this.crawlerStore = crawlerStore; + this.classifierStore = classifierStore; this.schemaRegistryService = schemaRegistryService; this.regionResolver = regionResolver; this.resourceGroupsTaggingService = resourceGroupsTaggingService; @@ -1621,6 +1632,166 @@ public class GlueService { LOG.infov("Deleted Glue Job: {0}", name); } + public void createClassifier(Classifier classifier) { + validateClassifierShape(classifier); + String name = classifier.name(); + validateClassifierName(name); + if (classifierStore.get(name).isPresent()) { + throw new AwsException("AlreadyExistsException", "Classifier " + name + " already exists.", 400); + } + + Map details = new LinkedHashMap<>(classifier.selectedDetails()); + validateClassifierDetails(classifier.selectedKind(), details); + double now = Instant.now().toEpochMilli() / 1000.0d; + details.put("CreationTime", now); + details.put("LastUpdated", now); + details.put("Version", 1L); + classifierStore.put(name, classifier.copyWithDetails(details)); + LOG.infov("Created Glue Classifier: {0}", name); + } + + public Classifier getClassifier(String name) { + validateClassifierName(name); + return classifierStore.get(name) + .orElseThrow(() -> new AwsException( + "EntityNotFoundException", "Classifier " + name + " not found.", 400)); + } + + public Page getClassifiers(Integer maxResults, String nextToken) { + List classifiers = classifierStore.scan(key -> true); + classifiers.sort(Comparator.comparing(Classifier::name)); + return paginate(classifiers, maxResults, nextToken); + } + + public void updateClassifier(Classifier update) { + validateClassifierShape(update); + String name = update.name(); + validateClassifierName(name); + Classifier existing = getClassifier(name); + if (!existing.selectedKind().equals(update.selectedKind())) { + throw new AwsException("InvalidInputException", "Classifier type cannot be changed.", 400); + } + + Map details = new LinkedHashMap<>(existing.selectedDetails()); + update.selectedDetails().forEach((key, value) -> { + if (!"CreationTime".equals(key) && !"LastUpdated".equals(key) && !"Version".equals(key)) { + details.put(key, value); + } + }); + validateClassifierDetails(existing.selectedKind(), details); + Number version = (Number) existing.selectedDetails().get("Version"); + details.put("CreationTime", existing.selectedDetails().get("CreationTime")); + details.put("LastUpdated", Instant.now().toEpochMilli() / 1000.0d); + details.put("Version", (version == null ? 1L : version.longValue()) + 1L); + classifierStore.put(name, existing.copyWithDetails(details)); + LOG.infov("Updated Glue Classifier: {0}", name); + } + + public void deleteClassifier(String name) { + validateClassifierName(name); + if (classifierStore.get(name).isEmpty()) { + throw new AwsException("EntityNotFoundException", "Classifier " + name + " not found.", 400); + } + classifierStore.delete(name); + LOG.infov("Deleted Glue Classifier: {0}", name); + } + + private void validateClassifierShape(Classifier classifier) { + if (classifier == null || classifier.selectedKindCount() != 1) { + throw new AwsException( + "InvalidInputException", "Exactly one classifier type must be specified.", 400); + } + } + + private void validateClassifierName(String name) { + validateRequired(name, "Name"); + if (name.length() > 255 || name.indexOf('\r') >= 0 || name.indexOf('\n') >= 0) { + throw new AwsException("InvalidInputException", "Name must be between 1 and 255 characters.", 400); + } + } + + private void validateClassifierDetails(String kind, Map details) { + validateClassifierName(stringValue(details, "Name", true)); + switch (kind) { + case "GrokClassifier" -> validateGrokClassifier(details); + case "XMLClassifier" -> stringValue(details, "Classification", true); + case "JsonClassifier" -> stringValue(details, "JsonPath", true); + case "CsvClassifier" -> validateCsvClassifier(details); + default -> throw new AwsException("InvalidInputException", "Unsupported classifier type.", 400); + } + } + + private void validateGrokClassifier(Map details) { + stringValue(details, "Classification", true); + String grokPattern = stringValue(details, "GrokPattern", true); + if (grokPattern.length() > 2048) { + throw new AwsException("InvalidInputException", "GrokPattern must not exceed 2048 characters.", 400); + } + String customPatterns = stringValue(details, "CustomPatterns", false); + if (customPatterns != null && customPatterns.length() > 16000) { + throw new AwsException("InvalidInputException", "CustomPatterns must not exceed 16000 characters.", 400); + } + } + + private void validateCsvClassifier(Map details) { + String delimiter = validateSingleCharacter(details, "Delimiter"); + String quoteSymbol = validateSingleCharacter(details, "QuoteSymbol"); + if (delimiter != null && delimiter.equals(quoteSymbol)) { + throw new AwsException( + "InvalidInputException", "QuoteSymbol must be different from Delimiter.", 400); + } + validateEnum(details, "ContainsHeader", CSV_HEADER_VALUES); + validateEnum(details, "Serde", CSV_SERDE_VALUES); + validateStringList(details, "Header", null); + validateStringList(details, "CustomDatatypes", CSV_CUSTOM_DATATYPES); + } + + private String validateSingleCharacter(Map details, String field) { + String value = stringValue(details, field, false); + if (value != null && (value.codePointCount(0, value.length()) != 1 + || value.indexOf('\r') >= 0 || value.indexOf('\n') >= 0)) { + throw new AwsException("InvalidInputException", field + " must be exactly one character.", 400); + } + return value; + } + + private void validateEnum(Map details, String field, Set allowed) { + String value = stringValue(details, field, false); + if (value != null && !allowed.contains(value)) { + throw new AwsException("InvalidInputException", "Invalid " + field + ": " + value, 400); + } + } + + private void validateStringList(Map details, String field, Set allowed) { + Object value = details.get(field); + if (value == null) { + return; + } + if (!(value instanceof List values)) { + throw new AwsException("InvalidInputException", field + " must be a list.", 400); + } + for (Object item : values) { + if (!(item instanceof String text) || text.isEmpty() || text.length() > 255 + || (allowed != null && !allowed.contains(text))) { + throw new AwsException("InvalidInputException", "Invalid value in " + field + ".", 400); + } + } + } + + private String stringValue(Map details, String field, boolean required) { + Object value = details.get(field); + if (value == null) { + if (required) { + throw new AwsException("InvalidInputException", field + " is required.", 400); + } + return null; + } + if (!(value instanceof String text) || (required && text.isBlank())) { + throw new AwsException("InvalidInputException", field + " must be a string.", 400); + } + return text; + } + public void createCrawler(Crawler crawler) { createCrawler(crawler, null, regionResolver.getDefaultRegion()); } diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/model/Classifier.java b/src/main/java/io/github/hectorvent/floci/services/glue/model/Classifier.java new file mode 100644 index 0000000000..24bf6fb9f8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/glue/model/Classifier.java @@ -0,0 +1,94 @@ +package io.github.hectorvent.floci.services.glue.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.LinkedHashMap; +import java.util.Map; + +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Classifier { + @JsonProperty("GrokClassifier") + private Map grokClassifier; + + @JsonProperty("XMLClassifier") + private Map xmlClassifier; + + @JsonProperty("JsonClassifier") + private Map jsonClassifier; + + @JsonProperty("CsvClassifier") + private Map csvClassifier; + + public Classifier() {} + + public Map getGrokClassifier() { return grokClassifier; } + public void setGrokClassifier(Map grokClassifier) { this.grokClassifier = grokClassifier; } + + public Map getXmlClassifier() { return xmlClassifier; } + public void setXmlClassifier(Map xmlClassifier) { this.xmlClassifier = xmlClassifier; } + + public Map getJsonClassifier() { return jsonClassifier; } + public void setJsonClassifier(Map jsonClassifier) { this.jsonClassifier = jsonClassifier; } + + public Map getCsvClassifier() { return csvClassifier; } + public void setCsvClassifier(Map csvClassifier) { this.csvClassifier = csvClassifier; } + + public String selectedKind() { + if (grokClassifier != null) { + return "GrokClassifier"; + } + if (xmlClassifier != null) { + return "XMLClassifier"; + } + if (jsonClassifier != null) { + return "JsonClassifier"; + } + if (csvClassifier != null) { + return "CsvClassifier"; + } + return null; + } + + public int selectedKindCount() { + int count = 0; + count += grokClassifier == null ? 0 : 1; + count += xmlClassifier == null ? 0 : 1; + count += jsonClassifier == null ? 0 : 1; + count += csvClassifier == null ? 0 : 1; + return count; + } + + public Map selectedDetails() { + return switch (selectedKind()) { + case "GrokClassifier" -> grokClassifier; + case "XMLClassifier" -> xmlClassifier; + case "JsonClassifier" -> jsonClassifier; + case "CsvClassifier" -> csvClassifier; + case null -> null; + default -> throw new IllegalStateException("Unknown classifier kind"); + }; + } + + public String name() { + Map details = selectedDetails(); + Object name = details == null ? null : details.get("Name"); + return name instanceof String value ? value : null; + } + + public Classifier copyWithDetails(Map details) { + Classifier copy = new Classifier(); + Map copiedDetails = new LinkedHashMap<>(details); + switch (selectedKind()) { + case "GrokClassifier" -> copy.setGrokClassifier(copiedDetails); + case "XMLClassifier" -> copy.setXmlClassifier(copiedDetails); + case "JsonClassifier" -> copy.setJsonClassifier(copiedDetails); + case "CsvClassifier" -> copy.setCsvClassifier(copiedDetails); + case null -> throw new IllegalStateException("Classifier kind is required"); + default -> throw new IllegalStateException("Unknown classifier kind"); + } + return copy; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerTest.java index b7f23ddc12..9c44ec9e7f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueJsonHandlerTest.java @@ -380,6 +380,133 @@ class GlueJsonHandlerTest { assertEquals("cron(0 0 * * ? *)", crawler.get("Schedule").get("ScheduleExpression").asText()); } + @Test + void classifierCrudPreservesPartialUpdatesAndMetadata() throws Exception { + ObjectNode create = mapper.createObjectNode(); + create.putObject("GrokClassifier") + .put("Name", "access-logs") + .put("Classification", "apache") + .put("GrokPattern", "%{COMMONAPACHELOG}") + .put("CustomPatterns", "ORIGINAL value"); + assertEquals(200, handler.handle("CreateClassifier", create, REGION).getStatus()); + + JsonNode created = mapper.valueToTree(body(handler.handle( + "GetClassifier", mapper.createObjectNode().put("Name", "access-logs"), REGION))) + .get("Classifier").get("GrokClassifier"); + assertEquals(1, created.get("Version").asLong()); + assertTrue(created.has("CreationTime")); + assertTrue(created.has("LastUpdated")); + + ObjectNode update = mapper.createObjectNode(); + update.putObject("GrokClassifier") + .put("Name", "access-logs") + .put("Classification", "apache-updated"); + assertEquals(200, handler.handle("UpdateClassifier", update, REGION).getStatus()); + + JsonNode updated = mapper.valueToTree(body(handler.handle( + "GetClassifier", mapper.createObjectNode().put("Name", "access-logs"), REGION))) + .get("Classifier").get("GrokClassifier"); + assertEquals("apache-updated", updated.get("Classification").asText()); + assertEquals("%{COMMONAPACHELOG}", updated.get("GrokPattern").asText()); + assertEquals("ORIGINAL value", updated.get("CustomPatterns").asText()); + assertEquals(created.get("CreationTime"), updated.get("CreationTime")); + assertEquals(2, updated.get("Version").asLong()); + + assertEquals(200, handler.handle( + "DeleteClassifier", mapper.createObjectNode().put("Name", "access-logs"), REGION).getStatus()); + AwsException missing = assertThrows(AwsException.class, () -> handler.handle( + "GetClassifier", mapper.createObjectNode().put("Name", "access-logs"), REGION)); + assertEquals("EntityNotFoundException", missing.getErrorCode()); + } + + @Test + void allClassifierKindsRoundTripAndListsArePaginatedByName() throws Exception { + ObjectNode grok = mapper.createObjectNode(); + grok.putObject("GrokClassifier") + .put("Name", "d-grok") + .put("Classification", "logs") + .put("GrokPattern", "%{GREEDYDATA:message}"); + ObjectNode json = mapper.createObjectNode(); + json.putObject("JsonClassifier").put("Name", "b-json").put("JsonPath", "$.records[*]"); + ObjectNode xml = mapper.createObjectNode(); + xml.putObject("XMLClassifier") + .put("Name", "a-xml") + .put("Classification", "xml") + .put("RowTag", "record"); + ObjectNode csv = mapper.createObjectNode(); + csv.putObject("CsvClassifier") + .put("Name", "c-csv") + .put("Delimiter", ",") + .put("QuoteSymbol", "\"") + .put("ContainsHeader", "PRESENT") + .put("Serde", "OpenCSVSerDe") + .putArray("CustomDatatypes").add("STRING").add("TIMESTAMP"); + assertEquals(200, handler.handle("CreateClassifier", grok, REGION).getStatus()); + assertEquals(200, handler.handle("CreateClassifier", json, REGION).getStatus()); + assertEquals(200, handler.handle("CreateClassifier", xml, REGION).getStatus()); + assertEquals(200, handler.handle("CreateClassifier", csv, REGION).getStatus()); + + ObjectNode firstRequest = mapper.createObjectNode().put("MaxResults", 2); + JsonNode first = mapper.valueToTree(body(handler.handle("GetClassifiers", firstRequest, REGION))); + assertEquals(2, first.get("Classifiers").size()); + assertEquals("a-xml", first.get("Classifiers").get(0).get("XMLClassifier").get("Name").asText()); + assertEquals("b-json", first.get("Classifiers").get(1).get("JsonClassifier").get("Name").asText()); + assertEquals("2", first.get("NextToken").asText()); + + ObjectNode secondRequest = mapper.createObjectNode().put("MaxResults", 2).put("NextToken", "2"); + JsonNode second = mapper.valueToTree(body(handler.handle("GetClassifiers", secondRequest, REGION))); + assertEquals(2, second.get("Classifiers").size()); + assertEquals("c-csv", second.get("Classifiers").get(0).get("CsvClassifier").get("Name").asText()); + assertEquals("d-grok", second.get("Classifiers").get(1).get("GrokClassifier").get("Name").asText()); + assertTrue(!second.has("NextToken")); + } + + @Test + void classifierValidationRejectsAmbiguousAndInvalidRequests() throws Exception { + ObjectNode ambiguous = mapper.createObjectNode(); + ambiguous.putObject("JsonClassifier").put("Name", "ambiguous").put("JsonPath", "$"); + ambiguous.putObject("XMLClassifier").put("Name", "ambiguous").put("Classification", "xml"); + assertClassifierError("InvalidInputException", "CreateClassifier", ambiguous); + + ObjectNode invalidCsv = mapper.createObjectNode(); + invalidCsv.putObject("CsvClassifier") + .put("Name", "invalid-csv") + .put("Delimiter", ",") + .put("QuoteSymbol", ",") + .put("ContainsHeader", "MAYBE"); + assertClassifierError("InvalidInputException", "CreateClassifier", invalidCsv); + + ObjectNode invalidGrok = mapper.createObjectNode(); + invalidGrok.putObject("GrokClassifier") + .put("Name", "invalid-grok") + .put("Classification", "logs"); + assertClassifierError("InvalidInputException", "CreateClassifier", invalidGrok); + } + + @Test + void classifierCreateUpdateAndDeleteUseAwsErrors() throws Exception { + ObjectNode create = mapper.createObjectNode(); + create.putObject("JsonClassifier").put("Name", "events").put("JsonPath", "$.events[*]"); + assertEquals(200, handler.handle("CreateClassifier", create, REGION).getStatus()); + assertClassifierError("AlreadyExistsException", "CreateClassifier", create); + + ObjectNode wrongKind = mapper.createObjectNode(); + wrongKind.putObject("XMLClassifier").put("Name", "events").put("Classification", "xml"); + assertClassifierError("InvalidInputException", "UpdateClassifier", wrongKind); + + ObjectNode missing = mapper.createObjectNode(); + missing.putObject("JsonClassifier").put("Name", "missing").put("JsonPath", "$"); + assertClassifierError("EntityNotFoundException", "UpdateClassifier", missing); + assertClassifierError("EntityNotFoundException", "DeleteClassifier", + mapper.createObjectNode().put("Name", "missing")); + } + + private void assertClassifierError(String errorCode, String action, JsonNode request) { + AwsException exception = assertThrows(AwsException.class, + () -> handler.handle(action, request, REGION)); + assertEquals(errorCode, exception.getErrorCode()); + } + @Test void createJobSucceeds() throws Exception { ObjectNode request = mapper.createObjectNode(); 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 80bda3da9f..0f67444e87 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 @@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.glue.model.Classifier; import io.github.hectorvent.floci.services.glue.model.Column; import io.github.hectorvent.floci.services.glue.model.Database; import io.github.hectorvent.floci.services.glue.model.Crawler; @@ -86,6 +87,7 @@ class GlueServiceTest { new InMemoryStorage(), new InMemoryStorage(), new InMemoryStorage(), + new InMemoryStorage(), schemaRegistryService, regionResolver, new ResourceGroupsTaggingService(null)); glueService.createDatabase(new Database("db1")); }