diff --git a/src/main/java/io/github/hectorvent/floci/services/athena/AthenaJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/athena/AthenaJsonHandler.java index 1c6ce97e0f..29cd4ba688 100644 --- a/src/main/java/io/github/hectorvent/floci/services/athena/AthenaJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/athena/AthenaJsonHandler.java @@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.athena; 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.services.athena.model.CreateWorkGroupRequest; import io.github.hectorvent.floci.services.athena.model.QueryExecution; import io.github.hectorvent.floci.services.athena.model.QueryExecutionContext; import io.github.hectorvent.floci.services.athena.model.ResultConfiguration; @@ -68,7 +69,11 @@ public class AthenaJsonHandler { yield Response.ok(Map.of("WorkGroup", athenaService.getWorkGroup(name))).build(); } case "ListWorkGroups" -> Response.ok(Map.of("WorkGroups", athenaService.listWorkGroups())).build(); - case "CreateWorkGroup" -> Response.ok(Map.of()).build(); + case "CreateWorkGroup" -> { + CreateWorkGroupRequest createRequest = mapper.treeToValue(request, CreateWorkGroupRequest.class); + athenaService.createWorkGroup(createRequest, region); + yield Response.ok(Map.of()).build(); + } case "ListDataCatalogs" -> Response.ok(Map.of("DataCatalogsSummary", athenaService.listDataCatalogs())).build(); case "GetDataCatalog" -> { String name = request.has("Name") ? request.get("Name").asText() : AthenaService.DEFAULT_CATALOG; diff --git a/src/main/java/io/github/hectorvent/floci/services/athena/AthenaService.java b/src/main/java/io/github/hectorvent/floci/services/athena/AthenaService.java index 9d742b93e9..97d5859f6b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/athena/AthenaService.java +++ b/src/main/java/io/github/hectorvent/floci/services/athena/AthenaService.java @@ -32,8 +32,11 @@ public class AthenaService { private static final Logger LOG = Logger.getLogger(AthenaService.class); public static final String DEFAULT_CATALOG = "AwsDataCatalog"; private static final String DEFAULT_OUTPUT_BUCKET = "floci-athena-results"; + private static final String DEFAULT_WORKGROUP = "primary"; + private static final String DEFAULT_ENGINE_VERSION = "Athena engine version 3"; private final StorageBackend queryStore; + private final StorageBackend workGroupStore; private final FlociDuckClient duckClient; private final GlueService glueService; private final S3Service s3Service; @@ -49,6 +52,8 @@ public class AthenaService { Vertx vertx) { this.queryStore = storageFactory.create("athena", "queries.json", new TypeReference<>() {}); + this.workGroupStore = storageFactory.create("athena", "workgroups.json", + new TypeReference<>() {}); this.duckClient = duckClient; this.glueService = glueService; this.s3Service = s3Service; @@ -122,14 +127,36 @@ public class AthenaService { queryStore.put(id, execution); } + public WorkGroup createWorkGroup(CreateWorkGroupRequest request, String region) { + validateWorkGroupName(request.getName()); + if (DEFAULT_WORKGROUP.equals(request.getName())) { + throw new AwsException("InvalidRequestException", + DEFAULT_WORKGROUP + " workGroup could not be created", 400); + } + String key = workGroupKey(region, request.getName()); + if (workGroupStore.get(key).isPresent()) { + throw new AwsException("InvalidRequestException", "WorkGroup already exists", 400); + } + + WorkGroup workGroup = new WorkGroup(); + workGroup.setName(request.getName()); + workGroup.setDescription(request.getDescription()); + workGroup.setState("ENABLED"); + workGroup.setCreationTime(Instant.now()); + workGroup.setTags(normalizeTags(request.getTags())); + workGroup.setConfiguration(normalizeWorkGroupConfiguration(request.getConfiguration())); + workGroupStore.put(key, workGroup); + return workGroup; + } + public Map getWorkGroup(String name) { return Map.of( - "Name", name == null || name.isBlank() ? "primary" : name, + "Name", name == null || name.isBlank() ? DEFAULT_WORKGROUP : name, "State", "ENABLED", "Configuration", Map.of( "EngineVersion", Map.of( - "SelectedEngineVersion", "Athena engine version 3", - "EffectiveEngineVersion", "Athena engine version 3" + "SelectedEngineVersion", DEFAULT_ENGINE_VERSION, + "EffectiveEngineVersion", DEFAULT_ENGINE_VERSION ), "ResultConfiguration", Map.of("OutputLocation", "s3://" + DEFAULT_OUTPUT_BUCKET + "/results/"), "EnforceWorkGroupConfiguration", false, @@ -140,7 +167,7 @@ public class AthenaService { } public List> listWorkGroups() { - return List.of(Map.of("Name", "primary", "State", "ENABLED")); + return List.of(Map.of("Name", DEFAULT_WORKGROUP, "State", "ENABLED")); } public List> listDataCatalogs() { @@ -251,6 +278,91 @@ public class AthenaService { return base.endsWith("/") ? base + queryId + "/" : base + "/" + queryId + "/"; } + private WorkGroupConfiguration normalizeWorkGroupConfiguration(CreateWorkGroupConfigurationRequest configuration) { + WorkGroupConfiguration normalized = defaultWorkGroupConfiguration(); + if (configuration == null) { + return normalized; + } + + if (configuration.getResultConfiguration() != null + && configuration.getResultConfiguration().getOutputLocation() != null + && !configuration.getResultConfiguration().getOutputLocation().isBlank()) { + normalized.setResultConfiguration( + new ResultConfiguration(configuration.getResultConfiguration().getOutputLocation())); + } + if (configuration.getEnforceWorkGroupConfiguration() != null) { + normalized.setEnforceWorkGroupConfiguration(configuration.getEnforceWorkGroupConfiguration()); + } + if (configuration.getPublishCloudWatchMetricsEnabled() != null) { + normalized.setPublishCloudWatchMetricsEnabled(configuration.getPublishCloudWatchMetricsEnabled()); + } + if (configuration.getRequesterPaysEnabled() != null) { + normalized.setRequesterPaysEnabled(configuration.getRequesterPaysEnabled()); + } + if (configuration.getBytesScannedCutoffPerQuery() != null) { + normalized.setBytesScannedCutoffPerQuery(configuration.getBytesScannedCutoffPerQuery()); + } + if (configuration.getEngineVersion() != null) { + String selectedEngineVersion = configuration.getEngineVersion().getSelectedEngineVersion(); + boolean hasSelectedEngineVersion = selectedEngineVersion != null && !selectedEngineVersion.isBlank(); + + if (hasSelectedEngineVersion) { + QueryExecution.EngineVersion engineVersion = new QueryExecution.EngineVersion(); + engineVersion.setSelectedEngineVersion(selectedEngineVersion); + engineVersion.setEffectiveEngineVersion(resolveEffectiveEngineVersion(selectedEngineVersion)); + normalized.setEngineVersion(engineVersion); + } + } + return normalized; + } + + private String resolveEffectiveEngineVersion(String selectedEngineVersion) { + if (selectedEngineVersion == null || selectedEngineVersion.isBlank() || "AUTO".equals(selectedEngineVersion)) { + return DEFAULT_ENGINE_VERSION; + } + return selectedEngineVersion; + } + + private WorkGroupConfiguration defaultWorkGroupConfiguration() { + WorkGroupConfiguration configuration = new WorkGroupConfiguration(); + configuration.setResultConfiguration(new ResultConfiguration("s3://" + DEFAULT_OUTPUT_BUCKET + "/results/")); + configuration.setEnforceWorkGroupConfiguration(false); + configuration.setPublishCloudWatchMetricsEnabled(false); + configuration.setRequesterPaysEnabled(false); + configuration.setEngineVersion(defaultEngineVersion()); + return configuration; + } + + private QueryExecution.EngineVersion defaultEngineVersion() { + QueryExecution.EngineVersion engineVersion = new QueryExecution.EngineVersion(); + engineVersion.setSelectedEngineVersion(DEFAULT_ENGINE_VERSION); + engineVersion.setEffectiveEngineVersion(DEFAULT_ENGINE_VERSION); + return engineVersion; + } + + private List normalizeTags(List tags) { + if (tags == null || tags.isEmpty()) { + return List.of(); + } + return tags.stream() + .filter(Objects::nonNull) + .map(tag -> new WorkGroupTag(tag.getKey(), tag.getValue())) + .toList(); + } + + private String workGroupKey(String region, String name) { + return region + ":" + name; + } + + private void validateWorkGroupName(String name) { + if (name == null || name.isBlank()) { + throw new AwsException("InvalidRequestException", "WorkGroup name is required", 400); + } + if (!name.matches("[A-Za-z0-9._-]{1,128}")) { + throw new AwsException("InvalidRequestException", "Invalid WorkGroup name: " + name, 400); + } + } + private void ensureOutputBucket(String s3Path) { String bucket = extractBucket(s3Path); if (bucket != null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/athena/model/CreateWorkGroupConfigurationRequest.java b/src/main/java/io/github/hectorvent/floci/services/athena/model/CreateWorkGroupConfigurationRequest.java new file mode 100644 index 0000000000..00a51778a2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/athena/model/CreateWorkGroupConfigurationRequest.java @@ -0,0 +1,49 @@ +package io.github.hectorvent.floci.services.athena.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public class CreateWorkGroupConfigurationRequest { + + @JsonProperty("ResultConfiguration") + private ResultConfiguration resultConfiguration; + + @JsonProperty("EnforceWorkGroupConfiguration") + private Boolean enforceWorkGroupConfiguration; + + @JsonProperty("PublishCloudWatchMetricsEnabled") + private Boolean publishCloudWatchMetricsEnabled; + + @JsonProperty("RequesterPaysEnabled") + private Boolean requesterPaysEnabled; + + @JsonProperty("BytesScannedCutoffPerQuery") + private Long bytesScannedCutoffPerQuery; + + @JsonProperty("EngineVersion") + private WorkGroupEngineVersionRequest engineVersion; + + public CreateWorkGroupConfigurationRequest() {} + + public ResultConfiguration getResultConfiguration() { return resultConfiguration; } + public void setResultConfiguration(ResultConfiguration resultConfiguration) { + this.resultConfiguration = resultConfiguration; + } + public Boolean getEnforceWorkGroupConfiguration() { return enforceWorkGroupConfiguration; } + public void setEnforceWorkGroupConfiguration(Boolean enforceWorkGroupConfiguration) { + this.enforceWorkGroupConfiguration = enforceWorkGroupConfiguration; + } + public Boolean getPublishCloudWatchMetricsEnabled() { return publishCloudWatchMetricsEnabled; } + public void setPublishCloudWatchMetricsEnabled(Boolean publishCloudWatchMetricsEnabled) { + this.publishCloudWatchMetricsEnabled = publishCloudWatchMetricsEnabled; + } + public Boolean getRequesterPaysEnabled() { return requesterPaysEnabled; } + public void setRequesterPaysEnabled(Boolean requesterPaysEnabled) { this.requesterPaysEnabled = requesterPaysEnabled; } + public Long getBytesScannedCutoffPerQuery() { return bytesScannedCutoffPerQuery; } + public void setBytesScannedCutoffPerQuery(Long bytesScannedCutoffPerQuery) { + this.bytesScannedCutoffPerQuery = bytesScannedCutoffPerQuery; + } + public WorkGroupEngineVersionRequest getEngineVersion() { return engineVersion; } + public void setEngineVersion(WorkGroupEngineVersionRequest engineVersion) { this.engineVersion = engineVersion; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/athena/model/CreateWorkGroupRequest.java b/src/main/java/io/github/hectorvent/floci/services/athena/model/CreateWorkGroupRequest.java new file mode 100644 index 0000000000..1fd4bb9f7e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/athena/model/CreateWorkGroupRequest.java @@ -0,0 +1,33 @@ +package io.github.hectorvent.floci.services.athena.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; + +@RegisterForReflection +public class CreateWorkGroupRequest { + + @JsonProperty("Name") + private String name; + + @JsonProperty("Description") + private String description; + + @JsonProperty("Tags") + private List tags; + + @JsonProperty("Configuration") + private CreateWorkGroupConfigurationRequest configuration; + + public CreateWorkGroupRequest() {} + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } + public CreateWorkGroupConfigurationRequest getConfiguration() { return configuration; } + public void setConfiguration(CreateWorkGroupConfigurationRequest configuration) { this.configuration = configuration; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/athena/model/WorkGroup.java b/src/main/java/io/github/hectorvent/floci/services/athena/model/WorkGroup.java new file mode 100644 index 0000000000..3d98ce7eda --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/athena/model/WorkGroup.java @@ -0,0 +1,45 @@ +package io.github.hectorvent.floci.services.athena.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +@RegisterForReflection +public class WorkGroup { + + @JsonProperty("Name") + private String name; + + @JsonProperty("Description") + private String description; + + @JsonProperty("State") + private String state; + + @JsonProperty("CreationTime") + private Instant creationTime; + + @JsonProperty("Tags") + private List tags = new ArrayList<>(); + + @JsonProperty("Configuration") + private WorkGroupConfiguration configuration; + + public WorkGroup() {} + + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + public String getState() { return state; } + public void setState(String state) { this.state = state; } + public Instant getCreationTime() { return creationTime; } + public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } + public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } + public WorkGroupConfiguration getConfiguration() { return configuration; } + public void setConfiguration(WorkGroupConfiguration configuration) { this.configuration = configuration; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/athena/model/WorkGroupConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/athena/model/WorkGroupConfiguration.java new file mode 100644 index 0000000000..762bcd1375 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/athena/model/WorkGroupConfiguration.java @@ -0,0 +1,47 @@ +package io.github.hectorvent.floci.services.athena.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public class WorkGroupConfiguration { + + @JsonProperty("ResultConfiguration") + private ResultConfiguration resultConfiguration; + + @JsonProperty("EnforceWorkGroupConfiguration") + private Boolean enforceWorkGroupConfiguration; + + @JsonProperty("PublishCloudWatchMetricsEnabled") + private Boolean publishCloudWatchMetricsEnabled; + + @JsonProperty("RequesterPaysEnabled") + private Boolean requesterPaysEnabled; + + @JsonProperty("BytesScannedCutoffPerQuery") + private Long bytesScannedCutoffPerQuery; + + @JsonProperty("EngineVersion") + private QueryExecution.EngineVersion engineVersion; + + public WorkGroupConfiguration() {} + + public ResultConfiguration getResultConfiguration() { return resultConfiguration; } + public void setResultConfiguration(ResultConfiguration resultConfiguration) { this.resultConfiguration = resultConfiguration; } + public Boolean getEnforceWorkGroupConfiguration() { return enforceWorkGroupConfiguration; } + public void setEnforceWorkGroupConfiguration(Boolean enforceWorkGroupConfiguration) { + this.enforceWorkGroupConfiguration = enforceWorkGroupConfiguration; + } + public Boolean getPublishCloudWatchMetricsEnabled() { return publishCloudWatchMetricsEnabled; } + public void setPublishCloudWatchMetricsEnabled(Boolean publishCloudWatchMetricsEnabled) { + this.publishCloudWatchMetricsEnabled = publishCloudWatchMetricsEnabled; + } + public Boolean getRequesterPaysEnabled() { return requesterPaysEnabled; } + public void setRequesterPaysEnabled(Boolean requesterPaysEnabled) { this.requesterPaysEnabled = requesterPaysEnabled; } + public Long getBytesScannedCutoffPerQuery() { return bytesScannedCutoffPerQuery; } + public void setBytesScannedCutoffPerQuery(Long bytesScannedCutoffPerQuery) { + this.bytesScannedCutoffPerQuery = bytesScannedCutoffPerQuery; + } + public QueryExecution.EngineVersion getEngineVersion() { return engineVersion; } + public void setEngineVersion(QueryExecution.EngineVersion engineVersion) { this.engineVersion = engineVersion; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/athena/model/WorkGroupEngineVersionRequest.java b/src/main/java/io/github/hectorvent/floci/services/athena/model/WorkGroupEngineVersionRequest.java new file mode 100644 index 0000000000..3411b635d5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/athena/model/WorkGroupEngineVersionRequest.java @@ -0,0 +1,25 @@ +package io.github.hectorvent.floci.services.athena.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public class WorkGroupEngineVersionRequest { + + @JsonProperty("SelectedEngineVersion") + private String selectedEngineVersion; + + @JsonProperty("EffectiveEngineVersion") + private String effectiveEngineVersion; + + public WorkGroupEngineVersionRequest() {} + + public String getSelectedEngineVersion() { return selectedEngineVersion; } + public void setSelectedEngineVersion(String selectedEngineVersion) { + this.selectedEngineVersion = selectedEngineVersion; + } + public String getEffectiveEngineVersion() { return effectiveEngineVersion; } + public void setEffectiveEngineVersion(String effectiveEngineVersion) { + this.effectiveEngineVersion = effectiveEngineVersion; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/athena/model/WorkGroupTag.java b/src/main/java/io/github/hectorvent/floci/services/athena/model/WorkGroupTag.java new file mode 100644 index 0000000000..479318f16d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/athena/model/WorkGroupTag.java @@ -0,0 +1,26 @@ +package io.github.hectorvent.floci.services.athena.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +public class WorkGroupTag { + + @JsonProperty("Key") + private String key; + + @JsonProperty("Value") + private String value; + + public WorkGroupTag() {} + + public WorkGroupTag(String key, String value) { + this.key = key; + this.value = value; + } + + public String getKey() { return key; } + public void setKey(String key) { this.key = key; } + public String getValue() { return value; } + public void setValue(String value) { this.value = value; } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/athena/AthenaCreateWorkGroupIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/athena/AthenaCreateWorkGroupIntegrationTest.java new file mode 100644 index 0000000000..e6fab4bafe --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/athena/AthenaCreateWorkGroupIntegrationTest.java @@ -0,0 +1,138 @@ +package io.github.hectorvent.floci.services.athena; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +@QuarkusTest +class AthenaCreateWorkGroupIntegrationTest { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void createWorkGroupReturnsHttp200WithEmptyJsonObjectBody() { + String responseBody = given() + .header("X-Amz-Target", "AmazonAthena.CreateWorkGroup") + .contentType(CONTENT_TYPE) + .body(""" + { + "Name": "analytics-empty-body" + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + + org.junit.jupiter.api.Assertions.assertEquals("{}", responseBody); + } + + @Test + void createDuplicateWorkGroupReturnsInvalidRequestException() { + String request = """ + { + "Name": "analytics-duplicate" + } + """; + + given() + .header("X-Amz-Target", "AmazonAthena.CreateWorkGroup") + .contentType(CONTENT_TYPE) + .body(request) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", "AmazonAthena.CreateWorkGroup") + .contentType(CONTENT_TYPE) + .body(request) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidRequestException")) + .body("message", equalTo("WorkGroup already exists")); + } + + @Test + void createWorkGroupRejectsPrimaryWorkGroup() { + given() + .header("X-Amz-Target", "AmazonAthena.CreateWorkGroup") + .contentType(CONTENT_TYPE) + .body(""" + { + "Name": "primary" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + } + + @Test + void createWorkGroupRejectsBlankName() { + given() + .header("X-Amz-Target", "AmazonAthena.CreateWorkGroup") + .contentType(CONTENT_TYPE) + .body(""" + { + "Name": "" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + } + + @Test + void createWorkGroupRejectsInvalidCharactersInName() { + given() + .header("X-Amz-Target", "AmazonAthena.CreateWorkGroup") + .contentType(CONTENT_TYPE) + .body(""" + { + "Name": "bad name with spaces" + } + """) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + } + + @Test + void createWorkGroupRejectsTooLongName() { + String tooLongName = "a".repeat(129); + + given() + .header("X-Amz-Target", "AmazonAthena.CreateWorkGroup") + .contentType(CONTENT_TYPE) + .body(""" + { + "Name": "%s" + } + """.formatted(tooLongName)) + .when() + .post("/") + .then() + .statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/athena/AthenaCreateWorkGroupPersistenceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/athena/AthenaCreateWorkGroupPersistenceIntegrationTest.java new file mode 100644 index 0000000000..2a1e1e6a73 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/athena/AthenaCreateWorkGroupPersistenceIntegrationTest.java @@ -0,0 +1,303 @@ +package io.github.hectorvent.floci.services.athena; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.storage.PersistentStorage; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +@TestProfile(AthenaCreateWorkGroupPersistenceIntegrationTest.PersistentStorageProfile.class) +class AthenaCreateWorkGroupPersistenceIntegrationTest { + + static final String STORAGE_DIR = "target/athena-workgroups-it"; + private static final Path WORKGROUPS_FILE = Path.of(STORAGE_DIR, "workgroups.json"); + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + + @BeforeAll + static void setup() throws Exception { + RestAssuredJsonUtils.configureAwsContentTypes(); + Files.deleteIfExists(WORKGROUPS_FILE); + } + + @Test + void createWorkGroupPersistsNormalizedStateWithoutSeedingPrimary() throws Exception { + Files.deleteIfExists(WORKGROUPS_FILE); + + given() + .header("X-Amz-Target", "AmazonAthena.CreateWorkGroup") + .contentType(CONTENT_TYPE) + .body(""" + { + "Name": "analytics", + "Description": "team analytics", + "Tags": [ + { "Key": "env", "Value": "dev" } + ], + "Configuration": { + "ResultConfiguration": { + "OutputLocation": "s3://floci-athena-results/results/" + }, + "EnforceWorkGroupConfiguration": true, + "PublishCloudWatchMetricsEnabled": true, + "RequesterPaysEnabled": true, + "BytesScannedCutoffPerQuery": 10000000, + "EngineVersion": { + "SelectedEngineVersion": "Athena engine version 3" + } + } + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + assertTrue(Files.exists(WORKGROUPS_FILE), "CreateWorkGroup should create workgroups.json"); + + var store = new PersistentStorage>( + WORKGROUPS_FILE, + new TypeReference>>() {}); + store.load(); + + Map persisted = store.get("000000000000/us-east-1:analytics").orElseThrow(); + assertEquals("analytics", persisted.get("Name")); + assertEquals("team analytics", persisted.get("Description")); + assertEquals("ENABLED", persisted.get("State")); + assertNotNull(persisted.get("CreationTime")); + + @SuppressWarnings("unchecked") + List> tags = (List>) persisted.get("Tags"); + assertEquals(List.of(Map.of("Key", "env", "Value", "dev")), tags); + + @SuppressWarnings("unchecked") + Map configuration = (Map) persisted.get("Configuration"); + @SuppressWarnings("unchecked") + Map resultConfiguration = (Map) configuration.get("ResultConfiguration"); + @SuppressWarnings("unchecked") + Map engineVersion = (Map) configuration.get("EngineVersion"); + + assertEquals("s3://floci-athena-results/results/", resultConfiguration.get("OutputLocation")); + assertEquals(true, configuration.get("EnforceWorkGroupConfiguration")); + assertEquals(true, configuration.get("PublishCloudWatchMetricsEnabled")); + assertEquals(true, configuration.get("RequesterPaysEnabled")); + assertEquals(10000000, configuration.get("BytesScannedCutoffPerQuery")); + assertEquals("Athena engine version 3", engineVersion.get("SelectedEngineVersion")); + assertEquals("Athena engine version 3", engineVersion.get("EffectiveEngineVersion")); + + assertFalse(store.get("000000000000/us-east-1:primary").isPresent(), + "primary should be lazy-created later, not written by CreateWorkGroup"); + } + + @Test + void createWorkGroupAppliesDefaultConfigurationWhenOmitted() throws Exception { + Files.deleteIfExists(WORKGROUPS_FILE); + + given() + .header("X-Amz-Target", "AmazonAthena.CreateWorkGroup") + .contentType(CONTENT_TYPE) + .body(""" + { + "Name": "defaulted-workgroup" + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + var store = new PersistentStorage>( + WORKGROUPS_FILE, + new TypeReference>>() {}); + store.load(); + + Map persisted = store.get("000000000000/us-east-1:defaulted-workgroup").orElseThrow(); + @SuppressWarnings("unchecked") + Map configuration = (Map) persisted.get("Configuration"); + @SuppressWarnings("unchecked") + Map resultConfiguration = (Map) configuration.get("ResultConfiguration"); + @SuppressWarnings("unchecked") + Map engineVersion = (Map) configuration.get("EngineVersion"); + @SuppressWarnings("unchecked") + List> tags = (List>) persisted.get("Tags"); + + assertEquals("s3://floci-athena-results/results/", resultConfiguration.get("OutputLocation")); + assertEquals(false, configuration.get("EnforceWorkGroupConfiguration")); + assertEquals(false, configuration.get("PublishCloudWatchMetricsEnabled")); + assertEquals(false, configuration.get("RequesterPaysEnabled")); + assertEquals("Athena engine version 3", engineVersion.get("SelectedEngineVersion")); + assertEquals("Athena engine version 3", engineVersion.get("EffectiveEngineVersion")); + assertEquals(List.of(), tags); + } + + @Test + void createWorkGroupNormalizesEffectiveEngineVersionFromSelectedVersion() throws Exception { + Files.deleteIfExists(WORKGROUPS_FILE); + + given() + .header("X-Amz-Target", "AmazonAthena.CreateWorkGroup") + .contentType(CONTENT_TYPE) + .body(""" + { + "Name": "engine-normalized", + "Configuration": { + "EngineVersion": { + "SelectedEngineVersion": "AUTO" + } + } + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + var store = new PersistentStorage>( + WORKGROUPS_FILE, + new TypeReference>>() {}); + store.load(); + + Map persisted = store.get("000000000000/us-east-1:engine-normalized").orElseThrow(); + @SuppressWarnings("unchecked") + Map configuration = (Map) persisted.get("Configuration"); + @SuppressWarnings("unchecked") + Map engineVersion = (Map) configuration.get("EngineVersion"); + + assertEquals("AUTO", engineVersion.get("SelectedEngineVersion")); + assertEquals("Athena engine version 3", engineVersion.get("EffectiveEngineVersion")); + } + + @Test + void createWorkGroupIgnoresExplicitEffectiveEngineVersionFromRequest() throws Exception { + Files.deleteIfExists(WORKGROUPS_FILE); + + given() + .header("X-Amz-Target", "AmazonAthena.CreateWorkGroup") + .contentType(CONTENT_TYPE) + .body(""" + { + "Name": "engine-explicit", + "Configuration": { + "EngineVersion": { + "SelectedEngineVersion": "AUTO", + "EffectiveEngineVersion": "Athena engine version 3" + } + } + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + var store = new PersistentStorage>( + WORKGROUPS_FILE, + new TypeReference>>() {}); + store.load(); + + Map persisted = store.get("000000000000/us-east-1:engine-explicit").orElseThrow(); + @SuppressWarnings("unchecked") + Map configuration = (Map) persisted.get("Configuration"); + @SuppressWarnings("unchecked") + Map engineVersion = (Map) configuration.get("EngineVersion"); + + assertEquals("AUTO", engineVersion.get("SelectedEngineVersion")); + assertEquals("Athena engine version 3", engineVersion.get("EffectiveEngineVersion")); + } + + @Test + void createWorkGroupKeepsDefaultEngineVersionWhenEngineVersionIsEmpty() throws Exception { + Files.deleteIfExists(WORKGROUPS_FILE); + + given() + .header("X-Amz-Target", "AmazonAthena.CreateWorkGroup") + .contentType(CONTENT_TYPE) + .body(""" + { + "Name": "engine-empty", + "Configuration": { + "EngineVersion": {} + } + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + var store = new PersistentStorage>( + WORKGROUPS_FILE, + new TypeReference>>() {}); + store.load(); + + Map persisted = store.get("000000000000/us-east-1:engine-empty").orElseThrow(); + @SuppressWarnings("unchecked") + Map configuration = (Map) persisted.get("Configuration"); + @SuppressWarnings("unchecked") + Map engineVersion = (Map) configuration.get("EngineVersion"); + + assertEquals("Athena engine version 3", engineVersion.get("SelectedEngineVersion")); + assertEquals("Athena engine version 3", engineVersion.get("EffectiveEngineVersion")); + } + + @Test + void createWorkGroupResolvesBlankSelectedEngineVersionToDefaultEffectiveVersion() throws Exception { + Files.deleteIfExists(WORKGROUPS_FILE); + + given() + .header("X-Amz-Target", "AmazonAthena.CreateWorkGroup") + .contentType(CONTENT_TYPE) + .body(""" + { + "Name": "engine-blank-selected", + "Configuration": { + "EngineVersion": { + "SelectedEngineVersion": "" + } + } + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + var store = new PersistentStorage>( + WORKGROUPS_FILE, + new TypeReference>>() {}); + store.load(); + + Map persisted = store.get("000000000000/us-east-1:engine-blank-selected").orElseThrow(); + @SuppressWarnings("unchecked") + Map configuration = (Map) persisted.get("Configuration"); + @SuppressWarnings("unchecked") + Map engineVersion = (Map) configuration.get("EngineVersion"); + + assertEquals("Athena engine version 3", engineVersion.get("SelectedEngineVersion")); + assertEquals("Athena engine version 3", engineVersion.get("EffectiveEngineVersion")); + } + + public static final class PersistentStorageProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of( + "floci.storage.mode", "persistent", + "floci.storage.persistent-path", STORAGE_DIR + ); + } + } +}