mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
feat(redshift-serverless): validate requests against the AWS model constraints (#5641)
* feat(redshift-serverless): validate requests against the AWS model constraints Generate the input constraints (required members, length, pattern, enum, number range, list size) from botocore's Redshift Serverless model with tools/aws/regen_redshift_serverless_shapes.py and vendor them under src/main/resources/aws, like the DynamoDB request shapes. A new RedshiftServerlessRequestShapes check runs before dispatch and answers a ValidationException. Pagination members are left to the services, which keep reporting InvalidPaginationException. Move the request parsing and error helpers that the JSON handler, the usage limit service and the service each carried a copy of into ServerlessSupport, so the resource families that follow share one implementation. * fix(redshift-serverless): address review findings on request validation - Match a model pattern against the whole value, so an unanchored pattern such as the account id no longer accepts a value that merely contains a match. - Count string lengths in Unicode code points, so a tag of 200 supplementary characters is not rejected for exceeding 256 UTF-16 units. - Validate only the actions the handler implements, so a modeled but unsupported action keeps answering UnknownOperationException. - Read every string member through ServerlessSupport.text and reject a tag key or value that is not a string, so a numeric nextToken or tag member is a ValidationException instead of being treated as absent or coerced. - Regenerate the vendored shapes from botocore 1.43.113, the version tools/aws/requirements.txt pins. - Cover the rejected-request case with a state check, and add the pattern, code point, page token and tag regressions. * refactor(redshift-serverless): use VendoredResources, ServerlessSupport.notFound and update docs
This commit is contained in:
1 parent
340e727ede
commit
77384dc3de
12 files changed
+2040
-277
No files matched your search
@@ -14,6 +14,8 @@
|
||||
# published partition metadata (plus two CDK region rules) by tools/aws/regen_partitions.py.
|
||||
# src/main/resources/aws/dynamodb-request-shapes.json is generated from botocore's DynamoDB
|
||||
# model by tools/aws/regen_dynamodb_shapes.py.
|
||||
# src/main/resources/aws/redshift-serverless-request-shapes.json is generated from botocore's Redshift
|
||||
# Serverless model by tools/aws/regen_redshift_serverless_shapes.py.
|
||||
# API Gateway integration types come from the public service model via tools/aws/regen_apigateway_types.py.
|
||||
|
||||
PYTHON ?= python3
|
||||
@@ -205,6 +207,7 @@ aws-data-sync: ## Regenerate src/main/resources/aws/*.json and the IAM managed-p
|
||||
$(PYTHON) tools/aws/regen_partitions.py
|
||||
$(PYTHON) tools/aws/regen_region_facts.py
|
||||
$(PYTHON) tools/aws/regen_dynamodb_shapes.py
|
||||
$(PYTHON) tools/aws/regen_redshift_serverless_shapes.py
|
||||
$(PYTHON) tools/aws/regen_apigateway_types.py
|
||||
$(PYTHON) tools/aws/regen_managed_policies.py
|
||||
|
||||
@@ -227,6 +230,12 @@ aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
|
||||
echo " Run 'make aws-data-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_redshift_serverless_shapes.py --check || { \
|
||||
echo ""; \
|
||||
echo "error: src/main/resources/aws/redshift-serverless-request-shapes.json is out of date."; \
|
||||
echo " Run 'make aws-data-sync' and commit the result."; \
|
||||
exit 1; \
|
||||
}
|
||||
@$(PYTHON) tools/aws/regen_apigateway_types.py --check || { \
|
||||
echo "error: API Gateway integration types are out of date; run 'make aws-data-sync'."; \
|
||||
exit 1; \
|
||||
|
||||
@@ -69,7 +69,7 @@ Namespace and workgroup state is account and Region scoped and persisted through
|
||||
|
||||
## AWS-compatible failures
|
||||
|
||||
Namespace and workgroup names, database names, log export values, ports and workgroup enum members are validated. Floci returns `ValidationException` for a malformed request, `ConflictException` when a namespace or workgroup name is already taken, when a namespace already has a workgroup, or when a namespace being deleted still has one, and `ResourceNotFoundException` for an unknown namespace or workgroup.
|
||||
Every request is checked against the AWS model constraints before dispatch: required members, string lengths and patterns (including resource names and tag keys and values), list sizes (including subnets, security groups, and tag lists), number ranges, and enum values. Floci returns `ValidationException` for a malformed request or one breaking these model constraints, `ConflictException` when a namespace or workgroup name is already taken, when a namespace already has a workgroup, or when a namespace being deleted still has one, and `ResourceNotFoundException` for an unknown namespace or workgroup.
|
||||
|
||||
AWS also models `AccessDeniedException`, `InternalServerException`, and `ThrottlingException`. Floci does not inject provider-side failures that cannot be derived from the request or emulator state.
|
||||
|
||||
|
||||
+111
-205
@@ -23,12 +23,11 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Redshift Serverless JSON 1.1 handler. Dispatched from
|
||||
@@ -40,16 +39,6 @@ public class RedshiftServerlessJsonHandler {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RedshiftServerlessJsonHandler.class);
|
||||
|
||||
/**
|
||||
* {@code Namespace.creationDate} carries {@code TimestampFormatTrait(ISO_8601)}, which
|
||||
* overrides the epoch-seconds default that awsJson1.1 would otherwise apply. Do not
|
||||
* generalise: roughly half the timestamp members in this model carry no format trait and
|
||||
* use the epoch default, so check each member's trait before emitting it. Emitting a number here is accepted by the CLI, because
|
||||
* botocore coerces it, but strict SDKs reject the response outright.
|
||||
*/
|
||||
private static final DateTimeFormatter CREATION_DATE_FORMAT =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
|
||||
|
||||
private final RedshiftServerlessService service;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RedshiftIamDbUserResolver iamDbUserResolver;
|
||||
@@ -72,37 +61,42 @@ public class RedshiftServerlessJsonHandler {
|
||||
public Response handle(String action, JsonNode request, String region, String authorizationHeader) {
|
||||
LOG.debugv("Redshift Serverless action: {0}", action);
|
||||
try {
|
||||
return switch (action) {
|
||||
case "CreateNamespace" -> handleCreateNamespace(request, region);
|
||||
case "GetNamespace" -> handleGetNamespace(request, region);
|
||||
case "ListNamespaces" -> handleListNamespaces(request, region);
|
||||
case "UpdateNamespace" -> handleUpdateNamespace(request, region);
|
||||
case "DeleteNamespace" -> handleDeleteNamespace(request, region);
|
||||
case "CreateWorkgroup" -> handleCreateWorkgroup(request, region);
|
||||
case "GetWorkgroup" -> handleGetWorkgroup(request, region);
|
||||
case "ListWorkgroups" -> handleListWorkgroups(request, region);
|
||||
case "UpdateWorkgroup" -> handleUpdateWorkgroup(request, region);
|
||||
case "DeleteWorkgroup" -> handleDeleteWorkgroup(request, region);
|
||||
case "CreateSnapshot" -> handleCreateSnapshot(request, region);
|
||||
case "GetSnapshot" -> handleGetSnapshot(request, region);
|
||||
case "ListSnapshots" -> handleListSnapshots(request, region);
|
||||
case "UpdateSnapshot" -> handleUpdateSnapshot(request, region);
|
||||
case "DeleteSnapshot" -> handleDeleteSnapshot(request, region);
|
||||
case "RestoreFromSnapshot" -> handleRestoreFromSnapshot(request, region);
|
||||
case "CreateUsageLimit" -> handleCreateUsageLimit(request, region);
|
||||
case "GetUsageLimit" -> handleGetUsageLimit(request, region);
|
||||
case "ListUsageLimits" -> handleListUsageLimits(request, region);
|
||||
case "UpdateUsageLimit" -> handleUpdateUsageLimit(request, region);
|
||||
case "DeleteUsageLimit" -> handleDeleteUsageLimit(request, region);
|
||||
case "GetCredentials" -> handleGetCredentials(request, region, authorizationHeader);
|
||||
case "ListTagsForResource" -> handleListTagsForResource(request, region);
|
||||
case "TagResource" -> handleTagResource(request, region);
|
||||
case "UntagResource" -> handleUntagResource(request, region);
|
||||
default -> Response.status(400)
|
||||
Supplier<Response> operation = switch (action) {
|
||||
case "CreateNamespace" -> () -> handleCreateNamespace(request, region);
|
||||
case "GetNamespace" -> () -> handleGetNamespace(request, region);
|
||||
case "ListNamespaces" -> () -> handleListNamespaces(request, region);
|
||||
case "UpdateNamespace" -> () -> handleUpdateNamespace(request, region);
|
||||
case "DeleteNamespace" -> () -> handleDeleteNamespace(request, region);
|
||||
case "CreateWorkgroup" -> () -> handleCreateWorkgroup(request, region);
|
||||
case "GetWorkgroup" -> () -> handleGetWorkgroup(request, region);
|
||||
case "ListWorkgroups" -> () -> handleListWorkgroups(request, region);
|
||||
case "UpdateWorkgroup" -> () -> handleUpdateWorkgroup(request, region);
|
||||
case "DeleteWorkgroup" -> () -> handleDeleteWorkgroup(request, region);
|
||||
case "CreateSnapshot" -> () -> handleCreateSnapshot(request, region);
|
||||
case "GetSnapshot" -> () -> handleGetSnapshot(request, region);
|
||||
case "ListSnapshots" -> () -> handleListSnapshots(request, region);
|
||||
case "UpdateSnapshot" -> () -> handleUpdateSnapshot(request, region);
|
||||
case "DeleteSnapshot" -> () -> handleDeleteSnapshot(request, region);
|
||||
case "RestoreFromSnapshot" -> () -> handleRestoreFromSnapshot(request, region);
|
||||
case "CreateUsageLimit" -> () -> handleCreateUsageLimit(request, region);
|
||||
case "GetUsageLimit" -> () -> handleGetUsageLimit(request, region);
|
||||
case "ListUsageLimits" -> () -> handleListUsageLimits(request, region);
|
||||
case "UpdateUsageLimit" -> () -> handleUpdateUsageLimit(request, region);
|
||||
case "DeleteUsageLimit" -> () -> handleDeleteUsageLimit(request, region);
|
||||
case "GetCredentials" -> () -> handleGetCredentials(request, region, authorizationHeader);
|
||||
case "ListTagsForResource" -> () -> handleListTagsForResource(request, region);
|
||||
case "TagResource" -> () -> handleTagResource(request, region);
|
||||
case "UntagResource" -> () -> handleUntagResource(request, region);
|
||||
default -> null;
|
||||
};
|
||||
if (operation == null) {
|
||||
return Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnknownOperationException",
|
||||
"Operation " + action + " is not supported."))
|
||||
.build();
|
||||
};
|
||||
}
|
||||
RedshiftServerlessRequestShapes.check(action, request);
|
||||
return operation.get();
|
||||
} catch (AwsException e) {
|
||||
return JsonErrorResponseUtils.createErrorResponse(e);
|
||||
} catch (Exception e) {
|
||||
@@ -113,26 +107,26 @@ public class RedshiftServerlessJsonHandler {
|
||||
|
||||
private Response handleCreateNamespace(JsonNode request, String region) {
|
||||
Namespace namespace = service.createNamespace(
|
||||
text(request, "namespaceName"),
|
||||
text(request, "adminUsername"),
|
||||
text(request, "adminUserPassword"),
|
||||
text(request, "dbName"),
|
||||
text(request, "kmsKeyId"),
|
||||
text(request, "defaultIamRoleArn"),
|
||||
parseStringList(request.path("iamRoles"), "iamRoles"),
|
||||
parseStringList(request.path("logExports"), "logExports"),
|
||||
ServerlessSupport.text(request, "namespaceName"),
|
||||
ServerlessSupport.text(request, "adminUsername"),
|
||||
ServerlessSupport.text(request, "adminUserPassword"),
|
||||
ServerlessSupport.text(request, "dbName"),
|
||||
ServerlessSupport.text(request, "kmsKeyId"),
|
||||
ServerlessSupport.text(request, "defaultIamRoleArn"),
|
||||
ServerlessSupport.stringList(request, "iamRoles"),
|
||||
ServerlessSupport.stringList(request, "logExports"),
|
||||
parseTagList(request.path("tags"), "tags"),
|
||||
region);
|
||||
return namespaceResponse(namespace);
|
||||
}
|
||||
|
||||
private Response handleGetNamespace(JsonNode request, String region) {
|
||||
return namespaceResponse(service.getNamespace(text(request, "namespaceName"), region));
|
||||
return namespaceResponse(service.getNamespace(ServerlessSupport.text(request, "namespaceName"), region));
|
||||
}
|
||||
|
||||
private Response handleListNamespaces(JsonNode request, String region) {
|
||||
PaginatedResult<Namespace> page = service.listNamespaces(
|
||||
region, parseMaxResults(request), text(request, "nextToken"));
|
||||
region, ServerlessSupport.maxResults(request), ServerlessSupport.text(request, "nextToken"));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode items = response.putArray("namespaces");
|
||||
page.items().forEach(namespace -> items.add(namespaceNode(namespace)));
|
||||
@@ -144,25 +138,25 @@ public class RedshiftServerlessJsonHandler {
|
||||
|
||||
private Response handleUpdateNamespace(JsonNode request, String region) {
|
||||
Namespace namespace = service.updateNamespace(
|
||||
text(request, "namespaceName"),
|
||||
text(request, "adminUsername"),
|
||||
text(request, "adminUserPassword"),
|
||||
text(request, "kmsKeyId"),
|
||||
text(request, "defaultIamRoleArn"),
|
||||
parseStringList(request.path("iamRoles"), "iamRoles"),
|
||||
parseStringList(request.path("logExports"), "logExports"),
|
||||
ServerlessSupport.text(request, "namespaceName"),
|
||||
ServerlessSupport.text(request, "adminUsername"),
|
||||
ServerlessSupport.text(request, "adminUserPassword"),
|
||||
ServerlessSupport.text(request, "kmsKeyId"),
|
||||
ServerlessSupport.text(request, "defaultIamRoleArn"),
|
||||
ServerlessSupport.stringList(request, "iamRoles"),
|
||||
ServerlessSupport.stringList(request, "logExports"),
|
||||
region);
|
||||
return namespaceResponse(namespace);
|
||||
}
|
||||
|
||||
private Response handleDeleteNamespace(JsonNode request, String region) {
|
||||
return namespaceResponse(service.deleteNamespace(text(request, "namespaceName"), region));
|
||||
return namespaceResponse(service.deleteNamespace(ServerlessSupport.text(request, "namespaceName"), region));
|
||||
}
|
||||
|
||||
private Response handleCreateWorkgroup(JsonNode request, String region) {
|
||||
Workgroup workgroup = service.createWorkgroup(
|
||||
text(request, "workgroupName"),
|
||||
text(request, "namespaceName"),
|
||||
ServerlessSupport.text(request, "workgroupName"),
|
||||
ServerlessSupport.text(request, "namespaceName"),
|
||||
parseWorkgroupSettings(request),
|
||||
parseTagList(request.path("tags"), "tags"),
|
||||
region);
|
||||
@@ -170,12 +164,12 @@ public class RedshiftServerlessJsonHandler {
|
||||
}
|
||||
|
||||
private Response handleGetWorkgroup(JsonNode request, String region) {
|
||||
return workgroupResponse(service.getWorkgroup(text(request, "workgroupName"), region));
|
||||
return workgroupResponse(service.getWorkgroup(ServerlessSupport.text(request, "workgroupName"), region));
|
||||
}
|
||||
|
||||
private Response handleListWorkgroups(JsonNode request, String region) {
|
||||
PaginatedResult<Workgroup> page = service.listWorkgroups(
|
||||
region, parseMaxResults(request), text(request, "nextToken"));
|
||||
region, ServerlessSupport.maxResults(request), ServerlessSupport.text(request, "nextToken"));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode items = response.putArray("workgroups");
|
||||
page.items().forEach(workgroup -> items.add(workgroupNode(workgroup)));
|
||||
@@ -187,11 +181,11 @@ public class RedshiftServerlessJsonHandler {
|
||||
|
||||
private Response handleUpdateWorkgroup(JsonNode request, String region) {
|
||||
return workgroupResponse(service.updateWorkgroup(
|
||||
text(request, "workgroupName"), parseWorkgroupSettings(request), region));
|
||||
ServerlessSupport.text(request, "workgroupName"), parseWorkgroupSettings(request), region));
|
||||
}
|
||||
|
||||
private Response handleDeleteWorkgroup(JsonNode request, String region) {
|
||||
return workgroupResponse(service.deleteWorkgroup(text(request, "workgroupName"), region));
|
||||
return workgroupResponse(service.deleteWorkgroup(ServerlessSupport.text(request, "workgroupName"), region));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -201,12 +195,12 @@ public class RedshiftServerlessJsonHandler {
|
||||
*/
|
||||
private Response handleGetCredentials(JsonNode request, String region, String authorizationHeader) {
|
||||
if (request.hasNonNull("customDomainName")) {
|
||||
throw validation("customDomainName is not supported; use workgroupName.");
|
||||
throw ServerlessSupport.validation("customDomainName is not supported; use workgroupName.");
|
||||
}
|
||||
TempCredential credential = service.getCredentials(
|
||||
text(request, "workgroupName"),
|
||||
text(request, "dbName"),
|
||||
parseInteger(request, "durationSeconds"),
|
||||
ServerlessSupport.text(request, "workgroupName"),
|
||||
ServerlessSupport.text(request, "dbName"),
|
||||
ServerlessSupport.integer(request, "durationSeconds"),
|
||||
iamDbUserResolver.resolveDbUser(authorizationHeader),
|
||||
region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
@@ -219,8 +213,8 @@ public class RedshiftServerlessJsonHandler {
|
||||
|
||||
private Response handleCreateSnapshot(JsonNode request, String region) {
|
||||
return snapshotResponse(service.createSnapshot(
|
||||
text(request, "snapshotName"), text(request, "namespaceName"),
|
||||
parseInteger(request, "retentionPeriod"), parseTagList(request.path("tags"), "tags"), region));
|
||||
ServerlessSupport.text(request, "snapshotName"), ServerlessSupport.text(request, "namespaceName"),
|
||||
ServerlessSupport.integer(request, "retentionPeriod"), parseTagList(request.path("tags"), "tags"), region));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -233,9 +227,9 @@ public class RedshiftServerlessJsonHandler {
|
||||
|
||||
private Response handleListSnapshots(JsonNode request, String region) {
|
||||
PaginatedResult<RedshiftServerlessSnapshot> page = service.listSnapshots(
|
||||
text(request, "namespaceName"), text(request, "namespaceArn"), text(request, "ownerAccount"),
|
||||
parseEpochSeconds(request, "startTime"), parseEpochSeconds(request, "endTime"), region,
|
||||
parseMaxResults(request), text(request, "nextToken"));
|
||||
ServerlessSupport.text(request, "namespaceName"), ServerlessSupport.text(request, "namespaceArn"), ServerlessSupport.text(request, "ownerAccount"),
|
||||
ServerlessSupport.epochSeconds(request, "startTime"), ServerlessSupport.epochSeconds(request, "endTime"), region,
|
||||
ServerlessSupport.maxResults(request), ServerlessSupport.text(request, "nextToken"));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode items = response.putArray("snapshots");
|
||||
page.items().forEach(snapshot -> items.add(snapshotNode(snapshot)));
|
||||
@@ -247,17 +241,17 @@ public class RedshiftServerlessJsonHandler {
|
||||
|
||||
private Response handleUpdateSnapshot(JsonNode request, String region) {
|
||||
return snapshotResponse(service.updateSnapshot(
|
||||
text(request, "snapshotName"), parseInteger(request, "retentionPeriod"), region));
|
||||
ServerlessSupport.text(request, "snapshotName"), ServerlessSupport.integer(request, "retentionPeriod"), region));
|
||||
}
|
||||
|
||||
private Response handleDeleteSnapshot(JsonNode request, String region) {
|
||||
return snapshotResponse(service.deleteSnapshot(text(request, "snapshotName"), region));
|
||||
return snapshotResponse(service.deleteSnapshot(ServerlessSupport.text(request, "snapshotName"), region));
|
||||
}
|
||||
|
||||
private Response handleRestoreFromSnapshot(JsonNode request, String region) {
|
||||
RedshiftServerlessService.RestoreResult result = service.restoreFromSnapshot(
|
||||
text(request, "namespaceName"), text(request, "workgroupName"),
|
||||
snapshotNameOf(request, region), text(request, "ownerAccount"), region);
|
||||
ServerlessSupport.text(request, "namespaceName"), ServerlessSupport.text(request, "workgroupName"),
|
||||
snapshotNameOf(request, region), ServerlessSupport.text(request, "ownerAccount"), region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("namespace", namespaceNode(result.namespace()));
|
||||
response.put("ownerAccount", result.snapshot().getOwnerAccount());
|
||||
@@ -267,32 +261,32 @@ public class RedshiftServerlessJsonHandler {
|
||||
|
||||
/** The snapshot name from {@code snapshotName}, or recovered from {@code snapshotArn} when absent. */
|
||||
private String snapshotNameOf(JsonNode request, String region) {
|
||||
String snapshotName = text(request, "snapshotName");
|
||||
String snapshotArn = text(request, "snapshotArn");
|
||||
String snapshotName = ServerlessSupport.text(request, "snapshotName");
|
||||
String snapshotArn = ServerlessSupport.text(request, "snapshotArn");
|
||||
if (snapshotName != null && snapshotArn != null) {
|
||||
throw validation("snapshotName and snapshotArn cannot both be specified.");
|
||||
throw ServerlessSupport.validation("snapshotName and snapshotArn cannot both be specified.");
|
||||
}
|
||||
return snapshotArn == null ? snapshotName : service.snapshotNameFromArn(snapshotArn, region);
|
||||
}
|
||||
|
||||
private Response handleCreateUsageLimit(JsonNode request, String region) {
|
||||
return usageLimitResponse(usageLimits.createUsageLimit(
|
||||
optionalText(request, "resourceArn"),
|
||||
optionalText(request, "usageType"),
|
||||
ServerlessSupport.text(request, "resourceArn"),
|
||||
ServerlessSupport.text(request, "usageType"),
|
||||
parseLong(request, "amount"),
|
||||
optionalText(request, "period"),
|
||||
optionalText(request, "breachAction"),
|
||||
ServerlessSupport.text(request, "period"),
|
||||
ServerlessSupport.text(request, "breachAction"),
|
||||
region));
|
||||
}
|
||||
|
||||
private Response handleGetUsageLimit(JsonNode request, String region) {
|
||||
return usageLimitResponse(usageLimits.getUsageLimit(optionalText(request, "usageLimitId"), region));
|
||||
return usageLimitResponse(usageLimits.getUsageLimit(ServerlessSupport.text(request, "usageLimitId"), region));
|
||||
}
|
||||
|
||||
private Response handleListUsageLimits(JsonNode request, String region) {
|
||||
PaginatedResult<UsageLimit> page = usageLimits.listUsageLimits(
|
||||
optionalText(request, "resourceArn"), optionalText(request, "usageType"), region,
|
||||
parseMaxResults(request), optionalText(request, "nextToken"));
|
||||
ServerlessSupport.text(request, "resourceArn"), ServerlessSupport.text(request, "usageType"), region,
|
||||
ServerlessSupport.maxResults(request), ServerlessSupport.text(request, "nextToken"));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode items = response.putArray("usageLimits");
|
||||
page.items().forEach(limit -> items.add(usageLimitNode(limit)));
|
||||
@@ -304,14 +298,14 @@ public class RedshiftServerlessJsonHandler {
|
||||
|
||||
private Response handleUpdateUsageLimit(JsonNode request, String region) {
|
||||
return usageLimitResponse(usageLimits.updateUsageLimit(
|
||||
optionalText(request, "usageLimitId"),
|
||||
ServerlessSupport.text(request, "usageLimitId"),
|
||||
parseLong(request, "amount"),
|
||||
optionalText(request, "breachAction"),
|
||||
ServerlessSupport.text(request, "breachAction"),
|
||||
region));
|
||||
}
|
||||
|
||||
private Response handleDeleteUsageLimit(JsonNode request, String region) {
|
||||
return usageLimitResponse(usageLimits.deleteUsageLimit(optionalText(request, "usageLimitId"), region));
|
||||
return usageLimitResponse(usageLimits.deleteUsageLimit(ServerlessSupport.text(request, "usageLimitId"), region));
|
||||
}
|
||||
|
||||
private Response usageLimitResponse(UsageLimit limit) {
|
||||
@@ -334,19 +328,19 @@ public class RedshiftServerlessJsonHandler {
|
||||
}
|
||||
|
||||
private Response handleListTagsForResource(JsonNode request, String region) {
|
||||
Map<String, String> tags = service.listTagsForResource(text(request, "resourceArn"), region);
|
||||
Map<String, String> tags = service.listTagsForResource(ServerlessSupport.text(request, "resourceArn"), region);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("tags", tagListNode(tags));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleTagResource(JsonNode request, String region) {
|
||||
service.tagResource(text(request, "resourceArn"), parseTagList(request.path("tags"), "tags"), region);
|
||||
service.tagResource(ServerlessSupport.text(request, "resourceArn"), parseTagList(request.path("tags"), "tags"), region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleUntagResource(JsonNode request, String region) {
|
||||
service.untagResource(text(request, "resourceArn"), parseStringList(request.path("tagKeys"), "tagKeys"), region);
|
||||
service.untagResource(ServerlessSupport.text(request, "resourceArn"), ServerlessSupport.stringList(request, "tagKeys"), region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
@@ -385,7 +379,7 @@ public class RedshiftServerlessJsonHandler {
|
||||
node.put("defaultIamRoleArn", namespace.getDefaultIamRoleArn());
|
||||
}
|
||||
if (namespace.getCreationDate() != null) {
|
||||
node.put("creationDate", CREATION_DATE_FORMAT.format(namespace.getCreationDate()));
|
||||
node.put("creationDate", ServerlessSupport.ISO_8601.format(namespace.getCreationDate()));
|
||||
}
|
||||
ArrayNode iamRoles = node.putArray("iamRoles");
|
||||
namespace.getIamRoles().forEach(iamRoles::add);
|
||||
@@ -418,7 +412,7 @@ public class RedshiftServerlessJsonHandler {
|
||||
node.put("snapshotRemainingDays", Math.max(0, snapshot.getRetentionPeriod() - elapsedDays));
|
||||
}
|
||||
if (snapshot.getSnapshotCreateTime() != null) {
|
||||
node.put("snapshotCreateTime", CREATION_DATE_FORMAT.format(snapshot.getSnapshotCreateTime()));
|
||||
node.put("snapshotCreateTime", ServerlessSupport.ISO_8601.format(snapshot.getSnapshotCreateTime()));
|
||||
}
|
||||
return node;
|
||||
}
|
||||
@@ -480,47 +474,25 @@ public class RedshiftServerlessJsonHandler {
|
||||
endpointNode.put("port", workgroup.getEndpoint().getPort());
|
||||
}
|
||||
if (workgroup.getCreationDate() != null) {
|
||||
node.put("creationDate", CREATION_DATE_FORMAT.format(workgroup.getCreationDate()));
|
||||
node.put("creationDate", ServerlessSupport.ISO_8601.format(workgroup.getCreationDate()));
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private WorkgroupSettings parseWorkgroupSettings(JsonNode request) {
|
||||
return new WorkgroupSettings(
|
||||
parseInteger(request, "baseCapacity"),
|
||||
parseInteger(request, "maxCapacity"),
|
||||
parseBoolean(request, "enhancedVpcRouting"),
|
||||
parseBoolean(request, "publiclyAccessible"),
|
||||
parseBoolean(request, "extraComputeForAutomaticOptimization"),
|
||||
ServerlessSupport.integer(request, "baseCapacity"),
|
||||
ServerlessSupport.integer(request, "maxCapacity"),
|
||||
ServerlessSupport.bool(request, "enhancedVpcRouting"),
|
||||
ServerlessSupport.bool(request, "publiclyAccessible"),
|
||||
ServerlessSupport.bool(request, "extraComputeForAutomaticOptimization"),
|
||||
parseConfigParameters(request.path("configParameters")),
|
||||
parseStringList(request.path("securityGroupIds"), "securityGroupIds"),
|
||||
parseStringList(request.path("subnetIds"), "subnetIds"),
|
||||
parseInteger(request, "port"),
|
||||
ServerlessSupport.stringList(request, "securityGroupIds"),
|
||||
ServerlessSupport.stringList(request, "subnetIds"),
|
||||
ServerlessSupport.integer(request, "port"),
|
||||
parsePricePerformanceTarget(request.path("pricePerformanceTarget")),
|
||||
text(request, "ipAddressType"),
|
||||
text(request, "trackName"));
|
||||
}
|
||||
|
||||
private Integer parseInteger(JsonNode request, String field) {
|
||||
JsonNode node = request.path(field);
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isIntegralNumber() || !node.canConvertToInt()) {
|
||||
throw validation(field + " must be an integer.");
|
||||
}
|
||||
return node.asInt();
|
||||
}
|
||||
|
||||
private Boolean parseBoolean(JsonNode request, String field) {
|
||||
JsonNode node = request.path(field);
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isBoolean()) {
|
||||
throw validation(field + " must be a boolean.");
|
||||
}
|
||||
return node.asBoolean();
|
||||
ServerlessSupport.text(request, "ipAddressType"),
|
||||
ServerlessSupport.text(request, "trackName"));
|
||||
}
|
||||
|
||||
private List<ConfigParameter> parseConfigParameters(JsonNode node) {
|
||||
@@ -528,14 +500,14 @@ public class RedshiftServerlessJsonHandler {
|
||||
return null;
|
||||
}
|
||||
if (!node.isArray()) {
|
||||
throw validation("configParameters must be an array of parameters.");
|
||||
throw ServerlessSupport.validation("configParameters must be an array of parameters.");
|
||||
}
|
||||
List<ConfigParameter> parameters = new ArrayList<>();
|
||||
for (JsonNode element : node) {
|
||||
if (!element.isObject()) {
|
||||
throw validation("configParameters must contain only parameter objects.");
|
||||
throw ServerlessSupport.validation("configParameters must contain only parameter objects.");
|
||||
}
|
||||
parameters.add(new ConfigParameter(text(element, "parameterKey"), text(element, "parameterValue")));
|
||||
parameters.add(new ConfigParameter(ServerlessSupport.text(element, "parameterKey"), ServerlessSupport.text(element, "parameterValue")));
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
@@ -545,33 +517,9 @@ public class RedshiftServerlessJsonHandler {
|
||||
return null;
|
||||
}
|
||||
if (!node.isObject()) {
|
||||
throw validation("pricePerformanceTarget must be an object.");
|
||||
throw ServerlessSupport.validation("pricePerformanceTarget must be an object.");
|
||||
}
|
||||
return new PricePerformanceTarget(text(node, "status"), parseInteger(node, "level"));
|
||||
}
|
||||
|
||||
/** A timestamp request member, which awsJson1.1 sends as epoch seconds unless the model says otherwise. */
|
||||
private Instant parseEpochSeconds(JsonNode request, String field) {
|
||||
JsonNode node = request.path(field);
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isNumber()) {
|
||||
throw validation(field + " must be a timestamp.");
|
||||
}
|
||||
return Instant.ofEpochMilli(Math.round(node.asDouble() * 1000));
|
||||
}
|
||||
|
||||
/** A string member: null when missing or null, a validation error when present with any other type. */
|
||||
private String optionalText(JsonNode request, String field) {
|
||||
JsonNode node = request.path(field);
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isTextual()) {
|
||||
throw validation(field + " must be a string.");
|
||||
}
|
||||
return node.textValue();
|
||||
return new PricePerformanceTarget(ServerlessSupport.text(node, "status"), ServerlessSupport.integer(node, "level"));
|
||||
}
|
||||
|
||||
private Long parseLong(JsonNode request, String field) {
|
||||
@@ -580,71 +528,29 @@ public class RedshiftServerlessJsonHandler {
|
||||
return null;
|
||||
}
|
||||
if (!node.isIntegralNumber() || !node.canConvertToLong()) {
|
||||
throw validation(field + " must be an integer.");
|
||||
throw ServerlessSupport.validation(field + " must be an integer.");
|
||||
}
|
||||
return node.asLong();
|
||||
}
|
||||
|
||||
private Integer parseMaxResults(JsonNode request) {
|
||||
JsonNode node = request.path("maxResults");
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isIntegralNumber() || !node.canConvertToInt()) {
|
||||
throw validation("maxResults must be an integer.");
|
||||
}
|
||||
return node.asInt();
|
||||
}
|
||||
|
||||
/**
|
||||
* Absent means absent and wrong means wrong: only a missing or null member returns null, so
|
||||
* that callers can distinguish "omitted, keep the stored value" from "supplied". Treating a
|
||||
* present member of the wrong type as absent would let a malformed UpdateNamespace silently
|
||||
* keep the old roles instead of reporting the request as invalid.
|
||||
*/
|
||||
private List<String> parseStringList(JsonNode node, String field) {
|
||||
if (node == null || node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isArray()) {
|
||||
throw validation(field + " must be an array of strings.");
|
||||
}
|
||||
List<String> list = new ArrayList<>();
|
||||
for (JsonNode element : node) {
|
||||
if (!element.isTextual()) {
|
||||
throw validation(field + " must contain only strings.");
|
||||
}
|
||||
list.add(element.textValue());
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private Map<String, String> parseTagList(JsonNode tagsNode, String field) {
|
||||
if (tagsNode == null || tagsNode.isMissingNode() || tagsNode.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!tagsNode.isArray()) {
|
||||
throw validation(field + " must be an array of tags.");
|
||||
throw ServerlessSupport.validation(field + " must be an array of tags.");
|
||||
}
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
for (JsonNode tag : tagsNode) {
|
||||
if (!tag.isObject()) {
|
||||
throw validation(field + " must contain only tag objects.");
|
||||
throw ServerlessSupport.validation(field + " must contain only tag objects.");
|
||||
}
|
||||
String key = tag.path("key").asText(null);
|
||||
String key = ServerlessSupport.text(tag, "key");
|
||||
String value = ServerlessSupport.text(tag, "value");
|
||||
if (key != null) {
|
||||
tags.put(key, tag.path("value").asText(null));
|
||||
tags.put(key, value);
|
||||
}
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
private static AwsException validation(String message) {
|
||||
return new AwsException("ValidationException", message, 400);
|
||||
}
|
||||
|
||||
private static String text(JsonNode request, String field) {
|
||||
JsonNode node = request == null ? null : request.get(field);
|
||||
return node != null && node.isTextual() ? node.textValue() : null;
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.VendoredResources;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Checks a Redshift Serverless request against the constraints of its input shape: required
|
||||
* members, string length and pattern, enum values, number range and list size. The shapes come from
|
||||
* the vendored {@code aws/redshift-serverless-request-shapes.json}, generated from botocore's
|
||||
* Redshift Serverless model by {@code tools/aws/regen_redshift_serverless_shapes.py}.
|
||||
*
|
||||
* <p>A pattern must match the whole value, as AWS applies the unanchored ones such as the account id, and a
|
||||
* length counts Unicode code points, not UTF-16 units. A JSON null counts as an absent member and a member the model does not know is ignored. A
|
||||
* member of the wrong JSON type is left for {@link ServerlessSupport} to report when the handler
|
||||
* reads it, so this check only judges values it can read as the modeled type.
|
||||
*/
|
||||
final class RedshiftServerlessRequestShapes {
|
||||
|
||||
static final String RESOURCE_NAME = "aws/redshift-serverless-request-shapes.json";
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* Skipped because only ListUsageLimits answers InvalidPaginationException for out-of-range
|
||||
* pagination values, while the other lists use ValidationException; the services report both themselves.
|
||||
*/
|
||||
private static final Set<String> PAGINATION_MEMBERS = Set.of("maxResults", "nextToken");
|
||||
|
||||
record Shape(String type, Map<String, String> members, List<String> required, String element,
|
||||
Long min, Long max, Pattern pattern, List<String> enumValues) {
|
||||
}
|
||||
|
||||
record Model(Map<String, String> operations, Map<String, Shape> shapes) {
|
||||
}
|
||||
|
||||
private static final class Holder {
|
||||
static final Model MODEL = VendoredResources.read(RESOURCE_NAME,
|
||||
"Redshift Serverless request shapes",
|
||||
in -> parse(MAPPER.readTree(in)));
|
||||
}
|
||||
|
||||
private RedshiftServerlessRequestShapes() {
|
||||
}
|
||||
|
||||
/** Throws a {@code ValidationException} when {@code request} breaks a constraint of {@code action}'s input shape. */
|
||||
static void check(String action, JsonNode request) {
|
||||
check(Holder.MODEL, action, request);
|
||||
}
|
||||
|
||||
static void check(Model model, String action, JsonNode request) {
|
||||
String input = model.operations().get(action);
|
||||
if (input != null && request != null && request.isObject()) {
|
||||
checkStructure(model, model.shapes().get(input), request, "");
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkStructure(Model model, Shape shape, JsonNode value, String path) {
|
||||
for (String name : shape.required()) {
|
||||
if (value.path(name).isMissingNode() || value.get(name).isNull()) {
|
||||
throw ServerlessSupport.validation(path + name + " is required.");
|
||||
}
|
||||
}
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = value.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> field = fields.next();
|
||||
String memberShape = shape.members().get(field.getKey());
|
||||
if (memberShape != null && !field.getValue().isNull() && !PAGINATION_MEMBERS.contains(field.getKey())) {
|
||||
checkValue(model, model.shapes().get(memberShape), field.getValue(), path + field.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkValue(Model model, Shape shape, JsonNode value, String path) {
|
||||
switch (shape.type()) {
|
||||
case "structure" -> {
|
||||
if (value.isObject()) {
|
||||
checkStructure(model, shape, value, path + ".");
|
||||
}
|
||||
}
|
||||
case "list" -> checkList(model, shape, value, path);
|
||||
case "string" -> {
|
||||
if (value.isTextual()) {
|
||||
checkString(shape, value.textValue(), path);
|
||||
}
|
||||
}
|
||||
case "integer", "long" -> {
|
||||
if (value.isIntegralNumber()) {
|
||||
checkNumber(shape, value.longValue(), path);
|
||||
}
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkList(Model model, Shape shape, JsonNode value, String path) {
|
||||
if (!value.isArray()) {
|
||||
return;
|
||||
}
|
||||
checkBounds(shape, value.size(), path, "size");
|
||||
Shape element = model.shapes().get(shape.element());
|
||||
int index = 0;
|
||||
for (JsonNode item : value) {
|
||||
if (!item.isNull()) {
|
||||
checkValue(model, element, item, path + "[" + index + "]");
|
||||
}
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkString(Shape shape, String value, String path) {
|
||||
checkBounds(shape, value.codePointCount(0, value.length()), path, "length");
|
||||
if (shape.enumValues() != null && !shape.enumValues().contains(value)) {
|
||||
throw ServerlessSupport.validation(path + " must be one of " + shape.enumValues() + ".");
|
||||
}
|
||||
if (shape.pattern() != null && !shape.pattern().matcher(value).matches()) {
|
||||
throw ServerlessSupport.validation(path + " must match the pattern " + shape.pattern().pattern() + ".");
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkNumber(Shape shape, long value, String path) {
|
||||
checkBounds(shape, value, path, "value");
|
||||
}
|
||||
|
||||
private static void checkBounds(Shape shape, long actual, String path, String what) {
|
||||
if (shape.min() != null && actual < shape.min()) {
|
||||
throw ServerlessSupport.validation(path + " must have " + what + " at least " + shape.min() + ".");
|
||||
}
|
||||
if (shape.max() != null && actual > shape.max()) {
|
||||
throw ServerlessSupport.validation(path + " must have " + what + " at most " + shape.max() + ".");
|
||||
}
|
||||
}
|
||||
|
||||
static Model parse(JsonNode root) {
|
||||
Map<String, String> operations = new HashMap<>();
|
||||
root.path("operations").fields().forEachRemaining(op -> operations.put(op.getKey(), op.getValue().asText()));
|
||||
Map<String, Shape> shapes = new HashMap<>();
|
||||
Iterator<Map.Entry<String, JsonNode>> entries = root.path("shapes").fields();
|
||||
while (entries.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = entries.next();
|
||||
JsonNode node = entry.getValue();
|
||||
Map<String, String> members = new LinkedHashMap<>();
|
||||
node.path("members").fields().forEachRemaining(m -> members.put(m.getKey(), m.getValue().asText()));
|
||||
shapes.put(entry.getKey(), new Shape(
|
||||
node.path("type").asText(),
|
||||
members,
|
||||
strings(node.path("required")),
|
||||
node.hasNonNull("member") ? node.get("member").asText() : null,
|
||||
node.hasNonNull("min") ? node.get("min").asLong() : null,
|
||||
node.hasNonNull("max") ? node.get("max").asLong() : null,
|
||||
node.hasNonNull("pattern") ? Pattern.compile(node.get("pattern").asText()) : null,
|
||||
node.has("enum") ? strings(node.get("enum")) : null));
|
||||
}
|
||||
return new Model(operations, shapes);
|
||||
}
|
||||
|
||||
private static List<String> strings(JsonNode array) {
|
||||
List<String> values = new ArrayList<>();
|
||||
array.forEach(element -> values.add(element.asText()));
|
||||
return values;
|
||||
}
|
||||
}
|
||||
+35
-48
@@ -216,7 +216,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
validateNamespaceName(namespaceName);
|
||||
String key = storageKey(region, namespaceName);
|
||||
if (namespaces.get(key).isPresent()) {
|
||||
throw conflict("The namespace " + namespaceName + " already exists.");
|
||||
throw ServerlessSupport.conflict("The namespace " + namespaceName + " already exists.");
|
||||
}
|
||||
|
||||
Namespace namespace = new Namespace();
|
||||
@@ -339,7 +339,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
// A workgroup cannot outlive its namespace; the model lists ConflictException for this call
|
||||
// but not its trigger, so this guard is the single place to relax if AWS turns out to differ.
|
||||
if (workgroupOf(namespaceName, region).isPresent()) {
|
||||
throw conflict("The namespace " + namespaceName + " still has a workgroup. Delete the workgroup first.");
|
||||
throw ServerlessSupport.conflict("The namespace " + namespaceName + " still has a workgroup. Delete the workgroup first.");
|
||||
}
|
||||
namespaces.delete(storageKey(region, namespaceName));
|
||||
deleted.setStatus("DELETING");
|
||||
@@ -361,7 +361,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
Namespace namespace = getNamespace(namespaceName, region);
|
||||
String key = storageKey(region, snapshotName);
|
||||
if (snapshots.get(key).isPresent()) {
|
||||
throw conflict("The snapshot " + snapshotName + " already exists.");
|
||||
throw ServerlessSupport.conflict("The snapshot " + snapshotName + " already exists.");
|
||||
}
|
||||
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot();
|
||||
snapshot.setSnapshotName(snapshotName);
|
||||
@@ -387,7 +387,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
return null;
|
||||
}
|
||||
if (retentionPeriod < 1 || retentionPeriod > MAX_RETENTION_DAYS) {
|
||||
throw validation("retentionPeriod must be -1 (indefinite) or between 1 and " + MAX_RETENTION_DAYS + ".");
|
||||
throw ServerlessSupport.validation("retentionPeriod must be -1 (indefinite) or between 1 and " + MAX_RETENTION_DAYS + ".");
|
||||
}
|
||||
return retentionPeriod;
|
||||
}
|
||||
@@ -430,7 +430,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
Path dir = dumpDir(region);
|
||||
Path file = dir.resolve(snapshotName + ".sql").normalize();
|
||||
if (!file.startsWith(dir)) {
|
||||
throw validation("Invalid snapshotName.");
|
||||
throw ServerlessSupport.validation("Invalid snapshotName.");
|
||||
}
|
||||
return file;
|
||||
}
|
||||
@@ -466,7 +466,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
public String snapshotNameFromArn(String snapshotArn, String region) {
|
||||
String prefix = regionResolver.buildArn("redshift-serverless", region, "snapshot/");
|
||||
if (snapshotArn == null || !snapshotArn.startsWith(prefix) || snapshotArn.length() == prefix.length()) {
|
||||
throw validation("snapshotArn does not identify a snapshot in this account and Region.");
|
||||
throw ServerlessSupport.validation("snapshotArn does not identify a snapshot in this account and Region.");
|
||||
}
|
||||
return snapshotArn.substring(prefix.length());
|
||||
}
|
||||
@@ -531,7 +531,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
}
|
||||
Workgroup workgroup = getWorkgroup(workgroupName, region);
|
||||
if (!namespaceName.equals(workgroup.getNamespaceName())) {
|
||||
throw validation("The workgroup " + workgroupName + " does not belong to the namespace "
|
||||
throw ServerlessSupport.validation("The workgroup " + workgroupName + " does not belong to the namespace "
|
||||
+ namespaceName + ".");
|
||||
}
|
||||
Namespace namespace = getNamespace(namespaceName, region);
|
||||
@@ -579,7 +579,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
throw resourceNotFound(resourceArn);
|
||||
}
|
||||
if (tagKeys == null) {
|
||||
throw validation("tagKeys is required.");
|
||||
throw ServerlessSupport.validation("tagKeys is required.");
|
||||
}
|
||||
return retag(resourceArn, region, tagMap -> tagKeys.forEach(tagMap::remove));
|
||||
}
|
||||
@@ -645,13 +645,12 @@ public class RedshiftServerlessService implements Resettable {
|
||||
|
||||
private static void requireResourceArn(String resourceArn) {
|
||||
if (resourceArn == null || resourceArn.isBlank()) {
|
||||
throw validation("resourceArn is required.");
|
||||
throw ServerlessSupport.validation("resourceArn is required.");
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException resourceNotFound(String resourceArn) {
|
||||
return new AwsException("ResourceNotFoundException",
|
||||
"The resource " + resourceArn + " was not found.", 400);
|
||||
return ServerlessSupport.notFound("The resource " + resourceArn + " was not found.");
|
||||
}
|
||||
|
||||
public synchronized Workgroup createWorkgroup(String workgroupName, String namespaceName,
|
||||
@@ -662,10 +661,10 @@ public class RedshiftServerlessService implements Resettable {
|
||||
Namespace namespace = getNamespace(namespaceName, region);
|
||||
String key = storageKey(region, workgroupName);
|
||||
if (workgroups.get(key).isPresent()) {
|
||||
throw conflict("The workgroup " + workgroupName + " already exists.");
|
||||
throw ServerlessSupport.conflict("The workgroup " + workgroupName + " already exists.");
|
||||
}
|
||||
if (workgroupOf(namespaceName, region).isPresent()) {
|
||||
throw conflict("The namespace " + namespaceName + " already has a workgroup.");
|
||||
throw ServerlessSupport.conflict("The namespace " + namespaceName + " already has a workgroup.");
|
||||
}
|
||||
|
||||
Workgroup workgroup = new Workgroup();
|
||||
@@ -802,8 +801,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
Namespace namespace = getNamespace(workgroup.getNamespaceName(), region);
|
||||
if (workgroup.getRuntimeHost() == null || workgroup.getRuntimePort() <= 0
|
||||
|| namespace.getAdminUserPassword() == null) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Workgroup runtime is not available for Data API execution.", 400);
|
||||
throw ServerlessSupport.validation("Workgroup runtime is not available for Data API execution.");
|
||||
}
|
||||
return new WorkgroupTarget(workgroup.getWorkgroupArn(), workgroup.getWorkgroupName(),
|
||||
workgroup.getRuntimeHost(), workgroup.getRuntimePort(), namespace.getDbName(),
|
||||
@@ -825,7 +823,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
|
||||
private Workgroup resolveWorkgroup(String nameOrArn, String region) {
|
||||
if (nameOrArn == null || nameOrArn.isBlank()) {
|
||||
throw validation("workgroupName is required.");
|
||||
throw ServerlessSupport.validation("workgroupName is required.");
|
||||
}
|
||||
if (!nameOrArn.startsWith("arn:")) {
|
||||
return getWorkgroup(nameOrArn, region);
|
||||
@@ -842,15 +840,15 @@ public class RedshiftServerlessService implements Resettable {
|
||||
Workgroup workgroup = resolveWorkgroup(workgroupName, region);
|
||||
Namespace namespace = getNamespace(workgroup.getNamespaceName(), region);
|
||||
if (dbName != null && !dbName.equals(namespace.getDbName())) {
|
||||
throw validation("dbName must be " + namespace.getDbName() + ", the only database in this workgroup.");
|
||||
throw ServerlessSupport.validation("dbName must be " + namespace.getDbName() + ", the only database in this workgroup.");
|
||||
}
|
||||
int duration = durationSeconds == null ? DEFAULT_CREDENTIAL_DURATION_SECONDS : durationSeconds;
|
||||
if (duration < MIN_CREDENTIAL_DURATION_SECONDS || duration > MAX_CREDENTIAL_DURATION_SECONDS) {
|
||||
throw validation("durationSeconds must be between " + MIN_CREDENTIAL_DURATION_SECONDS + " and "
|
||||
throw ServerlessSupport.validation("durationSeconds must be between " + MIN_CREDENTIAL_DURATION_SECONDS + " and "
|
||||
+ MAX_CREDENTIAL_DURATION_SECONDS + ".");
|
||||
}
|
||||
if (workgroup.getRuntimeHost() == null) {
|
||||
throw validation("Workgroup runtime is not available.");
|
||||
throw ServerlessSupport.validation("Workgroup runtime is not available.");
|
||||
}
|
||||
return runtime.issueCredential(workgroups.accountId(), region, workgroup.getWorkgroupName(), dbUser,
|
||||
duration);
|
||||
@@ -877,7 +875,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
newPassword);
|
||||
} catch (AwsException e) {
|
||||
if ("InvalidParameterValue".equals(e.getErrorCode())) {
|
||||
throw new AwsException("ValidationException", e.getMessage(), 400);
|
||||
throw ServerlessSupport.validation(e.getMessage());
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
@@ -930,24 +928,24 @@ public class RedshiftServerlessService implements Resettable {
|
||||
|
||||
private static void requireSnapshotName(String snapshotName) {
|
||||
if (snapshotName == null || snapshotName.isBlank()) {
|
||||
throw validation("snapshotName is required.");
|
||||
throw ServerlessSupport.validation("snapshotName is required.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateSnapshotName(String snapshotName) {
|
||||
requireSnapshotName(snapshotName);
|
||||
if (snapshotName.length() < 3 || snapshotName.length() > 255 || !SNAPSHOT_NAME.matcher(snapshotName).matches()) {
|
||||
throw validation("snapshotName must be 3-255 characters of lowercase letters, numbers, and hyphens.");
|
||||
throw ServerlessSupport.validation("snapshotName must be 3-255 characters of lowercase letters, numbers, and hyphens.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateNamespaceName(String namespaceName) {
|
||||
if (namespaceName == null || namespaceName.length() < 3 || namespaceName.length() > 64
|
||||
|| !NAMESPACE_NAME.matcher(namespaceName).matches()) {
|
||||
throw validation("namespaceName must be 3-64 characters of lowercase letters, numbers, and hyphens.");
|
||||
throw ServerlessSupport.validation("namespaceName must be 3-64 characters of lowercase letters, numbers, and hyphens.");
|
||||
}
|
||||
if (RESERVED_WORDS.contains(namespaceName)) {
|
||||
throw validation("namespaceName must not be an Amazon Redshift reserved word.");
|
||||
throw ServerlessSupport.validation("namespaceName must not be an Amazon Redshift reserved word.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -956,7 +954,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
return DEFAULT_DB_NAME;
|
||||
}
|
||||
if (dbName.length() > 127 || !DB_NAME.matcher(dbName).matches()) {
|
||||
throw validation("dbName must start with a letter and be at most 127 characters.");
|
||||
throw ServerlessSupport.validation("dbName must start with a letter and be at most 127 characters.");
|
||||
}
|
||||
return dbName;
|
||||
}
|
||||
@@ -965,7 +963,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
List<String> validated = copyOf(logExports);
|
||||
for (String logExport : validated) {
|
||||
if (!LOG_EXPORTS.contains(logExport)) {
|
||||
throw validation("logExports must contain only useractivitylog, userlog, and connectionlog.");
|
||||
throw ServerlessSupport.validation("logExports must contain only useractivitylog, userlog, and connectionlog.");
|
||||
}
|
||||
}
|
||||
return validated;
|
||||
@@ -982,7 +980,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
private static void validateWorkgroupName(String workgroupName) {
|
||||
if (workgroupName == null || workgroupName.length() < 3 || workgroupName.length() > 64
|
||||
|| !WORKGROUP_NAME.matcher(workgroupName).matches()) {
|
||||
throw validation("workgroupName must be 3-64 characters of lowercase letters, numbers, and hyphens.");
|
||||
throw ServerlessSupport.validation("workgroupName must be 3-64 characters of lowercase letters, numbers, and hyphens.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -990,29 +988,29 @@ public class RedshiftServerlessService implements Resettable {
|
||||
requirePositive(settings.baseCapacity(), "baseCapacity");
|
||||
requirePositive(settings.maxCapacity(), "maxCapacity");
|
||||
if (settings.port() != null && !isAllowedPort(settings.port())) {
|
||||
throw validation("port must be in the range 5431-5455 or 8191-8215.");
|
||||
throw ServerlessSupport.validation("port must be in the range 5431-5455 or 8191-8215.");
|
||||
}
|
||||
if (settings.ipAddressType() != null && !IP_ADDRESS_TYPES.contains(settings.ipAddressType())) {
|
||||
throw validation("ipAddressType must be ipv4 or dualstack.");
|
||||
throw ServerlessSupport.validation("ipAddressType must be ipv4 or dualstack.");
|
||||
}
|
||||
if (settings.trackName() != null
|
||||
&& (settings.trackName().isEmpty() || settings.trackName().length() > 256
|
||||
|| !TRACK_NAME.matcher(settings.trackName()).matches())) {
|
||||
throw validation("trackName must be 1-256 characters of letters, numbers, and underscores.");
|
||||
throw ServerlessSupport.validation("trackName must be 1-256 characters of letters, numbers, and underscores.");
|
||||
}
|
||||
PricePerformanceTarget target = settings.pricePerformanceTarget();
|
||||
if (target != null) {
|
||||
if (target.getStatus() != null && !PERFORMANCE_TARGET_STATUSES.contains(target.getStatus())) {
|
||||
throw validation("pricePerformanceTarget.status must be ENABLED or DISABLED.");
|
||||
throw ServerlessSupport.validation("pricePerformanceTarget.status must be ENABLED or DISABLED.");
|
||||
}
|
||||
if (target.getLevel() != null && (target.getLevel() < 1 || target.getLevel() > 100)) {
|
||||
throw validation("pricePerformanceTarget.level must be between 1 and 100.");
|
||||
throw ServerlessSupport.validation("pricePerformanceTarget.level must be between 1 and 100.");
|
||||
}
|
||||
}
|
||||
if (settings.configParameters() != null) {
|
||||
for (ConfigParameter parameter : settings.configParameters()) {
|
||||
if (parameter.getParameterKey() == null || parameter.getParameterKey().isBlank()) {
|
||||
throw validation("configParameters entries require a parameterKey.");
|
||||
throw ServerlessSupport.validation("configParameters entries require a parameterKey.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1020,7 +1018,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
|
||||
private static void requirePositive(Integer value, String field) {
|
||||
if (value != null && value < 1) {
|
||||
throw validation(field + " must be a positive integer.");
|
||||
throw ServerlessSupport.validation(field + " must be a positive integer.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1029,8 +1027,7 @@ public class RedshiftServerlessService implements Resettable {
|
||||
}
|
||||
|
||||
private static AwsException workgroupNotFound(String workgroupName) {
|
||||
return new AwsException("ResourceNotFoundException",
|
||||
"The workgroup " + workgroupName + " was not found.", 400);
|
||||
return ServerlessSupport.notFound("The workgroup " + workgroupName + " was not found.");
|
||||
}
|
||||
|
||||
private static String storageKey(String region, String namespaceName) {
|
||||
@@ -1038,20 +1035,10 @@ public class RedshiftServerlessService implements Resettable {
|
||||
}
|
||||
|
||||
private static AwsException notFound(String namespaceName) {
|
||||
return new AwsException("ResourceNotFoundException",
|
||||
"The namespace " + namespaceName + " was not found.", 400);
|
||||
return ServerlessSupport.notFound("The namespace " + namespaceName + " was not found.");
|
||||
}
|
||||
|
||||
private static AwsException snapshotNotFound(String snapshotName) {
|
||||
return new AwsException("ResourceNotFoundException",
|
||||
"The snapshot " + snapshotName + " was not found.", 400);
|
||||
}
|
||||
|
||||
private static AwsException conflict(String message) {
|
||||
return new AwsException("ConflictException", message, 400);
|
||||
}
|
||||
|
||||
private static AwsException validation(String message) {
|
||||
return new AwsException("ValidationException", message, 400);
|
||||
return ServerlessSupport.notFound("The snapshot " + snapshotName + " was not found.");
|
||||
}
|
||||
}
|
||||
+8
-23
@@ -1,7 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
@@ -52,18 +51,18 @@ public class RedshiftServerlessUsageLimitService implements Resettable {
|
||||
|
||||
public synchronized UsageLimit createUsageLimit(String resourceArn, String usageType, Long amount,
|
||||
String period, String breachAction, String region) {
|
||||
requireText(resourceArn, "resourceArn");
|
||||
requireText(usageType, "usageType");
|
||||
ServerlessSupport.requireText(resourceArn, "resourceArn");
|
||||
ServerlessSupport.requireText(usageType, "usageType");
|
||||
requireOneOf(usageType, USAGE_TYPES, "usageType");
|
||||
if (amount == null) {
|
||||
throw validation("amount is required.");
|
||||
throw ServerlessSupport.validation("amount is required.");
|
||||
}
|
||||
requirePositive(amount);
|
||||
String resolvedPeriod = period == null ? DEFAULT_PERIOD : requireOneOf(period, PERIODS, "period");
|
||||
String resolvedAction = breachAction == null
|
||||
? DEFAULT_BREACH_ACTION : requireOneOf(breachAction, BREACH_ACTIONS, "breachAction");
|
||||
serverless.findWorkgroupByArn(resourceArn, region)
|
||||
.orElseThrow(() -> notFound("The resource " + resourceArn + " was not found."));
|
||||
.orElseThrow(() -> ServerlessSupport.notFound("The resource " + resourceArn + " was not found."));
|
||||
|
||||
UsageLimit limit = new UsageLimit();
|
||||
limit.setUsageLimitId(UUID.randomUUID().toString());
|
||||
@@ -130,14 +129,14 @@ public class RedshiftServerlessUsageLimitService implements Resettable {
|
||||
}
|
||||
|
||||
private UsageLimit require(String usageLimitId, String region) {
|
||||
requireText(usageLimitId, "usageLimitId");
|
||||
ServerlessSupport.requireText(usageLimitId, "usageLimitId");
|
||||
UsageLimit limit = usageLimits.get(storageKey(region, usageLimitId)).orElse(null);
|
||||
if (limit != null && !isLive(limit, region)) {
|
||||
usageLimits.delete(storageKey(region, usageLimitId));
|
||||
limit = null;
|
||||
}
|
||||
if (limit == null) {
|
||||
throw notFound("The usage limit " + usageLimitId + " was not found.");
|
||||
throw ServerlessSupport.notFound("The usage limit " + usageLimitId + " was not found.");
|
||||
}
|
||||
return limit;
|
||||
}
|
||||
@@ -164,30 +163,16 @@ public class RedshiftServerlessUsageLimitService implements Resettable {
|
||||
return region + "::" + usageLimitId;
|
||||
}
|
||||
|
||||
private static void requireText(String value, String field) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw validation(field + " is required.");
|
||||
}
|
||||
}
|
||||
|
||||
private static String requireOneOf(String value, Set<String> allowed, String field) {
|
||||
if (!allowed.contains(value)) {
|
||||
throw validation(field + " must be one of " + allowed.stream().sorted().toList() + ".");
|
||||
throw ServerlessSupport.validation(field + " must be one of " + allowed.stream().sorted().toList() + ".");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void requirePositive(long amount) {
|
||||
if (amount < 1) {
|
||||
throw validation("amount must be a positive number.");
|
||||
throw ServerlessSupport.validation("amount must be a positive number.");
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException notFound(String message) {
|
||||
return new AwsException("ResourceNotFoundException", message, 400);
|
||||
}
|
||||
|
||||
private static AwsException validation(String message) {
|
||||
return new AwsException("ValidationException", message, 400);
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Request parsing and error helpers shared by the Redshift Serverless administration handlers and
|
||||
* services. A member that is missing or null reads as {@code null}; a member of the wrong type is a
|
||||
* {@code ValidationException}, so a malformed request is never mistaken for an omitted field.
|
||||
*/
|
||||
final class ServerlessSupport {
|
||||
|
||||
/** Use only for members whose model overrides the epoch-seconds default with ISO 8601. */
|
||||
static final DateTimeFormatter ISO_8601 =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
|
||||
|
||||
private ServerlessSupport() {
|
||||
}
|
||||
|
||||
static AwsException validation(String message) {
|
||||
return new AwsException("ValidationException", message, 400);
|
||||
}
|
||||
|
||||
static AwsException notFound(String message) {
|
||||
return new AwsException("ResourceNotFoundException", message, 400);
|
||||
}
|
||||
|
||||
static AwsException conflict(String message) {
|
||||
return new AwsException("ConflictException", message, 400);
|
||||
}
|
||||
|
||||
static void requireText(String value, String field) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw validation(field + " is required.");
|
||||
}
|
||||
}
|
||||
|
||||
static String text(JsonNode request, String field) {
|
||||
JsonNode node = request.path(field);
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isTextual()) {
|
||||
throw validation(field + " must be a string.");
|
||||
}
|
||||
return node.textValue();
|
||||
}
|
||||
|
||||
static Integer integer(JsonNode request, String field) {
|
||||
JsonNode node = request.path(field);
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isIntegralNumber() || !node.canConvertToInt()) {
|
||||
throw validation(field + " must be an integer.");
|
||||
}
|
||||
return node.asInt();
|
||||
}
|
||||
|
||||
static Boolean bool(JsonNode request, String field) {
|
||||
JsonNode node = request.path(field);
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isBoolean()) {
|
||||
throw validation(field + " must be a boolean.");
|
||||
}
|
||||
return node.asBoolean();
|
||||
}
|
||||
|
||||
/** A timestamp member, which awsJson1.1 sends as epoch seconds unless the model says otherwise. */
|
||||
static Instant epochSeconds(JsonNode request, String field) {
|
||||
JsonNode node = request.path(field);
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isNumber()) {
|
||||
throw validation(field + " must be a timestamp.");
|
||||
}
|
||||
return Instant.ofEpochMilli(Math.round(node.asDouble() * 1000));
|
||||
}
|
||||
|
||||
static List<String> stringList(JsonNode request, String field) {
|
||||
JsonNode node = request.path(field);
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isArray()) {
|
||||
throw validation(field + " must be an array of strings.");
|
||||
}
|
||||
List<String> list = new ArrayList<>();
|
||||
for (JsonNode element : node) {
|
||||
if (!element.isTextual()) {
|
||||
throw validation(field + " must contain only strings.");
|
||||
}
|
||||
list.add(element.textValue());
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
static JsonNode object(JsonNode request, String field) {
|
||||
JsonNode node = request.path(field);
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isObject()) {
|
||||
throw validation(field + " must be an object.");
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
static Integer maxResults(JsonNode request) {
|
||||
return integer(request, "maxResults");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+47
@@ -381,12 +381,59 @@ class RedshiftServerlessJsonHandlerTest {
|
||||
|
||||
@Test
|
||||
void anUnknownActionIsReportedAsUnknownOperation() {
|
||||
Response response = handler.handle("NoSuchOperation", mapper.createObjectNode(), REGION);
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
assertEquals("UnknownOperationException", errorType(response));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aModeledActionWithoutAnImplementationIsStillAnUnknownOperation() {
|
||||
Response response = handler.handle("CreateScheduledAction", mapper.createObjectNode(), REGION);
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
assertEquals("UnknownOperationException", errorType(response));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestBreakingTheModelConstraintsIsRejectedWithoutChangingState() {
|
||||
Response badEnum = handler.handle("CreateNamespace",
|
||||
parse("{\"namespaceName\":\"state-ns\",\"logExports\":[\"nope\"]}"), REGION);
|
||||
Response missingNamespace = handler.handle("CreateWorkgroup", parse("{\"workgroupName\":\"state-wg\"}"), REGION);
|
||||
Response missingName = handler.handle("GetWorkgroup", parse("{}"), REGION);
|
||||
|
||||
assertEquals("ValidationException", errorType(badEnum));
|
||||
assertEquals("ValidationException", errorType(missingNamespace));
|
||||
assertEquals("ValidationException", errorType(missingName));
|
||||
assertEquals("ResourceNotFoundException", errorType(
|
||||
handler.handle("GetNamespace", parse("{\"namespaceName\":\"state-ns\"}"), REGION)));
|
||||
assertEquals(0, body(handler.handle("ListWorkgroups", parse("{}"), REGION)).get("workgroups").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNonStringPageTokenIsRejectedInsteadOfRestartingTheListing() {
|
||||
for (String action : new String[] {"ListNamespaces", "ListWorkgroups", "ListSnapshots", "ListUsageLimits"}) {
|
||||
Response response = handler.handle(action, parse("{\"nextToken\":12345678}"), REGION);
|
||||
|
||||
assertEquals("ValidationException", errorType(response), action);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTagWithANonStringKeyOrValueIsRejectedInsteadOfCoerced() {
|
||||
String arn = body(handler.handle("CreateNamespace", parse("{\"namespaceName\":\"tag-ns\"}"), REGION))
|
||||
.get("namespace").get("namespaceArn").textValue();
|
||||
|
||||
for (String tag : new String[] {"{\"key\":123,\"value\":\"v\"}", "{\"key\":\"k\",\"value\":false}"}) {
|
||||
Response response = handler.handle("TagResource",
|
||||
parse("{\"resourceArn\":\"" + arn + "\",\"tags\":[" + tag + "]}"), REGION);
|
||||
|
||||
assertEquals("ValidationException", errorType(response), tag);
|
||||
}
|
||||
assertEquals(0, body(handler.handle("ListTagsForResource", parse("{\"resourceArn\":\"" + arn + "\"}"), REGION))
|
||||
.get("tags").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPresentCollectionMemberOfTheWrongTypeIsRejectedPerMember() {
|
||||
create("wrong-type-ns");
|
||||
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class RedshiftServerlessRequestShapesTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private static JsonNode parse(String json) {
|
||||
try {
|
||||
return MAPPER.readTree(json);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException rejected(String action, String json) {
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> RedshiftServerlessRequestShapes.check(action, parse(json)));
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
assertEquals(400, e.getHttpStatus());
|
||||
return e;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMissingRequiredMemberIsRejected() {
|
||||
assertTrue(rejected("GetTrack", "{}").getMessage().contains("trackName is required"));
|
||||
assertTrue(rejected("GetTrack", "{\"trackName\":null}").getMessage().contains("trackName is required"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequiredMemberInsideAListElementIsRejected() {
|
||||
AwsException e = rejected("TagResource", "{\"resourceArn\":\"arn:aws:redshift-serverless:us-east-1:"
|
||||
+ "000000000000:namespace/x\",\"tags\":[{\"key\":\"k\"}]}");
|
||||
|
||||
assertTrue(e.getMessage().contains("tags[0].value is required"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stringPatternLengthAndEnumFollowTheModel() {
|
||||
assertTrue(rejected("GetTrack", "{\"trackName\":\"has space\"}").getMessage().contains("pattern"));
|
||||
assertTrue(rejected("GetTrack", "{\"trackName\":\"\"}").getMessage().contains("at least 1"));
|
||||
assertTrue(rejected("GetTrack", "{\"trackName\":\"" + "a".repeat(257) + "\"}")
|
||||
.getMessage().contains("at most 256"));
|
||||
assertTrue(rejected("CreateNamespace", "{\"namespaceName\":\"ns-ok\",\"logExports\":[\"nope\"]}")
|
||||
.getMessage().contains("logExports[0] must be one of"));
|
||||
assertDoesNotThrow(() -> RedshiftServerlessRequestShapes.check("GetTrack", parse("{\"trackName\":\"current\"}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void numberRangeFollowsTheModel() {
|
||||
AwsException e = rejected("CreateWorkgroup", "{\"workgroupName\":\"wg-ok\",\"namespaceName\":\"ns-ok\","
|
||||
+ "\"pricePerformanceTarget\":{\"status\":\"ENABLED\",\"level\":101}}");
|
||||
|
||||
assertTrue(e.getMessage().contains("pricePerformanceTarget.level"), e.getMessage());
|
||||
assertTrue(e.getMessage().contains("at most 100"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void paginationMembersAreLeftToTheServices() {
|
||||
assertDoesNotThrow(() -> RedshiftServerlessRequestShapes.check("ListNamespaces", parse("{\"maxResults\":0}")));
|
||||
assertDoesNotThrow(() -> RedshiftServerlessRequestShapes.check("ListNamespaces", parse("{\"nextToken\":\"x\"}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPatternMustMatchTheWholeValue() {
|
||||
assertDoesNotThrow(() -> RedshiftServerlessRequestShapes.check("ListWorkgroups",
|
||||
parse("{\"ownerAccount\":\"123456789012\"}")));
|
||||
assertTrue(rejected("ListWorkgroups", "{\"ownerAccount\":\"x123456789012y\"}")
|
||||
.getMessage().contains("ownerAccount"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLengthCountsCodePointsNotUtf16Units() {
|
||||
String arn = "arn:aws:redshift-serverless:us-east-1:000000000000:namespace/x";
|
||||
String emoji200 = "\uD83D\uDE00".repeat(200);
|
||||
String emoji257 = "\uD83D\uDE00".repeat(257);
|
||||
|
||||
assertDoesNotThrow(() -> RedshiftServerlessRequestShapes.check("TagResource", parse(
|
||||
"{\"resourceArn\":\"" + arn + "\",\"tags\":[{\"key\":\"k\",\"value\":\"" + emoji200 + "\"}]}")));
|
||||
assertTrue(rejected("TagResource", "{\"resourceArn\":\"" + arn + "\",\"tags\":[{\"key\":\"k\",\"value\":\""
|
||||
+ emoji257 + "\"}]}").getMessage().contains("at most 256"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMemberOfTheWrongTypeIsLeftForTheHandlerToReport() {
|
||||
assertDoesNotThrow(() -> RedshiftServerlessRequestShapes.check("GetTrack", parse("{\"trackName\":7}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownActionsAndUnknownMembersAreIgnored() {
|
||||
assertDoesNotThrow(() -> RedshiftServerlessRequestShapes.check("NoSuchAction", parse("{}")));
|
||||
assertDoesNotThrow(() -> RedshiftServerlessRequestShapes.check("ListNamespaces", parse("{\"extra\":1}")));
|
||||
assertDoesNotThrow(() -> RedshiftServerlessRequestShapes.check("ListNamespaces", null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate src/main/resources/aws/redshift-serverless-request-shapes.json from botocore's model.
|
||||
|
||||
Redshift Serverless answers a request that breaks the model's constraints with a
|
||||
ValidationException before it runs the operation. The Java side
|
||||
(`RedshiftServerlessRequestShapes`) needs the same constraints, so this script keeps what that
|
||||
check reads: the input shape of every operation, and for every shape reachable from one its type,
|
||||
the shapes of its members, list elements or map values, its required members, its length or value
|
||||
bounds (`min`/`max`), its `pattern` and its `enum`.
|
||||
|
||||
The model is botocore's `redshift-serverless/2021-04-21/service-2.json` (Apache-2.0,
|
||||
https://github.com/boto/botocore). It is located, in order, at `--botocore-data`, the
|
||||
`local/aws/botocore` checkout, then the installed `botocore` package, which
|
||||
`requirements.txt` pins so CI regenerates the same bytes.
|
||||
|
||||
Run from anywhere in the repo:
|
||||
python3 tools/aws/regen_redshift_serverless_shapes.py # rewrite the vendored file in place
|
||||
python3 tools/aws/regen_redshift_serverless_shapes.py --check # exit 1 when the vendored file is stale
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import gzip
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from regen_partitions import resolve_botocore_data, strip_source
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
OUTPUT = REPO_ROOT / "src/main/resources/aws/redshift-serverless-request-shapes.json"
|
||||
MODEL = Path("redshift-serverless/2021-04-21/service-2.json")
|
||||
|
||||
# Constraint keys copied verbatim from a shape; `min` and `max` bound the length of a string or
|
||||
# list and the value of a number.
|
||||
CONSTRAINTS = ("min", "max", "pattern", "enum")
|
||||
|
||||
|
||||
def load_model(data: Path) -> dict:
|
||||
plain = data / MODEL
|
||||
if plain.exists():
|
||||
return json.loads(plain.read_text(encoding="utf-8"))
|
||||
compressed = plain.with_name(plain.name + ".gz")
|
||||
if compressed.exists():
|
||||
with gzip.open(compressed, "rt", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
raise SystemExit(f"error: {plain} not found")
|
||||
|
||||
|
||||
def build(model: dict, provenance: str) -> dict:
|
||||
shapes = model["shapes"]
|
||||
kept: dict[str, dict] = {}
|
||||
|
||||
def keep(name: str) -> None:
|
||||
if name in kept:
|
||||
return
|
||||
shape = shapes[name]
|
||||
kind = shape["type"]
|
||||
entry: dict = {"type": kind}
|
||||
kept[name] = entry
|
||||
for key in CONSTRAINTS:
|
||||
if key in shape:
|
||||
entry[key] = shape[key]
|
||||
if kind == "structure":
|
||||
if shape.get("required"):
|
||||
entry["required"] = list(shape["required"])
|
||||
entry["members"] = {member: spec["shape"] for member, spec in shape.get("members", {}).items()}
|
||||
for spec in shape.get("members", {}).values():
|
||||
keep(spec["shape"])
|
||||
elif kind == "list":
|
||||
entry["member"] = shape["member"]["shape"]
|
||||
keep(shape["member"]["shape"])
|
||||
elif kind == "map":
|
||||
entry["value"] = shape["value"]["shape"]
|
||||
keep(shape["value"]["shape"])
|
||||
|
||||
operations = {}
|
||||
for name, operation in sorted(model["operations"].items()):
|
||||
if "input" in operation:
|
||||
operations[name] = operation["input"]["shape"]
|
||||
keep(operation["input"]["shape"])
|
||||
|
||||
return {
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_redshift_serverless_shapes.py",
|
||||
"botocore": provenance,
|
||||
},
|
||||
"operations": operations,
|
||||
"shapes": dict(sorted(kept.items())),
|
||||
}
|
||||
|
||||
|
||||
def render(doc: dict) -> str:
|
||||
return json.dumps(doc, indent=2, sort_keys=False) + "\n"
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation")
|
||||
parser.add_argument("--botocore-data", type=Path, help="botocore data directory")
|
||||
parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
data, provenance = resolve_botocore_data(args.botocore_data)
|
||||
fresh = render(build(load_model(data), provenance))
|
||||
|
||||
if args.check:
|
||||
current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
|
||||
if strip_source(current) != strip_source(fresh):
|
||||
print(f"{args.output} is stale (generated from {provenance}).", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
args.output.write_text(fresh, encoding="utf-8")
|
||||
print(f"wrote {args.output.relative_to(REPO_ROOT)} from {provenance}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Tests for regen_redshift_serverless_shapes.
|
||||
|
||||
Run with: pytest tools/aws -q (or: make aws-data-test)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import regen_redshift_serverless_shapes as r
|
||||
|
||||
|
||||
MODEL = {
|
||||
"operations": {
|
||||
"GetTrack": {"input": {"shape": "GetTrackRequest"}, "output": {"shape": "GetTrackResponse"}},
|
||||
"ListTracks": {"input": {"shape": "ListTracksRequest"}},
|
||||
"NoInput": {},
|
||||
},
|
||||
"shapes": {
|
||||
"GetTrackRequest": {"type": "structure", "required": ["trackName"], "members": {
|
||||
"trackName": {"shape": "TrackName"},
|
||||
"tags": {"shape": "TagList"},
|
||||
}},
|
||||
"GetTrackResponse": {"type": "structure", "members": {"track": {"shape": "Marker"}}},
|
||||
"ListTracksRequest": {"type": "structure", "members": {"maxResults": {"shape": "MaxResults"}}},
|
||||
"TrackName": {"type": "string", "min": 1, "max": 256, "pattern": "^[a-zA-Z0-9_]+$"},
|
||||
"TagList": {"type": "list", "member": {"shape": "Tag"}, "min": 0, "max": 200},
|
||||
"Tag": {"type": "structure", "required": ["key", "value"], "members": {
|
||||
"key": {"shape": "TagKey"}, "value": {"shape": "TagValue"}}},
|
||||
"TagKey": {"type": "string", "min": 1, "max": 128},
|
||||
"TagValue": {"type": "string", "min": 0, "max": 256},
|
||||
"MaxResults": {"type": "integer", "min": 1, "max": 100},
|
||||
"Status": {"type": "string", "enum": ["a", "b"]},
|
||||
"Marker": {"type": "string"},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_keeps_only_input_shapes_with_their_constraints():
|
||||
doc = r.build(MODEL, "botocore test")
|
||||
|
||||
assert doc["_source"] == {"generator": "tools/aws/regen_redshift_serverless_shapes.py", "botocore": "botocore test"}
|
||||
assert doc["operations"] == {"GetTrack": "GetTrackRequest", "ListTracks": "ListTracksRequest"}
|
||||
assert "GetTrackResponse" not in doc["shapes"]
|
||||
assert "Status" not in doc["shapes"]
|
||||
assert doc["shapes"]["GetTrackRequest"] == {
|
||||
"type": "structure", "required": ["trackName"],
|
||||
"members": {"trackName": "TrackName", "tags": "TagList"}}
|
||||
assert doc["shapes"]["TrackName"] == {"type": "string", "min": 1, "max": 256, "pattern": "^[a-zA-Z0-9_]+$"}
|
||||
assert doc["shapes"]["TagList"] == {"type": "list", "min": 0, "max": 200, "member": "Tag"}
|
||||
assert doc["shapes"]["MaxResults"] == {"type": "integer", "min": 1, "max": 100}
|
||||
|
||||
|
||||
def test_enum_is_kept():
|
||||
model = {
|
||||
"operations": {"Op": {"input": {"shape": "OpRequest"}}},
|
||||
"shapes": {
|
||||
"OpRequest": {"type": "structure", "members": {"status": {"shape": "Status"}}},
|
||||
"Status": {"type": "string", "enum": ["a", "b"]},
|
||||
},
|
||||
}
|
||||
|
||||
assert r.build(model, "botocore test")["shapes"]["Status"] == {"type": "string", "enum": ["a", "b"]}
|
||||
|
||||
|
||||
def test_check_ignores_provenance(tmp_path, monkeypatch):
|
||||
output = tmp_path / "shapes.json"
|
||||
output.write_text(r.render(r.build(MODEL, "botocore 0.0.1 (local/aws/botocore)")), encoding="utf-8")
|
||||
monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "--botocore-data /elsewhere"))
|
||||
monkeypatch.setattr(r, "load_model", lambda data: MODEL)
|
||||
|
||||
assert r.main(["--check", "--output", str(output)]) == 0
|
||||
|
||||
|
||||
def test_check_reports_changed_constraints(tmp_path, monkeypatch):
|
||||
output = tmp_path / "shapes.json"
|
||||
changed = {**MODEL, "shapes": {**MODEL["shapes"], "MaxResults": {"type": "integer", "min": 1, "max": 50}}}
|
||||
output.write_text(r.render(r.build(changed, "botocore test")), encoding="utf-8")
|
||||
monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "botocore test"))
|
||||
monkeypatch.setattr(r, "load_model", lambda data: MODEL)
|
||||
|
||||
assert r.main(["--check", "--output", str(output)]) == 1
|
||||
|
||||
|
||||
def test_output_is_stable():
|
||||
first = r.render(r.build(MODEL, "botocore test"))
|
||||
second = r.render(r.build(MODEL, "botocore test"))
|
||||
|
||||
assert first == second
|
||||
assert first.endswith("\n")
|
||||
Reference in new issue
Block a user