Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(rds): read replicas with a point-in-time copy of the source (#3813)

David008aa9ba3552
diff --git a/docs/services/rds.md b/docs/services/rds.md
index 8ad7ea705a..651142212f 100644
--- a/docs/services/rds.md
+++ b/docs/services/rds.md
@@ -18,6 +18,10 @@ RDS Data API (`rds-data`) is documented separately because it uses REST JSON rou
| `DeleteDBInstance` | Stop and remove an instance |
| `ModifyDBInstance` | Update instance settings |
| `RebootDBInstance` | Restart a database instance |
+| `CreateDBInstanceReadReplica` | Create a read replica of a PostgreSQL instance, initialised from a copy of the source; see [Read replicas](#read-replicas) |
+| `PromoteReadReplica` | Detach a read replica into a standalone instance and turn automated backups on |
+| `SwitchoverReadReplica` | Refused with `InvalidDBInstanceState`: AWS supports switchover only for Oracle and SQL Server replicas, neither of which is emulated |
+| `PromoteReadReplicaDBCluster` | Refused with `InvalidDBClusterStateFault`: no cluster is created as a replica of an instance |
| `DescribeOrderableDBInstanceOptions` | List deterministic instance class options |
| `DescribeEvents` | - |
| `CreateDBSubnetGroup` | Create a DB subnet group; tags given here are readable through `ListTagsForResource` |
@@ -316,6 +320,35 @@ Known gaps, all deliberate:
| `OptionSetting` metadata (`DataType`, `ApplyType`, `AllowedValues`, `DefaultValue`, `Description`) | Omitted — it would require the per-engine option catalog `DescribeOptionGroupOptions` serves |
| `MaxRecords` / `Marker` pagination | Every group is returned in one page, as with every other RDS list action |
+## Read replicas
+
+`CreateDBInstanceReadReplica` creates a standalone instance with its own container and endpoint.
+As on AWS it inherits the source's engine, version, credentials and database name and, unless the
+request overrides them, the instance class, storage and minor version upgrade setting. A replica
+in the source's region also inherits the source's parameter group, option group, subnet group and
+security groups; a replica in another region (source given by ARN, `--region` set to the
+destination) gets that region's defaults. IAM authentication and `CopyTagsToSnapshot` are off
+unless requested. The replica starts with `BackupRetentionPeriod` 0. Both ends report the link
+the way `DescribeDBInstances` does: the replica carries `ReadReplicaSourceDBInstanceIdentifier`
+and a `StatusInfos` entry of type `read replication`, the source lists it under
+`ReadReplicaDBInstanceIdentifiers`; within a region the link is the identifier, across regions
+it is the ARN. A `DBSubnetGroupName` with a source given by plain identifier is refused with
+`DBSubnetGroupNotAllowedFault`, as on AWS.
+
+The replica's database is initialised from a `pg_dumpall` of the source taken when the replica is
+created, the same mechanism `RestoreDBInstanceFromDBSnapshot` uses, so it holds the source's data
+as of that moment. Writes made to the source afterwards are not streamed to the replica. Because
+the copy is dump based, only PostgreSQL sources are accepted; MySQL and MariaDB sources are refused
+with `InvalidDBInstanceState`, as `CreateDBSnapshot` refuses them. A source with automated backups
+off (`BackupRetentionPeriod` 0) is refused with the same error AWS uses.
+
+`PromoteReadReplica` clears the link on both ends, sets the requested `BackupRetentionPeriod`
+(one day when omitted) and `PreferredBackupWindow`, and reboots the instance as AWS does, so open
+connections drop while the container, endpoint and data stay. Deleting a source promotes its
+same-region replicas; a cross-region replica keeps its link with the replication status
+`terminated` until it is promoted or deleted, which is what AWS does for PostgreSQL. Deleting a
+replica drops it from its source's list.
+
## Persistence
Each DB instance and cluster gets its own named Docker volume (`floci-rds-{volumeId}`) created
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 8ee61ba762..39a3ad0a6f 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
@@ -25,6 +25,7 @@ import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
import io.github.hectorvent.floci.services.rds.model.OptionGroup;
import io.github.hectorvent.floci.services.rds.model.OptionGroupOption;
import io.github.hectorvent.floci.services.rds.model.RdsEvent;
+import io.github.hectorvent.floci.services.rds.model.ReadReplicaRequest;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedMap;
@@ -72,6 +73,10 @@ public class RdsQueryHandler {
case "DeleteDBInstance" -> handleDeleteDbInstance(params, region);
case "ModifyDBInstance" -> handleModifyDbInstance(params, region);
case "RebootDBInstance" -> handleRebootDbInstance(params, region);
+ case "CreateDBInstanceReadReplica" -> handleCreateDbInstanceReadReplica(params, region);
+ case "PromoteReadReplica" -> handlePromoteReadReplica(params, region);
+ case "SwitchoverReadReplica" -> handleSwitchoverReadReplica(params, region);
+ case "PromoteReadReplicaDBCluster" -> handlePromoteReadReplicaDbCluster(params, region);
case "DescribeOrderableDBInstanceOptions" -> handleDescribeOrderableDbInstanceOptions(params);
case "DescribeEvents" -> handleDescribeEvents(params, region);
case "CreateDBSubnetGroup" -> handleCreateDbSubnetGroup(params, region);
@@ -560,6 +565,84 @@ public class RdsQueryHandler {
}
}
+ // ── Read replicas ─────────────────────────────────────────────────────────
+
+ private Response handleCreateDbInstanceReadReplica(
+ MultivaluedMap<String, String> params, String region) {
+ String id = params.getFirst("DBInstanceIdentifier");
+ if (id == null || id.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400);
+ }
+ try {
+ ReadReplicaRequest request = new ReadReplicaRequest(
+ id,
+ params.getFirst("SourceDBInstanceIdentifier"),
+ params.getFirst("DBInstanceClass"),
+ params.getFirst("AvailabilityZone"),
+ parseOptionalBoolean(params, "MultiAZ"),
+ parseOptionalBoolean(params, "AutoMinorVersionUpgrade"),
+ params.getFirst("OptionGroupName"),
+ params.getFirst("DBParameterGroupName"),
+ parseOptionalBoolean(params, "PubliclyAccessible"),
+ params.getFirst("DBSubnetGroupName"),
+ hasMemberKeys(params, "VpcSecurityGroupIds") ? vpcSecurityGroupIds(params) : null,
+ parseOptionalBoolean(params, "CopyTagsToSnapshot"),
+ parseOptionalBoolean(params, "EnableIAMDatabaseAuthentication"),
+ optionalInt(params.getFirst("AllocatedStorage")),
+ params.getFirst("ReplicaMode"),
+ parseTags(params));
+ DbInstance replica = service.createDbInstanceReadReplica(request, region);
+ return Response.ok(AwsQueryResponse.envelope(
+ "CreateDBInstanceReadReplica", AwsNamespaces.RDS, dbInstanceXml(replica))).build();
+ } catch (AwsException e) {
+ return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
+ }
+ }
+
+ private Response handlePromoteReadReplica(MultivaluedMap<String, String> params, String region) {
+ String id = params.getFirst("DBInstanceIdentifier");
+ if (id == null || id.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400);
+ }
+ try {
+ DbInstance instance = service.promoteReadReplica(id,
+ optionalInt(params.getFirst("BackupRetentionPeriod")),
+ params.getFirst("PreferredBackupWindow"), region);
+ return Response.ok(AwsQueryResponse.envelope(
+ "PromoteReadReplica", AwsNamespaces.RDS, dbInstanceXml(instance))).build();
+ } catch (AwsException e) {
+ return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
+ }
+ }
+
+ private Response handleSwitchoverReadReplica(MultivaluedMap<String, String> params, String region) {
+ String id = params.getFirst("DBInstanceIdentifier");
+ if (id == null || id.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400);
+ }
+ try {
+ DbInstance instance = service.switchoverReadReplica(id, region);
+ return Response.ok(AwsQueryResponse.envelope(
+ "SwitchoverReadReplica", AwsNamespaces.RDS, dbInstanceXml(instance))).build();
+ } catch (AwsException e) {
+ return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
+ }
+ }
+
+ private Response handlePromoteReadReplicaDbCluster(MultivaluedMap<String, String> params, String region) {
+ String id = params.getFirst("DBClusterIdentifier");
+ if (id == null || id.isBlank()) {
+ return AwsQueryResponse.error("InvalidParameterValue", "DBClusterIdentifier is required.", AwsNamespaces.RDS, 400);
+ }
+ try {
+ DbCluster cluster = service.promoteReadReplicaDbCluster(id, region);
+ return Response.ok(AwsQueryResponse.envelope(
+ "PromoteReadReplicaDBCluster", AwsNamespaces.RDS, dbClusterXml(cluster))).build();
+ } catch (AwsException e) {
+ return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
+ }
+ }
+
// ── DB Clusters ───────────────────────────────────────────────────────────
private Response handleCreateDbCluster(MultivaluedMap<String, String> params, String region) {
@@ -1671,12 +1754,44 @@ public class RdsQueryHandler {
if (i.getDbClusterIdentifier() != null && !i.getDbClusterIdentifier().isBlank()) {
xml.elem("DBClusterIdentifier", i.getDbClusterIdentifier());
}
+ xml.raw(readReplicaXml(i));
xml.start("TagList");
writeTags(xml, i.getTags());
xml.end("TagList");
return xml.build();
}
+ /**
+ * The replication links as DescribeDBInstances reports them: the replica list is always
+ * present (empty on a standalone), the source and the "read replication" status entry only
+ * on a replica. Message is blank unless the entry reports an error, and terminated (the
+ * cross-Region source is gone) is the one non-normal state modelled.
+ */
+ private static String readReplicaXml(DbInstance i) {
+ XmlBuilder xml = new XmlBuilder();
+ if (i.hasReadReplicaSource()) {
+ xml.elem("ReadReplicaSourceDBInstanceIdentifier", i.getReadReplicaSourceDbInstanceIdentifier());
+ }
+ xml.start("ReadReplicaDBInstanceIdentifiers");
+ for (String replicaId : i.getReadReplicaDbInstanceIdentifiers()) {
+ xml.elem("ReadReplicaDBInstanceIdentifier", replicaId);
+ }
+ xml.end("ReadReplicaDBInstanceIdentifiers");
+ if (i.hasReadReplicaSource()) {
+ String status = i.getReadReplicationStatus() != null
+ ? i.getReadReplicationStatus() : RdsService.READ_REPLICATION_REPLICATING;
+ xml.start("StatusInfos")
+ .start("DBInstanceStatusInfo")
+ .elem("StatusType", "read replication")
+ .elem("Normal", RdsService.READ_REPLICATION_REPLICATING.equals(status))
+ .elem("Status", status)
+ .elem("Message", "")
+ .end("DBInstanceStatusInfo")
+ .end("StatusInfos");
+ }
+ return xml.build();
+ }
+
private String vpcSecurityGroupsXml(DbInstance i) {
List<String> groupIds = i.getVpcSecurityGroupIds().isEmpty()
? List.of("sg-00000000")
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 17eb0ea492..eb2c4d846c 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
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.BackupWindows;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkResolver;
@@ -37,6 +38,7 @@ import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
import io.github.hectorvent.floci.services.rds.model.DbProxyTarget;
import io.github.hectorvent.floci.services.rds.model.DbProxyTargetGroup;
import io.github.hectorvent.floci.services.rds.model.RdsEvent;
+import io.github.hectorvent.floci.services.rds.model.ReadReplicaRequest;
import io.github.hectorvent.floci.services.rds.model.DbSnapshot;
import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
import io.github.hectorvent.floci.services.rds.model.OptionGroup;
@@ -847,6 +849,335 @@ public class RdsService implements Resettable, ResourceProvider {
return instance;
}
+ // ── Read replicas ─────────────────────────────────────────────────────────
+
+ static final String READ_REPLICATION_REPLICATING = "replicating";
+ static final String READ_REPLICATION_TERMINATED = "terminated";
+
+ /**
+ * Creates a read replica the way AWS does: a new standalone instance that inherits engine,
+ * version, credentials and database name from the source and, unless the request overrides
+ * them, its instance class, storage and minor version upgrade setting. A same-Region replica
+ * also inherits the source's parameter group, option group, subnet group and security
+ * groups; a cross-Region replica (source named by ARN) gets the Region's defaults, as the
+ * API reference states. Backups start disabled. The two ends are linked the way
+ * DescribeDBInstances reports them: by identifier within a Region, by ARN across Regions.
+ *
+ * <p>The backing database is initialised from a dump of the source taken at creation time,
+ * the same mechanism RestoreDBInstanceFromDBSnapshot uses, so it holds the source's data as
+ * of that moment. Writes made to the source afterwards do not stream to the replica; that is
+ * the follow-up noted in the service docs.
+ */
+ public DbInstance createDbInstanceReadReplica(ReadReplicaRequest request, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ String id = request.dbInstanceIdentifier();
+ if (id == null || id.isBlank()) {
+ throw new AwsException("InvalidParameterValue", "DBInstanceIdentifier is required.", 400);
+ }
+ String sourceRef = request.sourceDbInstanceIdentifier();
+ if (sourceRef == null || sourceRef.isBlank()) {
+ throw new AwsException("InvalidParameterCombination",
+ "Either SourceDBInstanceIdentifier or SourceDBClusterIdentifier must be specified.", 400);
+ }
+ boolean sourceByArn = sourceRef.startsWith("arn:");
+ if (request.replicaMode() != null && !request.replicaMode().isBlank()) {
+ // ReplicaMode selects mounted or open-read-only for Db2 and Oracle replicas; no
+ // emulated engine is either, so AWS's parameter check applies to all of them.
+ throw new AwsException("InvalidParameterCombination",
+ "ReplicaMode is supported only for Db2 and Oracle DB instances.", 400);
+ }
+ if (request.dbSubnetGroupName() != null && !request.dbSubnetGroupName().isBlank()
+ && !sourceByArn) {
+ // The API reference's DBSubnetGroupNotAllowedFault: a subnet group goes with a source
+ // named by ARN (another VPC or Region); a plain identifier means the source's VPC.
+ throw new AwsException("DBSubnetGroupNotAllowedFault",
+ "The DBSubnetGroup shouldn't be specified while creating read replicas that "
+ + "lie in the same region as the source instance.", 400);
+ }
+
+ DbInstance source = resolveReadReplicaSource(sourceRef, effectiveRegion);
+ String sourceId = source.getDbInstanceIdentifier();
+ String sourceRegion = regionFromArn(source.getDbInstanceArn());
+ boolean sameRegion = sourceRegion.equals(effectiveRegion);
+ if (source.getDbClusterIdentifier() != null && !source.getDbClusterIdentifier().isBlank()) {
+ throw new AwsException("InvalidParameterValue",
+ "Read replicas of a DB instance that belongs to a DB cluster are not supported. "
+ + "Add a reader instance to DB cluster " + source.getDbClusterIdentifier()
+ + " instead.", 400);
+ }
+ if (source.getStatus() != DbInstanceStatus.AVAILABLE) {
+ throw new AwsException("InvalidDBInstanceState",
+ "DB instance " + sourceId + " is not in available state.", 400);
+ }
+ if (source.getBackupRetentionPeriod() <= 0) {
+ throw new AwsException("InvalidDBInstanceState",
+ "Automated backups are not enabled for this database instance. To enable "
+ + "automated backups, use ModifyDBInstance to set the backup retention period "
+ + "to a non-zero value.", 400);
+ }
+ if (source.getEngine() != DatabaseEngine.POSTGRES) {
+ // CreateDBSnapshot draws the same line: the point-in-time copy is pg_dumpall based.
+ throw new AwsException("InvalidDBInstanceState",
+ "Operation CreateDBInstanceReadReplica is not supported for engine "
+ + source.getEngine() + ".", 400);
+ }
+ if (id.equalsIgnoreCase(sourceId) && sameRegion) {
+ throw new AwsException("DBInstanceAlreadyExists",
+ "DB instance " + id + " already exists.", 400);
+ }
+
+ String engineParam = source.getEngineIdentifier() != null
+ ? source.getEngineIdentifier() : source.getEngine().name().toLowerCase();
+ String dbInstanceClass = firstNonBlank(request.dbInstanceClass(), source.getDbInstanceClass());
+ int allocatedStorage = request.allocatedStorage() != null
+ ? request.allocatedStorage() : source.getAllocatedStorage();
+ boolean iamEnabled = Boolean.TRUE.equals(request.iamDatabaseAuthenticationEnabled());
+ boolean copyTagsToSnapshot = Boolean.TRUE.equals(request.copyTagsToSnapshot());
+ String parameterGroupName = firstNonBlank(
+ request.dbParameterGroupName(), sameRegion ? source.getParameterGroupName() : null);
+ String optionGroupName = firstNonBlank(
+ request.optionGroupName(), sameRegion ? source.getOptionGroupName() : null);
+ String dbSubnetGroupName = firstNonBlank(
+ request.dbSubnetGroupName(), sameRegion ? source.getDbSubnetGroupName() : null);
+ List<String> vpcSecurityGroupIds = request.vpcSecurityGroupIds() != null
+ ? request.vpcSecurityGroupIds()
+ : sameRegion ? source.getVpcSecurityGroupIds() : List.of();
+ boolean autoMinorVersionUpgrade = request.autoMinorVersionUpgrade() != null
+ ? request.autoMinorVersionUpgrade() : source.isAutoMinorVersionUpgrade();
+ // Backups stay off on a replica; the source's windows carry over, and encryption follows
+ // the source because AWS never lets a replica be less protected than what it copies.
+ DbInstanceSettings settings = new DbInstanceSettings(
+ source.isStorageEncrypted() ? Boolean.TRUE : null,
+ source.isStorageEncrypted() && sameRegion ? source.getKmsKeyId() : null,
+ 0, source.getPreferredBackupWindow(), source.getPreferredMaintenanceWindow(),
+ copyTagsToSnapshot);
+ Map<String, String> tags = request.tags() != null ? request.tags() : Map.of();
+
+ DbInstance replica = createDbInstance(id, engineParam, source.getEngineVersion(),
+ source.getMasterUsername(), source.getMasterPassword(), source.getDbName(),
+ dbInstanceClass, allocatedStorage, iamEnabled, parameterGroupName,
+ dbSubnetGroupName, null, request.availabilityZone(),
+ Boolean.TRUE.equals(request.multiAz()), false, null, tags, vpcSecurityGroupIds,
+ optionGroupName, effectiveRegion, autoMinorVersionUpgrade, settings,
+ request.publiclyAccessible());
+
+ linkReadReplica(source, replica);
+ if (!config.services().rds().mock()
+ && source.getContainerId() != null && replica.getContainerId() != null) {
+ try {
+ String sqlDump = containerManager.createPostgresSnapshot(
+ source.getContainerId(), source.getMasterUsername());
+ containerManager.restorePostgresSnapshot(
+ replica.getContainerId(), replica.getMasterUsername(), sqlDump);
+ } catch (Exception e) {
+ try {
+ deleteDbInstance(id, effectiveRegion);
+ } catch (RuntimeException cleanupError) {
+ e.addSuppressed(cleanupError);
+ }
+ AwsException failure = new AwsException("InvalidDBInstanceState",
+ "Failed to initialise read replica " + id + " from " + sourceId + ": "
+ + e.getMessage(), 400);
+ failure.initCause(e);
+ throw failure;
+ }
+ }
+ synchronized (this) {
+ replica.setStatus(DbInstanceStatus.AVAILABLE);
+ putInstanceForScope(accountIdFromArn(replica.getDbInstanceArn()), effectiveRegion,
+ id, replica);
+ }
+ LOG.infov("Read replica {0} of DB instance {1} created", id, sourceId);
+ return replica;
+ }
+
+ /**
+ * Detaches a replica from its source: both links are dropped and automated backups start
+ * with the requested retention (one day when omitted, as on AWS). AWS then reboots the
+ * promoted instance before it is available again, so the same reboot runs here: connections
+ * drop, the container, endpoint and data stay.
+ */
+ public synchronized DbInstance promoteReadReplica(String id, Integer backupRetentionPeriod,
+ String preferredBackupWindow, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ DbInstance replica = getDbInstance(id, effectiveRegion);
+ requireReadReplica(replica);
+ if (replica.getStatus() != DbInstanceStatus.AVAILABLE) {
+ throw new AwsException("InvalidDBInstanceState",
+ "DB instance " + id + " is not in available state.", 400);
+ }
+ int retention = backupRetentionPeriod != null ? backupRetentionPeriod : 1;
+ if (retention < 0 || retention > 35) {
+ throw new AwsException("InvalidParameterValue",
+ "Invalid backup retention period: " + retention
+ + ". Retention period must be between 0 and 35.", 400);
+ }
+ if (retention == 0 && !replica.getReadReplicaDbInstanceIdentifiers().isEmpty()) {
+ // The API reference: "Can't be set to 0 if the DB instance is a source to read replicas."
+ throw new AwsException("InvalidParameterCombination",
+ "BackupRetentionPeriod can't be set to 0 because DB instance " + id
+ + " is a source for read replicas.", 400);
+ }
+ String backupWindow = preferredBackupWindow;
+ if (backupWindow != null && !backupWindow.isBlank()) {
+ BackupWindows.parseBackupWindow(backupWindow);
+ String maintenanceWindow = replica.getPreferredMaintenanceWindow() != null
+ ? replica.getPreferredMaintenanceWindow()
+ : DbInstanceSettings.DEFAULT_MAINTENANCE_WINDOW;
+ if (DbInstanceSettings.windowsOverlap(backupWindow, maintenanceWindow)) {
+ throw DbInstanceSettings.overlappingWindows();
+ }
+ }
+
+ unlinkReadReplica(replica);
+ replica.setBackupRetentionPeriod(retention);
+ if (backupWindow != null && !backupWindow.isBlank()) {
+ replica.setPreferredBackupWindow(backupWindow);
+ }
+ putInstanceForScope(accountIdFromArn(replica.getDbInstanceArn()), effectiveRegion, id, replica);
+ DbInstance promoted = rebootDbInstance(id, effectiveRegion);
+ LOG.infov("Read replica {0} promoted to a standalone DB instance", id);
+ return promoted;
+ }
+
+ /**
+ * SwitchoverReadReplica swaps an Oracle Data Guard or SQL Server standby with its primary.
+ * The API reference lists only DBInstanceNotFound and InvalidDBInstanceState as its errors,
+ * so a replica of any engine emulated here is refused with the latter.
+ */
+ public synchronized DbInstance switchoverReadReplica(String id, String region) {
+ DbInstance replica = getDbInstance(id, effectiveRegion(region));
+ requireReadReplica(replica);
+ throw new AwsException("InvalidDBInstanceState",
+ "SwitchoverReadReplica is supported only for Oracle and SQL Server read replicas; "
+ + "DB instance " + id + " runs " + replica.getEngine().name().toLowerCase() + ".", 400);
+ }
+
+ /**
+ * PromoteReadReplicaDBCluster applies to an Aurora cluster created as a replica of an RDS
+ * instance (ReplicationSourceIdentifier). No cluster here is created that way, so an existing
+ * cluster is refused the way AWS refuses a cluster that is not a replica.
+ */
+ public synchronized DbCluster promoteReadReplicaDbCluster(String id, String region) {
+ DbCluster cluster = getDbCluster(id, effectiveRegion(region));
+ throw new AwsException("InvalidDBClusterStateFault",
+ "DB cluster " + cluster.getDbClusterIdentifier() + " is not a read replica cluster.", 400);
+ }
+
+ private DbInstance resolveReadReplicaSource(String sourceRef, String requestRegion) {
+ String accountId = currentAccountId();
+ String region = requestRegion;
+ String sourceId = sourceRef;
+ if (sourceRef.startsWith("arn:")) {
+ // A source in another Region is named by ARN; the replica lands in the request Region.
+ String[] parts = sourceRef.split(":", 7);
+ if (parts.length == 7 && "rds".equals(parts[2]) && "db".equals(parts[5])
+ && accountId.equals(parts[4])) {
+ region = parts[3].isBlank() ? requestRegion : parts[3];
+ sourceId = parts[6];
+ } else {
+ throw new AwsException("DBInstanceNotFound",
+ "DB instance " + sourceRef + " not found.", 404);
+ }
+ }
+ String resolvedId = sourceId;
+ String resolvedRegion = region;
+ return Optional.ofNullable(findInstanceForScope(accountId, resolvedRegion, resolvedId))
+ .orElseThrow(() -> new AwsException("DBInstanceNotFound",
+ "DB instance " + resolvedId + " not found.", 404));
+ }
+
+ private static void requireReadReplica(DbInstance instance) {
+ if (!instance.hasReadReplicaSource()) {
+ throw new AwsException("InvalidDBInstanceState",
+ "DB instance " + instance.getDbInstanceIdentifier() + " is not a read replica.", 400);
+ }
+ }
+
+ /** The other end of a replication link as AWS names it: identifier in-Region, ARN across. */
+ private String replicationLinkName(DbInstance from, DbInstance to) {
+ return regionFromArn(from.getDbInstanceArn()).equals(regionFromArn(to.getDbInstanceArn()))
+ ? to.getDbInstanceIdentifier() : to.getDbInstanceArn();
+ }
+
+ private synchronized void linkReadReplica(DbInstance source, DbInstance replica) {
+ replica.setReadReplicaSourceDbInstanceIdentifier(replicationLinkName(replica, source));
+ replica.setReadReplicationStatus(READ_REPLICATION_REPLICATING);
+ replica.setStatus(DbInstanceStatus.CREATING);
+ putInstanceForScope(accountIdFromArn(replica.getDbInstanceArn()),
+ regionFromArn(replica.getDbInstanceArn()), replica.getDbInstanceIdentifier(), replica);
+ String replicaName = replicationLinkName(source, replica);
+ if (!source.getReadReplicaDbInstanceIdentifiers().contains(replicaName)) {
+ source.getReadReplicaDbInstanceIdentifiers().add(replicaName);
+ }
+ putInstanceForScope(accountIdFromArn(source.getDbInstanceArn()),
+ regionFromArn(source.getDbInstanceArn()), source.getDbInstanceIdentifier(), source);
+ }
+
+ /** Drops the replica's link to its source and the source's link back, if the source exists. */
+ private void unlinkReadReplica(DbInstance replica) {
+ String sourceRef = replica.getReadReplicaSourceDbInstanceIdentifier();
+ replica.setReadReplicaSourceDbInstanceIdentifier(null);
+ replica.setReadReplicationStatus(null);
+ if (sourceRef == null) {
+ return;
+ }
+ String accountId = accountIdFromArn(replica.getDbInstanceArn());
+ DbInstance source = findLinkedInstance(accountId, replica, sourceRef);
+ if (source != null && source.getReadReplicaDbInstanceIdentifiers()
+ .remove(replicationLinkName(source, replica))) {
+ putInstanceForScope(accountId, regionFromArn(source.getDbInstanceArn()),
+ source.getDbInstanceIdentifier(), source);
+ }
+ }
+
+ /**
+ * Resolves the other end of a replication link: an identifier names an instance in the same
+ * Region as the linking instance, an ARN names one anywhere in the account.
+ */
+ private DbInstance findLinkedInstance(String accountId, DbInstance from, String linkName) {
+ if (linkName.startsWith("arn:")) {
+ for (DbInstance candidate : instances.scan(k -> true)) {
+ if (linkName.equalsIgnoreCase(candidate.getDbInstanceArn())
+ && accountId.equals(accountIdFromArn(candidate.getDbInstanceArn()))) {
+ return findInstanceForScope(accountId, regionFromArn(candidate.getDbInstanceArn()),
+ candidate.getDbInstanceIdentifier());
+ }
+ }
+ return null;
+ }
+ return findInstanceForScope(accountId, regionFromArn(from.getDbInstanceArn()), linkName);
+ }
+
+ /**
+ * Deleting a replica drops it from its source's list. Deleting a source promotes the
+ * same-Region replicas it still has; a cross-Region PostgreSQL replica is not promoted, its
+ * replication status becomes terminated and it waits to be promoted or deleted by hand. Both
+ * are the documented AWS behaviours.
+ */
+ private void detachReadReplicaLinksBeforeDelete(DbInstance instance) {
+ if (instance.hasReadReplicaSource()) {
+ unlinkReadReplica(instance);
+ }
+ String accountId = accountIdFromArn(instance.getDbInstanceArn());
+ for (String replicaName : List.copyOf(instance.getReadReplicaDbInstanceIdentifiers())) {
+ DbInstance replica = findLinkedInstance(accountId, instance, replicaName);
+ if (replica == null || !replicationLinkName(replica, instance)
+ .equalsIgnoreCase(replica.getReadReplicaSourceDbInstanceIdentifier())) {
+ continue;
+ }
+ if (replicaName.startsWith("arn:")) {
+ replica.setReadReplicationStatus(READ_REPLICATION_TERMINATED);
+ } else {
+ replica.setReadReplicaSourceDbInstanceIdentifier(null);
+ replica.setReadReplicationStatus(null);
+ }
+ putInstanceForScope(accountId, regionFromArn(replica.getDbInstanceArn()),
+ replica.getDbInstanceIdentifier(), replica);
+ }
+ instance.getReadReplicaDbInstanceIdentifiers().clear();
+ }
+
public Collection<DbSnapshot> describeDbSnapshots(String snapshotId, String instanceId) {
return describeDbSnapshots(snapshotId, instanceId, regionResolver.getDefaultRegion());
}
@@ -1935,6 +2266,7 @@ public class RdsService implements Resettable, ResourceProvider {
instance.setStatus(DbInstanceStatus.DELETING);
putInstanceForScope(currentAccountId(), effectiveRegion, id, instance);
+ detachReadReplicaLinksBeforeDelete(instance);
boolean mock = config.services().rds().mock();
if (!mock) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java
index da0b147564..9ee5b21348 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java
@@ -54,6 +54,14 @@ public class DbInstance {
private Map<String, String> tags = new LinkedHashMap<>();
private Instant createdAt;
private int proxyPort;
+ // Read replication links, kept on both ends the way DescribeDBInstances reports them: a
+ // replica names its source, a source lists its replicas, by identifier within a Region and
+ // by ARN across Regions. Null and empty on a standalone. The status is the "read
+ // replication" StatusInfos entry: replicating, or terminated once a cross-Region source is
+ // gone.
+ private String readReplicaSourceDbInstanceIdentifier;
+ private List<String> readReplicaDbInstanceIdentifiers = new ArrayList<>();
+ private String readReplicationStatus;
private String dockerVolumeName;
private String volumeId;
@@ -200,6 +208,26 @@ public class DbInstance {
public String getMasterUserSecretKmsKeyId() { return masterUserSecretKmsKeyId; }
public void setMasterUserSecretKmsKeyId(String masterUserSecretKmsKeyId) { this.masterUserSecretKmsKeyId = masterUserSecretKmsKeyId; }
+ public String getReadReplicaSourceDbInstanceIdentifier() { return readReplicaSourceDbInstanceIdentifier; }
+ public void setReadReplicaSourceDbInstanceIdentifier(String readReplicaSourceDbInstanceIdentifier) {
+ this.readReplicaSourceDbInstanceIdentifier = readReplicaSourceDbInstanceIdentifier;
+ }
+
+ public List<String> getReadReplicaDbInstanceIdentifiers() { return readReplicaDbInstanceIdentifiers; }
+ public void setReadReplicaDbInstanceIdentifiers(List<String> readReplicaDbInstanceIdentifiers) {
+ this.readReplicaDbInstanceIdentifiers = readReplicaDbInstanceIdentifiers != null
+ ? new ArrayList<>(readReplicaDbInstanceIdentifiers) : new ArrayList<>();
+ }
+
+ public String getReadReplicationStatus() { return readReplicationStatus; }
+ public void setReadReplicationStatus(String readReplicationStatus) { this.readReplicationStatus = readReplicationStatus; }
+
+ // Not a bean getter on purpose: the persisted form must carry only settable properties.
+ public boolean hasReadReplicaSource() {
+ return readReplicaSourceDbInstanceIdentifier != null
+ && !readReplicaSourceDbInstanceIdentifier.isBlank();
+ }
+
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>(); }
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/ReadReplicaRequest.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/ReadReplicaRequest.java
new file mode 100644
index 0000000000..f04549e206
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/ReadReplicaRequest.java
@@ -0,0 +1,30 @@
+package io.github.hectorvent.floci.services.rds.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The CreateDBInstanceReadReplica request as the service consumes it. Every field but the two
+ * identifiers is optional; a null means "inherit from the source", which is what AWS does for the
+ * instance class, storage, parameter and option groups, subnet group and minor version upgrades.
+ */
+@RegisterForReflection
+public record ReadReplicaRequest(String dbInstanceIdentifier,
+ String sourceDbInstanceIdentifier,
+ String dbInstanceClass,
+ String availabilityZone,
+ Boolean multiAz,
+ Boolean autoMinorVersionUpgrade,
+ String optionGroupName,
+ String dbParameterGroupName,
+ Boolean publiclyAccessible,
+ String dbSubnetGroupName,
+ List<String> vpcSecurityGroupIds,
+ Boolean copyTagsToSnapshot,
+ Boolean iamDatabaseAuthenticationEnabled,
+ Integer allocatedStorage,
+ String replicaMode,
+ Map<String, String> tags) {
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsReadReplicaIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsReadReplicaIntegrationTest.java
new file mode 100644
index 0000000000..107da891cc
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsReadReplicaIntegrationTest.java
@@ -0,0 +1,178 @@
+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.not;
+
+/**
+ * CreateDBInstanceReadReplica, PromoteReadReplica, SwitchoverReadReplica and
+ * PromoteReadReplicaDBCluster over the Query protocol: the replica inherits the source, both
+ * ends report the link the way DescribeDBInstances does on AWS, promotion clears it, and the
+ * two operations that no emulated engine supports answer with the API reference's errors.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class RdsReadReplicaIntegrationTest {
+
+ private static final String SOURCE = "replica-test-source";
+ private static final String REPLICA = "replica-test-reader";
+
+ private static final String AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260615/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");
+ }
+
+ @Test
+ @Order(1)
+ void createReadReplicaLinksBothEndsInDescribeDbInstances() {
+ query("CreateDBInstance")
+ .formParam("DBInstanceIdentifier", SOURCE)
+ .formParam("Engine", "postgres")
+ .formParam("EngineVersion", "16.3")
+ .formParam("MasterUsername", "admin")
+ .formParam("MasterUserPassword", "password123")
+ .formParam("DBName", "appdb")
+ .formParam("DBInstanceClass", "db.t3.medium")
+ .formParam("AllocatedStorage", "40")
+ .when().post("/").then().statusCode(200)
+ .body(containsString("<ReadReplicaDBInstanceIdentifiers></ReadReplicaDBInstanceIdentifiers>"))
+ .body(not(containsString("<StatusInfos>")));
+
+ query("CreateDBInstanceReadReplica")
+ .formParam("DBInstanceIdentifier", REPLICA)
+ .formParam("SourceDBInstanceIdentifier", SOURCE)
+ .formParam("Tags.Tag.1.Key", "role")
+ .formParam("Tags.Tag.1.Value", "reader")
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<CreateDBInstanceReadReplicaResult>"))
+ .body(containsString("<DBInstanceIdentifier>" + REPLICA + "</DBInstanceIdentifier>"))
+ .body(containsString("<ReadReplicaSourceDBInstanceIdentifier>" + SOURCE
+ + "</ReadReplicaSourceDBInstanceIdentifier>"))
+ .body(containsString("<Engine>postgres</Engine>"))
+ .body(containsString("<EngineVersion>16.3</EngineVersion>"))
+ .body(containsString("<MasterUsername>admin</MasterUsername>"))
+ .body(containsString("<DBName>appdb</DBName>"))
+ .body(containsString("<DBInstanceClass>db.t3.medium</DBInstanceClass>"))
+ .body(containsString("<AllocatedStorage>40</AllocatedStorage>"))
+ .body(containsString("<BackupRetentionPeriod>0</BackupRetentionPeriod>"))
+ .body(containsString("<StatusType>read replication</StatusType>"))
+ .body(containsString("<Normal>true</Normal>"))
+ .body(containsString("<Status>replicating</Status>"))
+ .body(containsString("<Message></Message>"))
+ .body(containsString(":db:" + REPLICA + "</DBInstanceArn>"))
+ .body(containsString("<Value>reader</Value>"));
+
+ query("DescribeDBInstances")
+ .formParam("DBInstanceIdentifier", SOURCE)
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<ReadReplicaDBInstanceIdentifier>" + REPLICA
+ + "</ReadReplicaDBInstanceIdentifier>"))
+ .body(not(containsString("<ReadReplicaSourceDBInstanceIdentifier>")));
+ }
+
+ @Test
+ @Order(2)
+ void switchoverIsRefusedForAPostgresReplica() {
+ query("SwitchoverReadReplica")
+ .formParam("DBInstanceIdentifier", REPLICA)
+ .when().post("/")
+ .then()
+ .statusCode(400)
+ .body(containsString("<Code>InvalidDBInstanceState</Code>"));
+
+ query("SwitchoverReadReplica")
+ .formParam("DBInstanceIdentifier", "replica-test-missing")
+ .when().post("/")
+ .then()
+ .statusCode(404)
+ .body(containsString("<Code>DBInstanceNotFound</Code>"));
+ }
+
+ @Test
+ @Order(3)
+ void promoteReadReplicaClearsTheLinkAndTurnsBackupsOn() {
+ query("PromoteReadReplica")
+ .formParam("DBInstanceIdentifier", SOURCE)
+ .when().post("/")
+ .then()
+ .statusCode(400)
+ .body(containsString("<Code>InvalidDBInstanceState</Code>"))
+ .body(containsString("is not a read replica"));
+
+ query("PromoteReadReplica")
+ .formParam("DBInstanceIdentifier", REPLICA)
+ .formParam("BackupRetentionPeriod", "3")
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<PromoteReadReplicaResult>"))
+ .body(containsString("<DBInstanceIdentifier>" + REPLICA + "</DBInstanceIdentifier>"))
+ .body(containsString("<BackupRetentionPeriod>3</BackupRetentionPeriod>"))
+ .body(not(containsString("<ReadReplicaSourceDBInstanceIdentifier>")))
+ .body(not(containsString("<StatusInfos>")));
+
+ query("DescribeDBInstances")
+ .formParam("DBInstanceIdentifier", SOURCE)
+ .when().post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<ReadReplicaDBInstanceIdentifiers></ReadReplicaDBInstanceIdentifiers>"));
+ }
+
+ @Test
+ @Order(4)
+ void createReadReplicaRefusesAMissingOrUnnamedSource() {
+ query("CreateDBInstanceReadReplica")
+ .formParam("DBInstanceIdentifier", "replica-test-orphan")
+ .formParam("SourceDBInstanceIdentifier", "replica-test-missing")
+ .when().post("/")
+ .then()
+ .statusCode(404)
+ .body(containsString("<Code>DBInstanceNotFound</Code>"));
+
+ query("CreateDBInstanceReadReplica")
+ .formParam("DBInstanceIdentifier", "replica-test-orphan")
+ .when().post("/")
+ .then()
+ .statusCode(400)
+ .body(containsString("<Code>InvalidParameterCombination</Code>"));
+ }
+
+ @Test
+ @Order(5)
+ void promoteReadReplicaDbClusterAnswersWithTheClusterErrors() {
+ query("PromoteReadReplicaDBCluster")
+ .formParam("DBClusterIdentifier", "replica-test-no-cluster")
+ .when().post("/")
+ .then()
+ .statusCode(404)
+ .body(containsString("<Code>DBClusterNotFoundFault</Code>"));
+ }
+
+ @Test
+ @Order(6)
+ void cleanUp() {
+ query("DeleteDBInstance").formParam("DBInstanceIdentifier", REPLICA)
+ .when().post("/").then().statusCode(200);
+ query("DeleteDBInstance").formParam("DBInstanceIdentifier", SOURCE)
+ .when().post("/").then().statusCode(200);
+ }
+}
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 48da4fabd1..0af21f544c 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
@@ -32,6 +32,7 @@ import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
import io.github.hectorvent.floci.services.rds.model.OptionGroup;
import io.github.hectorvent.floci.services.rds.model.OptionGroupOption;
import io.github.hectorvent.floci.services.rds.model.RdsEvent;
+import io.github.hectorvent.floci.services.rds.model.ReadReplicaRequest;
import io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
@@ -6454,4 +6455,265 @@ class RdsServiceTest {
assertThrows(AwsException.class, () -> service.getDbInstance("mydb"),
"the deleted instance must not come back from the modify");
}
+
+ // ── Read replicas ─────────────────────────────────────────────────────────
+
+ private DbInstance createPostgresSource(String id) {
+ return rdsService.createDbInstance(id, "postgres", "16.3",
+ "admin", "password", "appdb", "db.t3.medium",
+ 50, false, null, null, null, null, false);
+ }
+
+ private static ReadReplicaRequest replicaRequest(String id, String source) {
+ return new ReadReplicaRequest(id, source, null, null, null, null, null, null, null,
+ null, null, null, null, null, null, Map.of());
+ }
+
+ @Test
+ void createReadReplicaInheritsTheSourceAndLinksBothEnds() {
+ when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> new RdsContainerHandle(
+ "cont-" + invocation.getArgument(1), invocation.getArgument(1), "localhost", 5432));
+ createPostgresSource("primary");
+ when(containerManager.createPostgresSnapshot("cont-primary", "admin")).thenReturn("DUMP");
+
+ DbInstance replica = rdsService.createDbInstanceReadReplica(
+ replicaRequest("primary-replica", "primary"), null);
+
+ assertEquals("primary", replica.getReadReplicaSourceDbInstanceIdentifier());
+ assertTrue(replica.hasReadReplicaSource());
+ assertEquals(DatabaseEngine.POSTGRES, replica.getEngine());
+ assertEquals("16.3", replica.getEngineVersion());
+ assertEquals("admin", replica.getMasterUsername());
+ assertEquals("password", replica.getMasterPassword());
+ assertEquals("appdb", replica.getDbName());
+ assertEquals("db.t3.medium", replica.getDbInstanceClass());
+ assertEquals(50, replica.getAllocatedStorage());
+ assertEquals(0, replica.getBackupRetentionPeriod(), "a replica starts with backups off");
+ assertEquals(DbInstanceStatus.AVAILABLE, replica.getStatus());
+ assertNotEquals(rdsService.getDbInstance("primary").getEndpoint().port(),
+ replica.getEndpoint().port(), "a replica has its own endpoint");
+ assertEquals(List.of("primary-replica"),
+ rdsService.getDbInstance("primary").getReadReplicaDbInstanceIdentifiers());
+ // The backing copy is a dump of the source restored into the replica's own container.
+ verify(containerManager).restorePostgresSnapshot("cont-primary-replica", "admin", "DUMP");
+ }
+
+ @Test
+ void createReadReplicaHonoursOverridesAndResolvesAnArnSource() {
+ createPostgresSource("primary");
+ when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("DUMP");
+
+ DbInstance replica = rdsService.createDbInstanceReadReplica(new ReadReplicaRequest(
+ "big-replica", "arn:aws:rds:us-east-1:123456789012:db:primary",
+ "db.r6g.large", "us-east-1b", false, false, null, null, true, null,
+ List.of("sg-replica"), true, true, 100, null, Map.of("role", "reader")), null);
+
+ assertEquals("primary", replica.getReadReplicaSourceDbInstanceIdentifier(),
+ "a same-Region source named by ARN is still reported by identifier");
+ assertEquals("db.r6g.large", replica.getDbInstanceClass());
+ assertEquals(100, replica.getAllocatedStorage());
+ assertEquals("us-east-1b", replica.getAvailabilityZone());
+ assertFalse(replica.isMultiAz());
+ assertFalse(replica.isAutoMinorVersionUpgrade());
+ assertTrue(replica.isPubliclyAccessible());
+ assertTrue(replica.isIamDatabaseAuthenticationEnabled());
+ assertTrue(replica.isCopyTagsToSnapshot());
+ assertEquals(List.of("sg-replica"), replica.getVpcSecurityGroupIds());
+ assertEquals(Map.of("role", "reader"), replica.getTags());
+ }
+
+ @Test
+ void sameRegionReplicaInheritsGroupsAndCrossRegionReplicaGetsDefaultsAndArnLinks() {
+ rdsService.createDbParameterGroup("primary-pg", "postgres16", "source group");
+ rdsService.createDbInstance("primary", "postgres", "16.3", "admin", "password", "appdb",
+ "db.t3.medium", 50, true, "primary-pg", null, null, null, false, false, null,
+ Map.of(), List.of("sg-source"), null, null, true,
+ new DbInstanceSettings(null, null, null, null, null, true));
+ when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("DUMP");
+
+ DbInstance local = rdsService.createDbInstanceReadReplica(
+ replicaRequest("local-replica", "primary"), null);
+ assertEquals("primary-pg", local.getParameterGroupName());
+ assertEquals(List.of("sg-source"), local.getVpcSecurityGroupIds());
+ assertFalse(local.isIamDatabaseAuthenticationEnabled(),
+ "IAM authentication is off unless the request enables it");
+ assertFalse(local.isCopyTagsToSnapshot(), "tags are not copied unless the request says so");
+
+ DbInstance remote = rdsService.createDbInstanceReadReplica(
+ replicaRequest("remote-replica", "arn:aws:rds:us-east-1:123456789012:db:primary"),
+ "eu-west-1");
+ assertEquals("arn:aws:rds:eu-west-1:123456789012:db:remote-replica", remote.getDbInstanceArn());
+ assertEquals("arn:aws:rds:us-east-1:123456789012:db:primary",
+ remote.getReadReplicaSourceDbInstanceIdentifier(),
+ "a cross-Region link names the source by ARN");
+ assertNull(remote.getParameterGroupName(), "a cross-Region replica gets the default group");
+ assertTrue(remote.getVpcSecurityGroupIds().isEmpty(), "and the default security group");
+ assertEquals(List.of("local-replica", "arn:aws:rds:eu-west-1:123456789012:db:remote-replica"),
+ rdsService.getDbInstance("primary").getReadReplicaDbInstanceIdentifiers());
+
+ // A subnet group goes with a source named by ARN; with a plain identifier AWS refuses it.
+ AwsException subnetGroup = assertThrows(AwsException.class, () ->
+ rdsService.createDbInstanceReadReplica(new ReadReplicaRequest("third", "primary",
+ null, null, null, null, null, null, null, "some-subnet-group", null, null,
+ null, null, null, Map.of()), null));
+ assertEquals("DBSubnetGroupNotAllowedFault", subnetGroup.getErrorCode());
+ }
+
+ @Test
+ void createReadReplicaRefusesWhatAwsRefuses() {
+ createPostgresSource("primary");
+ rdsService.createDbInstance("nobackups", "postgres", "16.3", "admin", "password", "appdb",
+ "db.t3.micro", 20, false, null, null, null, null, false, false, null,
+ Map.of(), List.of(), null, null, true,
+ new DbInstanceSettings(null, null, 0, null, null, null));
+ rdsService.createDbInstance("maria", "mariadb", "11.2", "admin", "password", "appdb",
+ "db.t3.micro", 20, false, null, null, null, null, false);
+
+ AwsException noSource = assertThrows(AwsException.class, () ->
+ rdsService.createDbInstanceReadReplica(replicaRequest("r", null), null));
+ assertEquals("InvalidParameterCombination", noSource.getErrorCode());
+
+ AwsException unknown = assertThrows(AwsException.class, () ->
+ rdsService.createDbInstanceReadReplica(replicaRequest("r", "missing"), null));
+ assertEquals("DBInstanceNotFound", unknown.getErrorCode());
+
+ AwsException backupsOff = assertThrows(AwsException.class, () ->
+ rdsService.createDbInstanceReadReplica(replicaRequest("r", "nobackups"), null));
+ assertEquals("InvalidDBInstanceState", backupsOff.getErrorCode());
+ assertTrue(backupsOff.getMessage().contains("Automated backups are not enabled"));
+
+ AwsException otherEngine = assertThrows(AwsException.class, () ->
+ rdsService.createDbInstanceReadReplica(replicaRequest("r", "maria"), null));
+ assertEquals("InvalidDBInstanceState", otherEngine.getErrorCode());
+
+ AwsException replicaMode = assertThrows(AwsException.class, () ->
+ rdsService.createDbInstanceReadReplica(new ReadReplicaRequest("r", "primary",
+ null, null, null, null, null, null, null, null, null, null, null, null,
+ "mounted", Map.of()), null));
+ assertEquals("InvalidParameterCombination", replicaMode.getErrorCode());
+
+ AwsException sameName = assertThrows(AwsException.class, () ->
+ rdsService.createDbInstanceReadReplica(replicaRequest("primary", "primary"), null));
+ assertEquals("DBInstanceAlreadyExists", sameName.getErrorCode());
+ assertTrue(rdsService.getDbInstance("primary").getReadReplicaDbInstanceIdentifiers().isEmpty(),
+ "a refused request leaves no dangling link on the source");
+ }
+
+ @Test
+ void createReadReplicaRollsBackWhenTheCopyFails() {
+ createPostgresSource("primary");
+ when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("DUMP");
+ doThrow(new RuntimeException("restore exploded"))
+ .when(containerManager).restorePostgresSnapshot(any(), eq("admin"), eq("DUMP"));
+
+ AwsException failure = assertThrows(AwsException.class, () ->
+ rdsService.createDbInstanceReadReplica(replicaRequest("primary-replica", "primary"), null));
+
+ assertEquals("InvalidDBInstanceState", failure.getErrorCode());
+ assertTrue(failure.getMessage().contains("restore exploded"));
+ assertThrows(AwsException.class, () -> rdsService.getDbInstance("primary-replica"));
+ assertTrue(rdsService.getDbInstance("primary").getReadReplicaDbInstanceIdentifiers().isEmpty());
+ }
+
+ @Test
+ void promoteReadReplicaDetachesItAndTurnsBackupsOn() {
+ createPostgresSource("primary");
+ when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("DUMP");
+ rdsService.createDbInstanceReadReplica(replicaRequest("primary-replica", "primary"), null);
+
+ DbInstance promoted = rdsService.promoteReadReplica("primary-replica", 7, "03:00-03:30", null);
+
+ assertFalse(promoted.hasReadReplicaSource());
+ assertNull(promoted.getReadReplicationStatus());
+ assertEquals(7, promoted.getBackupRetentionPeriod());
+ assertEquals("03:00-03:30", promoted.getPreferredBackupWindow());
+ assertEquals(DbInstanceStatus.AVAILABLE, promoted.getStatus());
+ assertTrue(rdsService.getDbInstance("primary").getReadReplicaDbInstanceIdentifiers().isEmpty());
+ assertFalse(rdsService.getDbInstance("primary-replica").hasReadReplicaSource());
+ // AWS reboots the promoted instance before it is available again.
+ verify(containerManager).stop(any());
+ verify(containerManager, times(3)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any());
+
+ // Omitted retention means one day, as on AWS; a standalone instance cannot be promoted.
+ rdsService.createDbInstanceReadReplica(replicaRequest("second-replica", "primary"), null);
+ assertEquals(1, rdsService.promoteReadReplica("second-replica", null, null, null)
+ .getBackupRetentionPeriod());
+ AwsException notReplica = assertThrows(AwsException.class, () ->
+ rdsService.promoteReadReplica("primary", null, null, null));
+ assertEquals("InvalidDBInstanceState", notReplica.getErrorCode());
+ AwsException badRetention = assertThrows(AwsException.class, () -> {
+ rdsService.createDbInstanceReadReplica(replicaRequest("third-replica", "primary"), null);
+ rdsService.promoteReadReplica("third-replica", 36, null, null);
+ });
+ assertEquals("InvalidParameterValue", badRetention.getErrorCode());
+ assertTrue(rdsService.getDbInstance("third-replica").hasReadReplicaSource(),
+ "a refused promotion leaves the replica attached");
+
+ // A replica that has replicas of its own (backups on, as AWS requires of any source)
+ // cannot turn backups off when promoted.
+ rdsService.modifyDbInstance("third-replica", null, null, null, null, null, null, null,
+ new DbInstanceSettings(null, null, 3, null, null, null), null);
+ rdsService.createDbInstanceReadReplica(replicaRequest("cascade", "third-replica"), null);
+ AwsException zeroWithReplicas = assertThrows(AwsException.class, () ->
+ rdsService.promoteReadReplica("third-replica", 0, null, null));
+ assertEquals("InvalidParameterCombination", zeroWithReplicas.getErrorCode());
+ }
+
+ @Test
+ void deletingEitherEndOfAReplicationLinkDropsTheLink() {
+ createPostgresSource("primary");
+ when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("DUMP");
+ rdsService.createDbInstanceReadReplica(replicaRequest("replica-a", "primary"), null);
+ rdsService.createDbInstanceReadReplica(replicaRequest("replica-b", "primary"), null);
+
+ rdsService.deleteDbInstance("replica-a");
+ assertEquals(List.of("replica-b"),
+ rdsService.getDbInstance("primary").getReadReplicaDbInstanceIdentifiers());
+
+ rdsService.createDbInstanceReadReplica(
+ replicaRequest("replica-c", "arn:aws:rds:us-east-1:123456789012:db:primary"),
+ "eu-west-1");
+
+ // Deleting the source promotes the same-Region replica; the cross-Region PostgreSQL
+ // replica keeps its link with replication terminated, both as AWS documents.
+ rdsService.deleteDbInstance("primary");
+ DbInstance promoted = rdsService.getDbInstance("replica-b");
+ assertFalse(promoted.hasReadReplicaSource());
+ assertEquals(DbInstanceStatus.AVAILABLE, promoted.getStatus());
+ DbInstance terminated = rdsService.getDbInstance("replica-c", "eu-west-1");
+ assertEquals("arn:aws:rds:us-east-1:123456789012:db:primary",
+ terminated.getReadReplicaSourceDbInstanceIdentifier());
+ assertEquals(RdsService.READ_REPLICATION_TERMINATED, terminated.getReadReplicationStatus());
+ // It can still be promoted by hand.
+ assertFalse(rdsService.promoteReadReplica("replica-c", null, null, "eu-west-1")
+ .hasReadReplicaSource());
+ }
+
+ @Test
+ void switchoverAndClusterPromotionAnswerWithTheApiReferenceErrors() {
+ createPostgresSource("primary");
+ when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("DUMP");
+ rdsService.createDbInstanceReadReplica(replicaRequest("primary-replica", "primary"), null);
+
+ AwsException missing = assertThrows(AwsException.class, () ->
+ rdsService.switchoverReadReplica("nope", null));
+ assertEquals("DBInstanceNotFound", missing.getErrorCode());
+ AwsException standalone = assertThrows(AwsException.class, () ->
+ rdsService.switchoverReadReplica("primary", null));
+ assertEquals("InvalidDBInstanceState", standalone.getErrorCode());
+ AwsException engine = assertThrows(AwsException.class, () ->
+ rdsService.switchoverReadReplica("primary-replica", null));
+ assertEquals("InvalidDBInstanceState", engine.getErrorCode());
+ assertTrue(engine.getMessage().contains("Oracle"));
+
+ AwsException noCluster = assertThrows(AwsException.class, () ->
+ rdsService.promoteReadReplicaDbCluster("nope", null));
+ assertEquals("DBClusterNotFoundFault", noCluster.getErrorCode());
+ rdsService.createDbCluster("aurora", "aurora-postgresql", "16.3",
+ "admin", "password", "appdb", false, null);
+ AwsException notReplicaCluster = assertThrows(AwsException.class, () ->
+ rdsService.promoteReadReplicaDbCluster("aurora", null));
+ assertEquals("InvalidDBClusterStateFault", notReplicaCluster.getErrorCode());
+ }
}