From 92eff0aca536e45cd0b67a92501c9c1738f36af1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20Th=E1=BA=BF=20Huy?= <31652864+vuthehuyht@users.noreply.github.com> Date: Tue, 10 Nov 2026 00:18:19 +0700 Subject: [PATCH] feat(redshift): support ModifyClusterSnapshot API action (#7755) (#7756) * feat(redshift): support ModifyClusterSnapshot API action (#7755) * docs(redshift): update operation count after merging CopyClusterSnapshot * fix(redshift): enforce ModifyClusterSnapshot retention, Force, and expiry of manual snapshots (#7755) * fix(redshift): address snapshot retention review feedback --- docs/services/index.md | 2 +- docs/services/redshift.md | 11 +- .../redshift/RedshiftQueryHandler.java | 17 +++ .../services/redshift/RedshiftService.java | 125 ++++++++++++++---- .../RedshiftAutomatedSnapshotServiceTest.java | 47 +++++++ .../RedshiftFinalSnapshotIntegrationTest.java | 4 + .../redshift/RedshiftOperationsTest.java | 20 ++- .../redshift/RedshiftQueryHandlerTest.java | 56 ++++++++ .../redshift/RedshiftServiceTest.java | 81 ++++++++++++ 9 files changed, 331 insertions(+), 32 deletions(-) diff --git a/docs/services/index.md b/docs/services/index.md index 752347221c..d8763fecba 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -80,7 +80,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 17 | | [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 20 | | [QuickSight](quicksight.md) | `/accounts/{AwsAccountId}/...` | REST JSON, metadata only | 16 | -| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 56 | +| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 57 | | [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 12 | | [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 55 | | [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 40 | diff --git a/docs/services/redshift.md b/docs/services/redshift.md index 6fc7c3f870..f86a36e62c 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -129,6 +129,7 @@ The attributes follow the [CloudFormation resource schema](https://docs.aws.amaz | `CreateClusterSnapshot` | Back up a cluster to a SQL dump via `pg_dump` | | `DescribeClusterSnapshots` | List snapshots, optionally filtered by snapshot or cluster identifier and SnapshotType (manual or automated) | | `DeleteClusterSnapshot` | Remove a snapshot and its stored dump | +| `ModifyClusterSnapshot` | Update the retention period of a manual cluster snapshot | | `CopyClusterSnapshot` | Copy an automated cluster snapshot to a manual snapshot with a new identifier and retention period | | `RestoreFromClusterSnapshot` | Create a new cluster and load a snapshot's dump into it via `psql`; accepts `SnapshotIdentifier` or a same-account, same-region `SnapshotArn` | | `CreateClusterParameterGroup` | Register a parameter group (metadata only) | @@ -207,9 +208,13 @@ committed is removed on failure; if the commit succeeded and a later flush repor the dump is retained for the committed snapshot. `FinalClusterSnapshotRetentionPeriod` defaults to `-1` and accepts `-1` or 1 to 3,653 days. -It is persisted and returned as the snapshot's `ManualSnapshotRetentionPeriod`; automatic -expiration is not implemented. Manual snapshots created by `CreateClusterSnapshot`, and older -snapshots without stored retention metadata, also return the default `-1`. Snapshot metadata +It is persisted and returned as the snapshot's `ManualSnapshotRetentionPeriod`. The background +retention sweep expires finite-retention manual snapshots, including final snapshots and +`CopyClusterSnapshot` targets, and removes their stored dumps. `ModifyClusterSnapshot` can change +this period; omitting `ManualSnapshotRetentionPeriod` preserves the current setting. An elapsed +new retention period requires `Force=true` to delete the snapshot immediately. +Manual snapshots created by `CreateClusterSnapshot`, and older snapshots without stored +retention metadata, return the default `-1` and are retained indefinitely. Snapshot metadata uses the configured storage mode. Persistent and WAL metadata commit failures are reported before teardown; hybrid retains its existing write-behind durability and logged flush failures. diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftQueryHandler.java b/src/main/java/io/floci/aws/services/redshift/RedshiftQueryHandler.java index b41a3f3d73..ba4ca4adc2 100644 --- a/src/main/java/io/floci/aws/services/redshift/RedshiftQueryHandler.java +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftQueryHandler.java @@ -241,6 +241,23 @@ public class RedshiftQueryHandler { .build(); return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); } + case "ModifyClusterSnapshot" -> { + String snapshotIdentifier = requireParam(params, "SnapshotIdentifier"); + Integer manualRetention = parseOptionalInteger(params, "ManualSnapshotRetentionPeriod"); + Boolean force = booleanParam(params, "Force"); + Snapshot snapshot = service.modifyClusterSnapshot(snapshotIdentifier, manualRetention, force); + String xml = new XmlBuilder() + .start("ModifyClusterSnapshotResponse") + .start("ModifyClusterSnapshotResult") + .raw(buildSnapshotXml(snapshot)) + .end("ModifyClusterSnapshotResult") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end("ModifyClusterSnapshotResponse") + .build(); + return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); + } case "CopyClusterSnapshot" -> { String sourceSnapshotId = requireParam(params, "SourceSnapshotIdentifier"); String targetSnapshotId = requireParam(params, "TargetSnapshotIdentifier"); diff --git a/src/main/java/io/floci/aws/services/redshift/RedshiftService.java b/src/main/java/io/floci/aws/services/redshift/RedshiftService.java index 8b36f551fc..736e7f2357 100644 --- a/src/main/java/io/floci/aws/services/redshift/RedshiftService.java +++ b/src/main/java/io/floci/aws/services/redshift/RedshiftService.java @@ -71,6 +71,7 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; +import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.regex.Pattern; @@ -2052,6 +2053,56 @@ public class RedshiftService implements ManagedSecretRotator { || clusterIdentifier.equals(snapshot.getClusterIdentifier()); } + public Snapshot modifyClusterSnapshot(String snapshotIdentifier, Integer manualSnapshotRetentionPeriod) { + return modifyClusterSnapshot(snapshotIdentifier, manualSnapshotRetentionPeriod, null); + } + + public Snapshot modifyClusterSnapshot(String snapshotIdentifier, Integer manualSnapshotRetentionPeriod, Boolean force) { + if (manualSnapshotRetentionPeriod != null) { + validateManualRetention(manualSnapshotRetentionPeriod); + } + String region = regionResolver.getRegion(); + + return withResourceLock("snapshot", snapshotIdentifier, () -> { + Snapshot snapshot = findSnapshot(snapshotIdentifier).orElseThrow(() -> new AwsException("ClusterSnapshotNotFound", + "Snapshot " + snapshotIdentifier + " not found", 404)); + if (!"available".equals(snapshot.getStatus())) { + throw new AwsException("InvalidClusterSnapshotState", + "Snapshot " + snapshotIdentifier + " is not available", 400); + } + if (!"manual".equals(snapshot.getSnapshotType())) { + throw new AwsException("InvalidClusterSnapshotState", + "Cannot modify an automated snapshot: " + snapshotIdentifier + + ". Only manual snapshots can be modified.", 400); + } + + if (manualSnapshotRetentionPeriod == null) { + return snapshot; + } + if (isManualRetentionElapsed(snapshot, manualSnapshotRetentionPeriod, Instant.now())) { + if (!Boolean.TRUE.equals(force)) { + throw new AwsException("InvalidRetentionPeriodFault", + "The retention period of " + manualSnapshotRetentionPeriod + " days has already passed for snapshot " + + snapshotIdentifier + ". Use Force to delete it.", 400); + } + // Force overrides the fault: the snapshot is already past its new deadline, so it goes now. + return mutate(() -> removeSnapshot(snapshotIdentifier, snapshot.getClusterIdentifier())); + } + + snapshot.setManualSnapshotRetentionPeriod(manualSnapshotRetentionPeriod); + String copyKey = copyKey(region, snapshotIdentifier); + if (snapshotCopies.get(copyKey).isPresent()) { + snapshotCopies.putAllAtomically(Map.of(copyKey, snapshot)); + snapshotCopies.flush(); + } else { + snapshots.putAllAtomically(Map.of(snapshotIdentifier, snapshot)); + snapshots.flush(); + } + + return snapshot; + }); + } + public Snapshot copyClusterSnapshot(String sourceSnapshotIdentifier, String targetSnapshotIdentifier, String sourceSnapshotClusterIdentifier, Integer manualRetention) { validateSnapshotIdentifier(targetSnapshotIdentifier); @@ -2981,6 +3032,47 @@ public class RedshiftService implements ManagedSecretRotator { entry.key(), entry.accountId()); } } + expireManualSnapshots(now); + } + + private static boolean isManualRetentionElapsed(Snapshot snapshot, int retentionDays, Instant now) { + return retentionDays > 0 && snapshot.getSnapshotCreateTime() != null + && !now.isBefore(snapshot.getSnapshotCreateTime().plus(retentionDays, ChronoUnit.DAYS)); + } + + /** Expires finite-retention manual snapshots, including final snapshots and CopyClusterSnapshot targets. */ + private void expireManualSnapshots(Instant now) { + expireSnapshots(snapshots, (entry, snapshot) -> isManualSnapshotExpired(snapshot, now)); + } + + private void expireSnapshots(AccountAwareStorageBackend store, + BiPredicate, Snapshot> expired) { + for (AccountAwareStorageBackend.AccountEntry entry : store.scanAllAccountEntries(key -> true)) { + if (Thread.currentThread().isInterrupted()) { + return; + } + try { + withResourceLock(entry.accountId(), "snapshot", entry.value().getSnapshotIdentifier(), () -> mutate(() -> { + // Read again under the lock: the scanned snapshot may have been modified or deleted meanwhile. + Snapshot current = store.getForAccount(entry.accountId(), entry.key()).orElse(null); + if (current == null || !expired.test(entry, current)) { + return null; + } + store.deleteAllAtomicallyForAccounts(Map.of(entry.accountId(), Set.of(entry.key()))); + store.flush(); + deleteSnapshotDump(entry.accountId(), current.getSqlDump()); + return null; + })); + } catch (RuntimeException e) { + LOG.warnv(e, "Could not expire Redshift snapshot {0} of account {1}; will retry", + entry.key(), entry.accountId()); + } + } + } + + private static boolean isManualSnapshotExpired(Snapshot snapshot, Instant now) { + return "manual".equals(snapshot.getSnapshotType()) + && isManualRetentionElapsed(snapshot, snapshot.getManualSnapshotRetentionPeriod(), now); } private void runSnapshotSchedule(String accountId, Cluster cluster, Instant now) { @@ -3182,7 +3274,7 @@ public class RedshiftService implements ManagedSecretRotator { } catch (RuntimeException e) { // The records change in memory before they are flushed, so undo them before the dump goes. rollbackSnapshotCopy(accountId, key, source); - deleteCopyDump(accountId, dump == null ? null : dump.toString()); + deleteSnapshotDump(accountId, dump == null ? null : dump.toString()); throw e; } return null; @@ -3252,27 +3344,8 @@ public class RedshiftService implements ManagedSecretRotator { } private void expireSnapshotCopies(Instant now) { - for (AccountAwareStorageBackend.AccountEntry entry : snapshotCopies.scanAllAccountEntries(key -> true)) { - if (Thread.currentThread().isInterrupted()) { - return; - } - try { - withResourceLock(entry.accountId(), "snapshot", entry.value().getSnapshotIdentifier(), () -> mutate(() -> { - // Read again under the lock: the scanned copy may have been replaced by a newer one meanwhile. - Snapshot current = snapshotCopies.getForAccount(entry.accountId(), entry.key()).orElse(null); - if (current == null || !isSnapshotCopyExpired(entry.accountId(), entry.key(), current, now)) { - return null; - } - snapshotCopies.deleteAllAtomicallyForAccounts(Map.of(entry.accountId(), Set.of(entry.key()))); - snapshotCopies.flush(); - deleteCopyDump(entry.accountId(), current.getSqlDump()); - return null; - })); - } catch (RuntimeException e) { - LOG.warnv(e, "Could not expire Redshift snapshot copy {0} of account {1}; will retry", - entry.key(), entry.accountId()); - } - } + expireSnapshots(snapshotCopies, + (entry, snapshot) -> isSnapshotCopyExpired(entry.accountId(), entry.key(), snapshot, now)); } /** @@ -3297,11 +3370,11 @@ public class RedshiftService implements ManagedSecretRotator { } else { retention = copy.getManualSnapshotRetentionPeriod(); } - return retention > 0 && !now.isBefore(copy.getSnapshotCreateTime().plus(retention, ChronoUnit.DAYS)); + return isManualRetentionElapsed(copy, retention, now); } - /** Deletes a copy's dump if it still lies in the account's directory; a failure is logged and the file left. */ - private void deleteCopyDump(String accountId, String stored) { + /** Deletes a snapshot's dump if it still lies in the account's directory; a failure is logged and the file left. */ + private void deleteSnapshotDump(String accountId, String stored) { if (stored == null || stored.isBlank()) { return; } @@ -3312,7 +3385,7 @@ public class RedshiftService implements ManagedSecretRotator { try { Files.deleteIfExists(file); } catch (IOException e) { - LOG.warnv(e, "Could not delete the dump file {0} of a Redshift snapshot copy", file); + LOG.warnv(e, "Could not delete the dump file {0} of a Redshift snapshot", file); } } diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftAutomatedSnapshotServiceTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftAutomatedSnapshotServiceTest.java index 26c5fb35bd..d7f68f120f 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftAutomatedSnapshotServiceTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftAutomatedSnapshotServiceTest.java @@ -120,6 +120,53 @@ class RedshiftAutomatedSnapshotServiceTest { .stream().map(Snapshot::getSnapshotIdentifier).toList()); } + @Test + void modifiedManualSnapshotExpiresOnceItsRetentionHasPassed() { + Fixture fixture = fixture(); + seed(fixture, ACCOUNT, "warehouse", "us-east-1", null); + Snapshot manual = fixture.service().createSnapshot("manual-backup", "warehouse"); + fixture.service().modifyClusterSnapshot("manual-backup", 5); + + fixture.service().runSnapshotSchedules(Instant.now().plus(Duration.ofDays(4))); + assertTrue(fixture.snapshots().getForAccount(ACCOUNT, "manual-backup").isPresent()); + assertTrue(Files.exists(Path.of(manual.getSqlDump()))); + + fixture.service().runSnapshotSchedules(Instant.now().plus(Duration.ofDays(6))); + assertTrue(fixture.snapshots().getForAccount(ACCOUNT, "manual-backup").isEmpty()); + assertFalse(Files.exists(Path.of(manual.getSqlDump()))); + } + + @Test + void manualSnapshotsWithoutAFiniteRetentionAreNeverExpired() { + Fixture fixture = fixture(); + seed(fixture, ACCOUNT, "warehouse", null, null); + Snapshot manual = fixture.service().createSnapshot("manual-backup", "warehouse"); + + fixture.service().runSnapshotSchedules(Instant.now().plus(Duration.ofDays(4000))); + + assertTrue(fixture.snapshots().getForAccount(ACCOUNT, "manual-backup").isPresent()); + assertTrue(Files.exists(Path.of(manual.getSqlDump()))); + } + + @Test + void modifyClusterSnapshotRejectsAnElapsedRetentionUnlessForced() { + Fixture fixture = fixture(); + seed(fixture, ACCOUNT, "warehouse", null, null); + Snapshot manual = fixture.service().createSnapshot("manual-backup", "warehouse"); + manual.setSnapshotCreateTime(Instant.now().minus(Duration.ofDays(10))); + fixture.snapshots().putForAccount(ACCOUNT, "manual-backup", manual); + + AwsException rejected = assertThrows(AwsException.class, + () -> fixture.service().modifyClusterSnapshot("manual-backup", 5, false)); + assertEquals("InvalidRetentionPeriodFault", rejected.getErrorCode()); + assertEquals(-1, fixture.snapshots().getForAccount(ACCOUNT, "manual-backup").orElseThrow() + .getManualSnapshotRetentionPeriod()); + + fixture.service().modifyClusterSnapshot("manual-backup", 5, true); + assertTrue(fixture.snapshots().getForAccount(ACCOUNT, "manual-backup").isEmpty()); + assertFalse(Files.exists(Path.of(manual.getSqlDump()))); + } + @Test void missingClustersLoseAutomatedSnapshotsButKeepManualBackups() { Fixture fixture = fixture(); diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftFinalSnapshotIntegrationTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftFinalSnapshotIntegrationTest.java index 240ba83ddd..af657e98cf 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftFinalSnapshotIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftFinalSnapshotIntegrationTest.java @@ -78,6 +78,10 @@ class RedshiftFinalSnapshotIntegrationTest { Snapshot snapshot = client.describeClusterSnapshots(request -> request.snapshotIdentifier(backup)) .snapshots().getFirst(); assertEquals(retention, snapshot.manualSnapshotRetentionPeriod()); + Snapshot unchanged = client.modifyClusterSnapshot(request -> request.snapshotIdentifier(backup).force(true)) + .snapshot(); + assertEquals(retention, unchanged.manualSnapshotRetentionPeriod()); + assertEquals(backup, unchanged.snapshotIdentifier()); assertEquals(source, snapshot.clusterIdentifier()); assertEquals("available", snapshot.status()); assertNotNull(snapshot.snapshotCreateTime()); diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftOperationsTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftOperationsTest.java index 7f55daae2e..db1938855c 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftOperationsTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftOperationsTest.java @@ -452,7 +452,23 @@ public class RedshiftOperationsTest { .contentType("application/xml") .body(containsString("snap-test-1")); - // 3b. CopyClusterSnapshot rejects manual snapshot + // 3b. ModifyClusterSnapshot updates retention period + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "ModifyClusterSnapshot") + .formParam("SnapshotIdentifier", "snap-test-1") + .formParam("ManualSnapshotRetentionPeriod", "45") + .when() + .post("/") + .then() + .statusCode(200) + .contentType("application/xml") + .body(containsString("")) + .body(containsString("snap-test-1")) + .body(containsString("45")); + + // 3c. CopyClusterSnapshot rejects manual snapshot given() .contentType("application/x-www-form-urlencoded") .header("Authorization", AUTH_HEADER) @@ -466,7 +482,7 @@ public class RedshiftOperationsTest { .contentType("application/xml") .body(containsString("InvalidClusterSnapshotState")); - // 3c. CopyClusterSnapshot succeeds when source is automated + // 3d. CopyClusterSnapshot succeeds when source is automated service.getSnapshot("snap-test-1").ifPresent(s -> s.setSnapshotType("automated")); given() .contentType("application/x-www-form-urlencoded") diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftQueryHandlerTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftQueryHandlerTest.java index 18ac190719..ddb2eda06e 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftQueryHandlerTest.java @@ -1478,6 +1478,62 @@ class RedshiftQueryHandlerTest { assertTrue(xml.contains("IAM:alice")); } + // ── ModifyClusterSnapshot ───────────────────────────────────────────────── + + @Test + void modifyClusterSnapshotRequiresIdentifier() { + MultivaluedMap params = new MultivaluedHashMap<>(); + AwsException ex1 = assertThrows(AwsException.class, () -> handler.handle("ModifyClusterSnapshot", params)); + assertEquals("InvalidParameterValue", ex1.getErrorCode()); + assertTrue(ex1.getMessage().contains("SnapshotIdentifier is required")); + } + + @Test + void modifyClusterSnapshotAllowsOmittedRetention() { + Snapshot snapshot = new Snapshot(); + snapshot.setSnapshotIdentifier("my-snap"); + snapshot.setManualSnapshotRetentionPeriod(7); + when(service.modifyClusterSnapshot("my-snap", null, null)).thenReturn(snapshot); + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("SnapshotIdentifier", "my-snap"); + + Response response = handler.handle("ModifyClusterSnapshot", params); + + assertEquals(200, response.getStatus()); + assertTrue(response.getEntity().toString().contains("7")); + verify(service).modifyClusterSnapshot("my-snap", null, null); + } + + @Test + void modifyClusterSnapshotDelegatesToServiceAndFormatsXml() { + Snapshot snapshot = new Snapshot(); + snapshot.setSnapshotIdentifier("my-snap"); + snapshot.setClusterIdentifier("my-cluster"); + snapshot.setSnapshotType("manual"); + snapshot.setStatus("available"); + snapshot.setMasterUsername("admin"); + snapshot.setPort(5439); + snapshot.setManualSnapshotRetentionPeriod(45); + snapshot.setSnapshotArn("arn:aws:redshift:us-east-1:111111111111:snapshot:my-cluster/my-snap"); + + when(service.modifyClusterSnapshot("my-snap", 45, true)).thenReturn(snapshot); + + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("SnapshotIdentifier", "my-snap"); + params.putSingle("ManualSnapshotRetentionPeriod", "45"); + params.putSingle("Force", "true"); + + Response response = handler.handle("ModifyClusterSnapshot", params); + assertEquals(200, response.getStatus()); + + String xml = (String) response.getEntity(); + assertTrue(xml.contains("")); + assertTrue(xml.contains("")); + assertTrue(xml.contains("my-snap")); + assertTrue(xml.contains("45")); + verify(service).modifyClusterSnapshot("my-snap", 45, true); + } + // ── CopyClusterSnapshot ────────────────────────────────────────────────── @Test diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java index fd8f41f009..57d7180952 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftServiceTest.java @@ -2539,6 +2539,87 @@ class RedshiftServiceTest { } } + @Test + void modifyClusterSnapshotSuccess() { + Snapshot manualSnap = snapshotOf("snap-1", "my-cluster"); + manualSnap.setStatus("available"); + manualSnap.setManualSnapshotRetentionPeriod(-1); + + when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(manualSnap)); + when(snapshotCopyBackend.get(anyString())).thenReturn(Optional.empty()); + + Snapshot modified = service.modifyClusterSnapshot("snap-1", 45); + + assertNotNull(modified); + assertEquals(45, modified.getManualSnapshotRetentionPeriod()); + verify(snapshotBackend).putAllAtomically(any()); + verify(snapshotBackend).flush(); + } + + @Test + void modifyClusterSnapshotNotFound() { + when(snapshotBackend.get("missing-snap")).thenReturn(Optional.empty()); + when(snapshotCopyBackend.get(anyString())).thenReturn(Optional.empty()); + + AwsException ex = assertThrows(AwsException.class, () -> + service.modifyClusterSnapshot("missing-snap", 30)); + assertEquals("ClusterSnapshotNotFound", ex.getErrorCode()); + assertEquals(404, ex.getHttpStatus()); + } + + @Test + void modifyClusterSnapshotAutomatedSnapshotRejected() { + automatedSnapshot("auto-snap-1"); + when(snapshotCopyBackend.get(anyString())).thenReturn(Optional.empty()); + + AwsException ex = assertThrows(AwsException.class, () -> + service.modifyClusterSnapshot("auto-snap-1", 30)); + assertEquals("InvalidClusterSnapshotState", ex.getErrorCode()); + assertEquals(400, ex.getHttpStatus()); + } + + @Test + void modifyClusterSnapshotNotAvailableRejected() { + Snapshot manualSnap = snapshotOf("snap-1", "my-cluster"); + manualSnap.setStatus("creating"); + + when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(manualSnap)); + when(snapshotCopyBackend.get(anyString())).thenReturn(Optional.empty()); + + AwsException ex = assertThrows(AwsException.class, () -> + service.modifyClusterSnapshot("snap-1", 30)); + assertEquals("InvalidClusterSnapshotState", ex.getErrorCode()); + assertEquals(400, ex.getHttpStatus()); + } + + @Test + void modifyClusterSnapshotInvalidRetentionPeriod() { + AwsException ex1 = assertThrows(AwsException.class, () -> + service.modifyClusterSnapshot("snap-1", 0)); + assertEquals("InvalidRetentionPeriodFault", ex1.getErrorCode()); + assertEquals(400, ex1.getHttpStatus()); + + AwsException ex2 = assertThrows(AwsException.class, () -> + service.modifyClusterSnapshot("snap-1", 3654)); + assertEquals("InvalidRetentionPeriodFault", ex2.getErrorCode()); + assertEquals(400, ex2.getHttpStatus()); + } + + @Test + void modifyClusterSnapshotWithoutRetentionPreservesExistingSettings() { + Snapshot snapshot = snapshotOf("snap-1", "my-cluster"); + snapshot.setStatus("available"); + snapshot.setManualSnapshotRetentionPeriod(7); + when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(snapshot)); + + Snapshot modified = service.modifyClusterSnapshot("snap-1", null, true); + + assertSame(snapshot, modified); + assertEquals(7, modified.getManualSnapshotRetentionPeriod()); + verify(snapshotBackend, never()).putAllAtomically(any()); + verify(snapshotBackend, never()).deleteAllAtomically(any()); + } + @Test void modifyClusterUpdatesMetadataAndPassword() { Cluster cluster = new Cluster();