diff --git a/Makefile b/Makefile index 0d82c1bbfe..95bafbda09 100644 --- a/Makefile +++ b/Makefile @@ -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; \ diff --git a/docs/services/redshift-serverless.md b/docs/services/redshift-serverless.md index 4b11f98c4b..80c7e1ef9a 100644 --- a/docs/services/redshift-serverless.md +++ b/docs/services/redshift-serverless.md @@ -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. diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandler.java index 4b6a53a99d..0bccc00ec7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandler.java @@ -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 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 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 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 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 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 tags = service.listTagsForResource(text(request, "resourceArn"), region); + Map 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 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 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 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 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 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 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; - } } diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessRequestShapes.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessRequestShapes.java new file mode 100644 index 0000000000..f831c31f41 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessRequestShapes.java @@ -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}. + * + *

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 PAGINATION_MEMBERS = Set.of("maxResults", "nextToken"); + + record Shape(String type, Map members, List required, String element, + Long min, Long max, Pattern pattern, List enumValues) { + } + + record Model(Map operations, Map 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> fields = value.fields(); + while (fields.hasNext()) { + Map.Entry 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 operations = new HashMap<>(); + root.path("operations").fields().forEachRemaining(op -> operations.put(op.getKey(), op.getValue().asText())); + Map shapes = new HashMap<>(); + Iterator> entries = root.path("shapes").fields(); + while (entries.hasNext()) { + Map.Entry entry = entries.next(); + JsonNode node = entry.getValue(); + Map 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 strings(JsonNode array) { + List values = new ArrayList<>(); + array.forEach(element -> values.add(element.asText())); + return values; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java index a8506fafc4..ab08667611 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java @@ -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 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."); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessUsageLimitService.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessUsageLimitService.java index 22e341cca2..c25ddff4d1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessUsageLimitService.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessUsageLimitService.java @@ -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 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); - } } diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/ServerlessSupport.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/ServerlessSupport.java new file mode 100644 index 0000000000..0364e3e821 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/ServerlessSupport.java @@ -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 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 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"); + } +} diff --git a/src/main/resources/aws/redshift-serverless-request-shapes.json b/src/main/resources/aws/redshift-serverless-request-shapes.json new file mode 100644 index 0000000000..f6b82eb4cd --- /dev/null +++ b/src/main/resources/aws/redshift-serverless-request-shapes.json @@ -0,0 +1,1225 @@ +{ + "_source": { + "generator": "tools/aws/regen_redshift_serverless_shapes.py", + "botocore": "botocore 1.43.113 (installed package)" + }, + "operations": { + "ConvertRecoveryPointToSnapshot": "ConvertRecoveryPointToSnapshotRequest", + "CreateCustomDomainAssociation": "CreateCustomDomainAssociationRequest", + "CreateEndpointAccess": "CreateEndpointAccessRequest", + "CreateNamespace": "CreateNamespaceRequest", + "CreateReservation": "CreateReservationRequest", + "CreateScheduledAction": "CreateScheduledActionRequest", + "CreateSnapshot": "CreateSnapshotRequest", + "CreateSnapshotCopyConfiguration": "CreateSnapshotCopyConfigurationRequest", + "CreateUsageLimit": "CreateUsageLimitRequest", + "CreateWorkgroup": "CreateWorkgroupRequest", + "DeleteCustomDomainAssociation": "DeleteCustomDomainAssociationRequest", + "DeleteEndpointAccess": "DeleteEndpointAccessRequest", + "DeleteNamespace": "DeleteNamespaceRequest", + "DeleteResourcePolicy": "DeleteResourcePolicyRequest", + "DeleteScheduledAction": "DeleteScheduledActionRequest", + "DeleteSnapshot": "DeleteSnapshotRequest", + "DeleteSnapshotCopyConfiguration": "DeleteSnapshotCopyConfigurationRequest", + "DeleteUsageLimit": "DeleteUsageLimitRequest", + "DeleteWorkgroup": "DeleteWorkgroupRequest", + "GetCredentials": "GetCredentialsRequest", + "GetCustomDomainAssociation": "GetCustomDomainAssociationRequest", + "GetEndpointAccess": "GetEndpointAccessRequest", + "GetIdentityCenterAuthToken": "GetIdentityCenterAuthTokenRequest", + "GetNamespace": "GetNamespaceRequest", + "GetRecoveryPoint": "GetRecoveryPointRequest", + "GetReservation": "GetReservationRequest", + "GetReservationOffering": "GetReservationOfferingRequest", + "GetResourcePolicy": "GetResourcePolicyRequest", + "GetScheduledAction": "GetScheduledActionRequest", + "GetSnapshot": "GetSnapshotRequest", + "GetTableRestoreStatus": "GetTableRestoreStatusRequest", + "GetTrack": "GetTrackRequest", + "GetUsageLimit": "GetUsageLimitRequest", + "GetWorkgroup": "GetWorkgroupRequest", + "ListCustomDomainAssociations": "ListCustomDomainAssociationsRequest", + "ListEndpointAccess": "ListEndpointAccessRequest", + "ListManagedWorkgroups": "ListManagedWorkgroupsRequest", + "ListNamespaces": "ListNamespacesRequest", + "ListRecoveryPoints": "ListRecoveryPointsRequest", + "ListReservationOfferings": "ListReservationOfferingsRequest", + "ListReservations": "ListReservationsRequest", + "ListScheduledActions": "ListScheduledActionsRequest", + "ListSnapshotCopyConfigurations": "ListSnapshotCopyConfigurationsRequest", + "ListSnapshots": "ListSnapshotsRequest", + "ListTableRestoreStatus": "ListTableRestoreStatusRequest", + "ListTagsForResource": "ListTagsForResourceRequest", + "ListTracks": "ListTracksRequest", + "ListUsageLimits": "ListUsageLimitsRequest", + "ListWorkgroups": "ListWorkgroupsRequest", + "PutResourcePolicy": "PutResourcePolicyRequest", + "RestoreFromRecoveryPoint": "RestoreFromRecoveryPointRequest", + "RestoreFromSnapshot": "RestoreFromSnapshotRequest", + "RestoreTableFromRecoveryPoint": "RestoreTableFromRecoveryPointRequest", + "RestoreTableFromSnapshot": "RestoreTableFromSnapshotRequest", + "TagResource": "TagResourceRequest", + "UntagResource": "UntagResourceRequest", + "UpdateCustomDomainAssociation": "UpdateCustomDomainAssociationRequest", + "UpdateEndpointAccess": "UpdateEndpointAccessRequest", + "UpdateLakehouseConfiguration": "UpdateLakehouseConfigurationRequest", + "UpdateNamespace": "UpdateNamespaceRequest", + "UpdateScheduledAction": "UpdateScheduledActionRequest", + "UpdateSnapshot": "UpdateSnapshotRequest", + "UpdateSnapshotCopyConfiguration": "UpdateSnapshotCopyConfigurationRequest", + "UpdateUsageLimit": "UpdateUsageLimitRequest", + "UpdateWorkgroup": "UpdateWorkgroupRequest" + }, + "shapes": { + "AmazonResourceName": { + "type": "string", + "min": 1, + "max": 1011 + }, + "Boolean": { + "type": "boolean" + }, + "Capacity": { + "type": "integer" + }, + "CatalogNameString": { + "type": "string", + "min": 1, + "max": 64, + "pattern": "^[a-z0-9_-]*[a-z]+[a-z0-9_-]*$" + }, + "ConfigParameter": { + "type": "structure", + "members": { + "parameterKey": "ParameterKey", + "parameterValue": "ParameterValue" + } + }, + "ConfigParameterList": { + "type": "list", + "member": "ConfigParameter" + }, + "ConvertRecoveryPointToSnapshotRequest": { + "type": "structure", + "required": [ + "recoveryPointId", + "snapshotName" + ], + "members": { + "recoveryPointId": "String", + "retentionPeriod": "Integer", + "snapshotName": "String", + "tags": "TagList" + } + }, + "CreateCustomDomainAssociationRequest": { + "type": "structure", + "required": [ + "customDomainCertificateArn", + "customDomainName", + "workgroupName" + ], + "members": { + "customDomainCertificateArn": "CustomDomainCertificateArnString", + "customDomainName": "CustomDomainName", + "workgroupName": "WorkgroupName" + } + }, + "CreateEndpointAccessRequest": { + "type": "structure", + "required": [ + "endpointName", + "subnetIds", + "workgroupName" + ], + "members": { + "endpointName": "String", + "ownerAccount": "OwnerAccount", + "subnetIds": "SubnetIdList", + "vpcSecurityGroupIds": "VpcSecurityGroupIdList", + "workgroupName": "String" + } + }, + "CreateNamespaceRequest": { + "type": "structure", + "required": [ + "namespaceName" + ], + "members": { + "adminPasswordSecretKmsKeyId": "KmsKeyId", + "adminUserPassword": "DbPassword", + "adminUsername": "DbUser", + "dbName": "String", + "defaultIamRoleArn": "String", + "iamRoles": "IamRoleArnList", + "kmsKeyId": "String", + "logExports": "LogExportList", + "manageAdminPassword": "Boolean", + "namespaceName": "NamespaceName", + "redshiftIdcApplicationArn": "RedshiftIdcApplicationArn", + "tags": "TagList" + } + }, + "CreateReservationRequest": { + "type": "structure", + "required": [ + "capacity", + "offeringId" + ], + "members": { + "capacity": "Capacity", + "clientToken": "String", + "offeringId": "CreateReservationRequestOfferingIdString" + } + }, + "CreateReservationRequestOfferingIdString": { + "type": "string", + "min": 1, + "max": 64 + }, + "CreateScheduledActionRequest": { + "type": "structure", + "required": [ + "namespaceName", + "roleArn", + "schedule", + "scheduledActionName", + "targetAction" + ], + "members": { + "enabled": "Boolean", + "endTime": "Timestamp", + "namespaceName": "NamespaceName", + "roleArn": "IamRoleArn", + "schedule": "Schedule", + "scheduledActionDescription": "String", + "scheduledActionName": "ScheduledActionName", + "startTime": "Timestamp", + "targetAction": "TargetAction" + } + }, + "CreateSnapshotCopyConfigurationRequest": { + "type": "structure", + "required": [ + "destinationRegion", + "namespaceName" + ], + "members": { + "destinationKmsKeyId": "KmsKeyId", + "destinationRegion": "String", + "namespaceName": "NamespaceName", + "snapshotRetentionPeriod": "Integer" + } + }, + "CreateSnapshotRequest": { + "type": "structure", + "required": [ + "namespaceName", + "snapshotName" + ], + "members": { + "namespaceName": "String", + "retentionPeriod": "Integer", + "snapshotName": "String", + "tags": "TagList" + } + }, + "CreateSnapshotScheduleActionParameters": { + "type": "structure", + "required": [ + "namespaceName", + "snapshotNamePrefix" + ], + "members": { + "namespaceName": "NamespaceName", + "retentionPeriod": "Integer", + "snapshotNamePrefix": "SnapshotNamePrefix", + "tags": "TagList" + } + }, + "CreateUsageLimitRequest": { + "type": "structure", + "required": [ + "amount", + "resourceArn", + "usageType" + ], + "members": { + "amount": "Long", + "breachAction": "UsageLimitBreachAction", + "period": "UsageLimitPeriod", + "resourceArn": "String", + "usageType": "UsageLimitUsageType" + } + }, + "CreateWorkgroupRequest": { + "type": "structure", + "required": [ + "namespaceName", + "workgroupName" + ], + "members": { + "baseCapacity": "Integer", + "configParameters": "ConfigParameterList", + "enhancedVpcRouting": "Boolean", + "extraComputeForAutomaticOptimization": "Boolean", + "ipAddressType": "IpAddressType", + "maxCapacity": "Integer", + "namespaceName": "NamespaceName", + "port": "Integer", + "pricePerformanceTarget": "PerformanceTarget", + "publiclyAccessible": "Boolean", + "securityGroupIds": "SecurityGroupIdList", + "subnetIds": "SubnetIdList", + "tags": "TagList", + "trackName": "TrackName", + "workgroupName": "WorkgroupName" + } + }, + "CustomDomainCertificateArnString": { + "type": "string", + "min": 20, + "max": 2048, + "pattern": "arn:[\\w+=/,.@-]+:acm:[\\w+=/,.@-]*:[0-9]+:[\\w+=,.@-]+(/[\\w+=,.@-]+)*" + }, + "CustomDomainName": { + "type": "string", + "min": 1, + "max": 253, + "pattern": "^(((?!-)[A-Za-z0-9-]{0,62}[A-Za-z0-9])\\.)+((?!-)[A-Za-z0-9-]{1,62}[A-Za-z0-9])$" + }, + "DbName": { + "type": "string" + }, + "DbPassword": { + "type": "string" + }, + "DbUser": { + "type": "string" + }, + "DeleteCustomDomainAssociationRequest": { + "type": "structure", + "required": [ + "customDomainName", + "workgroupName" + ], + "members": { + "customDomainName": "CustomDomainName", + "workgroupName": "WorkgroupName" + } + }, + "DeleteEndpointAccessRequest": { + "type": "structure", + "required": [ + "endpointName" + ], + "members": { + "endpointName": "String" + } + }, + "DeleteNamespaceRequest": { + "type": "structure", + "required": [ + "namespaceName" + ], + "members": { + "finalSnapshotName": "String", + "finalSnapshotRetentionPeriod": "Integer", + "namespaceName": "NamespaceName" + } + }, + "DeleteResourcePolicyRequest": { + "type": "structure", + "required": [ + "resourceArn" + ], + "members": { + "resourceArn": "String" + } + }, + "DeleteScheduledActionRequest": { + "type": "structure", + "required": [ + "scheduledActionName" + ], + "members": { + "scheduledActionName": "ScheduledActionName" + } + }, + "DeleteSnapshotCopyConfigurationRequest": { + "type": "structure", + "required": [ + "snapshotCopyConfigurationId" + ], + "members": { + "snapshotCopyConfigurationId": "String" + } + }, + "DeleteSnapshotRequest": { + "type": "structure", + "required": [ + "snapshotName" + ], + "members": { + "snapshotName": "String" + } + }, + "DeleteUsageLimitRequest": { + "type": "structure", + "required": [ + "usageLimitId" + ], + "members": { + "usageLimitId": "String" + } + }, + "DeleteWorkgroupRequest": { + "type": "structure", + "required": [ + "workgroupName" + ], + "members": { + "workgroupName": "WorkgroupName" + } + }, + "GetCredentialsRequest": { + "type": "structure", + "members": { + "customDomainName": "CustomDomainName", + "dbName": "DbName", + "durationSeconds": "Integer", + "workgroupName": "WorkgroupName" + } + }, + "GetCustomDomainAssociationRequest": { + "type": "structure", + "required": [ + "customDomainName", + "workgroupName" + ], + "members": { + "customDomainName": "CustomDomainName", + "workgroupName": "WorkgroupName" + } + }, + "GetEndpointAccessRequest": { + "type": "structure", + "required": [ + "endpointName" + ], + "members": { + "endpointName": "String" + } + }, + "GetIdentityCenterAuthTokenRequest": { + "type": "structure", + "required": [ + "workgroupNames" + ], + "members": { + "workgroupNames": "WorkgroupNameList" + } + }, + "GetNamespaceRequest": { + "type": "structure", + "required": [ + "namespaceName" + ], + "members": { + "namespaceName": "NamespaceName" + } + }, + "GetRecoveryPointRequest": { + "type": "structure", + "required": [ + "recoveryPointId" + ], + "members": { + "recoveryPointId": "String" + } + }, + "GetReservationOfferingRequest": { + "type": "structure", + "required": [ + "offeringId" + ], + "members": { + "offeringId": "GetReservationOfferingRequestOfferingIdString" + } + }, + "GetReservationOfferingRequestOfferingIdString": { + "type": "string", + "min": 1, + "max": 64 + }, + "GetReservationRequest": { + "type": "structure", + "required": [ + "reservationId" + ], + "members": { + "reservationId": "GetReservationRequestReservationIdString" + } + }, + "GetReservationRequestReservationIdString": { + "type": "string", + "min": 1, + "max": 64 + }, + "GetResourcePolicyRequest": { + "type": "structure", + "required": [ + "resourceArn" + ], + "members": { + "resourceArn": "String" + } + }, + "GetScheduledActionRequest": { + "type": "structure", + "required": [ + "scheduledActionName" + ], + "members": { + "scheduledActionName": "ScheduledActionName" + } + }, + "GetSnapshotRequest": { + "type": "structure", + "members": { + "ownerAccount": "String", + "snapshotArn": "String", + "snapshotName": "String" + } + }, + "GetTableRestoreStatusRequest": { + "type": "structure", + "required": [ + "tableRestoreRequestId" + ], + "members": { + "tableRestoreRequestId": "String" + } + }, + "GetTrackRequest": { + "type": "structure", + "required": [ + "trackName" + ], + "members": { + "trackName": "TrackName" + } + }, + "GetUsageLimitRequest": { + "type": "structure", + "required": [ + "usageLimitId" + ], + "members": { + "usageLimitId": "String" + } + }, + "GetWorkgroupRequest": { + "type": "structure", + "required": [ + "workgroupName" + ], + "members": { + "workgroupName": "WorkgroupName" + } + }, + "IamRoleArn": { + "type": "string" + }, + "IamRoleArnList": { + "type": "list", + "member": "IamRoleArn" + }, + "Integer": { + "type": "integer" + }, + "IpAddressType": { + "type": "string", + "pattern": "^(ipv4|dualstack)$" + }, + "KmsKeyId": { + "type": "string" + }, + "LakehouseIdcRegistration": { + "type": "string", + "enum": [ + "Associate", + "Disassociate" + ] + }, + "LakehouseRegistration": { + "type": "string", + "enum": [ + "Register", + "Deregister" + ] + }, + "ListCustomDomainAssociationsRequest": { + "type": "structure", + "members": { + "customDomainCertificateArn": "CustomDomainCertificateArnString", + "customDomainName": "CustomDomainName", + "maxResults": "ListCustomDomainAssociationsRequestMaxResultsInteger", + "nextToken": "PaginationToken" + } + }, + "ListCustomDomainAssociationsRequestMaxResultsInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListEndpointAccessRequest": { + "type": "structure", + "members": { + "maxResults": "ListEndpointAccessRequestMaxResultsInteger", + "nextToken": "String", + "ownerAccount": "OwnerAccount", + "vpcId": "String", + "workgroupName": "String" + } + }, + "ListEndpointAccessRequestMaxResultsInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListManagedWorkgroupsRequest": { + "type": "structure", + "members": { + "maxResults": "ListManagedWorkgroupsRequestMaxResultsInteger", + "nextToken": "PaginationToken", + "sourceArn": "SourceArn" + } + }, + "ListManagedWorkgroupsRequestMaxResultsInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListNamespacesRequest": { + "type": "structure", + "members": { + "maxResults": "ListNamespacesRequestMaxResultsInteger", + "nextToken": "String" + } + }, + "ListNamespacesRequestMaxResultsInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListRecoveryPointsRequest": { + "type": "structure", + "members": { + "endTime": "Timestamp", + "maxResults": "ListRecoveryPointsRequestMaxResultsInteger", + "namespaceArn": "String", + "namespaceName": "NamespaceName", + "nextToken": "String", + "startTime": "Timestamp" + } + }, + "ListRecoveryPointsRequestMaxResultsInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListReservationOfferingsRequest": { + "type": "structure", + "members": { + "maxResults": "ListReservationOfferingsRequestMaxResultsInteger", + "nextToken": "PaginationToken" + } + }, + "ListReservationOfferingsRequestMaxResultsInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListReservationsRequest": { + "type": "structure", + "members": { + "maxResults": "ListReservationsRequestMaxResultsInteger", + "nextToken": "PaginationToken" + } + }, + "ListReservationsRequestMaxResultsInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListScheduledActionsRequest": { + "type": "structure", + "members": { + "maxResults": "ListScheduledActionsRequestMaxResultsInteger", + "namespaceName": "NamespaceName", + "nextToken": "PaginationToken" + } + }, + "ListScheduledActionsRequestMaxResultsInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListSnapshotCopyConfigurationsRequest": { + "type": "structure", + "members": { + "maxResults": "ListSnapshotCopyConfigurationsRequestMaxResultsInteger", + "namespaceName": "NamespaceName", + "nextToken": "PaginationToken" + } + }, + "ListSnapshotCopyConfigurationsRequestMaxResultsInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListSnapshotsRequest": { + "type": "structure", + "members": { + "endTime": "Timestamp", + "maxResults": "ListSnapshotsRequestMaxResultsInteger", + "namespaceArn": "String", + "namespaceName": "String", + "nextToken": "String", + "ownerAccount": "String", + "startTime": "Timestamp" + } + }, + "ListSnapshotsRequestMaxResultsInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListTableRestoreStatusRequest": { + "type": "structure", + "members": { + "maxResults": "ListTableRestoreStatusRequestMaxResultsInteger", + "namespaceName": "String", + "nextToken": "PaginationToken", + "workgroupName": "String" + } + }, + "ListTableRestoreStatusRequestMaxResultsInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListTagsForResourceRequest": { + "type": "structure", + "required": [ + "resourceArn" + ], + "members": { + "resourceArn": "AmazonResourceName" + } + }, + "ListTracksRequest": { + "type": "structure", + "members": { + "maxResults": "ListTracksRequestMaxResultsInteger", + "nextToken": "PaginationToken" + } + }, + "ListTracksRequestMaxResultsInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListUsageLimitsRequest": { + "type": "structure", + "members": { + "maxResults": "ListUsageLimitsRequestMaxResultsInteger", + "nextToken": "PaginationToken", + "resourceArn": "String", + "usageType": "UsageLimitUsageType" + } + }, + "ListUsageLimitsRequestMaxResultsInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "ListWorkgroupsRequest": { + "type": "structure", + "members": { + "maxResults": "ListWorkgroupsRequestMaxResultsInteger", + "nextToken": "String", + "ownerAccount": "OwnerAccount" + } + }, + "ListWorkgroupsRequestMaxResultsInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "LogDestinationType": { + "type": "string", + "enum": [ + "s3table", + "cloudwatch" + ] + }, + "LogExport": { + "type": "string", + "enum": [ + "useractivitylog", + "userlog", + "connectionlog" + ] + }, + "LogExportList": { + "type": "list", + "min": 0, + "max": 16, + "member": "LogExport" + }, + "Long": { + "type": "long" + }, + "NamespaceName": { + "type": "string", + "min": 3, + "max": 64, + "pattern": "^[a-z0-9-]+$" + }, + "OwnerAccount": { + "type": "string", + "min": 1, + "max": 12, + "pattern": "(\\d{12})" + }, + "PaginationToken": { + "type": "string", + "min": 8, + "max": 1024 + }, + "ParameterKey": { + "type": "string" + }, + "ParameterValue": { + "type": "string" + }, + "PerformanceTarget": { + "type": "structure", + "members": { + "level": "PerformanceTargetLevelInteger", + "status": "PerformanceTargetStatus" + } + }, + "PerformanceTargetLevelInteger": { + "type": "integer", + "min": 1, + "max": 100 + }, + "PerformanceTargetStatus": { + "type": "string", + "enum": [ + "ENABLED", + "DISABLED" + ] + }, + "PutResourcePolicyRequest": { + "type": "structure", + "required": [ + "policy", + "resourceArn" + ], + "members": { + "policy": "String", + "resourceArn": "String" + } + }, + "RedshiftIdcApplicationArn": { + "type": "string", + "min": 1, + "max": 1024 + }, + "RestoreFromRecoveryPointRequest": { + "type": "structure", + "required": [ + "namespaceName", + "recoveryPointId", + "workgroupName" + ], + "members": { + "maintainIntegration": "Boolean", + "namespaceName": "NamespaceName", + "recoveryPointId": "String", + "workgroupName": "WorkgroupName" + } + }, + "RestoreFromSnapshotRequest": { + "type": "structure", + "required": [ + "namespaceName", + "workgroupName" + ], + "members": { + "adminPasswordSecretKmsKeyId": "KmsKeyId", + "maintainIntegration": "Boolean", + "manageAdminPassword": "Boolean", + "namespaceName": "NamespaceName", + "ownerAccount": "String", + "snapshotArn": "String", + "snapshotName": "String", + "workgroupName": "WorkgroupName" + } + }, + "RestoreTableFromRecoveryPointRequest": { + "type": "structure", + "required": [ + "namespaceName", + "newTableName", + "recoveryPointId", + "sourceDatabaseName", + "sourceTableName", + "workgroupName" + ], + "members": { + "activateCaseSensitiveIdentifier": "Boolean", + "namespaceName": "String", + "newTableName": "String", + "recoveryPointId": "String", + "sourceDatabaseName": "String", + "sourceSchemaName": "String", + "sourceTableName": "String", + "targetDatabaseName": "String", + "targetSchemaName": "String", + "workgroupName": "String" + } + }, + "RestoreTableFromSnapshotRequest": { + "type": "structure", + "required": [ + "namespaceName", + "newTableName", + "snapshotName", + "sourceDatabaseName", + "sourceTableName", + "workgroupName" + ], + "members": { + "activateCaseSensitiveIdentifier": "Boolean", + "namespaceName": "String", + "newTableName": "String", + "snapshotName": "String", + "sourceDatabaseName": "String", + "sourceSchemaName": "String", + "sourceTableName": "String", + "targetDatabaseName": "String", + "targetSchemaName": "String", + "workgroupName": "String" + } + }, + "S3TableAction": { + "type": "string", + "enum": [ + "Enable", + "Disable" + ] + }, + "S3TableGranularity": { + "type": "string", + "enum": [ + "namespace", + "account" + ] + }, + "S3TableName": { + "type": "string", + "min": 1, + "max": 128, + "pattern": "^(all|sys_[a-z0-9_]+)$" + }, + "S3TableNameList": { + "type": "list", + "min": 0, + "max": 256, + "member": "S3TableName" + }, + "Schedule": { + "type": "structure", + "members": { + "at": "Timestamp", + "cron": "String" + } + }, + "ScheduledActionName": { + "type": "string", + "min": 3, + "max": 60, + "pattern": "^[a-z0-9-]+$" + }, + "SecurityGroupId": { + "type": "string" + }, + "SecurityGroupIdList": { + "type": "list", + "member": "SecurityGroupId" + }, + "SnapshotNamePrefix": { + "type": "string", + "min": 1, + "max": 235 + }, + "SourceArn": { + "type": "string", + "pattern": "^arn:aws[a-z-]*:glue:[a-z0-9-]+:\\d+:(database|catalog)[a-z0-9-:]*(?:/[A-Za-z0-9-_]{1,255})*$" + }, + "String": { + "type": "string" + }, + "SubnetId": { + "type": "string" + }, + "SubnetIdList": { + "type": "list", + "member": "SubnetId" + }, + "Tag": { + "type": "structure", + "required": [ + "key", + "value" + ], + "members": { + "key": "TagKey", + "value": "TagValue" + } + }, + "TagKey": { + "type": "string", + "min": 1, + "max": 128 + }, + "TagKeyList": { + "type": "list", + "min": 0, + "max": 200, + "member": "TagKey" + }, + "TagList": { + "type": "list", + "min": 0, + "max": 200, + "member": "Tag" + }, + "TagResourceRequest": { + "type": "structure", + "required": [ + "resourceArn", + "tags" + ], + "members": { + "resourceArn": "AmazonResourceName", + "tags": "TagList" + } + }, + "TagValue": { + "type": "string", + "min": 0, + "max": 256 + }, + "TargetAction": { + "type": "structure", + "members": { + "createSnapshot": "CreateSnapshotScheduleActionParameters" + } + }, + "Timestamp": { + "type": "timestamp" + }, + "TrackName": { + "type": "string", + "min": 1, + "max": 256, + "pattern": "^[a-zA-Z0-9_]+$" + }, + "UntagResourceRequest": { + "type": "structure", + "required": [ + "resourceArn", + "tagKeys" + ], + "members": { + "resourceArn": "AmazonResourceName", + "tagKeys": "TagKeyList" + } + }, + "UpdateCustomDomainAssociationRequest": { + "type": "structure", + "required": [ + "customDomainCertificateArn", + "customDomainName", + "workgroupName" + ], + "members": { + "customDomainCertificateArn": "CustomDomainCertificateArnString", + "customDomainName": "CustomDomainName", + "workgroupName": "WorkgroupName" + } + }, + "UpdateEndpointAccessRequest": { + "type": "structure", + "required": [ + "endpointName" + ], + "members": { + "endpointName": "String", + "vpcSecurityGroupIds": "VpcSecurityGroupIdList" + } + }, + "UpdateLakehouseConfigurationRequest": { + "type": "structure", + "required": [ + "namespaceName" + ], + "members": { + "catalogName": "CatalogNameString", + "dryRun": "Boolean", + "lakehouseIdcApplicationArn": "String", + "lakehouseIdcRegistration": "LakehouseIdcRegistration", + "lakehouseRegistration": "LakehouseRegistration", + "namespaceName": "NamespaceName" + } + }, + "UpdateNamespaceRequest": { + "type": "structure", + "required": [ + "namespaceName" + ], + "members": { + "adminPasswordSecretKmsKeyId": "KmsKeyId", + "adminUserPassword": "DbPassword", + "adminUsername": "DbUser", + "defaultIamRoleArn": "String", + "iamRoles": "IamRoleArnList", + "kmsKeyId": "String", + "logDestinationType": "LogDestinationType", + "logExports": "LogExportList", + "manageAdminPassword": "Boolean", + "namespaceName": "NamespaceName", + "s3TableAction": "S3TableAction", + "s3TableGranularity": "S3TableGranularity", + "s3TableKmsKeyId": "KmsKeyId", + "s3TableNames": "S3TableNameList" + } + }, + "UpdateScheduledActionRequest": { + "type": "structure", + "required": [ + "scheduledActionName" + ], + "members": { + "enabled": "Boolean", + "endTime": "Timestamp", + "roleArn": "IamRoleArn", + "schedule": "Schedule", + "scheduledActionDescription": "String", + "scheduledActionName": "ScheduledActionName", + "startTime": "Timestamp", + "targetAction": "TargetAction" + } + }, + "UpdateSnapshotCopyConfigurationRequest": { + "type": "structure", + "required": [ + "snapshotCopyConfigurationId" + ], + "members": { + "snapshotCopyConfigurationId": "String", + "snapshotRetentionPeriod": "Integer" + } + }, + "UpdateSnapshotRequest": { + "type": "structure", + "required": [ + "snapshotName" + ], + "members": { + "retentionPeriod": "Integer", + "snapshotName": "String" + } + }, + "UpdateUsageLimitRequest": { + "type": "structure", + "required": [ + "usageLimitId" + ], + "members": { + "amount": "Long", + "breachAction": "UsageLimitBreachAction", + "usageLimitId": "String" + } + }, + "UpdateWorkgroupRequest": { + "type": "structure", + "required": [ + "workgroupName" + ], + "members": { + "baseCapacity": "Integer", + "configParameters": "ConfigParameterList", + "enhancedVpcRouting": "Boolean", + "extraComputeForAutomaticOptimization": "Boolean", + "ipAddressType": "IpAddressType", + "maxCapacity": "Integer", + "port": "Integer", + "pricePerformanceTarget": "PerformanceTarget", + "publiclyAccessible": "Boolean", + "securityGroupIds": "SecurityGroupIdList", + "subnetIds": "SubnetIdList", + "trackName": "TrackName", + "workgroupName": "WorkgroupName" + } + }, + "UsageLimitBreachAction": { + "type": "string", + "enum": [ + "log", + "emit-metric", + "deactivate" + ] + }, + "UsageLimitPeriod": { + "type": "string", + "enum": [ + "daily", + "weekly", + "monthly" + ] + }, + "UsageLimitUsageType": { + "type": "string", + "enum": [ + "serverless-compute", + "cross-region-datasharing" + ] + }, + "VpcSecurityGroupId": { + "type": "string" + }, + "VpcSecurityGroupIdList": { + "type": "list", + "member": "VpcSecurityGroupId" + }, + "WorkgroupName": { + "type": "string", + "min": 3, + "max": 64, + "pattern": "^[a-z0-9-]+$" + }, + "WorkgroupNameList": { + "type": "list", + "min": 1, + "max": 20, + "member": "WorkgroupName" + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java index a0bd873dc8..30777ab7ad 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java @@ -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"); diff --git a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessRequestShapesTest.java b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessRequestShapesTest.java new file mode 100644 index 0000000000..28c9050f96 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessRequestShapesTest.java @@ -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)); + } +} diff --git a/tools/aws/regen_redshift_serverless_shapes.py b/tools/aws/regen_redshift_serverless_shapes.py new file mode 100644 index 0000000000..5b7acb9cec --- /dev/null +++ b/tools/aws/regen_redshift_serverless_shapes.py @@ -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()) diff --git a/tools/aws/test_regen_redshift_serverless_shapes.py b/tools/aws/test_regen_redshift_serverless_shapes.py new file mode 100644 index 0000000000..a05a62d552 --- /dev/null +++ b/tools/aws/test_regen_redshift_serverless_shapes.py @@ -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")