feat(athena): support named queries (#8002)

Closes #8000

Workgroup deletion bypassed saved-query storage and ignored RecursiveDeleteOption. Reject non-recursive deletion when saved queries exist, and remove saved queries and retry records before deleting the workgroup. Serialize deletion with named-query creation to prevent orphaned records.

Vendor all Athena input constraints from pinned botocore and check requests through RequestConstraintCheck. Remove copied named-query bounds and type checks, allow creation without a client request token, and share workgroup scans and isolated test-client setup. Update required-field expectations and cover generation drift, nested constraints, Unicode bounds, and untokened creation.

Move the standard member-constraint Messages implementation and formatter into RequestConstraintCheck, parameterized by error code. Migrate Athena, ECR, and both Payment Cryptography APIs and remove the redundant PaymentCryptographyShapeErrors class. Preserve HTTP 400, existing rule wording, operation-prefix removal, nested list paths, and each service error code with shared contract and service tests.
This commit is contained in:
jwoa95 authored and GitHub committed 2026-11-11 14:08:46 -04:00
1 parent 475fb1822a
commit 77587de2e6
26 files changed
+2533 -144

No files matched your search

@@ -42,6 +42,46 @@ public final class RequestConstraintCheck {
AwsException required(String path);
}
/** Standard member-constraint messages, using the service's error code and HTTP 400. */
public static Messages standardMessages(String errorCode) {
return new Messages() {
@Override
public AwsException type(String path, String type) {
return invalid(path, "Member must be a " + type);
}
@Override
public AwsException bounds(String path, String type, Long min, Long max, long size) {
String measure = "integer".equals(type) || "long".equals(type) ? "value" : "length";
return min != null && size < min
? invalid(path, "Member must have " + measure + " greater than or equal to " + min)
: invalid(path, "Member must have " + measure + " less than or equal to " + max);
}
@Override
public AwsException pattern(String path, String pattern) {
return invalid(path, "must satisfy regular expression '" + pattern + "'");
}
@Override
public AwsException enumValue(String path, List<String> values) {
return invalid(path, "Member must satisfy enum value set: " + values);
}
@Override
public AwsException required(String path) {
return invalid(path, "Member must not be null");
}
private AwsException invalid(String path, String rule) {
int dot = path.indexOf('.');
String member = (dot < 0 ? "" : path.substring(dot + 1)).replace("[]", "");
return new AwsException(errorCode,
"Invalid parameter at '" + member + "' failed to satisfy constraint: '" + rule + "'", 400);
}
};
}
private final JsonNode model;
private final Map<String, Pattern> patterns = new HashMap<>();
private final Messages messages;
@@ -66,6 +106,11 @@ public final class RequestConstraintCheck {
return new RequestConstraintCheck(model, messages);
}
/** Whether the vendored model declares an input for {@code operation}. */
public boolean hasOperation(String operation) {
return model.path("operations").has(operation);
}
/** Checks {@code request}, the body of {@code operation}, against the operation's input shape. */
public void check(String operation, JsonNode request) {
checkValue(model.path("operations").path(operation).asText(), request, operation);
@@ -6,6 +6,7 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.services.athena.model.CreateWorkGroupRequest;
import io.floci.aws.services.athena.model.NamedQuery;
import io.floci.aws.services.athena.model.QueryExecution;
import io.floci.aws.services.athena.model.QueryExecutionContext;
import io.floci.aws.services.athena.model.ResultConfiguration;
@@ -25,16 +26,59 @@ import java.util.Map;
public class AthenaJsonHandler {
private final AthenaService athenaService;
private final AthenaNamedQueryService namedQueryService;
private final ObjectMapper mapper;
@Inject
public AthenaJsonHandler(AthenaService athenaService, ObjectMapper mapper) {
public AthenaJsonHandler(AthenaService athenaService, AthenaNamedQueryService namedQueryService,
ObjectMapper mapper) {
this.athenaService = athenaService;
this.namedQueryService = namedQueryService;
this.mapper = mapper;
}
public Response handle(String action, JsonNode request, String region) throws Exception {
AthenaRequestShapes.check(action, request);
return switch (action) {
case "CreateNamedQuery" -> {
String id = namedQueryService.createNamedQuery(region, text(request, "Name"),
text(request, "Database"), text(request, "QueryString"),
text(request, "Description"), text(request, "WorkGroup"),
text(request, "ClientRequestToken"));
yield Response.ok(Map.of("NamedQueryId", id)).build();
}
case "GetNamedQuery" -> Response.ok(Map.of("NamedQuery",
namedQueryService.getNamedQuery(region, text(request, "NamedQueryId")))).build();
case "BatchGetNamedQuery" -> {
JsonNode ids = request.get("NamedQueryIds");
List<String> queryIds = new ArrayList<>();
for (JsonNode id : ids) {
queryIds.add(id.textValue());
}
yield Response.ok(namedQueryService.batchGetNamedQuery(region, queryIds)).build();
}
case "ListNamedQueries" -> {
PaginatedResult<NamedQuery> page = namedQueryService.listNamedQueries(region,
text(request, "WorkGroup"),
Pagination.parseMaxResults(request, "MaxResults", "InvalidRequestException"),
Pagination.parseNextToken(request, "NextToken", "InvalidRequestException"));
Map<String, Object> response = new LinkedHashMap<>();
response.put("NamedQueryIds", page.items().stream().map(NamedQuery::namedQueryId).toList());
if (page.nextToken() != null) {
response.put("NextToken", page.nextToken());
}
yield Response.ok(response).build();
}
case "UpdateNamedQuery" -> {
namedQueryService.updateNamedQuery(region, text(request, "NamedQueryId"),
text(request, "Name"), text(request, "QueryString"),
text(request, "Description"));
yield Response.ok().build();
}
case "DeleteNamedQuery" -> {
namedQueryService.deleteNamedQuery(region, text(request, "NamedQueryId"));
yield Response.ok().build();
}
case "StartQueryExecution" -> {
String query = request.get("QueryString").asText();
String named = text(request, "WorkGroup");
@@ -173,14 +217,8 @@ public class AthenaJsonHandler {
yield Response.ok(Map.of("Tags", athenaService.listTagsForResource(resourceArn))).build();
}
case "DeleteWorkGroup" -> {
String wg = request.path("WorkGroup").asText(null);
if (wg == null || !wg.matches("[a-zA-Z0-9._-]{1,128}")) {
throw new AwsException("InvalidRequestException", "WorkGroup is required.", 400);
}
if ("primary".equals(wg)) {
throw new AwsException("InvalidRequestException", "The primary workgroup cannot be deleted.", 400);
}
athenaService.deleteWorkGroup(wg, region);
String wg = text(request, "WorkGroup");
namedQueryService.deleteWorkGroup(region, wg, request.path("RecursiveDeleteOption").asBoolean(false));
yield Response.ok(Map.of()).build();
}
default -> throw new AwsException("InvalidAction", "Action " + action + " is not supported", 400);
@@ -0,0 +1,136 @@
package io.floci.aws.services.athena;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.athena.model.NamedQuery;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
@ApplicationScoped
public class AthenaNamedQueryService {
private final StorageBackend<String, NamedQuery> queries;
private final StorageBackend<String, NamedQuery> requests;
private final AthenaService athenaService;
private final RegionResolver regionResolver;
@Inject
public AthenaNamedQueryService(StorageFactory storageFactory, AthenaService athenaService,
RegionResolver regionResolver) {
this.queries = storageFactory.create("athena", "athena-named-queries.json", new TypeReference<>() {});
this.requests = storageFactory.create("athena", "athena-named-query-requests.json", new TypeReference<>() {});
this.athenaService = athenaService;
this.regionResolver = regionResolver;
}
public synchronized String createNamedQuery(String region, String name, String database, String queryString,
String description, String workGroup, String clientRequestToken) {
String group = resolveWorkGroup(workGroup);
NamedQuery previous = clientRequestToken == null ? null : requests.get(key(region, clientRequestToken)).orElse(null);
if (previous != null) {
if (!previous.name().equals(name) || !previous.database().equals(database)
|| !previous.queryString().equals(queryString) || !Objects.equals(previous.description(), description)
|| !previous.workGroup().equals(group)) {
throw invalid("ClientRequestToken has already been used with different parameters.");
}
return previous.namedQueryId();
}
athenaService.getWorkGroup(group, region);
String id = UUID.randomUUID().toString();
NamedQuery query = new NamedQuery(id, name, database, queryString, description, group);
queries.put(key(region, id), query);
if (clientRequestToken != null) {
requests.put(key(region, clientRequestToken), query);
}
return id;
}
public NamedQuery getNamedQuery(String region, String id) {
return queries.get(key(region, id))
.orElseThrow(() -> invalid("Named query " + id + " does not exist."));
}
public Map<String, Object> batchGetNamedQuery(String region, List<String> ids) {
List<NamedQuery> found = new ArrayList<>();
List<Map<String, String>> unprocessed = new ArrayList<>();
for (String id : ids) {
NamedQuery query = queries.get(key(region, id)).orElse(null);
if (query == null) {
unprocessed.add(Map.of("NamedQueryId", id, "ErrorCode", "InvalidRequestException",
"ErrorMessage", "Named query " + id + " does not exist."));
} else {
found.add(query);
}
}
return Map.of("NamedQueries", found, "UnprocessedNamedQueryIds", unprocessed);
}
public PaginatedResult<NamedQuery> listNamedQueries(String region, String workGroup,
Integer maxResults, String nextToken) {
String group = resolveWorkGroup(workGroup);
athenaService.getWorkGroup(group, region);
int limit = maxResults == null || maxResults == 0 ? 50 : maxResults;
return Pagination.paginate(queriesInWorkGroup(region, group), NamedQuery::namedQueryId, limit, nextToken,
"ListNamedQueries:" + regionResolver.getAccountId() + ":" + region + ":" + group,
token -> invalid("Invalid NextToken."));
}
public synchronized void updateNamedQuery(String region, String id, String name,
String queryString, String description) {
NamedQuery previous = getNamedQuery(region, id);
queries.put(key(region, id), new NamedQuery(id, name, previous.database(), queryString,
description == null ? previous.description() : description, previous.workGroup()));
}
public synchronized void deleteNamedQuery(String region, String id) {
queries.delete(key(region, id));
}
public synchronized void deleteWorkGroup(String region, String workGroup, boolean recursive) {
if ("primary".equals(workGroup)) {
throw invalid("The primary workgroup cannot be deleted.");
}
List<NamedQuery> contents = queriesInWorkGroup(region, workGroup);
if (!recursive && !contents.isEmpty()) {
throw invalid("WorkGroup contains named queries. Set RecursiveDeleteOption to true to delete it.");
}
for (NamedQuery query : contents) {
queries.delete(key(region, query.namedQueryId()));
}
for (String requestKey : requests.keys()) {
if (requestKey.startsWith(region + ":") && requests.get(requestKey)
.map(query -> workGroup.equals(query.workGroup())).orElse(false)) {
requests.delete(requestKey);
}
}
athenaService.removeWorkGroup(workGroup, region);
}
private List<NamedQuery> queriesInWorkGroup(String region, String workGroup) {
return queries.scan(k -> k.startsWith(region + ":")).stream()
.filter(query -> workGroup.equals(query.workGroup())).toList();
}
private static String resolveWorkGroup(String workGroup) {
return workGroup == null ? "primary" : workGroup;
}
private static String key(String region, String value) {
return region + ":" + value;
}
private static AwsException invalid(String message) {
return new AwsException("InvalidRequestException", message, 400);
}
}
@@ -0,0 +1,21 @@
package io.floci.aws.services.athena;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.RequestConstraintCheck;
/** Checks Athena requests against the constraints generated by {@code tools/aws/regen_athena_shapes.py}. */
final class AthenaRequestShapes {
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load(
"aws/athena-request-shapes.json", "Athena request shapes",
RequestConstraintCheck.standardMessages("InvalidRequestException"));
private AthenaRequestShapes() {
}
static void check(String operation, JsonNode request) {
if (CHECK.hasOperation(operation)) {
CHECK.check(operation, request);
}
}
}
@@ -326,7 +326,7 @@ public class AthenaService {
workGroupStore.put(workGroupKey(region, workGroup.getName()), workGroup);
}
public void deleteWorkGroup(String name, String region) {
void removeWorkGroup(String name, String region) {
workGroupStore.delete(workGroupKey(region, name));
}
@@ -0,0 +1,14 @@
package io.floci.aws.services.athena.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public record NamedQuery(
@JsonProperty("NamedQueryId") String namedQueryId,
@JsonProperty("Name") String name,
@JsonProperty("Database") String database,
@JsonProperty("QueryString") String queryString,
@JsonProperty("Description") String description,
@JsonProperty("WorkGroup") String workGroup) {
}
@@ -1,11 +1,8 @@
package io.floci.aws.services.ecr;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestConstraintCheck;
import java.util.List;
/**
* Checks an ECR request against the constraints vendored in {@code aws/ecr-request-shapes.json} by
* {@code tools/aws/regen_ecr_shapes.py}. A violation is {@code InvalidParameterException} in ECR's
@@ -16,35 +13,7 @@ final class EcrRequestShapes {
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load(
"aws/ecr-request-shapes.json", "ECR request shapes",
new RequestConstraintCheck.Messages() {
@Override
public AwsException type(String path, String type) {
return invalid(path, "Member must be a " + type);
}
@Override
public AwsException bounds(String path, String type, Long min, Long max, long size) {
String measure = "integer".equals(type) || "long".equals(type) ? "value" : "length";
return min != null && size < min
? invalid(path, "Member must have " + measure + " greater than or equal to " + min)
: invalid(path, "Member must have " + measure + " less than or equal to " + max);
}
@Override
public AwsException pattern(String path, String pattern) {
return invalid(path, "must satisfy regular expression '" + pattern + "'");
}
@Override
public AwsException enumValue(String path, List<String> values) {
return invalid(path, "Member must satisfy enum value set: " + values);
}
@Override
public AwsException required(String path) {
return invalid(path, "Member must not be null");
}
});
RequestConstraintCheck.standardMessages("InvalidParameterException"));
private EcrRequestShapes() {
}
@@ -52,12 +21,4 @@ final class EcrRequestShapes {
static void check(String operation, JsonNode request) {
CHECK.check(operation, request);
}
/** The member's path below the operation, with list elements folded into their list. */
private static AwsException invalid(String path, String rule) {
int dot = path.indexOf('.');
String member = (dot < 0 ? "" : path.substring(dot + 1)).replace("[]", "");
return new AwsException("InvalidParameterException",
"Invalid parameter at '" + member + "' failed to satisfy constraint: '" + rule + "'", 400);
}
}
@@ -18,7 +18,7 @@ final class PaymentCryptographyDataRequestShapes {
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load(
"aws/payment-cryptography-data-request-shapes.json",
"Payment Cryptography data plane request shapes",
PaymentCryptographyShapeErrors.MESSAGES);
RequestConstraintCheck.standardMessages("ValidationException"));
private PaymentCryptographyDataRequestShapes() {
}
@@ -17,7 +17,7 @@ final class PaymentCryptographyRequestShapes {
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load(
"aws/payment-cryptography-request-shapes.json", "Payment Cryptography request shapes",
PaymentCryptographyShapeErrors.MESSAGES);
RequestConstraintCheck.standardMessages("ValidationException"));
private PaymentCryptographyRequestShapes() {
}
@@ -1,59 +0,0 @@
package io.floci.aws.services.paymentcryptography;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestConstraintCheck;
import java.util.List;
/**
* How a Payment Cryptography request that breaks a constraint is refused.
*
* <p>The control plane and the data plane are checked by the same machinery and are worded the
* same way, so the wording is here rather than in each of them. The path a violation names is the
* member's path below the operation, with the list elements folded into their list.
*/
final class PaymentCryptographyShapeErrors {
/** The wording every constraint violation of this service is refused with. */
static final RequestConstraintCheck.Messages MESSAGES = new RequestConstraintCheck.Messages() {
@Override
public AwsException type(String path, String type) {
return invalid(path, "Member must be a " + type);
}
@Override
public AwsException bounds(String path, String type, Long min, Long max, long size) {
String measure = "integer".equals(type) || "long".equals(type) ? "value" : "length";
return min != null && size < min
? invalid(path, "Member must have " + measure + " greater than or equal to " + min)
: invalid(path, "Member must have " + measure + " less than or equal to " + max);
}
@Override
public AwsException pattern(String path, String pattern) {
return invalid(path, "must satisfy regular expression '" + pattern + "'");
}
@Override
public AwsException enumValue(String path, List<String> values) {
return invalid(path, "Member must satisfy enum value set: " + values);
}
@Override
public AwsException required(String path) {
return invalid(path, "Member must not be null");
}
};
private PaymentCryptographyShapeErrors() {
}
/** The violation, as the service refuses it. */
static AwsException invalid(String path, String rule) {
int dot = path.indexOf('.');
String member = (dot < 0 ? "" : path.substring(dot + 1)).replace("[]", "");
return new AwsException("ValidationException",
"Invalid parameter at '" + member + "' failed to satisfy constraint: '" + rule + "'", 400);
}
}