Light, fluffy, and always free - The AWS Local Emulator alternative
feat(redshiftserverless): add namespace lifecycle and tagging (#3631)
Allen Sanborn4b3923712a64
diff --git a/AGENTS.md b/AGENTS.mdindex ac108e72ec..280a2fe4d1 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -259,12 +259,17 @@ When adding functionality:6. Obtain storage through `StorageFactory` and implement `Resettable`7. List any static `Random` or `SecureRandom` field under `--initialize-at-run-time` in`application.yml`-8. Add `<Svc>ServiceTest` and `<Svc>IntegrationTest`-9. Document it: `docs/services/<svc>.md`, a `mkdocs.yml` nav entry, a Service Matrix row in+8. Check every timestamp member you emit for a `TimestampFormatTrait` before using the+ epoch-seconds idiom. It is the awsJson1.1 default, but a model can override it per+ member, and the mismatch is invisible to the AWS CLI because botocore coerces the+ value, while strict SDKs (Go, Java) reject the whole response. `javap -c` on the SDK+ model class shows the traits on each `SdkField`+9. Add `<Svc>ServiceTest` and `<Svc>IntegrationTest`+10. Document it: `docs/services/<svc>.md`, a `mkdocs.yml` nav entry, a Service Matrix row in`docs/services/index.md`, and a row in the README category table-10. Register the handler in `tools/docs/services.yaml`, then run `make docs-sync` and+11. Register the handler in `tools/docs/services.yaml`, then run `make docs-sync` and`make docs-check`-11. Add a `TestFixtures` client factory and a `<Svc>Test` in `compatibility-tests/sdk-test-java`+12. Add a `TestFixtures` client factory and a `<Svc>Test` in `compatibility-tests/sdk-test-java`---diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex ae9d6c80f3..7a868646c7 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -166,12 +166,20 @@ you add or change; leave unrelated cleanups for their own PR.6. Add `floci.services.<key>.enabled` to both `src/main/resources/application.yml` and `src/test/resources/application.yml`7. Wire controller/handler dispatch for the service (JSON 1.1 handlers are injected into `AwsJson11Controller`)8. Obtain storage through `StorageFactory` and implement `Resettable`; list any static `Random` or `SecureRandom` field under `--initialize-at-run-time` in `application.yml`-9. Add `*ServiceTest.java` and `*IntegrationTest.java` tests-10. Document it: `docs/services/<service>.md`, a `mkdocs.yml` nav entry, a Service Matrix row in `docs/services/index.md`, and a row in the README category table-11. Register the handler in `tools/docs/services.yaml`, then run `make docs-sync` and `make docs-check`-12. Add a client factory in the compat suite's `TestFixtures` and a `<Svc>Test` under `compatibility-tests/sdk-test-java`--`ServiceRegistry`, `ServiceEnabledFilter`, and `StorageFactory` resolve service metadata from the descriptor catalog. Adding a service should not require new service-keyed switch statements in those consumers. `make docs-check` gates steps 10 and 11: a registered service with no matrix row, a `docs/services` page with no matrix row, and a stale action table all fail CI.+9. Check every timestamp member you emit for a `TimestampFormatTrait` before reaching for the+ epoch-seconds idiom. It is the awsJson1.1 default, but a model can override it per member,+ and a mismatch is invisible to the AWS CLI because botocore coerces the value, while strict+ SDKs (Go, Java) reject the whole response. `javap -c` on the SDK model class shows the+ traits attached to each `SdkField`. In Redshift Serverless, for instance,+ `Namespace.creationDate` is `ISO_8601` while roughly half the model's other timestamp+ members carry no trait and use the epoch default. The trait is per member, so check each+ one you emit+10. Add `*ServiceTest.java` and `*IntegrationTest.java` tests+11. Document it: `docs/services/<service>.md`, a `mkdocs.yml` nav entry, a Service Matrix row in `docs/services/index.md`, and a row in the README category table+12. Register the handler in `tools/docs/services.yaml`, then run `make docs-sync` and `make docs-check`+13. Add a client factory in the compat suite's `TestFixtures` and a `<Svc>Test` under `compatibility-tests/sdk-test-java`++`ServiceRegistry`, `ServiceEnabledFilter`, and `StorageFactory` resolve service metadata from the descriptor catalog. Adding a service should not require new service-keyed switch statements in those consumers. `make docs-check` gates steps 11 and 12: a registered service with no matrix row, a `docs/services` page with no matrix row, and a stale action table all fail CI.Always implement the **real AWS wire protocol**. Never invent custom endpoints. The AWS SDK must work against Floci without modification.diff --git a/README.md b/README.mdindex 4c8ac959cb..0c1d5804e2 100644--- a/README.md+++ b/README.md@@ -297,7 +297,7 @@ Floci supports local emulation for application services, data services, eventing| Events and workflows | EventBridge, EventBridge Pipes, EventBridge Scheduler, Step Functions, SWF, CloudWatch Logs, CloudWatch Metrics, CloudWatch OAM, CloudWatch RUM, Managed Prometheus (AMP) || API and identity | API Gateway REST, API Gateway v2, AppSync, Cognito, Cognito Identity, ACM, Route53, Route 53 Resolver, Cloud Map, Global Accelerator || Containers and compute | ECS, EC2, Lightsail, EKS, MWAA, ECR, EFS, CodeBuild, CodeDeploy, CodePipeline, CodeGuru Reviewer, CodeArtifact, AWS Batch, Auto Scaling, Application Auto Scaling, Elastic Beanstalk, ELB v2, ELB Classic |-| Data, analytics, and AI | Athena, Glue, Lake Formation, EMR, EMR Serverless, Redshift, Redshift Data API, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Comprehend, Rekognition, Translate, Bedrock, Bedrock Runtime, Bedrock AgentCore, Bedrock AgentCore Control, SageMaker |+| Data, analytics, and AI | Athena, Glue, Lake Formation, EMR, EMR Serverless, Redshift, Redshift Data API, Redshift Serverless, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Comprehend, Rekognition, Translate, Bedrock, Bedrock Runtime, Bedrock AgentCore, Bedrock AgentCore Control, SageMaker || Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, DMS, MemoryDB, ElastiCache, Timestream for InfluxDB || Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, DataSync, IoT Core, Amazon Connect, Amazon AppIntegrations || Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, Amazon Inspector, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin, OIDC, Access Portal, SCIM), Identity Store, Amazon Macie, Amazon Detective, Security Hub, Amazon Verified Permissions, Control Catalog, Control Tower, Service Catalog, AWS Marketplace |diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xmlindex 59f9540de2..8294fefa04 100644--- a/compatibility-tests/sdk-test-java/pom.xml+++ b/compatibility-tests/sdk-test-java/pom.xml@@ -108,6 +108,10 @@<groupId>software.amazon.awssdk</groupId><artifactId>redshiftdata</artifactId></dependency>+ <dependency>+ <groupId>software.amazon.awssdk</groupId>+ <artifactId>redshiftserverless</artifactId>+ </dependency><dependency><groupId>software.amazon.awssdk</groupId><artifactId>sns</artifactId>diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.javaindex 96bf9b61a0..2117f6a32d 100644--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java@@ -5,6 +5,7 @@ import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;import software.amazon.awssdk.regions.Region;import software.amazon.awssdk.services.account.AccountClient;import software.amazon.awssdk.services.accessanalyzer.AccessAnalyzerClient;+import software.amazon.awssdk.services.redshiftserverless.RedshiftServerlessClient;import software.amazon.awssdk.services.cloudformation.CloudFormationClient;import software.amazon.awssdk.services.cloudhsmv2.CloudHsmV2Client;import software.amazon.awssdk.services.cloudfront.CloudFrontClient;@@ -354,6 +355,14 @@ public final class TestFixtures {.build();}+ public static RedshiftServerlessClient redshiftServerlessClient() {+ return RedshiftServerlessClient.builder()+ .endpointOverride(ENDPOINT)+ .region(REGION)+ .credentialsProvider(CREDENTIALS)+ .build();+ }+public static AccessAnalyzerClient accessAnalyzerClient() {return AccessAnalyzerClient.builder().endpointOverride(ENDPOINT)diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftServerlessTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftServerlessTest.javanew file mode 100644index 0000000000..e91a527e6e--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftServerlessTest.java@@ -0,0 +1,80 @@+package com.floci.test;++import org.jboss.logging.Logger;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.redshiftserverless.RedshiftServerlessClient;+import software.amazon.awssdk.services.redshiftserverless.model.ConflictException;+import software.amazon.awssdk.services.redshiftserverless.model.Namespace;+import software.amazon.awssdk.services.redshiftserverless.model.NamespaceStatus;+import software.amazon.awssdk.services.redshiftserverless.model.ResourceNotFoundException;+import software.amazon.awssdk.services.redshiftserverless.model.Tag;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.assertj.core.api.Assertions.tuple;+import static org.junit.jupiter.api.Assumptions.assumeFalse;++@DisplayName("Redshift Serverless namespace lifecycle")+class RedshiftServerlessTest {++ private static final Logger LOG = Logger.getLogger(RedshiftServerlessTest.class);++ @Test+ void namespaceLifecycleUsesAwsSdk() {+ assumeFalse(TestFixtures.isRealAws(), "Creates a namespace and asserts emulator-local defaults");++ try (RedshiftServerlessClient client = TestFixtures.redshiftServerlessClient()) {+ String namespaceName = "floci-compat-ns";+ try {+ Namespace created = client.createNamespace(request -> request+ .namespaceName(namespaceName)+ .adminUsername("admin")+ .adminUserPassword("Secret123!")).namespace();++ assertThat(created.namespaceName()).isEqualTo(namespaceName);+ assertThat(created.dbName()).isEqualTo("dev");+ assertThat(created.kmsKeyId()).isEqualTo("AWS_OWNED_KMS_KEY");+ assertThat(created.status()).isEqualTo(NamespaceStatus.AVAILABLE);+ assertThat(created.namespaceArn()).contains(":redshift-serverless:");++ Namespace fetched = client.getNamespace(request -> request.namespaceName(namespaceName)).namespace();+ assertThat(fetched.namespaceId()).isEqualTo(created.namespaceId());++ assertThat(client.listNamespaces(request -> {}).namespaces())+ .extracting(Namespace::namespaceName)+ .contains(namespaceName);++ assertThatThrownBy(() -> client.createNamespace(request -> request+ .namespaceName(namespaceName)+ .adminUsername("admin")))+ .isInstanceOf(ConflictException.class);++ String arn = created.namespaceArn();+ client.tagResource(request -> request.resourceArn(arn)+ .tags(Tag.builder().key("env").value("dev").build()));+ assertThat(client.listTagsForResource(request -> request.resourceArn(arn)).tags())+ .extracting(Tag::key, Tag::value)+ .contains(tuple("env", "dev"));++ client.untagResource(request -> request.resourceArn(arn).tagKeys("env"));+ assertThat(client.listTagsForResource(request -> request.resourceArn(arn)).tags())+ .extracting(Tag::key)+ .doesNotContain("env");+ } finally {+ deleteBestEffort(client, namespaceName);+ }++ assertThatThrownBy(() -> client.getNamespace(request -> request.namespaceName(namespaceName)))+ .isInstanceOf(ResourceNotFoundException.class);+ }+ }++ private static void deleteBestEffort(RedshiftServerlessClient client, String namespaceName) {+ try {+ client.deleteNamespace(request -> request.namespaceName(namespaceName));+ } catch (Exception cleanupError) {+ LOG.warnf(cleanupError, "Best-effort cleanup failed for namespaceName=%s", namespaceName);+ }+ }+}diff --git a/docs/services/index.md b/docs/services/index.mdindex 2f5a48ce00..ae2480e533 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -75,6 +75,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac| [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 6 || [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 29 || [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 11 |+| [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 8 || [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 24 || [EMR Serverless](emr-serverless.md) | `/applications/*` | REST JSON | 7 || [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 6 |diff --git a/docs/services/redshift-serverless.md b/docs/services/redshift-serverless.mdnew file mode 100644index 0000000000..8b335d7bab--- /dev/null+++ b/docs/services/redshift-serverless.md@@ -0,0 +1,70 @@+# Redshift Serverless++**Protocol:** JSON 1.1+**Endpoint:** `POST http://localhost:4566/` with `X-Amz-Target: RedshiftServerless.<Operation>` and `Content-Type: application/x-amz-json-1.1`++Floci emulates the namespace lifecycle of Amazon Redshift Serverless: the account and Region scoped container that holds a serverless database, its admin credentials, and its IAM roles. This is the surface Terraform's `aws_redshiftserverless_namespace` drives.++For the upstream API shape, see the [Amazon Redshift Serverless API Reference](https://docs.aws.amazon.com/redshift-serverless/latest/APIReference/Welcome.html).++## Supported Actions++<!-- floci:actions:start -->+| Action | Description |+| --- | --- |+| `CreateNamespace` | Create a namespace, applying AWS defaults for `dbName`, `kmsKeyId`, and `logExports` |+| `GetNamespace` | Return a namespace by name |+| `ListNamespaces` | Page through the namespaces in the account and Region |+| `UpdateNamespace` | Apply the supplied fields to an existing namespace and return it |+| `DeleteNamespace` | Remove a namespace and return it with `status` `DELETING` |+| `ListTagsForResource` | Return the tags on the namespace named by `resourceArn` |+| `TagResource` | Merge tags into the namespace named by `resourceArn` |+| `UntagResource` | Remove tags by key from the namespace named by `resourceArn` |+<!-- floci:actions:end -->++Namespace state is account and Region scoped and persisted through `StorageFactory`.++## Compatibility Notes++- **Namespaces only.** Workgroups, snapshots, recovery points, usage limits, and endpoint access are not emulated. A namespace has no compute attached and no endpoint to connect to, so the Redshift Data API still rejects `WorkgroupName`.+- **`adminUserPassword` is accepted and never returned**, matching AWS. No secret is created for `manageAdminPassword`.+- **Defaults follow AWS.** `dbName` defaults to `dev`, `kmsKeyId` to `AWS_OWNED_KMS_KEY`, `logExports` to an empty list, and `status` to `AVAILABLE` immediately: there is no `MODIFYING` or `CREATING` phase to poll through.+- **`creationDate` is an ISO-8601 string**, for example `2026-09-11T18:12:55.433Z`, not the+ epoch-seconds number that awsJson1.1 uses by default. `Namespace.creationDate` carries+ `TimestampFormatTrait(ISO_8601)` in the API model, and strict SDKs reject a number here even+ though the AWS CLI accepts one. (Not a model-wide rule: roughly half the model's timestamp+ members carry no format trait and use the epoch default, so check each member when extending+ this service.)+- **`namespaceId` is a generated UUID** and `namespaceArn` is `arn:aws:redshift-serverless:<region>:<account>:namespace/<namespaceId>`.+- **`DeleteNamespace` returns the deleted namespace with `status` `DELETING`** and removes it in the same call, so the next `GetNamespace` returns `ResourceNotFoundException`.+- **`UpdateNamespace` applies only the fields present in the request.** An omitted field keeps its stored value; an explicitly empty `iamRoles` or `logExports` array clears it.+- **Tagging is keyed by `resourceArn`, not by namespace name**, and the namespace is the only taggable Redshift Serverless resource in Floci. `TagResource` merges into the existing tags rather than replacing them, `UntagResource` removes by key, and any ARN that does not name a known namespace in the caller's Region returns `ResourceNotFoundException`. Tags supplied to `CreateNamespace` are readable through `ListTagsForResource` and survive an `UpdateNamespace`.++## AWS-compatible failures++Namespace names, database names, and log export values are validated. Floci returns `ValidationException` for a malformed request, `ConflictException` when the namespace name is already taken, and `ResourceNotFoundException` for an unknown namespace.++AWS also models `AccessDeniedException`, `InternalServerException`, and `ThrottlingException`. Floci does not inject provider-side failures that cannot be derived from the request or emulator state.++## Configuration++| Variable | Default | Description |+|---|---|---|+| `FLOCI_SERVICES_REDSHIFT_SERVERLESS_ENABLED` | `true` | Enable or disable Redshift Serverless |++## Example++```bash+export AWS_ENDPOINT_URL=http://localhost:4566++aws redshift-serverless create-namespace \+ --namespace-name analytics \+ --admin-username admin \+ --admin-user-password Secret123! \+ --db-name dev++aws redshift-serverless get-namespace --namespace-name analytics+aws redshift-serverless list-namespaces+aws redshift-serverless update-namespace --namespace-name analytics --log-exports userlog+aws redshift-serverless delete-namespace --namespace-name analytics+```diff --git a/mkdocs.yml b/mkdocs.ymlindex 74062f38c3..d0648313da 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -151,6 +151,7 @@ nav:- Athena: services/athena.md- Redshift: services/redshift.md- Redshift Data API: services/redshift-data.md+ - Redshift Serverless: services/redshift-serverless.md- Data Firehose: services/firehose.md- EventBridge: services/eventbridge.md- EventBridge Pipes: services/pipes.mddiff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 99da83390b..1996668dcc 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -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();diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.javaindex 6b9bdeb2a8..e3ae133b78 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJson11Controller.java@@ -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());diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.javaindex cabd06b768..ef7bb3d806 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java@@ -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,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.javanew file mode 100644index 0000000000..6a7caca238--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandler.java@@ -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;+ }+}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.javanew file mode 100644index 0000000000..8a352f4921--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java@@ -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);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/model/Namespace.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/model/Namespace.javanew file mode 100644index 0000000000..7a4ebb5dc8--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/model/Namespace.java@@ -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;+ }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex bf7e036ece..5ce38f14a1 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -424,6 +424,8 @@ floci:redshift-data:enabled: trueresult-ttl-hours: 24+ redshift-serverless:+ enabled: trueneptune:enabled: trueproxy-base-port: 8182diff --git a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessIntegrationTest.javanew file mode 100644index 0000000000..271e83f86b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessIntegrationTest.java@@ -0,0 +1,176 @@+package io.github.hectorvent.floci.services.redshiftserverless;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasItem;+import static org.hamcrest.Matchers.matchesPattern;+import static org.hamcrest.Matchers.nullValue;++@QuarkusTest+class RedshiftServerlessIntegrationTest {++ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";+ private static final String TARGET_PREFIX = "RedshiftServerless.";+ private static final String AUTH =+ "AWS4-HMAC-SHA256 Credential=AKID/20260904/us-east-1/redshift-serverless/aws4_request";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void createAppliesAwsDefaultsAndNeverReturnsTheAdminPassword() {+ call("CreateNamespace", """+ {"namespaceName":"defaults-ns","adminUsername":"admin","adminUserPassword":"Secret123!"}+ """)+ .statusCode(200)+ .body("namespace.namespaceName", equalTo("defaults-ns"))+ .body("namespace.namespaceId", matchesPattern(+ "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"))+ .body("namespace.namespaceArn", matchesPattern(+ "arn:aws:redshift-serverless:us-east-1:\\d{12}:namespace/"+ + "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"))+ .body("namespace.dbName", equalTo("dev"))+ .body("namespace.kmsKeyId", equalTo("AWS_OWNED_KMS_KEY"))+ .body("namespace.status", equalTo("AVAILABLE"))+ .body("namespace.adminUsername", equalTo("admin"))+ .body("namespace.logExports.size()", equalTo(0))+ .body("namespace.creationDate", matchesPattern(+ "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"))+ .body("namespace.adminUserPassword", nullValue());++ call("GetNamespace", "{\"namespaceName\":\"defaults-ns\"}")+ .statusCode(200)+ .body("namespace.dbName", equalTo("dev"))+ .body("namespace.kmsKeyId", equalTo("AWS_OWNED_KMS_KEY"))+ .body("namespace.adminUserPassword", nullValue());++ call("DeleteNamespace", "{\"namespaceName\":\"defaults-ns\"}").statusCode(200);+ }++ @Test+ void namespaceLifecycleIsVisibleThroughSeparateReads() {+ call("CreateNamespace", """+ {"namespaceName":"lifecycle-ns","adminUsername":"admin","dbName":"analytics",+ "logExports":["userlog"],"iamRoles":["arn:aws:iam::000000000000:role/one"]}+ """)+ .statusCode(200)+ .body("namespace.dbName", equalTo("analytics"));++ call("ListNamespaces", "{}")+ .statusCode(200)+ .body("namespaces.namespaceName", hasItem("lifecycle-ns"));++ call("UpdateNamespace", """+ {"namespaceName":"lifecycle-ns","kmsKeyId":"custom-key",+ "logExports":["userlog","connectionlog"],"iamRoles":[]}+ """)+ .statusCode(200);++ call("GetNamespace", "{\"namespaceName\":\"lifecycle-ns\"}")+ .statusCode(200)+ .body("namespace.kmsKeyId", equalTo("custom-key"))+ .body("namespace.logExports", hasItem("connectionlog"))+ .body("namespace.iamRoles.size()", equalTo(0))+ .body("namespace.dbName", equalTo("analytics"));++ call("DeleteNamespace", "{\"namespaceName\":\"lifecycle-ns\"}")+ .statusCode(200)+ .body("namespace.namespaceName", equalTo("lifecycle-ns"))+ .body("namespace.status", equalTo("DELETING"));++ call("GetNamespace", "{\"namespaceName\":\"lifecycle-ns\"}")+ .statusCode(404)+ .body("__type", equalTo("ResourceNotFoundException"));+ }++ @Test+ void duplicateNamespaceNameIsRejected() {+ call("CreateNamespace", "{\"namespaceName\":\"conflict-ns\",\"adminUsername\":\"admin\"}")+ .statusCode(200);+ call("CreateNamespace", "{\"namespaceName\":\"conflict-ns\",\"adminUsername\":\"admin\"}")+ .statusCode(409)+ .body("__type", equalTo("ConflictException"));+ call("DeleteNamespace", "{\"namespaceName\":\"conflict-ns\"}").statusCode(200);+ }++ @Test+ void deletingAnUnknownNamespaceReturnsResourceNotFound() {+ call("DeleteNamespace", "{\"namespaceName\":\"absent-ns\"}")+ .statusCode(404)+ .body("__type", equalTo("ResourceNotFoundException"));+ }++ @Test+ void invalidNamespaceNameReturnsValidationError() {+ call("CreateNamespace", "{\"namespaceName\":\"Upper-Case\",\"adminUsername\":\"admin\"}")+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ @Test+ void invalidLogExportReturnsValidationError() {+ call("CreateNamespace", """+ {"namespaceName":"bad-logs-ns","adminUsername":"admin","logExports":["nosuchlog"]}+ """)+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ @Test+ void tagsCreatedWithTheNamespaceAreReadableAndEditable() {+ String arn = call("CreateNamespace", """+ {"namespaceName":"tagged-ns","adminUsername":"admin","tags":[{"key":"env","value":"dev"}]}+ """)+ .statusCode(200)+ .extract().jsonPath().getString("namespace.namespaceArn");++ call("ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}")+ .statusCode(200)+ .body("tags.size()", equalTo(1))+ .body("tags[0].key", equalTo("env"))+ .body("tags[0].value", equalTo("dev"));++ call("TagResource", "{\"resourceArn\":\"" + arn + "\",\"tags\":[{\"key\":\"team\",\"value\":\"data\"}]}")+ .statusCode(200);+ call("ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}")+ .statusCode(200)+ .body("tags.key", hasItem("team"))+ .body("tags.key", hasItem("env"));++ call("UntagResource", "{\"resourceArn\":\"" + arn + "\",\"tagKeys\":[\"env\"]}")+ .statusCode(200);+ call("ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}")+ .statusCode(200)+ .body("tags.size()", equalTo(1))+ .body("tags[0].key", equalTo("team"));++ call("DeleteNamespace", "{\"namespaceName\":\"tagged-ns\"}").statusCode(200);+ }++ @Test+ void taggingAnUnknownArnReturnsResourceNotFound() {+ String absent = "arn:aws:redshift-serverless:us-east-1:000000000000:"+ + "namespace/00000000-0000-0000-0000-000000000000";+ call("ListTagsForResource", "{\"resourceArn\":\"" + absent + "\"}")+ .statusCode(404)+ .body("__type", equalTo("ResourceNotFoundException"));+ }++ private static io.restassured.response.ValidatableResponse call(String action, String body) {+ return given()+ .header("X-Amz-Target", TARGET_PREFIX + action)+ .header("Authorization", AUTH)+ .contentType(CONTENT_TYPE)+ .body(body)+ .when()+ .post("/")+ .then();+ }+}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.javanew file mode 100644index 0000000000..bda254351e--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandlerTest.java@@ -0,0 +1,221 @@+package io.github.hectorvent.floci.services.redshiftserverless;++import com.fasterxml.jackson.core.type.TypeReference;+import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.RegionResolver;+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.ws.rs.core.Response;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.time.Duration;+import java.time.Instant;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++/**+ * Covers the wire layer the service tests cannot reach: how values are shaped on the way out.+ * The timestamp case is a regression guard. {@code creationDate} was first emitted as+ * epoch seconds, the awsJson1.1 default, but {@code Namespace.creationDate} carries+ * {@code TimestampFormatTrait(ISO_8601)} (other members of this model vary; check each). The AWS CLI accepted the number because+ * botocore coerces it, so an integration test asserting only "not null" stayed green while+ * strict SDKs rejected the response.+ */+class RedshiftServerlessJsonHandlerTest {+ private static final String REGION = "us-east-1";+ private static final String ACCOUNT_ID = "123456789012";++ private final ObjectMapper mapper = new ObjectMapper();+ private RedshiftServerlessJsonHandler handler;++ @BeforeEach+ @SuppressWarnings({"unchecked", "rawtypes"})+ void setUp() {+ StorageFactory storageFactory = mock(StorageFactory.class);+ AccountAwareStorageBackend<Namespace> store = AccountAwareStorageBackend.inMemory(ACCOUNT_ID);+ when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-namespaces.json"),+ any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);++ RegionResolver regionResolver = mock(RegionResolver.class);+ when(regionResolver.buildArn(eq("redshift-serverless"), any(String.class), any(String.class)))+ .thenAnswer(invocation -> "arn:aws:redshift-serverless:"+ + invocation.getArgument(1, String.class) + ":" + ACCOUNT_ID + ":"+ + invocation.getArgument(2, String.class));+ handler = new RedshiftServerlessJsonHandler(+ new RedshiftServerlessService(storageFactory, regionResolver), mapper);+ }++ @Test+ void creationDateIsAnIso8601StringNotEpochSeconds() {+ JsonNode namespace = body(create("timestamp-ns")).get("namespace");++ JsonNode creationDate = namespace.get("creationDate");+ assertTrue(creationDate.isTextual(),+ "creationDate must be a JSON string; a number is what strict SDKs reject");+ assertTrue(creationDate.textValue().matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"),+ "unexpected creationDate shape: " + creationDate.textValue());+ // Parsed by the same ISO-8601 reader an SDK uses, so a well-formed string carrying a+ // wrong offset or a stale clock cannot pass on shape alone.+ Instant parsed = Instant.parse(creationDate.textValue());+ assertTrue(Duration.between(parsed, Instant.now()).abs().toMinutes() < 5,+ "creationDate is not close to now, check the zone offset: " + creationDate.textValue());+ }++ @Test+ void creationDateSurvivesAReadBackThroughGetNamespace() {+ create("reread-ns");+ JsonNode fetched = body(handler.handle("GetNamespace", request("namespaceName", "reread-ns"), REGION));+ assertTrue(fetched.get("namespace").get("creationDate").isTextual());+ }++ @Test+ void listNamespacesEmitsNextTokenOnlyWhenAPageRemains() {+ create("page-one-ns");+ create("page-two-ns");++ ObjectNode paged = request("maxResults", null);+ paged.put("maxResults", 1);+ JsonNode firstPage = body(handler.handle("ListNamespaces", paged, REGION));+ assertEquals(1, firstPage.get("namespaces").size());+ assertTrue(firstPage.hasNonNull("nextToken"), "a remaining page must advertise nextToken");++ ObjectNode second = mapper.createObjectNode();+ second.put("maxResults", 1);+ second.put("nextToken", firstPage.get("nextToken").textValue());+ JsonNode lastPage = body(handler.handle("ListNamespaces", second, REGION));+ assertEquals(1, lastPage.get("namespaces").size());+ assertFalse(lastPage.has("nextToken"), "the final page must not advertise nextToken");+ }++ @Test+ void aStringMaxResultsIsAValidationExceptionEvenWhenItLooksLikeANumber() {+ // "12" is the case that actually pins the type guard. A non-numeric string such as+ // "twelve" coerces to 0 through asInt() and is rejected downstream by the pagination+ // bound anyway, so it cannot tell a present guard from an absent one.+ for (String malformed : new String[] {"twelve", "12"}) {+ ObjectNode bad = mapper.createObjectNode();+ bad.put("maxResults", malformed);++ Response response = handler.handle("ListNamespaces", bad, REGION);++ assertEquals(400, response.getStatus(), "maxResults=\"" + malformed + "\" must be rejected");+ assertEquals("ValidationException", errorType(response),+ "maxResults=\"" + malformed + "\" must be a ValidationException");+ }+ }++ @Test+ void anUnknownActionIsReportedAsUnknownOperation() {+ Response response = handler.handle("CreateWorkgroup", mapper.createObjectNode(), REGION);++ assertEquals(400, response.getStatus());+ assertEquals("UnknownOperationException", errorType(response));+ }++ @Test+ void aPresentCollectionMemberOfTheWrongTypeIsRejectedPerMember() {+ create("wrong-type-ns");++ for (String member : new String[] {"iamRoles", "logExports"}) {+ for (String malformed : new String[] {"\"a-string\"", "7", "{\"k\":\"v\"}", "true"}) {+ ObjectNode request = (ObjectNode) parse(+ "{\"namespaceName\":\"wrong-type-ns\"," + quoted(member) + ":" + malformed + "}");++ Response response = handler.handle("UpdateNamespace", request, REGION);++ assertEquals(400, response.getStatus(),+ member + "=" + malformed + " must not be accepted");+ assertEquals("ValidationException", errorType(response),+ member + "=" + malformed + " must be a ValidationException");+ }+ }+ }++ @Test+ void aWrongTypedCollectionIsNotSilentlyTreatedAsOmitted() {+ ObjectNode created = (ObjectNode) parse("{\"namespaceName\":\"not-omitted-ns\","+ + "\"adminUsername\":\"admin\",\"iamRoles\":[\"arn:aws:iam::000000000000:role/one\"]}");+ body(handler.handle("CreateNamespace", created, REGION));++ Response response = handler.handle("UpdateNamespace",+ (ObjectNode) parse("{\"namespaceName\":\"not-omitted-ns\",\"iamRoles\":\"role/one\"}"), REGION);++ assertEquals(400, response.getStatus(),+ "a malformed iamRoles must fail the request, not quietly keep the stored roles");+ JsonNode unchanged = body(handler.handle("GetNamespace",+ request("namespaceName", "not-omitted-ns"), REGION)).get("namespace");+ assertEquals(1, unchanged.get("iamRoles").size(), "the rejected update must not have applied");+ }++ @Test+ void nonStringElementsInACollectionAreRejected() {+ create("bad-element-ns");++ Response response = handler.handle("UpdateNamespace",+ (ObjectNode) parse("{\"namespaceName\":\"bad-element-ns\",\"iamRoles\":[7]}"), REGION);++ assertEquals(400, response.getStatus());+ assertEquals("ValidationException", errorType(response));+ }++ @Test+ void aWrongTypedTagsOrTagKeysMemberIsRejected() {+ JsonNode namespace = body(create("tag-type-ns")).get("namespace");+ String arn = namespace.get("namespaceArn").textValue();++ Response tagged = handler.handle("TagResource",+ (ObjectNode) parse("{\"resourceArn\":" + quoted(arn) + ",\"tags\":\"env=dev\"}"), REGION);+ assertEquals(400, tagged.getStatus());+ assertEquals("ValidationException", errorType(tagged));++ Response untagged = handler.handle("UntagResource",+ (ObjectNode) parse("{\"resourceArn\":" + quoted(arn) + ",\"tagKeys\":\"env\"}"), REGION);+ assertEquals(400, untagged.getStatus());+ assertEquals("ValidationException", errorType(untagged));+ }++ private JsonNode parse(String json) {+ try {+ return mapper.readTree(json);+ } catch (Exception e) {+ throw new IllegalArgumentException("bad test fixture: " + json, e);+ }+ }++ private static String quoted(String value) {+ return '"' + value + '"';+ }++ private Response create(String namespaceName) {+ ObjectNode request = request("namespaceName", namespaceName);+ request.put("adminUsername", "admin");+ return handler.handle("CreateNamespace", request, REGION);+ }++ private ObjectNode request(String field, String value) {+ ObjectNode request = mapper.createObjectNode();+ if (value != null) {+ request.put(field, value);+ }+ return request;+ }++ private JsonNode body(Response response) {+ assertEquals(200, response.getStatus(), "expected a successful response, got " + response.getEntity());+ return mapper.valueToTree(response.getEntity());+ }++ private String errorType(Response response) {+ return mapper.valueToTree(response.getEntity()).path("__type").asText(null);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessServiceTest.javanew file mode 100644index 0000000000..0f5f71a769--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessServiceTest.java@@ -0,0 +1,305 @@+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.RegionResolver;+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 org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.List;+import java.util.Map;+import java.util.UUID;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;+import static org.junit.jupiter.api.Assertions.assertNotSame;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.clearInvocations;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.spy;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++class RedshiftServerlessServiceTest {+ private static final String REGION = "us-east-1";+ private static final String ACCOUNT_ID = "123456789012";++ private RedshiftServerlessService service;+ private AccountAwareStorageBackend<Namespace> store;++ @BeforeEach+ @SuppressWarnings({"unchecked", "rawtypes"})+ void setUp() {+ StorageFactory storageFactory = mock(StorageFactory.class);+ // A spy, not a plain in-memory backend: the in-memory store hands back the same object+ // reference a mutation already changed, so only an explicit write assertion can tell a+ // service that persists its change from one that merely mutated a shared instance. That+ // distinction is invisible under "memory" mode and load-bearing under "hybrid" and "wal".+ store = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID));+ when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-namespaces.json"),+ any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);++ RegionResolver regionResolver = mock(RegionResolver.class);+ when(regionResolver.buildArn(eq("redshift-serverless"), any(String.class), any(String.class)))+ .thenAnswer(invocation -> "arn:aws:redshift-serverless:"+ + invocation.getArgument(1, String.class) + ":" + ACCOUNT_ID + ":"+ + invocation.getArgument(2, String.class));+ service = new RedshiftServerlessService(storageFactory, regionResolver);+ }++ @Test+ void createAppliesAwsDefaultsAndAUniqueNamespaceId() {+ Namespace first = create("first-ns");+ Namespace second = create("second-ns");++ assertEquals("dev", first.getDbName());+ assertEquals("AWS_OWNED_KMS_KEY", first.getKmsKeyId());+ assertEquals("AVAILABLE", first.getStatus());+ assertTrue(first.getLogExports().isEmpty());+ assertEquals("arn:aws:redshift-serverless:us-east-1:" + ACCOUNT_ID + ":namespace/" + first.getNamespaceId(),+ first.getNamespaceArn());+ assertEquals(first.getNamespaceId(), UUID.fromString(first.getNamespaceId()).toString());+ assertNotEquals(first.getNamespaceId(), second.getNamespaceId());+ }++ @Test+ void createRejectsADuplicateNamespaceName() {+ create("duplicate-ns");+ AwsException conflict = assertThrows(AwsException.class, () -> create("duplicate-ns"));+ assertEquals("ConflictException", conflict.getErrorCode());+ }++ @Test+ void getAndDeleteRejectAnUnknownNamespace() {+ assertEquals("ResourceNotFoundException",+ assertThrows(AwsException.class, () -> service.getNamespace("absent-ns", REGION)).getErrorCode());+ assertEquals("ResourceNotFoundException",+ assertThrows(AwsException.class, () -> service.deleteNamespace("absent-ns", REGION)).getErrorCode());+ }++ @Test+ void updatePersistsOnlyTheSuppliedFields() {+ service.createNamespace("update-ns", "admin", "analytics", null, null,+ List.of("arn:aws:iam::123456789012:role/one"), List.of("userlog"), Map.of(), REGION);++ service.updateNamespace("update-ns", null, "custom-key", null, List.of(), null, REGION);++ Namespace reread = service.getNamespace("update-ns", REGION);+ assertEquals("custom-key", reread.getKmsKeyId());+ assertEquals("admin", reread.getAdminUsername());+ assertEquals("analytics", reread.getDbName());+ assertEquals(List.of("userlog"), reread.getLogExports());+ assertTrue(reread.getIamRoles().isEmpty());+ }++ @Test+ void deleteReportsDeletingAndRemovesTheNamespace() {+ create("delete-ns");+ assertEquals("DELETING", service.deleteNamespace("delete-ns", REGION).getStatus());+ assertThrows(AwsException.class, () -> service.getNamespace("delete-ns", REGION));+ }++ @Test+ void invalidNamespaceNamesAndLogExportsAreRejected() {+ assertEquals("ValidationException",+ assertThrows(AwsException.class, () -> create("Upper-Case")).getErrorCode());+ assertEquals("ValidationException",+ assertThrows(AwsException.class, () -> create("ab")).getErrorCode());+ assertEquals("ValidationException", assertThrows(AwsException.class,+ () -> service.createNamespace("logs-ns", "admin", null, null, null, null,+ List.of("nosuchlog"), Map.of(), REGION)).getErrorCode());+ }++ @Test+ void reservedWordNamespaceNamesAreRejectedByEveryOperation() {+ // "select" and "user" pass the length and [a-z0-9-] rules, so only the reserved-word+ // check can reject them. Asserting on create and on the read path as well, because+ // update and delete reach the validator through getNamespace.+ for (String reserved : List.of("select", "user")) {+ assertEquals("ValidationException",+ assertThrows(AwsException.class, () -> create(reserved)).getErrorCode());+ assertEquals("ValidationException",+ assertThrows(AwsException.class, () -> service.getNamespace(reserved, REGION)).getErrorCode());+ assertEquals("ValidationException", assertThrows(AwsException.class,+ () -> service.deleteNamespace(reserved, REGION)).getErrorCode());+ assertEquals("ValidationException", assertThrows(AwsException.class,+ () -> service.updateNamespace(reserved, null, "k", null, null, null, REGION)).getErrorCode());+ }++ // A name that merely looks SQL-ish is not reserved and must still be accepted, and the+ // namespace must be readable back through a separate call rather than trusting create.+ create("analytics");+ assertEquals("analytics", service.getNamespace("analytics", REGION).getNamespaceName());+ }++ @Test+ void listIsScopedToTheRegionAndPaginates() {+ create("alpha-ns");+ create("beta-ns");+ service.createNamespace("gamma-ns", "admin", null, null, null, null, null, Map.of(), "us-west-2");++ assertEquals(List.of("alpha-ns", "beta-ns"),+ service.listNamespaces(REGION, null, null).items().stream()+ .map(Namespace::getNamespaceName).toList());++ var firstPage = service.listNamespaces(REGION, 1, null);+ assertEquals(List.of("alpha-ns"), firstPage.items().stream().map(Namespace::getNamespaceName).toList());+ assertEquals(List.of("beta-ns"), service.listNamespaces(REGION, 1, firstPage.nextToken()).items().stream()+ .map(Namespace::getNamespaceName).toList());+ }++ @Test+ void clearRemovesPersistedState() {+ create("reset-ns");+ service.clear();+ assertTrue(service.listNamespaces(REGION, null, null).items().isEmpty());+ }++ @Test+ void tagsSuppliedAtCreateAreReadableThroughListTagsForResource() {+ Namespace created = service.createNamespace("tagged-ns", "admin", null, null, null, null, null,+ Map.of("env", "dev"), REGION);++ assertEquals(Map.of("env", "dev"),+ service.listTagsForResource(created.getNamespaceArn(), REGION));+ }++ @Test+ void tagResourceMergesAndUntagResourceRemovesByKey() {+ Namespace created = service.createNamespace("merge-ns", "admin", null, null, null, null, null,+ Map.of("env", "dev"), REGION);+ String arn = created.getNamespaceArn();++ service.tagResource(arn, Map.of("team", "data"), REGION);+ assertEquals(Map.of("env", "dev", "team", "data"), service.listTagsForResource(arn, REGION),+ "TagResource must merge: the pre-existing env tag has to survive a call that does not mention it");++ service.tagResource(arn, Map.of("env", "prod"), REGION);+ assertEquals(Map.of("env", "prod", "team", "data"), service.listTagsForResource(arn, REGION));++ service.untagResource(arn, List.of("env"), REGION);+ assertEquals(Map.of("team", "data"), service.listTagsForResource(arn, REGION));+ }++ @Test+ void taggingAnUnknownArnIsResourceNotFoundEvenWhenOtherNamespacesExist() {+ create("decoy-ns");+ create("second-decoy-ns");+ String absent = "arn:aws:redshift-serverless:us-east-1:" + ACCOUNT_ID+ + ":namespace/00000000-0000-0000-0000-000000000000";+ assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,+ () -> service.listTagsForResource(absent, REGION)).getErrorCode());+ assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,+ () -> service.tagResource(absent, Map.of("a", "b"), REGION)).getErrorCode());+ assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,+ () -> service.untagResource(absent, List.of("a"), REGION)).getErrorCode());+ }++ @Test+ void tagsSurviveAnUnrelatedNamespaceUpdate() {+ Namespace created = service.createNamespace("keep-tags-ns", "admin", null, null, null, null, null,+ Map.of("env", "dev"), REGION);++ service.updateNamespace("keep-tags-ns", null, "custom-key", null, null, null, REGION);++ assertEquals(Map.of("env", "dev"), service.listTagsForResource(created.getNamespaceArn(), REGION));+ }++ @Test+ void anArnFromAnotherRegionIsNotTaggableFromThisOne() {+ Namespace elsewhere = service.createNamespace("west-ns", "admin", null, null, null, null, null,+ Map.of("env", "dev"), "us-west-2");++ assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,+ () -> service.listTagsForResource(elsewhere.getNamespaceArn(), REGION)).getErrorCode());+ assertEquals(Map.of("env", "dev"),+ service.listTagsForResource(elsewhere.getNamespaceArn(), "us-west-2"));+ }++ @Test+ void tagMutationsAreWrittenBackToStorage() {+ Namespace created = service.createNamespace("persist-ns", "admin", null, null, null, null, null,+ Map.of("env", "dev"), REGION);+ String arn = created.getNamespaceArn();++ clearInvocations(store);+ service.tagResource(arn, Map.of("team", "data"), REGION);+ verify(store).put(eq(REGION + "::persist-ns"), any(Namespace.class));++ clearInvocations(store);+ service.untagResource(arn, List.of("team"), REGION);+ verify(store).put(eq(REGION + "::persist-ns"), any(Namespace.class));+ }++ @Test+ void updateStoresACopySoAReaderNeverSeesAHalfAppliedChange() {+ service.createNamespace("copy-ns", "admin", "analytics", null, null,+ List.of("arn:aws:iam::123456789012:role/one"), List.of("userlog"), Map.of(), REGION);+ Namespace readBeforeUpdate = service.getNamespace("copy-ns", REGION);++ service.updateNamespace("copy-ns", "newadmin", "custom-key", null, List.of(), null, REGION);++ Namespace readAfterUpdate = service.getNamespace("copy-ns", REGION);+ assertNotSame(readBeforeUpdate, readAfterUpdate, "update must store a new instance, not mutate the stored one");+ // The instance a concurrent reader was already holding is untouched, which is what makes+ // a torn read structurally impossible rather than merely unlikely.+ assertEquals("admin", readBeforeUpdate.getAdminUsername());+ assertEquals("AWS_OWNED_KMS_KEY", readBeforeUpdate.getKmsKeyId());+ assertEquals(List.of("arn:aws:iam::123456789012:role/one"), readBeforeUpdate.getIamRoles());+ assertEquals("newadmin", readAfterUpdate.getAdminUsername());+ assertEquals("custom-key", readAfterUpdate.getKmsKeyId());+ assertTrue(readAfterUpdate.getIamRoles().isEmpty());+ }++ @Test+ void tagMutationsAlsoStoreACopy() {+ Namespace created = service.createNamespace("copy-tags-ns", "admin", null, null, null, null, null,+ Map.of("env", "dev"), REGION);+ Namespace readBeforeTagging = service.getNamespace("copy-tags-ns", REGION);++ service.tagResource(created.getNamespaceArn(), Map.of("team", "data"), REGION);++ Namespace readAfterTagging = service.getNamespace("copy-tags-ns", REGION);+ assertNotSame(readBeforeTagging, readAfterTagging);+ assertEquals(Map.of("env", "dev"), readBeforeTagging.getTags());+ assertEquals(Map.of("env", "dev", "team", "data"), readAfterTagging.getTags());+ }++ @Test+ void deleteDoesNotMutateTheInstanceAReaderMayHold() {+ create("delete-copy-ns");+ Namespace readBeforeDelete = service.getNamespace("delete-copy-ns", REGION);++ Namespace returned = service.deleteNamespace("delete-copy-ns", REGION);++ assertEquals("DELETING", returned.getStatus());+ assertEquals("AVAILABLE", readBeforeDelete.getStatus(),+ "delete must not flip the status on an instance handed out by an earlier read");+ }++ @Test+ void theCopyConstructorSharesNoMutableState() {+ Namespace original = service.createNamespace("copy-ctor-ns", "admin", null, null, null,+ List.of("arn:aws:iam::123456789012:role/one"), List.of("userlog"),+ Map.of("env", "dev"), REGION);++ Namespace copy = new Namespace(original);+ copy.getIamRoles().add("arn:aws:iam::123456789012:role/two");+ copy.getLogExports().add("connectionlog");+ copy.getTags().put("team", "data");++ assertEquals(List.of("arn:aws:iam::123456789012:role/one"), original.getIamRoles());+ assertEquals(List.of("userlog"), original.getLogExports());+ assertEquals(Map.of("env", "dev"), original.getTags());+ }++ private Namespace create(String namespaceName) {+ return service.createNamespace(namespaceName, "admin", null, null, null, null, null, Map.of(), REGION);+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex 91dfd4f8ce..bb48878108 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -212,6 +212,8 @@ floci:redshift-data:enabled: trueresult-ttl-hours: 24+ redshift-serverless:+ enabled: trueneptune:enabled: trueproxy-base-port: 8182diff --git a/tools/docs/services.yaml b/tools/docs/services.yamlindex 57142a43b5..4f2ca8bffe 100644--- a/tools/docs/services.yaml+++ b/tools/docs/services.yaml@@ -296,6 +296,10 @@ services:# ExecuteSql / BatchExecuteSql are the deprecated pre-2020 operations: the handler# recognizes them only to return a ValidationException, they are not supported actions.exclude_actions: [ExecuteSql, BatchExecuteSql]+ - service: redshiftserverless+ doc: docs/services/redshift-serverless.md+ sources:+ - { path: src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessJsonHandler.java, mode: switch }- service: cognitoidentitydoc: docs/services/cognitoidentity.mdsources: