diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java index 72919c5f54..72897f48ea 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java @@ -11,16 +11,20 @@ import software.amazon.awssdk.services.ec2.Ec2Client; import software.amazon.awssdk.services.ec2.model.DescribeSubnetsResponse; import software.amazon.awssdk.services.rds.RdsClient; import software.amazon.awssdk.services.rds.model.ConnectionPoolConfigurationInfo; +import software.amazon.awssdk.services.rds.model.CreateDbClusterEndpointResponse; import software.amazon.awssdk.services.rds.model.CreateDbClusterResponse; import software.amazon.awssdk.services.rds.model.CreateDbInstanceResponse; import software.amazon.awssdk.services.rds.model.CreateDbProxyResponse; import software.amazon.awssdk.services.rds.model.CreateDbSubnetGroupResponse; import software.amazon.awssdk.services.rds.model.CreateOptionGroupResponse; import software.amazon.awssdk.services.rds.model.DBCluster; +import software.amazon.awssdk.services.rds.model.DBClusterEndpoint; import software.amazon.awssdk.services.rds.model.DBClusterSnapshot; import software.amazon.awssdk.services.rds.model.DBInstance; import software.amazon.awssdk.services.rds.model.DBProxyTarget; import software.amazon.awssdk.services.rds.model.DBSnapshot; +import software.amazon.awssdk.services.rds.model.DbClusterEndpointAlreadyExistsException; +import software.amazon.awssdk.services.rds.model.DbClusterEndpointNotFoundException; import software.amazon.awssdk.services.rds.model.DbClusterSnapshotNotFoundException; import software.amazon.awssdk.services.rds.model.DbSnapshotAlreadyExistsException; import software.amazon.awssdk.services.rds.model.DbSnapshotNotFoundException; @@ -34,6 +38,7 @@ import software.amazon.awssdk.services.rds.model.DescribeOrderableDbInstanceOpti import software.amazon.awssdk.services.rds.model.InvalidOptionGroupStateException; import software.amazon.awssdk.services.rds.model.InvalidRestoreException; import software.amazon.awssdk.services.rds.model.ListTagsForResourceResponse; +import software.amazon.awssdk.services.rds.model.ModifyDbClusterEndpointResponse; import software.amazon.awssdk.services.rds.model.ModifyDbClusterResponse; import software.amazon.awssdk.services.rds.model.ModifyDbProxyResponse; import software.amazon.awssdk.services.rds.model.ModifyDbProxyTargetGroupResponse; @@ -676,6 +681,78 @@ class RdsControlPlaneTest { } } + @Test + @DisplayName("Custom cluster endpoints round-trip with the built-in writer and reader endpoints") + void sdkRoundTripsCustomClusterEndpoints() { + String clusterName = TestFixtures.uniqueName("rds-cep-cluster"); + String writerName = clusterName + "-w"; + String readerName = clusterName + "-r"; + String endpointName = TestFixtures.uniqueName("rds-cep"); + try { + rds.createDBCluster(b -> b + .dbClusterIdentifier(clusterName) + .engine("aurora-postgresql") + .engineVersion("16.3") + .masterUsername("admin") + .masterUserPassword("cep-secret")); + for (String instance : List.of(writerName, readerName)) { + rds.createDBInstance(b -> b + .dbInstanceIdentifier(instance) + .dbClusterIdentifier(clusterName) + .engine("aurora-postgresql") + .dbInstanceClass("db.r6g.large")); + } + + CreateDbClusterEndpointResponse created = rds.createDBClusterEndpoint(b -> b + .dbClusterIdentifier(clusterName) + .dbClusterEndpointIdentifier(endpointName) + .endpointType("READER") + .staticMembers(readerName) + .tags(Tag.builder().key("team").value("analytics").build())); + assertThat(created.endpointType()).isEqualTo("CUSTOM"); + assertThat(created.customEndpointType()).isEqualTo("READER"); + assertThat(created.staticMembers()).containsExactly(readerName); + assertThat(created.dbClusterEndpointArn()).endsWith(":cluster-endpoint:" + endpointName); + + List endpoints = rds.describeDBClusterEndpoints(b -> b + .dbClusterIdentifier(clusterName)).dbClusterEndpoints(); + assertThat(endpoints).extracting(DBClusterEndpoint::endpointType) + .containsExactly("WRITER", "READER", "CUSTOM"); + + ModifyDbClusterEndpointResponse modified = rds.modifyDBClusterEndpoint(b -> b + .dbClusterEndpointIdentifier(endpointName) + .endpointType("ANY") + .excludedMembers(writerName)); + assertThat(modified.customEndpointType()).isEqualTo("ANY"); + assertThat(modified.staticMembers()).isEmpty(); + assertThat(modified.excludedMembers()).containsExactly(writerName); + + assertThatThrownBy(() -> rds.createDBClusterEndpoint(b -> b + .dbClusterIdentifier(clusterName) + .dbClusterEndpointIdentifier(endpointName) + .endpointType("ANY"))) + .isInstanceOf(DbClusterEndpointAlreadyExistsException.class); + + assertThat(rds.deleteDBClusterEndpoint(b -> b.dbClusterEndpointIdentifier(endpointName)).status()) + .isEqualTo("deleting"); + assertThatThrownBy(() -> rds.deleteDBClusterEndpoint(b -> b.dbClusterEndpointIdentifier(endpointName))) + .isInstanceOf(DbClusterEndpointNotFoundException.class); + } finally { + try { + rds.deleteDBClusterEndpoint(b -> b.dbClusterEndpointIdentifier(endpointName)); + } catch (DbClusterEndpointNotFoundException expected) { + // Already deleted by the test body. + } + deleteDbInstance(rds, readerName); + deleteDbInstance(rds, writerName); + try { + rds.deleteDBCluster(b -> b.dbClusterIdentifier(clusterName).skipFinalSnapshot(true)); + } catch (Exception e) { + LOG.log(Level.WARNING, "Failed to clean up RDS cluster " + clusterName, e); + } + } + } + private static CreateDbProxyResponse createIamProxy(RdsClient client, String name, List vpcSubnetIds) { return client.createDBProxy(b -> b .dbProxyName(name) diff --git a/docs/services/index.md b/docs/services/index.md index 67bb963fa1..a61253fda2 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -62,7 +62,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Amazon Data Lifecycle Manager](dlm.md) | `/policies`, `/policies/{policyId}`, `/tags/{resourceArn}` | REST JSON | 8 | | [ElastiCache](elasticache.md) | `POST /` with `Action=` param + TCP proxy | Query + RESP | 22 | | [MemoryDB](memorydb.md) | `POST /` + `X-Amz-Target: AmazonMemoryDB.*` + TCP proxy | JSON 1.1 + RESP | 13 | -| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 86 | +| [RDS](rds.md) | `POST /` with `Action=` param + TCP proxy | Query + wire | 90 | | [RDS Data API](rds-data.md) | `/Execute`, `/BeginTransaction`, `/CommitTransaction`, `/RollbackTransaction` | REST JSON | 4 | | [Timestream for InfluxDB](timestream-influxdb.md) | `POST /` + `X-Amz-Target: AmazonTimestreamInfluxDB.*` + InfluxDB container | JSON 1.0 + InfluxDB HTTP | 24 | | [MSK](msk.md) | `/v1/clusters/...`, `/api/v2/clusters/...` + Redpanda broker | REST JSON + Kafka | 8 | diff --git a/docs/services/rds.md b/docs/services/rds.md index d1ebcdc2d3..0992e26f3e 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -63,6 +63,10 @@ RDS Data API (`rds-data`) is documented separately because it uses REST JSON rou | `DescribeEventSubscriptions` | List subscriptions, or the one the request names | | `ModifyEventSubscription` | Update the members the request names | | `DeleteEventSubscription` | Delete a subscription | +| `CreateDBClusterEndpoint` | Create an Aurora custom endpoint (`READER` or `ANY`) with a static or exclusion member list; see [Cluster endpoints](#cluster-endpoints) | +| `DescribeDBClusterEndpoints` | List a cluster's built-in writer and reader endpoints and its custom endpoints, with the four documented filters | +| `ModifyDBClusterEndpoint` | Change a custom endpoint's type or member list | +| `DeleteDBClusterEndpoint` | Delete a custom endpoint | | `AddSourceIdentifierToSubscription` | Add a source id to a subscription | | `RemoveSourceIdentifierFromSubscription` | Remove a source id from a subscription | | `CreateDBSubnetGroup` | Create a DB subnet group; tags given here are readable through `ListTagsForResource` | @@ -528,6 +532,34 @@ same-region replicas; a cross-region replica keeps its link with the replication `terminated` until it is promoted or deleted, which is what AWS does for PostgreSQL. Deleting a replica drops it from its source's list. +## Cluster endpoints + +`CreateDBClusterEndpoint` adds an Aurora custom endpoint to an available cluster. As the Aurora user +guide describes, its type is `READER` or `ANY` (case-insensitive, as the CLI sends it), it holds either +a static list or an exclusion list of the cluster's instances but not both +(`InvalidParameterCombination`), and a `READER` endpoint cannot list the writer. A member that is not +an instance of the cluster is `DBInstanceNotFound`. The identifier follows the RDS identifier rules +(at most 63 characters), is stored lower case and is unique in the Region +(`DBClusterEndpointAlreadyExistsFault`); a cluster holds at most five custom endpoints +(`DBClusterEndpointQuotaExceededFault`). The endpoint's ARN, +`arn:aws:rds:::cluster-endpoint:`, works with the tagging actions. + +`DescribeDBClusterEndpoints` lists each cluster's built-in `WRITER` and `READER` endpoints followed by +its custom endpoints, narrowed by `DBClusterIdentifier`, `DBClusterEndpointIdentifier` and the filters +`db-cluster-endpoint-type`, `db-cluster-endpoint-custom-type`, `db-cluster-endpoint-id` and +`db-cluster-endpoint-status`. `ModifyDBClusterEndpoint` changes the type or replaces the member list +(giving static members clears the exclusion list, and the other way round). Deleting a cluster deletes +its custom endpoints, and a deleted instance drops out of the lists that name it. + +A `READER` endpoint leaves out the cluster's current writer, so after a failover the promoted +instance no longer shows among its members, as Aurora adjusts `READER` membership. Member names match +the cluster's instances regardless of case and are stored as the cluster spells them. + +Custom endpoints are modelled, not routed: a custom endpoint reports the cluster's own endpoint host +(read from the cluster each time, so it follows a restart onto another proxy port), so it is +reachable, but connections through it go where the cluster endpoint sends them rather than being +spread across the chosen members. + ## Point in time restore `RestoreDBInstanceToPointInTime` and `RestoreDBClusterToPointInTime` check the request as AWS does: diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java index d0552c3e38..18398ace1e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java @@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.AwsQueryResponse; import io.github.hectorvent.floci.core.common.XmlBuilder; import io.github.hectorvent.floci.services.rds.model.DatabaseEngine; import io.github.hectorvent.floci.services.rds.model.DbCluster; +import io.github.hectorvent.floci.services.rds.model.DbClusterEndpoint; import io.github.hectorvent.floci.services.rds.model.DbClusterSnapshot; import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup; import io.github.hectorvent.floci.services.rds.model.DbEndpoint; @@ -97,6 +98,10 @@ public class RdsQueryHandler { case "DescribeEventSubscriptions" -> handleDescribeEventSubscriptions(params, region); case "ModifyEventSubscription" -> handleModifyEventSubscription(params, region); case "DeleteEventSubscription" -> handleDeleteEventSubscription(params, region); + case "CreateDBClusterEndpoint" -> handleCreateDbClusterEndpoint(params, region); + case "DescribeDBClusterEndpoints" -> handleDescribeDbClusterEndpoints(params, region); + case "ModifyDBClusterEndpoint" -> handleModifyDbClusterEndpoint(params, region); + case "DeleteDBClusterEndpoint" -> handleDeleteDbClusterEndpoint(params, region); case "AddSourceIdentifierToSubscription" -> handleAddSourceIdentifierToSubscription(params, region); case "RemoveSourceIdentifierFromSubscription" -> @@ -343,6 +348,93 @@ public class RdsQueryHandler { new XmlBuilder().raw(eventSubscriptionXml(subscription)).build())).build(); } + private Response handleCreateDbClusterEndpoint(MultivaluedMap params, String region) { + DbClusterEndpoint endpoint = service.createDbClusterEndpoint(region, + params.getFirst("DBClusterIdentifier"), + params.getFirst("DBClusterEndpointIdentifier"), + params.getFirst("EndpointType"), + memberList(params, "StaticMembers"), + memberList(params, "ExcludedMembers"), + parseTags(params)); + return Response.ok(AwsQueryResponse.envelope("CreateDBClusterEndpoint", AwsNamespaces.RDS, + dbClusterEndpointInnerXml(endpoint))).build(); + } + + private Response handleModifyDbClusterEndpoint(MultivaluedMap params, String region) { + // A list left out of the request keeps the endpoint's lists; one given replaces them. + DbClusterEndpoint endpoint = service.modifyDbClusterEndpoint(region, + params.getFirst("DBClusterEndpointIdentifier"), + params.getFirst("EndpointType"), + hasMemberKeys(params, "StaticMembers") ? memberList(params, "StaticMembers") : null, + hasMemberKeys(params, "ExcludedMembers") ? memberList(params, "ExcludedMembers") : null); + return Response.ok(AwsQueryResponse.envelope("ModifyDBClusterEndpoint", AwsNamespaces.RDS, + dbClusterEndpointInnerXml(endpoint))).build(); + } + + private Response handleDeleteDbClusterEndpoint(MultivaluedMap params, String region) { + DbClusterEndpoint endpoint = service.deleteDbClusterEndpoint(region, + params.getFirst("DBClusterEndpointIdentifier")); + return Response.ok(AwsQueryResponse.envelope("DeleteDBClusterEndpoint", AwsNamespaces.RDS, + dbClusterEndpointInnerXml(endpoint))).build(); + } + + private Response handleDescribeDbClusterEndpoints(MultivaluedMap params, String region) { + Map> filters = new LinkedHashMap<>(); + for (String name : List.of("db-cluster-endpoint-type", "db-cluster-endpoint-custom-type", + "db-cluster-endpoint-id", "db-cluster-endpoint-status")) { + List values = extractRdsFilterValues(params, name); + if (!values.isEmpty()) { + filters.put(name, values); + } + } + RdsService.ClusterEndpointPage page = service.describeDbClusterEndpoints(region, + params.getFirst("DBClusterIdentifier"), + params.getFirst("DBClusterEndpointIdentifier"), + filters, + optionalInt(params.getFirst("MaxRecords")), + params.getFirst("Marker")); + XmlBuilder xml = new XmlBuilder().start("DBClusterEndpoints"); + for (DbClusterEndpoint endpoint : page.endpoints()) { + xml.start("DBClusterEndpointList").raw(dbClusterEndpointInnerXml(endpoint)).end("DBClusterEndpointList"); + } + xml.end("DBClusterEndpoints"); + if (page.marker() != null) { + xml.elem("Marker", page.marker()); + } + return Response.ok(AwsQueryResponse.envelope("DescribeDBClusterEndpoints", AwsNamespaces.RDS, + xml.build())).build(); + } + + /** The DBClusterEndpoint members; a built-in endpoint has no identifier, ARN, custom type or lists. */ + private static String dbClusterEndpointInnerXml(DbClusterEndpoint e) { + XmlBuilder xml = new XmlBuilder(); + if (e.getDbClusterEndpointIdentifier() != null) { + xml.elem("DBClusterEndpointIdentifier", e.getDbClusterEndpointIdentifier()); + } + xml.elem("DBClusterIdentifier", e.getDbClusterIdentifier()); + if (e.getDbClusterEndpointResourceIdentifier() != null) { + xml.elem("DBClusterEndpointResourceIdentifier", e.getDbClusterEndpointResourceIdentifier()); + } + if (e.getEndpoint() != null) { + xml.elem("Endpoint", e.getEndpoint()); + } + xml.elem("Status", e.getStatus()) + .elem("EndpointType", e.getEndpointType()); + if (e.getCustomEndpointType() != null) { + xml.elem("CustomEndpointType", e.getCustomEndpointType()); + xml.start("StaticMembers"); + e.getStaticMembers().forEach(member -> xml.elem("member", member)); + xml.end("StaticMembers"); + xml.start("ExcludedMembers"); + e.getExcludedMembers().forEach(member -> xml.elem("member", member)); + xml.end("ExcludedMembers"); + } + if (e.getDbClusterEndpointArn() != null) { + xml.elem("DBClusterEndpointArn", e.getDbClusterEndpointArn()); + } + return xml.build(); + } + private Response handleDescribeEventSubscriptions(MultivaluedMap params, String region) { RdsService.EventSubscriptionPage page = service.describeEventSubscriptions(region, params.getFirst("SubscriptionName"), diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java index 14976edcd9..32fc276221 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java @@ -32,6 +32,7 @@ import io.github.hectorvent.floci.services.rds.container.RdsContainerHandle; import io.github.hectorvent.floci.services.rds.container.RdsContainerManager; import io.github.hectorvent.floci.services.rds.model.DatabaseEngine; import io.github.hectorvent.floci.services.rds.model.DbCluster; +import io.github.hectorvent.floci.services.rds.model.DbClusterEndpoint; import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup; import io.github.hectorvent.floci.services.rds.model.DbClusterSnapshot; import io.github.hectorvent.floci.services.rds.model.DbEndpoint; @@ -80,6 +81,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import java.util.regex.Matcher; @@ -172,6 +174,7 @@ public class RdsService implements Resettable, ResourceProvider { private final StorageBackend snapshotData; private StorageBackend events = new InMemoryStorage<>(); private final StorageBackend eventSubscriptions; + private final StorageBackend clusterEndpoints; private final RdsContainerManager containerManager; private final RdsProxyManager proxyManager; // CreateDBCluster/CreateDBInstance register the new resource only after the @@ -245,6 +248,8 @@ public class RdsService implements Resettable, ResourceProvider { new TypeReference>() {}); this.eventSubscriptions = storageFactory.create("rds", "rds-event-subscriptions.json", new TypeReference>() {}); + this.clusterEndpoints = storageFactory.create("rds", "rds-cluster-endpoints.json", + new TypeReference>() {}); this.clusters = storageFactory.create("rds", "rds-clusters.json", new TypeReference>() {}); this.parameterGroups = storageFactory.create("rds", "rds-parameter-groups.json", @@ -406,6 +411,7 @@ public class RdsService implements Resettable, ResourceProvider { this.clusterSnapshots = new InMemoryStorage<>(); this.snapshotData = new io.github.hectorvent.floci.core.storage.InMemoryStorage<>(); this.eventSubscriptions = new InMemoryStorage<>(); + this.clusterEndpoints = new InMemoryStorage<>(); } public void restorePersistedRuntime() { @@ -2339,6 +2345,14 @@ public class RdsService implements Resettable, ResourceProvider { putSnapshotForScope(currentAccountId(), effectiveRegion, resourceId, snapshot); }); } + case "cluster-endpoint" -> { + DbClusterEndpoint endpoint = requireClusterEndpoint(effectiveRegion, resourceId); + yield new TagHandle(endpoint.getTags(), updated -> { + endpoint.setTags(updated); + clusterEndpoints.put(clusterEndpointKey(effectiveRegion, + endpoint.getDbClusterEndpointIdentifier()), endpoint); + }); + } case "es" -> { EventSubscription subscription = eventSubscriptions .get(eventSubscriptionKey(effectiveRegion, resourceId)) @@ -3781,6 +3795,7 @@ public class RdsService implements Resettable, ResourceProvider { // Losing the writer promotes a remaining member, as Aurora fails over on its own. cluster.setClusterWriterIdentifier(cluster.resolveWriterIdentifier()); putClusterForScope(currentAccountId(), effectiveRegion, clusterId, cluster); + dropFromClusterEndpoints(effectiveRegion, clusterId, id); } } @@ -4496,6 +4511,9 @@ public class RdsService implements Resettable, ResourceProvider { releaseProxyPort(cluster.getProxyPort()); deleteClusterForScope(currentAccountId(), effectiveRegion, id); + // Custom endpoints belong to their cluster and go with it. + clusterEndpointsOf(effectiveRegion, id).forEach(endpoint -> clusterEndpoints.delete( + clusterEndpointKey(effectiveRegion, endpoint.getDbClusterEndpointIdentifier()))); LOG.infov("DB cluster {0} deleted", id); } @@ -9299,6 +9317,310 @@ public class RdsService implements Resettable, ResourceProvider { "Subscription " + subscriptionName + " not found.", 404)); } + // ── Cluster endpoints ───────────────────────────────────────────────────── + + private static final int MAX_CUSTOM_ENDPOINTS_PER_CLUSTER = 5; + private static final int MAX_CLUSTER_ENDPOINT_IDENTIFIER_LENGTH = 63; + // The Aurora user guide's custom endpoint types; WRITER is the built-in endpoint's type. + private static final Set CUSTOM_ENDPOINT_TYPES = Set.of("READER", "ANY"); + + public record ClusterEndpointPage(List endpoints, String marker) {} + + /** + * Creates an Aurora custom endpoint. It is modelled, not routed: it reports the cluster's own + * endpoint host, so connections through it go where the cluster endpoint sends them. + */ + public synchronized DbClusterEndpoint createDbClusterEndpoint(String region, String clusterId, String endpointId, + String endpointType, List staticMembers, + List excludedMembers, Map tags) { + String effectiveRegion = effectiveRegion(region); + if (isBlank(clusterId)) { + throw new AwsException("InvalidParameterValue", "DBClusterIdentifier is required.", 400); + } + String id = requireClusterEndpointIdentifier(endpointId); + DbCluster cluster = getDbCluster(clusterId, effectiveRegion); + if (cluster.getStatus() != null && cluster.getStatus() != DbInstanceStatus.AVAILABLE) { + throw new AwsException("InvalidDBClusterStateFault", + "DB cluster " + cluster.getDbClusterIdentifier() + " is not in available state.", 400); + } + String customType = requireCustomEndpointType(endpointType); + staticMembers = clusterMembersNamed(cluster, staticMembers); + excludedMembers = clusterMembersNamed(cluster, excludedMembers); + requireEndpointMembers(cluster, customType, staticMembers, excludedMembers); + String key = clusterEndpointKey(effectiveRegion, id); + if (clusterEndpoints.get(key).isPresent()) { + throw new AwsException("DBClusterEndpointAlreadyExistsFault", + "DB cluster endpoint " + id + " already exists.", 400); + } + if (clusterEndpointsOf(effectiveRegion, cluster.getDbClusterIdentifier()).size() + >= MAX_CUSTOM_ENDPOINTS_PER_CLUSTER) { + throw new AwsException("DBClusterEndpointQuotaExceededFault", + "DB cluster " + cluster.getDbClusterIdentifier() + " already has " + + MAX_CUSTOM_ENDPOINTS_PER_CLUSTER + " custom endpoints.", 403); + } + DbClusterEndpoint endpoint = new DbClusterEndpoint(); + endpoint.setDbClusterEndpointIdentifier(id); + endpoint.setDbClusterIdentifier(cluster.getDbClusterIdentifier()); + endpoint.setDbClusterEndpointResourceIdentifier("cluster-endpoint-" + + UUID.randomUUID().toString().replace("-", "").substring(0, 24).toLowerCase(Locale.ROOT)); + endpoint.setEndpoint(clusterEndpointHost(cluster)); + endpoint.setStatus("available"); + endpoint.setEndpointType("CUSTOM"); + endpoint.setCustomEndpointType(customType); + endpoint.setStaticMembers(staticMembers != null ? new ArrayList<>(staticMembers) : new ArrayList<>()); + endpoint.setExcludedMembers(excludedMembers != null ? new ArrayList<>(excludedMembers) : new ArrayList<>()); + endpoint.setDbClusterEndpointArn(regionResolver.buildArn("rds", effectiveRegion, "cluster-endpoint:" + id)); + endpoint.setTags(tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>()); + clusterEndpoints.put(key, endpoint); + return endpoint; + } + + /** + * Changes a custom endpoint's type or member lists. A list in the request replaces the + * endpoint's list type: static members clear the exclusion list and the other way round. + */ + public synchronized DbClusterEndpoint modifyDbClusterEndpoint(String region, String endpointId, String endpointType, + List staticMembers, + List excludedMembers) { + String effectiveRegion = effectiveRegion(region); + DbClusterEndpoint endpoint = requireClusterEndpoint(effectiveRegion, endpointId); + DbCluster cluster = getDbCluster(endpoint.getDbClusterIdentifier(), effectiveRegion); + String customType = isBlank(endpointType) ? endpoint.getCustomEndpointType() : requireCustomEndpointType(endpointType); + boolean listsGiven = staticMembers != null || excludedMembers != null; + List newStatic = listsGiven ? clusterMembersNamed(cluster, staticMembers) : endpoint.getStaticMembers(); + List newExcluded = listsGiven ? clusterMembersNamed(cluster, excludedMembers) : endpoint.getExcludedMembers(); + // The writer rule applies to a list the request supplies. A kept list may name an instance + // that failover has since made the writer; it stays stored, so it is a member again after a + // failback, and the endpoint's view leaves it out while it is the writer. + requireEndpointMembers(cluster, listsGiven ? customType : null, newStatic, newExcluded); + endpoint.setCustomEndpointType(customType); + endpoint.setStaticMembers(newStatic != null ? new ArrayList<>(newStatic) : new ArrayList<>()); + endpoint.setExcludedMembers(newExcluded != null ? new ArrayList<>(newExcluded) : new ArrayList<>()); + clusterEndpoints.put(clusterEndpointKey(effectiveRegion, endpoint.getDbClusterEndpointIdentifier()), endpoint); + return currentView(endpoint, cluster); + } + + /** Deletes a custom endpoint; the response reports it as {@code deleting}, as AWS does. */ + public synchronized DbClusterEndpoint deleteDbClusterEndpoint(String region, String endpointId) { + String effectiveRegion = effectiveRegion(region); + DbClusterEndpoint endpoint = requireClusterEndpoint(effectiveRegion, endpointId); + clusterEndpoints.delete(clusterEndpointKey(effectiveRegion, endpoint.getDbClusterEndpointIdentifier())); + DbClusterEndpoint deleted = currentView(endpoint, + findClusterForScope(currentAccountId(), effectiveRegion, endpoint.getDbClusterIdentifier())); + deleted.setStatus("deleting"); + return deleted; + } + + /** + * The built-in WRITER and READER endpoints of each cluster in scope, followed by its custom + * endpoints, narrowed by the request's cluster, endpoint identifier and filters. Filter names + * and values are those the API reference lists; values match case-insensitively. + */ + public synchronized ClusterEndpointPage describeDbClusterEndpoints(String region, String clusterId, String endpointId, + Map> filters, + Integer maxRecords, String marker) { + String effectiveRegion = effectiveRegion(region); + if (maxRecords != null && (maxRecords < MIN_MAX_RECORDS || maxRecords > MAX_MAX_RECORDS)) { + throw new AwsException("InvalidParameterValue", + "MaxRecords must be between " + MIN_MAX_RECORDS + " and " + MAX_MAX_RECORDS + ".", 400); + } + List scope = !isBlank(clusterId) + ? List.of(getDbCluster(clusterId, effectiveRegion)) + : listDbClusters(null, effectiveRegion).stream() + .sorted(Comparator.comparing(DbCluster::getDbClusterIdentifier)) + .toList(); + List all = new ArrayList<>(); + for (DbCluster cluster : scope) { + if (isBlank(endpointId)) { + if (cluster.getEndpoint() != null) { + all.add(builtInClusterEndpoint(cluster, "WRITER", cluster.getEndpoint().address())); + } + if (cluster.getReaderEndpoint() != null) { + all.add(builtInClusterEndpoint(cluster, "READER", cluster.getReaderEndpoint().address())); + } + } + clusterEndpointsOf(effectiveRegion, cluster.getDbClusterIdentifier()).stream() + .filter(e -> isBlank(endpointId) + || e.getDbClusterEndpointIdentifier().equals(endpointId.toLowerCase(Locale.ROOT))) + .sorted(Comparator.comparing(DbClusterEndpoint::getDbClusterEndpointIdentifier)) + .map(e -> currentView(e, cluster)) + .forEach(all::add); + } + List matching = all.stream() + .filter(e -> matchesFilter(filters, "db-cluster-endpoint-type", e.getEndpointType())) + .filter(e -> matchesFilter(filters, "db-cluster-endpoint-custom-type", e.getCustomEndpointType())) + .filter(e -> matchesFilter(filters, "db-cluster-endpoint-id", e.getDbClusterEndpointIdentifier())) + .filter(e -> matchesFilter(filters, "db-cluster-endpoint-status", e.getStatus())) + .toList(); + int from = 0; + if (!isBlank(marker)) { + try { + from = Integer.parseInt(marker); + } catch (NumberFormatException e) { + throw new AwsException("InvalidParameterValue", "Invalid marker: " + marker, 400); + } + } + int limit = maxRecords == null ? DEFAULT_MAX_RECORDS : maxRecords; + int start = Math.min(Math.max(from, 0), matching.size()); + int to = Math.min(matching.size(), start + limit); + return new ClusterEndpointPage(matching.subList(start, to), + to < matching.size() ? Integer.toString(to) : null); + } + + private static boolean matchesFilter(Map> filters, String name, String value) { + List wanted = filters != null ? filters.get(name) : null; + if (wanted == null || wanted.isEmpty()) { + return true; + } + return value != null && wanted.stream().anyMatch(w -> w.equalsIgnoreCase(value)); + } + + private DbClusterEndpoint builtInClusterEndpoint(DbCluster cluster, String type, String address) { + DbClusterEndpoint endpoint = new DbClusterEndpoint(); + endpoint.setDbClusterIdentifier(cluster.getDbClusterIdentifier()); + endpoint.setEndpoint(address); + endpoint.setStatus("available"); + endpoint.setEndpointType(type); + return endpoint; + } + + /** + * A custom endpoint as it stands now. Its address follows the cluster's endpoint, which a + * restart can move to another proxy port. A READER endpoint leaves out the cluster's current + * writer, as Aurora adjusts READER membership on failover and promotion (user guide). + */ + private static DbClusterEndpoint currentView(DbClusterEndpoint stored, DbCluster cluster) { + DbClusterEndpoint view = new DbClusterEndpoint(); + view.setDbClusterEndpointIdentifier(stored.getDbClusterEndpointIdentifier()); + view.setDbClusterIdentifier(stored.getDbClusterIdentifier()); + view.setDbClusterEndpointResourceIdentifier(stored.getDbClusterEndpointResourceIdentifier()); + view.setStatus(stored.getStatus()); + view.setEndpointType(stored.getEndpointType()); + view.setCustomEndpointType(stored.getCustomEndpointType()); + view.setDbClusterEndpointArn(stored.getDbClusterEndpointArn()); + view.setTags(stored.getTags()); + view.setExcludedMembers(new ArrayList<>(stored.getExcludedMembers())); + List staticMembers = new ArrayList<>(stored.getStaticMembers()); + String host = stored.getEndpoint(); + if (cluster != null) { + host = clusterEndpointHost(cluster) != null ? clusterEndpointHost(cluster) : host; + String writer = cluster.resolveWriterIdentifier(); + if ("READER".equals(stored.getCustomEndpointType()) && writer != null) { + staticMembers.removeIf(writer::equalsIgnoreCase); + } + } + view.setEndpoint(host); + view.setStaticMembers(staticMembers); + return view; + } + + /** + * The members as the cluster spells them: instance identifiers match regardless of case, as + * the failover lookup does. A name that is no instance of the cluster is kept as given, so the + * membership check reports it. + */ + private static List clusterMembersNamed(DbCluster cluster, List members) { + if (members == null) { + return null; + } + return members.stream() + .map(member -> cluster.getDbClusterMembers().stream() + .filter(member::equalsIgnoreCase) + .findFirst() + .orElse(member)) + .toList(); + } + + private static String clusterEndpointHost(DbCluster cluster) { + return cluster.getEndpoint() != null ? cluster.getEndpoint().address() : null; + } + + private DbClusterEndpoint requireClusterEndpoint(String region, String endpointId) { + if (isBlank(endpointId)) { + throw new AwsException("InvalidParameterValue", "DBClusterEndpointIdentifier is required.", 400); + } + String id = endpointId.toLowerCase(Locale.ROOT); + return clusterEndpoints.get(clusterEndpointKey(region, id)) + .orElseThrow(() -> new AwsException("DBClusterEndpointNotFoundFault", + "DB cluster endpoint " + id + " not found.", 400)); + } + + /** RDS identifier rules: a letter first, letters, digits and single hyphens, no trailing hyphen. */ + private static String requireClusterEndpointIdentifier(String endpointId) { + if (isBlank(endpointId)) { + throw new AwsException("InvalidParameterValue", "DBClusterEndpointIdentifier is required.", 400); + } + if (endpointId.length() > MAX_CLUSTER_ENDPOINT_IDENTIFIER_LENGTH + || !DB_PROXY_NAME_PATTERN.matcher(endpointId).matches()) { + throw new AwsException("InvalidParameterValue", + "DBClusterEndpointIdentifier must begin with a letter, contain only letters, digits and " + + "single hyphens, not end with a hyphen, and be at most " + + MAX_CLUSTER_ENDPOINT_IDENTIFIER_LENGTH + " characters.", 400); + } + // Stored as a lowercase string (API reference). + return endpointId.toLowerCase(Locale.ROOT); + } + + private static String requireCustomEndpointType(String endpointType) { + String type = endpointType == null ? "" : endpointType.toUpperCase(Locale.ROOT); + if (!CUSTOM_ENDPOINT_TYPES.contains(type)) { + throw new AwsException("InvalidParameterValue", + "EndpointType must be READER or ANY for a custom endpoint.", 400); + } + return type; + } + + /** + * A custom endpoint holds a static list or an exclusion list, never both; every member is an + * instance of the cluster, and a READER endpoint cannot name the writer. A null type skips the + * writer rule, for lists kept from before. + */ + private static void requireEndpointMembers(DbCluster cluster, String customType, + List staticMembers, List excludedMembers) { + boolean hasStatic = staticMembers != null && !staticMembers.isEmpty(); + boolean hasExcluded = excludedMembers != null && !excludedMembers.isEmpty(); + if (hasStatic && hasExcluded) { + throw new AwsException("InvalidParameterCombination", + "A custom endpoint takes StaticMembers or ExcludedMembers, not both.", 400); + } + List named = hasStatic ? staticMembers : hasExcluded ? excludedMembers : List.of(); + for (String member : named) { + if (!cluster.getDbClusterMembers().contains(member)) { + throw new AwsException("DBInstanceNotFound", + "DB instance " + member + " is not a member of DB cluster " + + cluster.getDbClusterIdentifier() + ".", 404); + } + } + if (hasStatic && "READER".equals(customType) + && staticMembers.contains(cluster.resolveWriterIdentifier())) { + throw new AwsException("InvalidParameterValue", + "A READER custom endpoint can't include the writer instance " + + cluster.resolveWriterIdentifier() + ".", 400); + } + } + + private List clusterEndpointsOf(String region, String clusterId) { + String prefix = clusterEndpointKey(region, ""); + return clusterEndpoints.scan(k -> k.startsWith(prefix)).stream() + .filter(e -> clusterId.equals(e.getDbClusterIdentifier())) + .toList(); + } + + /** A deleted instance drops out of the static and exclusion lists that name it. */ + private void dropFromClusterEndpoints(String region, String clusterId, String instanceId) { + for (DbClusterEndpoint endpoint : clusterEndpointsOf(region, clusterId)) { + boolean changed = endpoint.getStaticMembers().remove(instanceId) + | endpoint.getExcludedMembers().remove(instanceId); + if (changed) { + clusterEndpoints.put(clusterEndpointKey(region, endpoint.getDbClusterEndpointIdentifier()), endpoint); + } + } + } + + private static String clusterEndpointKey(String region, String endpointId) { + return "cep::" + region + "::" + endpointId; + } + private static String eventSubscriptionKey(String region, String subscriptionName) { return "es::" + region + "::" + subscriptionName; } diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbClusterEndpoint.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbClusterEndpoint.java new file mode 100644 index 0000000000..b2509962e4 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbClusterEndpoint.java @@ -0,0 +1,66 @@ +package io.github.hectorvent.floci.services.rds.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * An Aurora cluster endpoint as DescribeDBClusterEndpoints reports it. Custom endpoints are stored; + * a cluster's built-in WRITER and READER endpoints are built from the cluster when described and + * carry no identifier, ARN or custom type. + */ +@RegisterForReflection +public class DbClusterEndpoint { + + private String dbClusterEndpointIdentifier; + private String dbClusterIdentifier; + private String dbClusterEndpointResourceIdentifier; + private String endpoint; + private String status; + /** WRITER, READER or CUSTOM. */ + private String endpointType; + /** READER or ANY for a custom endpoint; null for a built-in one. */ + private String customEndpointType; + private List staticMembers = new ArrayList<>(); + private List excludedMembers = new ArrayList<>(); + private String dbClusterEndpointArn; + private Map tags = new LinkedHashMap<>(); + + public DbClusterEndpoint() {} + + public String getDbClusterEndpointIdentifier() { return dbClusterEndpointIdentifier; } + public void setDbClusterEndpointIdentifier(String dbClusterEndpointIdentifier) { this.dbClusterEndpointIdentifier = dbClusterEndpointIdentifier; } + + public String getDbClusterIdentifier() { return dbClusterIdentifier; } + public void setDbClusterIdentifier(String dbClusterIdentifier) { this.dbClusterIdentifier = dbClusterIdentifier; } + + public String getDbClusterEndpointResourceIdentifier() { return dbClusterEndpointResourceIdentifier; } + public void setDbClusterEndpointResourceIdentifier(String dbClusterEndpointResourceIdentifier) { this.dbClusterEndpointResourceIdentifier = dbClusterEndpointResourceIdentifier; } + + public String getEndpoint() { return endpoint; } + public void setEndpoint(String endpoint) { this.endpoint = endpoint; } + + public String getStatus() { return status; } + public void setStatus(String status) { this.status = status; } + + public String getEndpointType() { return endpointType; } + public void setEndpointType(String endpointType) { this.endpointType = endpointType; } + + public String getCustomEndpointType() { return customEndpointType; } + public void setCustomEndpointType(String customEndpointType) { this.customEndpointType = customEndpointType; } + + public List getStaticMembers() { return staticMembers; } + public void setStaticMembers(List staticMembers) { this.staticMembers = staticMembers; } + + public List getExcludedMembers() { return excludedMembers; } + public void setExcludedMembers(List excludedMembers) { this.excludedMembers = excludedMembers; } + + public String getDbClusterEndpointArn() { return dbClusterEndpointArn; } + public void setDbClusterEndpointArn(String dbClusterEndpointArn) { this.dbClusterEndpointArn = dbClusterEndpointArn; } + + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsClusterEndpointIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsClusterEndpointIntegrationTest.java new file mode 100644 index 0000000000..e33d160997 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsClusterEndpointIntegrationTest.java @@ -0,0 +1,232 @@ +package io.github.hectorvent.floci.services.rds; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static io.restassured.http.ContentType.URLENC; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; + +/** + * Aurora custom endpoints over the Query protocol: create, describe alongside the built-in + * writer and reader endpoints, modify, tag and delete, with the API reference's and the Aurora + * user guide's rules on types, member lists, identifiers and the per-cluster limit. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class RdsClusterEndpointIntegrationTest { + + private static final String CLUSTER = "cep-cluster"; + private static final String WRITER = "cep-writer"; + private static final String READER = "cep-reader"; + private static final String DESCRIBE_LIST = + "DescribeDBClusterEndpointsResponse.DescribeDBClusterEndpointsResult.DBClusterEndpoints.DBClusterEndpointList"; + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261004/us-east-1/rds/aws4_request, " + + "SignedHeaders=content-type;host, Signature=test"; + + private static RequestSpecification query(String action) { + return given().header("Authorization", AUTH) + .contentType(URLENC) + .formParam("Action", action) + .formParam("Version", "2014-10-31"); + } + + private static RequestSpecification createEndpoint(String id, String type) { + return query("CreateDBClusterEndpoint") + .formParam("DBClusterIdentifier", CLUSTER) + .formParam("DBClusterEndpointIdentifier", id) + .formParam("EndpointType", type); + } + + @Test + @Order(1) + void createsACustomEndpointOnAClusterWithAWriterAndAReader() { + query("CreateDBCluster") + .formParam("DBClusterIdentifier", CLUSTER) + .formParam("Engine", "aurora-postgresql") + .formParam("EngineVersion", "16.3") + .formParam("MasterUsername", "admin") + .formParam("MasterUserPassword", "password123") + .when().post("/").then().statusCode(200); + for (String instance : new String[] {WRITER, READER}) { + query("CreateDBInstance") + .formParam("DBInstanceIdentifier", instance) + .formParam("DBClusterIdentifier", CLUSTER) + .formParam("Engine", "aurora-postgresql") + .formParam("DBInstanceClass", "db.r6g.large") + .when().post("/").then().statusCode(200); + } + + // The CLI sends the type in lower case, and the identifier is stored lower case. + createEndpoint("Reports-EP", "reader") + .formParam("StaticMembers.member.1", READER) + .formParam("Tags.Tag.1.Key", "team") + .formParam("Tags.Tag.1.Value", "analytics") + .when().post("/").then() + .statusCode(200) + .body(containsString("")) + .body(containsString("reports-ep")) + .body(containsString("" + CLUSTER + "")) + .body(containsString("cluster-endpoint-")) + .body(containsString("")) + .body(containsString("available")) + .body(containsString("CUSTOM")) + .body(containsString("READER")) + .body(containsString("" + READER + "")) + .body(containsString("")) + .body(containsString(":cluster-endpoint:reports-ep")); + } + + @Test + @Order(2) + void describeListsTheBuiltInEndpointsWithTheCustomOneAndFilters() { + query("DescribeDBClusterEndpoints").formParam("DBClusterIdentifier", CLUSTER) + .when().post("/").then() + .statusCode(200) + .body(DESCRIBE_LIST + ".size()", equalTo(3)) + .body(DESCRIBE_LIST + "[0].EndpointType", equalTo("WRITER")) + .body(DESCRIBE_LIST + "[1].EndpointType", equalTo("READER")) + .body(DESCRIBE_LIST + "[2].DBClusterEndpointIdentifier", equalTo("reports-ep")); + + query("DescribeDBClusterEndpoints") + .formParam("DBClusterIdentifier", CLUSTER) + .formParam("Filters.Filter.1.Name", "db-cluster-endpoint-type") + .formParam("Filters.Filter.1.Values.Value.1", "custom") + .when().post("/").then().statusCode(200) + .body(DESCRIBE_LIST + ".DBClusterEndpointIdentifier", equalTo("reports-ep")); + + query("DescribeDBClusterEndpoints") + .formParam("DBClusterIdentifier", CLUSTER) + .formParam("Filters.Filter.1.Name", "db-cluster-endpoint-custom-type") + .formParam("Filters.Filter.1.Values.Value.1", "any") + .when().post("/").then().statusCode(200) + .body(not(containsString(""))); + + query("DescribeDBClusterEndpoints").formParam("DBClusterEndpointIdentifier", "REPORTS-EP") + .when().post("/").then().statusCode(200) + .body(DESCRIBE_LIST + ".DBClusterEndpointIdentifier", equalTo("reports-ep")); + + query("DescribeDBClusterEndpoints").formParam("DBClusterIdentifier", "cep-missing") + .when().post("/").then().statusCode(404) + .body(containsString("DBClusterNotFoundFault")); + } + + @Test + @Order(3) + void createRefusesWhatTheApiAndUserGuideRuleOut() { + createEndpoint("reports-ep", "READER") + .when().post("/").then().statusCode(400) + .body(containsString("DBClusterEndpointAlreadyExistsFault")); + createEndpoint("writer-in-reader", "READER") + .formParam("StaticMembers.member.1", WRITER) + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")); + createEndpoint("both-lists", "ANY") + .formParam("StaticMembers.member.1", READER) + .formParam("ExcludedMembers.member.1", WRITER) + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterCombination")); + createEndpoint("stranger", "ANY") + .formParam("StaticMembers.member.1", "cep-not-a-member") + .when().post("/").then().statusCode(404) + .body(containsString("DBInstanceNotFound")); + createEndpoint("writer-type", "WRITER") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")); + createEndpoint("-bad-name", "ANY") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")); + query("CreateDBClusterEndpoint") + .formParam("DBClusterIdentifier", "cep-missing") + .formParam("DBClusterEndpointIdentifier", "orphan") + .formParam("EndpointType", "ANY") + .when().post("/").then().statusCode(404) + .body(containsString("DBClusterNotFoundFault")); + } + + @Test + @Order(4) + void aClusterHoldsAtMostFiveCustomEndpoints() { + for (int i = 2; i <= 5; i++) { + createEndpoint("extra-" + i, "ANY").when().post("/").then().statusCode(200); + } + createEndpoint("extra-6", "ANY") + .when().post("/").then().statusCode(403) + .body(containsString("DBClusterEndpointQuotaExceededFault")); + for (int i = 2; i <= 5; i++) { + query("DeleteDBClusterEndpoint").formParam("DBClusterEndpointIdentifier", "extra-" + i) + .when().post("/").then().statusCode(200); + } + } + + @Test + @Order(5) + void modifySwitchesTheTypeAndListAndTagsFollowTheArn() { + query("ModifyDBClusterEndpoint") + .formParam("DBClusterEndpointIdentifier", "reports-ep") + .formParam("EndpointType", "ANY") + .formParam("ExcludedMembers.member.1", READER) + .when().post("/").then() + .statusCode(200) + .body(containsString("")) + .body(containsString("ANY")) + .body(containsString("")) + .body(containsString("" + READER + "")); + + query("ModifyDBClusterEndpoint") + .formParam("DBClusterEndpointIdentifier", "cep-missing-ep") + .formParam("EndpointType", "ANY") + .when().post("/").then().statusCode(400) + .body(containsString("DBClusterEndpointNotFoundFault")); + + query("ListTagsForResource") + .formParam("ResourceName", "arn:aws:rds:us-east-1:000000000000:cluster-endpoint:reports-ep") + .when().post("/").then().statusCode(200) + .body(containsString("analytics")); + } + + @Test + @Order(6) + void aDeletedInstanceLeavesTheListsAndDeleteRemovesTheEndpoint() { + query("DeleteDBInstance").formParam("DBInstanceIdentifier", READER) + .when().post("/").then().statusCode(200); + query("DescribeDBClusterEndpoints").formParam("DBClusterEndpointIdentifier", "reports-ep") + .when().post("/").then().statusCode(200) + .body(containsString("")); + + query("DeleteDBClusterEndpoint").formParam("DBClusterEndpointIdentifier", "reports-ep") + .when().post("/").then() + .statusCode(200) + .body(containsString("")) + .body(containsString("deleting")); + query("DescribeDBClusterEndpoints").formParam("DBClusterEndpointIdentifier", "reports-ep") + .when().post("/").then().statusCode(200) + .body(not(containsString(""))); + query("DeleteDBClusterEndpoint").formParam("DBClusterEndpointIdentifier", "reports-ep") + .when().post("/").then().statusCode(400) + .body(containsString("DBClusterEndpointNotFoundFault")); + } + + @Test + @Order(7) + void deletingTheClusterDeletesItsCustomEndpoints() { + createEndpoint("last-ep", "ANY").when().post("/").then().statusCode(200); + query("DeleteDBInstance").formParam("DBInstanceIdentifier", WRITER) + .when().post("/").then().statusCode(200); + query("DeleteDBCluster") + .formParam("DBClusterIdentifier", CLUSTER) + .formParam("SkipFinalSnapshot", "true") + .when().post("/").then().statusCode(200); + query("DescribeDBClusterEndpoints").formParam("DBClusterEndpointIdentifier", "last-ep") + .when().post("/").then().statusCode(200) + .body(not(containsString(""))); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java index 88434c107d..e26754caaf 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java @@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.ec2.model.Vpc; import io.github.hectorvent.floci.services.ec2.model.VpcIpv6CidrBlockAssociation; import io.github.hectorvent.floci.services.rds.model.DatabaseEngine; import io.github.hectorvent.floci.services.rds.model.DbCluster; +import io.github.hectorvent.floci.services.rds.model.DbClusterEndpoint; import io.github.hectorvent.floci.services.rds.model.DbClusterSnapshot; import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup; import io.github.hectorvent.floci.services.rds.container.AutoPauseListener; @@ -8391,6 +8392,42 @@ class RdsServiceTest { assertEquals("GlobalClusterAlreadyExistsFault", taken.getErrorCode()); } + @Test + void customClusterEndpointFollowsTheClusterNamesWriterAndAddress() { + rdsService.createDbCluster("Mixed-Cluster", "aurora-postgresql", "16.3", "admin", "password", "appdb", false, null); + for (String member : List.of("Writer-1", "Reader-1")) { + rdsService.createDbInstance(member, "aurora-postgresql", "16.3", + "admin", "password", "appdb", "db.r5.large", + 20, false, null, null, "Mixed-Cluster", null, false, false, null, + Map.of(), List.of(), null, null, true, DbInstanceSettings.defaults()); + } + + // The cluster is found under its own spelling, and a member named in other capitals is + // stored as the cluster spells it. + DbClusterEndpoint created = rdsService.createDbClusterEndpoint("us-east-1", "Mixed-Cluster", "reports", + "READER", List.of("READER-1"), null, Map.of()); + assertEquals(List.of("Reader-1"), created.getStaticMembers()); + + // After a failover the new writer drops out of the READER endpoint, as Aurora adjusts it. + rdsService.failoverDbCluster("Mixed-Cluster", "Reader-1", "us-east-1"); + DbClusterEndpoint afterFailover = rdsService.describeDbClusterEndpoints("us-east-1", null, "reports", + Map.of(), null, null).endpoints().getFirst(); + assertEquals(List.of(), afterFailover.getStaticMembers()); + // A modify that leaves the lists alone still succeeds, and a failback makes the member a + // reader of the endpoint again, since failover never removed it from the stored list. + DbClusterEndpoint retyped = rdsService.modifyDbClusterEndpoint("us-east-1", "reports", "READER", null, null); + assertEquals(List.of(), retyped.getStaticMembers()); + rdsService.failoverDbCluster("Mixed-Cluster", "Writer-1", "us-east-1"); + assertEquals(List.of("Reader-1"), rdsService.describeDbClusterEndpoints("us-east-1", null, "reports", + Map.of(), null, null).endpoints().getFirst().getStaticMembers()); + + // The address follows the cluster's endpoint rather than the one stored at create. + rdsService.getDbCluster("Mixed-Cluster").setEndpoint(new DbEndpoint("moved.example", 7099)); + DbClusterEndpoint moved = rdsService.describeDbClusterEndpoints("us-east-1", null, "reports", + Map.of(), null, null).endpoints().getFirst(); + assertEquals("moved.example", moved.getEndpoint()); + } + @Test void failoverDbClusterMovesTheWriterRole() { rdsService.createDbCluster("aurora", "aurora-postgresql", "16.3", "admin", "password", "appdb", false, null);