feat(redshift-serverless): copy snapshots into the configured destination region (#7024)

* feat(redshift-serverless): copy snapshots into the configured destination region

A SnapshotCopyConfiguration used to be stored and echoed, with nothing copied.
A background sweep now carries each AVAILABLE snapshot of the namespace, taken
at or after the configuration was created, into the destination Region with its
dump and metadata. The copy is an ordinary snapshot there, so describe, restore,
delete and expiration work on it unchanged.

- The source records the Regions it has been copied to, so a deleted or expired
  copy is not made again and a retry or restart after a crash makes no second
  copy. A copy made for an earlier snapshot of the same name is replaced.
- Retention and KMS key come from the configuration. A name already taken by
  an unrelated snapshot in the destination is kept and logged.
- Rules carry the account and namespace id, so accounts never collide and a
  recreated namespace does not inherit its predecessor's configuration.
- The destination must be a known Region in the namespace's partition.
- ResetAll now removes every snapshot dump, which it used to leak.
- New switches: snapshot-copy-enabled and snapshot-copy-sweep-interval-seconds.

* fix(redshift-serverless): keep the earlier snapshot copy restorable when a replacement fails

Each copy now gets its own dump file and the replaced copy's dump is removed
only after the new record is saved. Drop the slow, partition-bound
compatibility test; the in-repo engine and integration tests cover the copy.

* fix(redshift-serverless): name a snapshot copy's dump by id so long snapshot names still copy
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-30 14:44:26 -04:00
1 parent fa243bf78e
commit 9b69b3dac3
14 files changed
+1241 -10

No files matched your search

@@ -0,0 +1,405 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessSnapshotCopyService.CopyRule;
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
import io.github.hectorvent.floci.services.redshiftserverless.model.RedshiftServerlessSnapshot;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
class RedshiftServerlessSnapshotCopyEngineTest {
private static final String SOURCE = "us-east-1";
private static final String DESTINATION = "us-west-2";
private static final String ACCOUNT_ID = "123456789012";
private static final String OTHER_ACCOUNT_ID = "999999999999";
private static final String NAMESPACE = "copy-ns";
private static final Instant CONFIGURED = Instant.parse("2026-10-01T00:00:00Z");
private static final Instant TAKEN = Instant.parse("2026-10-02T00:00:00Z");
private static final Instant NOW = Instant.parse("2026-10-30T00:00:00Z");
@TempDir
Path persistentPath;
private static final String NAMESPACE_ID = "namespace-id";
private AccountAwareStorageBackend<RedshiftServerlessSnapshot> snapshots;
private AccountAwareStorageBackend<Namespace> namespaces;
private RedshiftServerlessService service;
@BeforeEach
@SuppressWarnings({"unchecked", "rawtypes"})
void setUp() {
StorageFactory storageFactory = mock(StorageFactory.class);
for (String file : List.of("namespaces", "workgroups", "snapshots", "snapshotcopyconfigurations")) {
AccountAwareStorageBackend<?> store = file.equals("snapshots")
? spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID))
: AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
if (file.equals("snapshots")) {
snapshots = (AccountAwareStorageBackend<RedshiftServerlessSnapshot>) store;
}
if (file.equals("namespaces")) {
namespaces = (AccountAwareStorageBackend<Namespace>) store;
}
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-" + file + ".json"),
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
}
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
RedshiftServerlessEndpoints endpoints = mock(RedshiftServerlessEndpoints.class);
when(endpoints.allocate()).thenReturn(new Endpoint("localhost", 7100));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.storage().persistentPath()).thenReturn(persistentPath.toString());
service = new RedshiftServerlessService(storageFactory, regionResolver, endpoints,
mock(RedshiftServerlessRuntime.class), config);
for (String account : List.of(ACCOUNT_ID, OTHER_ACCOUNT_ID)) {
Namespace namespace = new Namespace();
namespace.setNamespaceName(NAMESPACE);
namespace.setNamespaceId(NAMESPACE_ID);
namespaces.putForAccount(account, SOURCE + "::" + NAMESPACE, namespace);
}
}
@Test
void skipsARuleWhoseNamespaceWasRecreatedSinceTheRuleWasListed() throws IOException {
seed(ACCOUNT_ID, SOURCE, "nightly", TAKEN, null);
CopyRule stale = new CopyRule(ACCOUNT_ID, SOURCE, NAMESPACE, "the-earlier-namespace-id", DESTINATION,
null, null, CONFIGURED);
service.copySnapshots(NOW, List.of(stale));
assertTrue(snapshots.get(DESTINATION + "::nightly").isEmpty());
assertTrue(stored(ACCOUNT_ID, SOURCE, "nightly").getCopiedToRegions().isEmpty());
}
@Test
void copiesMetadataAndDumpIntoTheDestinationRegion() throws IOException {
RedshiftServerlessSnapshot source = seed(ACCOUNT_ID, SOURCE, "nightly", TAKEN, "-- data");
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, null)));
RedshiftServerlessSnapshot copy = stored(ACCOUNT_ID, DESTINATION, "nightly");
assertEquals("nightly", copy.getSnapshotName());
assertEquals(DESTINATION, copy.getRegion());
assertEquals("AVAILABLE", copy.getStatus());
assertEquals("arn:aws:redshift-serverless:" + DESTINATION + ":" + ACCOUNT_ID + ":snapshot/nightly",
copy.getSnapshotArn());
assertEquals(source.getSnapshotArn(), copy.getCopiedFromSnapshotArn());
assertEquals(NAMESPACE, copy.getNamespaceName());
assertEquals(source.getOwnerAccount(), copy.getOwnerAccount());
assertEquals(source.getAdminUsername(), copy.getAdminUsername());
assertEquals(Map.of("team", "data"), copy.getTags());
assertEquals(NOW, copy.getSnapshotCreateTime());
assertEquals(dumpOf(ACCOUNT_ID, DESTINATION, "nightly").getParent(),
Path.of(copy.getSqlDump()).getParent());
assertEquals("-- data", Files.readString(copiedDump(ACCOUNT_ID, "nightly")));
assertTrue(Files.exists(dumpOf(ACCOUNT_ID, SOURCE, "nightly")), "the source dump stays");
assertEquals(Set.of(DESTINATION), stored(ACCOUNT_ID, SOURCE, "nightly").getCopiedToRegions());
}
@Test
void clearRemovesDumpsEvenWhenTheStoreWasEmptiedFirst() throws IOException {
seed(ACCOUNT_ID, SOURCE, "nightly", TAKEN, "-- data");
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, null)));
Path copiedFile = copiedDump(ACCOUNT_ID, "nightly");
assertTrue(Files.exists(copiedFile));
// ResetAll empties every storage backend before it calls each service's clear().
snapshots.clear();
service.clear();
assertFalse(Files.exists(dumpOf(ACCOUNT_ID, SOURCE, "nightly")));
assertFalse(Files.exists(copiedFile));
}
@Test
void copiesAMetadataOnlySnapshotWithoutADump() throws IOException {
seed(ACCOUNT_ID, SOURCE, "bare", TAKEN, null);
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, null)));
assertNull(stored(ACCOUNT_ID, DESTINATION, "bare").getSqlDump());
}
@Test
void appliesRetentionAndKmsKeyOfTheConfiguration() throws IOException {
seed(ACCOUNT_ID, SOURCE, "kept", TAKEN, null);
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, "key-in-west", 14)));
RedshiftServerlessSnapshot kept = stored(ACCOUNT_ID, DESTINATION, "kept");
assertEquals(14, kept.getRetentionPeriod());
assertEquals("key-in-west", kept.getKmsKeyId());
}
@Test
void keepsTheCopyIndefinitelyWhenTheConfigurationSaysSo() throws IOException {
seed(ACCOUNT_ID, SOURCE, "forever", TAKEN, null);
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, -1)));
assertNull(stored(ACCOUNT_ID, DESTINATION, "forever").getRetentionPeriod());
assertNull(stored(ACCOUNT_ID, DESTINATION, "forever").getKmsKeyId());
}
@Test
void skipsSnapshotsCreatedBeforeTheConfiguration() throws IOException {
seed(ACCOUNT_ID, SOURCE, "older", CONFIGURED.minus(1, ChronoUnit.DAYS), null);
seed(ACCOUNT_ID, SOURCE, "newer", CONFIGURED.plus(1, ChronoUnit.DAYS), null);
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, null)));
assertTrue(snapshots.get(DESTINATION + "::older").isEmpty());
assertTrue(snapshots.get(DESTINATION + "::newer").isPresent());
}
@Test
void skipsSnapshotsThatAreNotAvailableOrBelongToAnotherNamespace() throws IOException {
RedshiftServerlessSnapshot deleted = seed(ACCOUNT_ID, SOURCE, "gone", TAKEN, null);
deleted.setStatus("DELETED");
snapshots.put(SOURCE + "::gone", deleted);
RedshiftServerlessSnapshot foreign = seed(ACCOUNT_ID, SOURCE, "elsewhere", TAKEN, null);
foreign.setNamespaceName("another-ns");
snapshots.put(SOURCE + "::elsewhere", foreign);
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, null)));
assertTrue(snapshots.get(DESTINATION + "::gone").isEmpty());
assertTrue(snapshots.get(DESTINATION + "::elsewhere").isEmpty());
}
@Test
void doesNotCopyAgainAfterTheCopyWasDeleted() throws IOException {
seed(ACCOUNT_ID, SOURCE, "nightly", TAKEN, "-- data");
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, null)));
Path copiedFile = copiedDump(ACCOUNT_ID, "nightly");
service.deleteSnapshot("nightly", DESTINATION);
service.copySnapshots(NOW.plusSeconds(60), List.of(rule(ACCOUNT_ID, null, null)));
assertTrue(snapshots.get(DESTINATION + "::nightly").isEmpty());
assertFalse(Files.exists(copiedFile));
}
@Test
void doesNotCopyAgainAfterTheCopyExpired() throws IOException {
RedshiftServerlessSnapshot source = seed(ACCOUNT_ID, SOURCE, "nightly", TAKEN, null);
// The source must outlive the copy, or the later sweep has nothing to copy and proves nothing.
source.setRetentionPeriod(null);
snapshots.put(SOURCE + "::nightly", source);
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, 1)));
assertTrue(snapshots.get(DESTINATION + "::nightly").isPresent());
service.expireSnapshots(NOW.plus(2, ChronoUnit.DAYS), entry -> { });
assertTrue(snapshots.get(DESTINATION + "::nightly").isEmpty());
assertEquals(Set.of(DESTINATION), stored(ACCOUNT_ID, SOURCE, "nightly").getCopiedToRegions());
service.copySnapshots(NOW.plus(2, ChronoUnit.DAYS), List.of(rule(ACCOUNT_ID, null, 1)));
assertTrue(snapshots.get(DESTINATION + "::nightly").isEmpty());
}
@Test
void replacesTheCopyOfAnEarlierSnapshotThatUsedTheSameName() throws IOException {
seed(ACCOUNT_ID, SOURCE, "nightly", TAKEN, "-- old");
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, null)));
Path oldCopyFile = copiedDump(ACCOUNT_ID, "nightly");
assertEquals("-- old", Files.readString(oldCopyFile));
// Deleting a snapshot and taking another of the same name yields the same ARN.
Instant retaken = TAKEN.plus(1, ChronoUnit.DAYS);
seed(ACCOUNT_ID, SOURCE, "nightly", retaken, "-- new");
service.copySnapshots(NOW.plusSeconds(60), List.of(rule(ACCOUNT_ID, null, null)));
RedshiftServerlessSnapshot copy = stored(ACCOUNT_ID, DESTINATION, "nightly");
assertEquals("-- new", Files.readString(copiedDump(ACCOUNT_ID, "nightly")));
assertFalse(Files.exists(oldCopyFile), "the replaced copy's dump is removed once the new one is saved");
assertEquals(retaken, copy.getCopiedFromSnapshotCreateTime());
assertEquals(NOW.plusSeconds(60), copy.getSnapshotCreateTime());
assertEquals(Set.of(DESTINATION), stored(ACCOUNT_ID, SOURCE, "nightly").getCopiedToRegions());
}
@Test
void copiesASnapshotWhoseNameIsAsLongAsAllowed() throws IOException {
String name = "a".repeat(220);
seed(ACCOUNT_ID, SOURCE, name, TAKEN, "-- long");
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, null)));
assertEquals("-- long", Files.readString(Path.of(stored(ACCOUNT_ID, DESTINATION, name).getSqlDump())));
assertTrue(Path.of(stored(ACCOUNT_ID, DESTINATION, name).getSqlDump()).getFileName().toString()
.length() < 100);
}
@Test
void keepsTheEarlierCopyUsableWhenSavingTheReplacementFails() throws IOException {
seed(ACCOUNT_ID, SOURCE, "nightly", TAKEN, "-- old");
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, null)));
Path oldCopyFile = copiedDump(ACCOUNT_ID, "nightly");
seed(ACCOUNT_ID, SOURCE, "nightly", TAKEN.plus(1, ChronoUnit.DAYS), "-- new");
doThrow(new IllegalStateException("disk full")).when(snapshots)
.putAllAtomicallyForAccount(eq(ACCOUNT_ID), any());
service.copySnapshots(NOW.plusSeconds(60), List.of(rule(ACCOUNT_ID, null, null)));
doCallRealMethod().when(snapshots).putAllAtomicallyForAccount(eq(ACCOUNT_ID), any());
assertEquals("-- old", Files.readString(oldCopyFile));
assertEquals(oldCopyFile, copiedDump(ACCOUNT_ID, "nightly"));
try (Stream<Path> files = Files.list(oldCopyFile.getParent())) {
assertEquals(1, files.count(), "the failed replacement leaves no dump behind");
}
}
@Test
void leavesTheSourceIntactAndRetriesWhenTheDumpIsMissing() throws IOException {
RedshiftServerlessSnapshot source = seed(ACCOUNT_ID, SOURCE, "nightly", TAKEN, "-- data");
Files.delete(dumpOf(ACCOUNT_ID, SOURCE, "nightly"));
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, null)));
assertTrue(snapshots.get(DESTINATION + "::nightly").isEmpty());
assertTrue(stored(ACCOUNT_ID, SOURCE, "nightly").getCopiedToRegions().isEmpty());
assertEquals("AVAILABLE", stored(ACCOUNT_ID, SOURCE, "nightly").getStatus());
assertEquals(source.getSqlDump(), stored(ACCOUNT_ID, SOURCE, "nightly").getSqlDump());
Files.writeString(dumpOf(ACCOUNT_ID, SOURCE, "nightly"), "-- data");
service.copySnapshots(NOW.plusSeconds(60), List.of(rule(ACCOUNT_ID, null, null)));
assertTrue(snapshots.get(DESTINATION + "::nightly").isPresent());
}
@Test
void refusesADumpOutsideTheSourceDirectoryAndLeavesNoCopy() throws IOException {
RedshiftServerlessSnapshot source = seed(ACCOUNT_ID, SOURCE, "nightly", TAKEN, null);
Path outside = persistentPath.resolve("outside.sql");
Files.writeString(outside, "-- secret");
source.setSqlDump(outside.toString());
snapshots.put(SOURCE + "::nightly", source);
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, null)));
assertTrue(snapshots.get(DESTINATION + "::nightly").isEmpty());
assertTrue(stored(ACCOUNT_ID, SOURCE, "nightly").getCopiedToRegions().isEmpty());
}
@Test
void repairsTheMarkerWithoutADuplicateAfterACrash() throws IOException {
RedshiftServerlessSnapshot source = seed(ACCOUNT_ID, SOURCE, "nightly", TAKEN, null);
RedshiftServerlessSnapshot committed = new RedshiftServerlessSnapshot(source);
committed.setRegion(DESTINATION);
committed.setSnapshotArn("arn:aws:redshift-serverless:" + DESTINATION + ":" + ACCOUNT_ID + ":snapshot/nightly");
committed.setCopiedFromSnapshotArn(source.getSnapshotArn());
committed.setCopiedFromSnapshotCreateTime(source.getSnapshotCreateTime());
committed.setSnapshotCreateTime(NOW.minusSeconds(30));
snapshots.put(DESTINATION + "::nightly", committed);
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, null)));
assertEquals(NOW.minusSeconds(30), stored(ACCOUNT_ID, DESTINATION, "nightly").getSnapshotCreateTime());
assertEquals(Set.of(DESTINATION), stored(ACCOUNT_ID, SOURCE, "nightly").getCopiedToRegions());
assertEquals(2, snapshots.scan(key -> true).size());
}
@Test
void keepsAnExistingSnapshotOfTheSameNameInTheDestination() throws IOException {
seed(ACCOUNT_ID, SOURCE, "nightly", TAKEN, null);
RedshiftServerlessSnapshot users = seed(ACCOUNT_ID, DESTINATION, "nightly", TAKEN, null);
users.setNamespaceName("users-own-ns");
snapshots.put(DESTINATION + "::nightly", users);
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, null)));
RedshiftServerlessSnapshot kept = stored(ACCOUNT_ID, DESTINATION, "nightly");
assertEquals("users-own-ns", kept.getNamespaceName());
assertNull(kept.getCopiedFromSnapshotArn());
assertEquals(Set.of(DESTINATION), stored(ACCOUNT_ID, SOURCE, "nightly").getCopiedToRegions());
}
@Test
void copiesPerAccountWithoutCollision() throws IOException {
seed(ACCOUNT_ID, SOURCE, "nightly", TAKEN, "-- first");
seed(OTHER_ACCOUNT_ID, SOURCE, "nightly", TAKEN, "-- second");
service.copySnapshots(NOW, List.of(rule(ACCOUNT_ID, null, null), rule(OTHER_ACCOUNT_ID, null, null)));
RedshiftServerlessSnapshot first = stored(ACCOUNT_ID, DESTINATION, "nightly");
RedshiftServerlessSnapshot second = stored(OTHER_ACCOUNT_ID, DESTINATION, "nightly");
assertNotEquals(first.getSnapshotArn(), second.getSnapshotArn());
assertTrue(second.getSnapshotArn().contains(":" + OTHER_ACCOUNT_ID + ":"));
assertEquals("-- first", Files.readString(copiedDump(ACCOUNT_ID, "nightly")));
assertEquals("-- second", Files.readString(copiedDump(OTHER_ACCOUNT_ID, "nightly")));
}
private static CopyRule rule(String accountId, String kmsKeyId, Integer retention) {
return new CopyRule(accountId, SOURCE, NAMESPACE, NAMESPACE_ID, DESTINATION, kmsKeyId, retention, CONFIGURED);
}
private RedshiftServerlessSnapshot stored(String accountId, String region, String name) {
return snapshots.getForAccount(accountId, region + "::" + name).orElseThrow();
}
private Path copiedDump(String accountId, String name) {
return Path.of(stored(accountId, DESTINATION, name).getSqlDump());
}
private Path dumpOf(String accountId, String region, String name) {
return persistentPath.resolve("redshift-serverless-dumps").resolve(accountId).resolve(region)
.resolve(name + ".sql").toAbsolutePath().normalize();
}
private RedshiftServerlessSnapshot seed(String accountId, String region, String name, Instant taken,
String dump) throws IOException {
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot();
snapshot.setSnapshotName(name);
snapshot.setNamespaceName(NAMESPACE);
snapshot.setNamespaceArn("arn:aws:redshift-serverless:" + region + ":" + accountId + ":namespace/n");
snapshot.setRegion(region);
snapshot.setAccountId(accountId);
snapshot.setOwnerAccount(accountId);
snapshot.setSnapshotArn("arn:aws:redshift-serverless:" + region + ":" + accountId + ":snapshot/" + name);
snapshot.setStatus("AVAILABLE");
snapshot.setSnapshotCreateTime(taken);
snapshot.setAdminUsername("admin");
snapshot.setAdminUserPassword("Secret123");
snapshot.setKmsKeyId("key-in-" + region);
snapshot.setRetentionPeriod(30);
snapshot.setTags(Map.of("team", "data"));
if (dump != null) {
Path file = dumpOf(accountId, region, name);
Files.createDirectories(file.getParent());
Files.writeString(file, dump);
snapshot.setSqlDump(file.toString());
}
snapshots.putForAccount(accountId, region + "::" + name, snapshot);
return snapshot;
}
}
@@ -0,0 +1,172 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
import io.quarkus.test.InjectMock;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.redshiftserverless.RedshiftServerlessClient;
import software.amazon.awssdk.services.redshiftserverless.model.ResourceNotFoundException;
import software.amazon.awssdk.services.redshiftserverless.model.Snapshot;
import java.net.URI;
import java.time.Instant;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.when;
@QuarkusTest
class RedshiftServerlessSnapshotCopyIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
/** The copy needs no PostgreSQL container: the snapshots here are metadata only. */
@InjectMock
RedshiftServerlessRuntime runtime;
@Inject
RedshiftServerlessSnapshotCopyScheduler scheduler;
@BeforeEach
void stubRuntime() {
when(runtime.generatePassword()).thenReturn("Generated123");
when(runtime.start(any(String.class), any(String.class), any(String.class), any(String.class),
any(String.class), any(String.class), any(Endpoint.class), anyBoolean(), any()))
.thenReturn(new RedshiftServerlessRuntime.Backend("127.0.0.1", 55432));
}
private RedshiftServerlessClient client(Region region) {
return RedshiftServerlessClient.builder().endpointOverride(endpoint).region(region)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))
.build();
}
private static String unique(String prefix) {
return prefix + "-" + UUID.randomUUID().toString().substring(0, 8);
}
/** The application is shared with other tests, so what a test made is removed, not left for later sweeps. */
private static void cleanUp(RedshiftServerlessClient east, RedshiftServerlessClient west, String namespace,
String snapshotName, String restoreNamespace, String restoreWorkgroup) {
removeIfPresent(() -> west.deleteWorkgroup(request -> request.workgroupName(restoreWorkgroup)));
removeIfPresent(() -> west.deleteNamespace(request -> request.namespaceName(restoreNamespace)));
removeIfPresent(() -> west.deleteSnapshot(request -> request.snapshotName(snapshotName)));
removeIfPresent(() -> east.deleteSnapshot(request -> request.snapshotName(snapshotName)));
removeIfPresent(() -> east.listSnapshotCopyConfigurations(request -> request.namespaceName(namespace))
.snapshotCopyConfigurations().forEach(configuration -> east.deleteSnapshotCopyConfiguration(
request -> request.snapshotCopyConfigurationId(configuration.snapshotCopyConfigurationId()))));
removeIfPresent(() -> east.deleteNamespace(request -> request.namespaceName(namespace)));
}
private static void removeIfPresent(Runnable removal) {
try {
removal.run();
} catch (ResourceNotFoundException alreadyGone) {
// The test itself deleted it, or never got far enough to create it.
}
}
@Test
void copiedSnapshotIsVisibleAndRestorableInTheDestinationRegion() {
String namespace = unique("copy-src");
String snapshotName = unique("copy-snap");
String restoreNamespace = unique("copy-dst");
String restoreWorkgroup = unique("copy-wg");
try (RedshiftServerlessClient east = client(Region.US_EAST_1);
RedshiftServerlessClient west = client(Region.US_WEST_2)) {
try {
east.createNamespace(request -> request.namespaceName(namespace).adminUsername("admin")
.adminUserPassword("Password123!"));
east.createSnapshotCopyConfiguration(request -> request.namespaceName(namespace)
.destinationRegion("us-west-2").snapshotRetentionPeriod(14));
Snapshot source = east.createSnapshot(request -> request.namespaceName(namespace)
.snapshotName(snapshotName)).snapshot();
scheduler.tick(Instant.now());
Snapshot copy = west.getSnapshot(request -> request.snapshotName(snapshotName)).snapshot();
assertEquals("AVAILABLE", copy.statusAsString());
assertTrue(copy.snapshotArn().contains(":us-west-2:"), copy.snapshotArn());
assertEquals(source.ownerAccount(), copy.ownerAccount());
assertEquals(14, copy.snapshotRetentionPeriod());
assertTrue(west.listSnapshots(request -> request.namespaceName(namespace)).snapshots().stream()
.anyMatch(snapshot -> snapshotName.equals(snapshot.snapshotName())));
assertThrows(ResourceNotFoundException.class,
() -> east.getSnapshot(request -> request.snapshotName(snapshotName + "-missing")));
west.createNamespace(request -> request.namespaceName(restoreNamespace).adminUsername("admin")
.adminUserPassword("Password123!"));
west.createWorkgroup(request -> request.workgroupName(restoreWorkgroup)
.namespaceName(restoreNamespace));
assertEquals("AVAILABLE", west.restoreFromSnapshot(request -> request
.namespaceName(restoreNamespace).workgroupName(restoreWorkgroup)
.snapshotName(snapshotName)).namespace().statusAsString());
} finally {
cleanUp(east, west, namespace, snapshotName, restoreNamespace, restoreWorkgroup);
}
}
}
@Test
void deletingTheCopyKeepsTheSourceAndIsNotUndoneBySweeps() {
String namespace = unique("copy-del");
String snapshotName = unique("copy-snap");
try (RedshiftServerlessClient east = client(Region.US_EAST_1);
RedshiftServerlessClient west = client(Region.US_WEST_2)) {
try {
east.createNamespace(request -> request.namespaceName(namespace).adminUsername("admin")
.adminUserPassword("Password123!"));
east.createSnapshotCopyConfiguration(request -> request.namespaceName(namespace)
.destinationRegion("us-west-2"));
east.createSnapshot(request -> request.namespaceName(namespace).snapshotName(snapshotName));
scheduler.tick(Instant.now());
west.deleteSnapshot(request -> request.snapshotName(snapshotName));
scheduler.tick(Instant.now().plusSeconds(60));
assertThrows(ResourceNotFoundException.class,
() -> west.getSnapshot(request -> request.snapshotName(snapshotName)));
assertEquals("AVAILABLE", east.getSnapshot(request -> request.snapshotName(snapshotName))
.snapshot().statusAsString());
} finally {
cleanUp(east, west, namespace, snapshotName, unique("none"), unique("none"));
}
}
}
@Test
void deletingTheConfigurationStopsFurtherCopies() {
String namespace = unique("copy-off");
String snapshotName = unique("copy-snap");
try (RedshiftServerlessClient east = client(Region.US_EAST_1);
RedshiftServerlessClient west = client(Region.US_WEST_2)) {
try {
east.createNamespace(request -> request.namespaceName(namespace).adminUsername("admin")
.adminUserPassword("Password123!"));
String configurationId = east.createSnapshotCopyConfiguration(request -> request
.namespaceName(namespace).destinationRegion("us-west-2"))
.snapshotCopyConfiguration().snapshotCopyConfigurationId();
east.deleteSnapshotCopyConfiguration(request -> request
.snapshotCopyConfigurationId(configurationId));
east.createSnapshot(request -> request.namespaceName(namespace).snapshotName(snapshotName));
scheduler.tick(Instant.now());
assertThrows(ResourceNotFoundException.class,
() -> west.getSnapshot(request -> request.snapshotName(snapshotName)));
} finally {
cleanUp(east, west, namespace, snapshotName, unique("none"), unique("none"));
}
}
}
}
@@ -0,0 +1,61 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.testutil.ShutdownOrdering;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RedshiftServerlessSnapshotCopySchedulerTest {
private static final Instant NOW = Instant.parse("2030-01-07T02:00:00Z");
private final RedshiftServerlessSnapshotCopyService copies = mock(RedshiftServerlessSnapshotCopyService.class);
private RedshiftServerlessSnapshotCopyScheduler scheduler(boolean serviceEnabled, boolean copyEnabled) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().redshiftServerless().enabled()).thenReturn(serviceEnabled);
when(config.services().redshiftServerless().snapshotCopyEnabled()).thenReturn(copyEnabled);
when(config.services().redshiftServerless().snapshotCopySweepIntervalSeconds()).thenReturn(60);
return new RedshiftServerlessSnapshotCopyScheduler(copies, config);
}
@Test
void workerExistsOnlyWhenTheServiceAndTheSwitchAreBothOn() {
assertTrue(scheduler(true, true).active());
assertFalse(scheduler(true, false).active());
assertFalse(scheduler(false, true).active());
}
@Test
void shutdownObserverRunsBeforeStorageIsFlushedAndClosed() throws Exception {
ShutdownOrdering.assertStopsBeforeStorageCloses(RedshiftServerlessSnapshotCopyScheduler.class);
}
@Test
void tickRunsTheCopySweepAtTheGivenInstant() {
scheduler(true, false).tick(NOW);
verify(copies).runCopySweep(NOW);
}
@Test
void tickIsSkippedBetweenBeforeResetAndAfterReset() {
RedshiftServerlessSnapshotCopyScheduler scheduler = scheduler(true, false);
scheduler.beforeReset();
scheduler.tick(NOW);
verify(copies, never()).runCopySweep(any());
scheduler.afterReset();
scheduler.tick(NOW);
verify(copies).runCopySweep(eq(NOW));
}
}
@@ -0,0 +1,236 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
import io.github.hectorvent.floci.services.redshiftserverless.model.RedshiftServerlessSnapshot;
import io.github.hectorvent.floci.services.redshiftserverless.model.SnapshotCopyConfiguration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class RedshiftServerlessSnapshotCopyServiceTest {
private static final String REGION = "us-east-1";
private static final String DESTINATION = "us-west-2";
private static final String ACCOUNT_ID = "123456789012";
private static final String OTHER_ACCOUNT_ID = "999999999999";
private final Map<String, AccountAwareStorageBackend<?>> stores = new HashMap<>();
private RedshiftServerlessService serverless;
private RedshiftServerlessSnapshotCopyService copies;
@BeforeEach
@SuppressWarnings({"unchecked", "rawtypes"})
void setUp() {
StorageFactory storageFactory = mock(StorageFactory.class);
for (String file : List.of("namespaces", "workgroups", "snapshots", "snapshotcopyconfigurations")) {
AccountAwareStorageBackend<?> store = AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
stores.put(file, store);
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-" + file + ".json"),
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
}
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
when(regionResolver.buildArn(eq("redshift-serverless"), any(String.class), any(String.class)))
.thenAnswer(invocation -> "arn:aws:redshift-serverless:"
+ invocation.getArgument(1, String.class) + ":" + ACCOUNT_ID + ":"
+ invocation.getArgument(2, String.class));
RedshiftServerlessEndpoints endpoints = mock(RedshiftServerlessEndpoints.class);
when(endpoints.allocate()).thenReturn(new Endpoint("localhost", 7100));
RedshiftServerlessRuntime runtime = mock(RedshiftServerlessRuntime.class);
when(runtime.generatePassword()).thenReturn("Generated123");
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.storage().persistentPath()).thenReturn(System.getProperty("java.io.tmpdir"));
serverless = new RedshiftServerlessService(storageFactory, regionResolver, endpoints, runtime, config);
copies = new RedshiftServerlessSnapshotCopyService(storageFactory, regionResolver, serverless);
}
@Test
void createSnapshotCopyConfigurationStampsCreatedAt() {
serverless.createNamespace("copy-ns", "admin", "dev", null, null, List.of(), List.of(), Map.of(), REGION);
Instant before = Instant.now();
SnapshotCopyConfiguration configuration =
copies.createSnapshotCopyConfiguration("copy-ns", DESTINATION, null, null, REGION);
Instant after = Instant.now();
assertNotNull(configuration.getCreatedAt());
assertFalse(configuration.getCreatedAt().isBefore(before));
assertFalse(configuration.getCreatedAt().isAfter(after));
}
@Test
void configurationCopyConstructorCopiesCreatedAt() {
SnapshotCopyConfiguration original = new SnapshotCopyConfiguration();
Instant created = Instant.parse("2026-10-30T00:00:00Z");
original.setCreatedAt(created);
assertEquals(created, new SnapshotCopyConfiguration(original).getCreatedAt());
}
@Test
void snapshotCopyConstructorCopiesTheCopyBookkeeping() {
RedshiftServerlessSnapshot original = new RedshiftServerlessSnapshot();
original.setCopiedFromSnapshotArn("arn:aws:redshift-serverless:us-east-1:123456789012:snapshot/s");
original.setCopiedToRegions(new LinkedHashSet<>(Set.of(DESTINATION)));
RedshiftServerlessSnapshot copy = new RedshiftServerlessSnapshot(original);
copy.getCopiedToRegions().add("eu-west-1");
assertEquals(original.getCopiedFromSnapshotArn(), copy.getCopiedFromSnapshotArn());
assertEquals(Set.of(DESTINATION), original.getCopiedToRegions());
assertNotSame(original.getCopiedToRegions(), copy.getCopiedToRegions());
}
@Test
void activeRulesListsConfigurationsOfEveryAccount() {
serverless.createNamespace("copy-ns", "admin", "dev", null, null, List.of(), List.of(), Map.of(), REGION);
copies.createSnapshotCopyConfiguration("copy-ns", DESTINATION, "kms-1", 7, REGION);
seedForeignConfiguration("other-ns", "us-west-1", "eu-west-1");
List<RedshiftServerlessSnapshotCopyService.CopyRule> rules = copies.activeRules();
assertEquals(2, rules.size());
RedshiftServerlessSnapshotCopyService.CopyRule own = ruleOf(rules, ACCOUNT_ID);
assertEquals(REGION, own.sourceRegion());
assertEquals("copy-ns", own.namespaceName());
assertEquals(DESTINATION, own.destinationRegion());
assertEquals("kms-1", own.destinationKmsKeyId());
assertEquals(7, own.retentionPeriod());
assertNotNull(own.createdAt());
RedshiftServerlessSnapshotCopyService.CopyRule foreign = ruleOf(rules, OTHER_ACCOUNT_ID);
assertEquals("us-west-1", foreign.sourceRegion());
assertEquals("other-ns", foreign.namespaceName());
assertEquals("eu-west-1", foreign.destinationRegion());
}
@Test
void activeRulesDropsTheRuleOfARecreatedNamespace() {
Namespace namespace = serverless.createNamespace("copy-ns", "admin", "dev", null, null, List.of(),
List.of(), Map.of(), REGION);
copies.createSnapshotCopyConfiguration("copy-ns", DESTINATION, null, null, REGION);
Namespace recreated = new Namespace(namespace);
recreated.setNamespaceId("a-different-namespace-id");
namespaceStore().put(REGION + "::copy-ns", recreated);
assertTrue(copies.activeRules().isEmpty());
}
@Test
void activeRulesCarryTheIdOfTheirNamespace() {
Namespace namespace = serverless.createNamespace("copy-ns", "admin", "dev", null, null, List.of(),
List.of(), Map.of(), REGION);
copies.createSnapshotCopyConfiguration("copy-ns", DESTINATION, null, null, REGION);
assertEquals(namespace.getNamespaceId(), copies.activeRules().get(0).namespaceId());
}
@Test
@SuppressWarnings("unchecked")
void activeRulesBackfillTheCreationTimeOfAConfigurationThatHasNone() {
serverless.createNamespace("copy-ns", "admin", "dev", null, null, List.of(), List.of(), Map.of(), REGION);
SnapshotCopyConfiguration created =
copies.createSnapshotCopyConfiguration("copy-ns", DESTINATION, null, null, REGION);
SnapshotCopyConfiguration older = new SnapshotCopyConfiguration(created);
older.setCreatedAt(null);
((AccountAwareStorageBackend<SnapshotCopyConfiguration>) stores.get("snapshotcopyconfigurations"))
.put(REGION + "::" + created.getSnapshotCopyConfigurationId(), older);
Instant before = Instant.now();
Instant first = copies.activeRules().get(0).createdAt();
assertNotNull(first);
assertFalse(first.isBefore(before));
assertEquals(first, copies.activeRules().get(0).createdAt());
}
@Test
void activeRulesIgnoresDeletedConfigurations() {
serverless.createNamespace("copy-ns", "admin", "dev", null, null, List.of(), List.of(), Map.of(), REGION);
SnapshotCopyConfiguration configuration =
copies.createSnapshotCopyConfiguration("copy-ns", DESTINATION, null, null, REGION);
copies.deleteSnapshotCopyConfiguration(configuration.getSnapshotCopyConfigurationId(), REGION);
assertTrue(copies.activeRules().isEmpty());
}
@Test
void rejectsAnUnknownDestinationRegion() {
serverless.createNamespace("copy-ns", "admin", "dev", null, null, List.of(), List.of(), Map.of(), REGION);
AwsException failure = assertThrows(AwsException.class,
() -> copies.createSnapshotCopyConfiguration("copy-ns", "mars-north-1", null, null, REGION));
assertTrue(failure.getMessage().contains("destinationRegion"), failure.getMessage());
assertTrue(copies.activeRules().isEmpty());
}
@Test
void rejectsADestinationInAnotherPartition() {
serverless.createNamespace("copy-ns", "admin", "dev", null, null, List.of(), List.of(), Map.of(), REGION);
AwsException failure = assertThrows(AwsException.class,
() -> copies.createSnapshotCopyConfiguration("copy-ns", "cn-north-1", null, null, REGION));
assertTrue(failure.getMessage().contains("partition"), failure.getMessage());
assertTrue(copies.activeRules().isEmpty());
}
@SuppressWarnings("unchecked")
private AccountAwareStorageBackend<Namespace> namespaceStore() {
return (AccountAwareStorageBackend<Namespace>) stores.get("namespaces");
}
@SuppressWarnings("unchecked")
private void seedForeignConfiguration(String namespaceName, String region, String destination) {
Namespace namespace = new Namespace();
namespace.setNamespaceName(namespaceName);
namespace.setNamespaceId("foreign-namespace-id");
namespaceStore().putForAccount(OTHER_ACCOUNT_ID, region + "::" + namespaceName, namespace);
SnapshotCopyConfiguration configuration = new SnapshotCopyConfiguration();
configuration.setSnapshotCopyConfigurationId("foreign-configuration");
configuration.setNamespaceName(namespaceName);
configuration.setOwnerId("foreign-namespace-id");
configuration.setDestinationRegion(destination);
configuration.setCreatedAt(Instant.parse("2026-10-30T00:00:00Z"));
((AccountAwareStorageBackend<SnapshotCopyConfiguration>) stores.get("snapshotcopyconfigurations"))
.putForAccount(OTHER_ACCOUNT_ID, region + "::foreign-configuration", configuration);
}
private static RedshiftServerlessSnapshotCopyService.CopyRule ruleOf(
List<RedshiftServerlessSnapshotCopyService.CopyRule> rules, String accountId) {
return rules.stream().filter(rule -> rule.accountId().equals(accountId)).findFirst().orElseThrow();
}
@Test
void snapshotNeverExposesANullCopiedToRegions() {
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot();
assertTrue(snapshot.getCopiedToRegions().isEmpty());
snapshot.setCopiedToRegions(null);
assertTrue(snapshot.getCopiedToRegions().isEmpty());
}
}