mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
feat(redshiftserverless): add namespace lifecycle and tagging (#3631)
* feat(redshiftserverless): add namespace lifecycle Amazon Redshift Serverless was absent entirely: every call returned UnknownOperationException, so Terraform's aws_redshiftserverless_namespace could not be planned or applied against Floci. Add a JSON 1.1 service under the RedshiftServerless. target prefix with CreateNamespace, GetNamespace, ListNamespaces, UpdateNamespace, and DeleteNamespace. Namespaces are account and Region scoped and stored through StorageFactory. AWS defaults are applied on create (dbName dev, kmsKeyId AWS_OWNED_KMS_KEY, empty logExports, status AVAILABLE), adminUserPassword is accepted and never returned, DeleteNamespace returns the removed namespace with status DELETING, and UpdateNamespace applies only the supplied fields. Workgroups, snapshots, and the tagging operations remain unemulated. * feat(redshiftserverless): add namespace tagging operations Terraform's aws_redshiftserverless_namespace calls ListTagsForResource on every read once tags are involved, so the namespace lifecycle alone left the resource broken as soon as a config set tags. Add ListTagsForResource, TagResource, and UntagResource. Lookup is by resourceArn rather than namespace name, scoped to the caller's Region, since that is how AWS keys these operations; the namespace is currently the only taggable Redshift Serverless resource, so any other ARN is reported absent. TagResource merges into the existing tags, UntagResource removes by key, and tags passed to CreateNamespace are readable back and survive UpdateNamespace. * fix(redshiftserverless): emit creationDate as ISO-8601 per the API model The awsJson1.1 default is epoch seconds and 133 call sites use it, but this model overrides it: TimestampFormatTrait ISO_8601 on creationDate (and on all eleven other timestamp members in the package, audited). Strict clients broke on the number: Terraform's Go SDK failed to decode and orphaned the created namespace outside state; the Java SDK failed to unmarshall. Only botocore's lenient parsing let CLI checks pass. Emitted via the repo's millisecond-ISO idiom; format pinned by regex in the integration test and by a new handler-level unit test class covering the wire layer that had none (timestamp shape, nextToken emission, maxResults type guard). Checklist note added to AGENTS.md + CONTRIBUTING.md so the next service checks the trait before reaching for the epoch idiom. * docs(redshiftserverless): the ISO-8601 rule is per member, not model-wide Review follow-up: the earlier claim that every timestamp member in this model carries TimestampFormatTrait(ISO_8601) is wrong — 15 of the model's 30 INSTANT members carry no trait and fall back to the awsJson1.1 epoch default. The shipped code is unaffected (creationDate, the only timestamp emitted, is genuinely ISO_8601), but the claim was load-bearing guidance: whoever adds snapshots or scheduled actions next would have applied ISO-8601 to trait-free members and reintroduced the bug in the opposite direction. Narrowed in all four places it appeared. * fix(redshiftserverless): validate collection types, copy-on-update; drop em dashes A present iamRoles, logExports, tags or tagKeys member that was not a JSON array parsed to null and was then indistinguishable from an omitted member, so a malformed UpdateNamespace silently kept the stored value and returned 200 instead of reporting the request as invalid. Only a missing or null member now means "omitted"; a present member of the wrong type, or a collection holding a non-string element, is a ValidationException naming the member. updateNamespace mutated the stored Namespace in place while GetNamespace and ListNamespaces read without taking the same monitor, so a concurrent reader could observe a torn object with some fields updated and some not. Build the new state on a copy and store that instead, which also makes the write-back explicit. The same in-place mutation was present in tagResource, untagResource and deleteNamespace, so all four now copy. Merge semantics are unchanged. Replace the em dashes in the timestamp guidance with commas and periods, per the repository ban. * fix(redshiftserverless): reject Redshift reserved words as namespace names CreateNamespace rejects a namespace name that is an Amazon Redshift SQL reserved word, so names like select or user passed the length and [a-z0-9-] checks here and were persisted. Add the documented reserved word list to the shared namespace-name validator, which create, get, update and delete all reach, so the rejection is consistent.
This commit is contained in:
1 parent
dc70f60a66
commit
4b3923712a
21 files changed
+1552
-10
No files matched your search
@@ -681,6 +681,7 @@ public interface EmulatorConfig {
|
||||
RedshiftServiceConfig redshift();
|
||||
RdsDataServiceConfig rdsData();
|
||||
RedshiftDataServiceConfig redshiftData();
|
||||
RedshiftServerlessServiceConfig redshiftServerless();
|
||||
EventBridgeServiceConfig eventbridge();
|
||||
CloudMapServiceConfig cloudmap();
|
||||
EmrServiceConfig emr();
|
||||
@@ -1577,6 +1578,11 @@ public interface EmulatorConfig {
|
||||
int resultTtlHours();
|
||||
}
|
||||
|
||||
interface RedshiftServerlessServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface NeptuneServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.ObjectReader;
|
||||
import io.github.hectorvent.floci.services.acm.AcmJsonHandler;
|
||||
import io.github.hectorvent.floci.services.athena.AthenaJsonHandler;
|
||||
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataJsonHandler;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessJsonHandler;
|
||||
import io.github.hectorvent.floci.services.cloudhsmv2.CloudHsmV2JsonHandler;
|
||||
import io.github.hectorvent.floci.services.codebuild.CodeBuildJsonHandler;
|
||||
import io.github.hectorvent.floci.services.codedeploy.CodeDeployJsonHandler;
|
||||
@@ -106,6 +107,7 @@ public class AwsJson11Controller {
|
||||
private final GlueJsonHandler glueJsonHandler;
|
||||
private final AthenaJsonHandler athenaJsonHandler;
|
||||
private final RedshiftDataJsonHandler redshiftDataJsonHandler;
|
||||
private final RedshiftServerlessJsonHandler redshiftServerlessJsonHandler;
|
||||
private final FirehoseJsonHandler firehoseJsonHandler;
|
||||
private final ResourceGroupsTaggingJsonHandler resourceGroupsTaggingJsonHandler;
|
||||
private final CodeBuildJsonHandler codeBuildJsonHandler;
|
||||
@@ -162,6 +164,7 @@ public class AwsJson11Controller {
|
||||
EcrJsonHandler ecrJsonHandler, GlueJsonHandler glueJsonHandler,
|
||||
AthenaJsonHandler athenaJsonHandler,
|
||||
RedshiftDataJsonHandler redshiftDataJsonHandler,
|
||||
RedshiftServerlessJsonHandler redshiftServerlessJsonHandler,
|
||||
FirehoseJsonHandler firehoseJsonHandler,
|
||||
ResourceGroupsTaggingJsonHandler resourceGroupsTaggingJsonHandler,
|
||||
CodeBuildJsonHandler codeBuildJsonHandler,
|
||||
@@ -222,6 +225,7 @@ public class AwsJson11Controller {
|
||||
this.glueJsonHandler = glueJsonHandler;
|
||||
this.athenaJsonHandler = athenaJsonHandler;
|
||||
this.redshiftDataJsonHandler = redshiftDataJsonHandler;
|
||||
this.redshiftServerlessJsonHandler = redshiftServerlessJsonHandler;
|
||||
this.firehoseJsonHandler = firehoseJsonHandler;
|
||||
this.resourceGroupsTaggingJsonHandler = resourceGroupsTaggingJsonHandler;
|
||||
this.codeBuildJsonHandler = codeBuildJsonHandler;
|
||||
@@ -320,6 +324,7 @@ public class AwsJson11Controller {
|
||||
case "glue" -> glueJsonHandler.handle(action, request, region);
|
||||
case "athena" -> athenaJsonHandler.handle(action, request, region);
|
||||
case "redshift-data" -> redshiftDataJsonHandler.handle(action, request, region);
|
||||
case "redshift-serverless" -> redshiftServerlessJsonHandler.handle(action, request, region);
|
||||
case "firehose" -> firehoseJsonHandler.handle(action, request, region);
|
||||
case "tagging" -> resourceGroupsTaggingJsonHandler.handle(action, request, region);
|
||||
case "codebuild" -> codeBuildJsonHandler.handle(action, request, region, regionResolver.getAccountId());
|
||||
|
||||
@@ -200,6 +200,11 @@ public class ResolvedServiceCatalog {
|
||||
"redshift-data", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
Set.of("RedshiftData."), Set.of("redshift-data"), Set.of(), Set.of()),
|
||||
descriptor("redshift-serverless", "redshift-serverless",
|
||||
config.services().redshiftServerless().enabled(), true,
|
||||
"redshiftserverless", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
Set.of("RedshiftServerless."), Set.of("redshift-serverless"), Set.of(), Set.of()),
|
||||
|
||||
descriptor("events", "eventbridge", config.services().eventbridge().enabled(), true,
|
||||
"eventbridge", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
|
||||
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* Redshift Serverless JSON 1.1 handler. Dispatched from
|
||||
* {@link io.github.hectorvent.floci.core.common.AwsJson11Controller}
|
||||
* under the {@code RedshiftServerless.} target prefix.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
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;
|
||||
|
||||
@Inject
|
||||
public RedshiftServerlessJsonHandler(RedshiftServerlessService service, ObjectMapper objectMapper) {
|
||||
this.service = service;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
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 "ListTagsForResource" -> handleListTagsForResource(request, region);
|
||||
case "TagResource" -> handleTagResource(request, region);
|
||||
case "UntagResource" -> handleUntagResource(request, region);
|
||||
default -> Response.status(400)
|
||||
.entity(new AwsErrorResponse("UnknownOperationException",
|
||||
"Operation " + action + " is not supported."))
|
||||
.build();
|
||||
};
|
||||
} catch (AwsException e) {
|
||||
return JsonErrorResponseUtils.createErrorResponse(e);
|
||||
} catch (Exception e) {
|
||||
LOG.errorf(e, "Redshift Serverless error processing action %s", action);
|
||||
return JsonErrorResponseUtils.createErrorResponse(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleCreateNamespace(JsonNode request, String region) {
|
||||
Namespace namespace = service.createNamespace(
|
||||
text(request, "namespaceName"),
|
||||
text(request, "adminUsername"),
|
||||
text(request, "dbName"),
|
||||
text(request, "kmsKeyId"),
|
||||
text(request, "defaultIamRoleArn"),
|
||||
parseStringList(request.path("iamRoles"), "iamRoles"),
|
||||
parseStringList(request.path("logExports"), "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));
|
||||
}
|
||||
|
||||
private Response handleListNamespaces(JsonNode request, String region) {
|
||||
PaginatedResult<Namespace> page = service.listNamespaces(
|
||||
region, parseMaxResults(request), text(request, "nextToken"));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode items = response.putArray("namespaces");
|
||||
page.items().forEach(namespace -> items.add(namespaceNode(namespace)));
|
||||
if (page.nextToken() != null) {
|
||||
response.put("nextToken", page.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleUpdateNamespace(JsonNode request, String region) {
|
||||
Namespace namespace = service.updateNamespace(
|
||||
text(request, "namespaceName"),
|
||||
text(request, "adminUsername"),
|
||||
text(request, "kmsKeyId"),
|
||||
text(request, "defaultIamRoleArn"),
|
||||
parseStringList(request.path("iamRoles"), "iamRoles"),
|
||||
parseStringList(request.path("logExports"), "logExports"),
|
||||
region);
|
||||
return namespaceResponse(namespace);
|
||||
}
|
||||
|
||||
private Response handleDeleteNamespace(JsonNode request, String region) {
|
||||
return namespaceResponse(service.deleteNamespace(text(request, "namespaceName"), region));
|
||||
}
|
||||
|
||||
private Response handleListTagsForResource(JsonNode request, String region) {
|
||||
Map<String, String> tags = service.listTagsForResource(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);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private Response handleUntagResource(JsonNode request, String region) {
|
||||
service.untagResource(text(request, "resourceArn"), parseStringList(request.path("tagKeys"), "tagKeys"), region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
private ArrayNode tagListNode(Map<String, String> tags) {
|
||||
ArrayNode node = objectMapper.createArrayNode();
|
||||
tags.forEach((key, value) -> {
|
||||
ObjectNode tag = node.addObject();
|
||||
tag.put("key", key);
|
||||
tag.put("value", value);
|
||||
});
|
||||
return node;
|
||||
}
|
||||
|
||||
private Response namespaceResponse(Namespace namespace) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("namespace", namespaceNode(namespace));
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code adminUserPassword} is deliberately absent: AWS never returns it on any namespace
|
||||
* operation, and the Terraform provider treats a returned value as a permanent diff.
|
||||
*/
|
||||
private ObjectNode namespaceNode(Namespace namespace) {
|
||||
ObjectNode node = objectMapper.createObjectNode();
|
||||
node.put("namespaceName", namespace.getNamespaceName());
|
||||
node.put("namespaceId", namespace.getNamespaceId());
|
||||
node.put("namespaceArn", namespace.getNamespaceArn());
|
||||
node.put("dbName", namespace.getDbName());
|
||||
node.put("kmsKeyId", namespace.getKmsKeyId());
|
||||
node.put("status", namespace.getStatus());
|
||||
if (namespace.getAdminUsername() != null) {
|
||||
node.put("adminUsername", namespace.getAdminUsername());
|
||||
}
|
||||
if (namespace.getDefaultIamRoleArn() != null) {
|
||||
node.put("defaultIamRoleArn", namespace.getDefaultIamRoleArn());
|
||||
}
|
||||
if (namespace.getCreationDate() != null) {
|
||||
node.put("creationDate", CREATION_DATE_FORMAT.format(namespace.getCreationDate()));
|
||||
}
|
||||
ArrayNode iamRoles = node.putArray("iamRoles");
|
||||
namespace.getIamRoles().forEach(iamRoles::add);
|
||||
ArrayNode logExports = node.putArray("logExports");
|
||||
namespace.getLogExports().forEach(logExports::add);
|
||||
return node;
|
||||
}
|
||||
|
||||
private Integer parseMaxResults(JsonNode request) {
|
||||
JsonNode node = request.path("maxResults");
|
||||
if (node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isNumber()) {
|
||||
throw validation("maxResults must be an integer.");
|
||||
}
|
||||
return node.asInt();
|
||||
}
|
||||
|
||||
/**
|
||||
* Absent means absent and wrong means wrong: only a missing or null member returns null, so
|
||||
* that callers can distinguish "omitted, keep the stored value" from "supplied". Treating a
|
||||
* present member of the wrong type as absent would let a malformed UpdateNamespace silently
|
||||
* keep the old roles instead of reporting the request as invalid.
|
||||
*/
|
||||
private List<String> parseStringList(JsonNode node, String field) {
|
||||
if (node == null || node.isMissingNode() || node.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!node.isArray()) {
|
||||
throw validation(field + " must be an array of strings.");
|
||||
}
|
||||
List<String> list = new ArrayList<>();
|
||||
for (JsonNode element : node) {
|
||||
if (!element.isTextual()) {
|
||||
throw validation(field + " must contain only strings.");
|
||||
}
|
||||
list.add(element.textValue());
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private Map<String, String> parseTagList(JsonNode tagsNode, String field) {
|
||||
if (tagsNode == null || tagsNode.isMissingNode() || tagsNode.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!tagsNode.isArray()) {
|
||||
throw validation(field + " must be an array of tags.");
|
||||
}
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
for (JsonNode tag : tagsNode) {
|
||||
if (!tag.isObject()) {
|
||||
throw validation(field + " must contain only tag objects.");
|
||||
}
|
||||
String key = tag.path("key").asText(null);
|
||||
if (key != null) {
|
||||
tags.put(key, tag.path("value").asText(null));
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
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;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class RedshiftServerlessService implements Resettable {
|
||||
public static final String DEFAULT_DB_NAME = "dev";
|
||||
public static final String AWS_OWNED_KMS_KEY = "AWS_OWNED_KMS_KEY";
|
||||
|
||||
private static final Pattern NAMESPACE_NAME = Pattern.compile("[a-z0-9-]+");
|
||||
private static final Pattern DB_NAME = Pattern.compile("[a-zA-Z][a-zA-Z_0-9+.@-]*");
|
||||
private static final Set<String> LOG_EXPORTS = Set.of("useractivitylog", "userlog", "connectionlog");
|
||||
|
||||
/**
|
||||
* Amazon Redshift's SQL reserved words, which CreateNamespace rejects as namespace names even
|
||||
* though they satisfy the length and character rules. Held lowercase because a namespace name
|
||||
* is already constrained to lowercase letters, digits and hyphens, so a direct lookup suffices.
|
||||
* Transcribed from https://docs.aws.amazon.com/redshift/latest/dg/r_pg_keywords.html
|
||||
*/
|
||||
private static final Set<String> RESERVED_WORDS = Set.of(
|
||||
"aes128", "aes256", "all", "allowoverwrite", "analyse", "analyze",
|
||||
"and", "any", "array", "as", "asc", "authorization",
|
||||
"az64", "backup", "between", "binary", "blanksasnull", "both",
|
||||
"bytedict", "bzip2", "case", "cast", "check", "collate",
|
||||
"column", "constraint", "create", "credentials", "cross", "current_date",
|
||||
"current_time", "current_timestamp", "current_user", "current_user_id", "default", "deferrable",
|
||||
"deflate", "defrag", "delta", "delta32k", "desc", "disable",
|
||||
"distinct", "do", "else", "emptyasnull", "enable", "encode",
|
||||
"encrypt", "encryption", "end", "except", "explicit", "false",
|
||||
"for", "foreign", "freeze", "from", "full", "globaldict256",
|
||||
"globaldict64k", "grant", "group", "gzip", "having", "identity",
|
||||
"ignore", "ilike", "in", "initially", "inner", "intersect",
|
||||
"interval", "into", "is", "isnull", "join", "leading",
|
||||
"left", "like", "limit", "localtime", "localtimestamp", "lun",
|
||||
"luns", "lzo", "lzop", "minus", "mostly16", "mostly32",
|
||||
"mostly8", "natural", "new", "not", "notnull", "null",
|
||||
"nulls", "off", "offline", "offset", "oid", "old",
|
||||
"on", "only", "open", "or", "order", "outer",
|
||||
"overlaps", "parallel", "partition", "percent", "permissions", "pivot",
|
||||
"placing", "primary", "raw", "readratio", "recover", "references",
|
||||
"rejectlog", "resort", "respect", "restore", "right", "select",
|
||||
"session_user", "similar", "snapshot", "some", "sysdate", "system",
|
||||
"table", "tag", "tdes", "text255", "text32k", "then",
|
||||
"timestamp", "to", "top", "trailing", "true", "truncatecolumns",
|
||||
"union", "unique", "unnest", "unpivot", "user", "using",
|
||||
"verbose", "wallet", "when", "where", "with", "without");
|
||||
|
||||
private final AccountAwareStorageBackend<Namespace> namespaces;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public RedshiftServerlessService(StorageFactory storageFactory, RegionResolver regionResolver) {
|
||||
this.namespaces = storageFactory.create("redshiftserverless", "redshiftserverless-namespaces.json",
|
||||
new TypeReference<Map<String, Namespace>>() {});
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
public synchronized Namespace createNamespace(String namespaceName, String adminUsername, String dbName,
|
||||
String kmsKeyId, String defaultIamRoleArn, List<String> iamRoles,
|
||||
List<String> logExports, Map<String, String> tags, String region) {
|
||||
validateNamespaceName(namespaceName);
|
||||
String key = storageKey(region, namespaceName);
|
||||
if (namespaces.get(key).isPresent()) {
|
||||
throw new AwsException("ConflictException",
|
||||
"The namespace " + namespaceName + " already exists.", 409);
|
||||
}
|
||||
|
||||
Namespace namespace = new Namespace();
|
||||
namespace.setNamespaceName(namespaceName);
|
||||
namespace.setNamespaceId(UUID.randomUUID().toString());
|
||||
namespace.setNamespaceArn(regionResolver.buildArn("redshift-serverless", region,
|
||||
"namespace/" + namespace.getNamespaceId()));
|
||||
namespace.setAdminUsername(adminUsername);
|
||||
namespace.setDbName(validateDbName(dbName));
|
||||
namespace.setKmsKeyId(kmsKeyId == null || kmsKeyId.isBlank() ? AWS_OWNED_KMS_KEY : kmsKeyId);
|
||||
namespace.setDefaultIamRoleArn(defaultIamRoleArn);
|
||||
namespace.setIamRoles(copyOf(iamRoles));
|
||||
namespace.setLogExports(validateLogExports(logExports));
|
||||
namespace.setStatus("AVAILABLE");
|
||||
namespace.setCreationDate(Instant.now());
|
||||
namespace.setTags(tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags));
|
||||
namespaces.put(key, namespace);
|
||||
return namespace;
|
||||
}
|
||||
|
||||
public Namespace getNamespace(String namespaceName, String region) {
|
||||
validateNamespaceName(namespaceName);
|
||||
return namespaces.get(storageKey(region, namespaceName))
|
||||
.orElseThrow(() -> notFound(namespaceName));
|
||||
}
|
||||
|
||||
public PaginatedResult<Namespace> listNamespaces(String region, Integer maxResults, String nextToken) {
|
||||
List<Namespace> all = namespaces.scan(key -> key.startsWith(region + "::"));
|
||||
return Pagination.paginate(all, Namespace::getNamespaceName, maxResults, nextToken,
|
||||
100, 100, "ValidationException");
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the new state on a copy and stores that, rather than mutating the stored instance.
|
||||
* Reads do not take the monitor this method holds, so an in-place mutation lets a concurrent
|
||||
* GetNamespace or ListNamespaces observe a torn object: some fields updated, some not.
|
||||
*/
|
||||
public synchronized Namespace updateNamespace(String namespaceName, String adminUsername, String kmsKeyId,
|
||||
String defaultIamRoleArn, List<String> iamRoles,
|
||||
List<String> logExports, String region) {
|
||||
String key = storageKey(region, namespaceName);
|
||||
Namespace updated = new Namespace(getNamespace(namespaceName, region));
|
||||
if (adminUsername != null) {
|
||||
updated.setAdminUsername(adminUsername);
|
||||
}
|
||||
if (kmsKeyId != null && !kmsKeyId.isBlank()) {
|
||||
updated.setKmsKeyId(kmsKeyId);
|
||||
}
|
||||
if (defaultIamRoleArn != null) {
|
||||
updated.setDefaultIamRoleArn(defaultIamRoleArn);
|
||||
}
|
||||
if (iamRoles != null) {
|
||||
updated.setIamRoles(copyOf(iamRoles));
|
||||
}
|
||||
if (logExports != null) {
|
||||
updated.setLogExports(validateLogExports(logExports));
|
||||
}
|
||||
namespaces.put(key, updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
public synchronized Namespace deleteNamespace(String namespaceName, String region) {
|
||||
Namespace deleted = new Namespace(getNamespace(namespaceName, region));
|
||||
namespaces.delete(storageKey(region, namespaceName));
|
||||
deleted.setStatus("DELETING");
|
||||
return deleted;
|
||||
}
|
||||
|
||||
public Map<String, String> listTagsForResource(String resourceArn, String region) {
|
||||
return new LinkedHashMap<>(resolveByArn(resourceArn, region).getTags());
|
||||
}
|
||||
|
||||
public synchronized Map<String, String> tagResource(String resourceArn, Map<String, String> tags, String region) {
|
||||
Namespace updated = new Namespace(resolveByArn(resourceArn, region));
|
||||
if (tags != null) {
|
||||
updated.getTags().putAll(tags);
|
||||
}
|
||||
namespaces.put(storageKey(region, updated.getNamespaceName()), updated);
|
||||
return new LinkedHashMap<>(updated.getTags());
|
||||
}
|
||||
|
||||
public synchronized Map<String, String> untagResource(String resourceArn, List<String> tagKeys, String region) {
|
||||
Namespace resolved = resolveByArn(resourceArn, region);
|
||||
if (tagKeys == null) {
|
||||
throw validation("tagKeys is required.");
|
||||
}
|
||||
Namespace updated = new Namespace(resolved);
|
||||
tagKeys.forEach(updated.getTags()::remove);
|
||||
namespaces.put(storageKey(region, updated.getNamespaceName()), updated);
|
||||
return new LinkedHashMap<>(updated.getTags());
|
||||
}
|
||||
|
||||
/**
|
||||
* Redshift Serverless tags whatever the ARN names, so the lookup is by ARN rather than by
|
||||
* namespace name. Only namespaces are taggable in Floci, so any other Redshift Serverless ARN
|
||||
* resolves to nothing and is reported as absent rather than as an unsupported resource type.
|
||||
*/
|
||||
private Namespace resolveByArn(String resourceArn, String region) {
|
||||
if (resourceArn == null || resourceArn.isBlank()) {
|
||||
throw validation("resourceArn is required.");
|
||||
}
|
||||
return namespaces.scan(key -> key.startsWith(region + "::")).stream()
|
||||
.filter(namespace -> resourceArn.equals(namespace.getNamespaceArn()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"The resource " + resourceArn + " was not found.", 404));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
namespaces.clear();
|
||||
}
|
||||
|
||||
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.");
|
||||
}
|
||||
if (RESERVED_WORDS.contains(namespaceName)) {
|
||||
throw validation("namespaceName must not be an Amazon Redshift reserved word.");
|
||||
}
|
||||
}
|
||||
|
||||
private static String validateDbName(String dbName) {
|
||||
if (dbName == null || dbName.isBlank()) {
|
||||
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.");
|
||||
}
|
||||
return dbName;
|
||||
}
|
||||
|
||||
private static List<String> validateLogExports(List<String> logExports) {
|
||||
List<String> validated = copyOf(logExports);
|
||||
for (String logExport : validated) {
|
||||
if (!LOG_EXPORTS.contains(logExport)) {
|
||||
throw validation("logExports must contain only useractivitylog, userlog, and connectionlog.");
|
||||
}
|
||||
}
|
||||
return validated;
|
||||
}
|
||||
|
||||
private static List<String> copyOf(List<String> values) {
|
||||
return values == null ? new ArrayList<>() : new ArrayList<>(values);
|
||||
}
|
||||
|
||||
private static String storageKey(String region, String namespaceName) {
|
||||
return region + "::" + namespaceName;
|
||||
}
|
||||
|
||||
private static AwsException notFound(String namespaceName) {
|
||||
return new AwsException("ResourceNotFoundException",
|
||||
"The namespace " + namespaceName + " was not found.", 404);
|
||||
}
|
||||
|
||||
private static AwsException validation(String message) {
|
||||
return new AwsException("ValidationException", message, 400);
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package io.github.hectorvent.floci.services.redshiftserverless.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Namespace {
|
||||
private String namespaceName;
|
||||
private String namespaceId;
|
||||
private String namespaceArn;
|
||||
private String adminUsername;
|
||||
private String dbName;
|
||||
private String kmsKeyId;
|
||||
private String defaultIamRoleArn;
|
||||
private List<String> iamRoles = new ArrayList<>();
|
||||
private List<String> logExports = new ArrayList<>();
|
||||
private String status;
|
||||
private Instant creationDate;
|
||||
private Map<String, String> tags = new LinkedHashMap<>();
|
||||
|
||||
public Namespace() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Deep enough copy that a mutation of the copy cannot be observed through the original:
|
||||
* the collections are copied, and every other member is immutable. Services build an
|
||||
* updated namespace on a copy and store that, so a reader holding the previous instance
|
||||
* never sees a half-applied update.
|
||||
*/
|
||||
public Namespace(Namespace other) {
|
||||
this.namespaceName = other.namespaceName;
|
||||
this.namespaceId = other.namespaceId;
|
||||
this.namespaceArn = other.namespaceArn;
|
||||
this.adminUsername = other.adminUsername;
|
||||
this.dbName = other.dbName;
|
||||
this.kmsKeyId = other.kmsKeyId;
|
||||
this.defaultIamRoleArn = other.defaultIamRoleArn;
|
||||
this.iamRoles = new ArrayList<>(other.iamRoles);
|
||||
this.logExports = new ArrayList<>(other.logExports);
|
||||
this.status = other.status;
|
||||
this.creationDate = other.creationDate;
|
||||
this.tags = new LinkedHashMap<>(other.tags);
|
||||
}
|
||||
|
||||
public String getNamespaceName() {
|
||||
return namespaceName;
|
||||
}
|
||||
|
||||
public void setNamespaceName(String namespaceName) {
|
||||
this.namespaceName = namespaceName;
|
||||
}
|
||||
|
||||
public String getNamespaceId() {
|
||||
return namespaceId;
|
||||
}
|
||||
|
||||
public void setNamespaceId(String namespaceId) {
|
||||
this.namespaceId = namespaceId;
|
||||
}
|
||||
|
||||
public String getNamespaceArn() {
|
||||
return namespaceArn;
|
||||
}
|
||||
|
||||
public void setNamespaceArn(String namespaceArn) {
|
||||
this.namespaceArn = namespaceArn;
|
||||
}
|
||||
|
||||
public String getAdminUsername() {
|
||||
return adminUsername;
|
||||
}
|
||||
|
||||
public void setAdminUsername(String adminUsername) {
|
||||
this.adminUsername = adminUsername;
|
||||
}
|
||||
|
||||
public String getDbName() {
|
||||
return dbName;
|
||||
}
|
||||
|
||||
public void setDbName(String dbName) {
|
||||
this.dbName = dbName;
|
||||
}
|
||||
|
||||
public String getKmsKeyId() {
|
||||
return kmsKeyId;
|
||||
}
|
||||
|
||||
public void setKmsKeyId(String kmsKeyId) {
|
||||
this.kmsKeyId = kmsKeyId;
|
||||
}
|
||||
|
||||
public String getDefaultIamRoleArn() {
|
||||
return defaultIamRoleArn;
|
||||
}
|
||||
|
||||
public void setDefaultIamRoleArn(String defaultIamRoleArn) {
|
||||
this.defaultIamRoleArn = defaultIamRoleArn;
|
||||
}
|
||||
|
||||
public List<String> getIamRoles() {
|
||||
return iamRoles;
|
||||
}
|
||||
|
||||
public void setIamRoles(List<String> iamRoles) {
|
||||
this.iamRoles = iamRoles;
|
||||
}
|
||||
|
||||
public List<String> getLogExports() {
|
||||
return logExports;
|
||||
}
|
||||
|
||||
public void setLogExports(List<String> logExports) {
|
||||
this.logExports = logExports;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Instant getCreationDate() {
|
||||
return creationDate;
|
||||
}
|
||||
|
||||
public void setCreationDate(Instant creationDate) {
|
||||
this.creationDate = creationDate;
|
||||
}
|
||||
|
||||
public Map<String, String> getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public void setTags(Map<String, String> tags) {
|
||||
this.tags = tags;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user