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

@@ -454,7 +454,7 @@ class RedshiftServerlessTest {
@Test
void snapshotCopyDestinationCanChangeOnlyAfterDeletion() {
assumeFalse(TestFixtures.isRealAws(), "Asserts metadata-only snapshot copying");
assumeFalse(TestFixtures.isRealAws(), "Asserts emulator-local snapshot copy configuration rules");
try (RedshiftServerlessClient client = TestFixtures.redshiftServerlessClient()) {
String namespaceName = "floci-compat-copy-ns";
try {
+3 -3
View File
@@ -58,7 +58,7 @@ For the upstream API shape, see the [Amazon Redshift Serverless API Reference](h
| `ListCustomDomainAssociations` | Page through the associations, filtered by `customDomainName` and `customDomainCertificateArn` |
| `UpdateCustomDomainAssociation` | Point an association at another certificate ARN |
| `DeleteCustomDomainAssociation` | Remove a custom domain association |
| `CreateSnapshotCopyConfiguration` | Record a snapshot copy configuration to another Region; nothing is copied |
| `CreateSnapshotCopyConfiguration` | Copy the namespace's snapshots to another Region from now on |
| `ListSnapshotCopyConfigurations` | Page through the snapshot copy configurations, filtered by `namespaceName` |
| `UpdateSnapshotCopyConfiguration` | Change the `snapshotRetentionPeriod` of a snapshot copy configuration |
| `DeleteSnapshotCopyConfiguration` | Remove a snapshot copy configuration and return it |
@@ -141,10 +141,10 @@ aws redshift-serverless update-workgroup --workgroup-name analytics-wg --base-ca
aws redshift-serverless delete-workgroup --workgroup-name analytics-wg
aws redshift-serverless delete-namespace --namespace-name analytics
```
- **Snapshots dump the database.** While the namespace's workgroup is running, `CreateSnapshot` runs `pg_dump` on its container and stores the dump under `<persistent-path>/redshift-serverless-dumps/<account>/<region>/`. `RestoreFromSnapshot` drops every user schema (the catalog bootstrap schema excepted) and replays the dump with `psql`, stopping at the first failing statement, so rows written after the snapshot are gone. The current contents are dumped first and put back if replay or credential changes fail, and a restore whose recorded dump file has gone missing fails instead of reporting success. A snapshot taken with no running workgroup is metadata only, and restoring it leaves the database untouched. `DeleteSnapshot` removes the dump. Snapshot ARNs use the snapshot name as their id, snapshot names are 3-255 lowercase letters, digits and hyphens, and `retentionPeriod` is `-1` (indefinite, the default) or 1 to 3653 days. Snapshots are taggable by ARN. `snapshotName` and `snapshotArn` cannot be sent together. Floci's own `floci_internal` bootstrap schema, which feeds the `svv_external_*` views from the Glue catalog, is left out of both the dump and the reset, matching AWS where the Glue catalog is outside a namespace snapshot, so a client schema with that exact name is not captured. Snapshots with finite retention expire at their creation time plus the retention period. A dedicated background worker removes expired metadata, dumps and resource policies across all accounts and Regions. It runs every `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_EXPIRATION_SWEEP_INTERVAL_SECONDS` (60 by default) and can be disabled with `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_EXPIRATION_ENABLED=false`. Indefinite snapshots are preserved. Cleanup serializes with restore and retention updates. A failed cleanup remains `DELETED`, rejects restore and retention updates, and is retried on later sweeps, including after restart. Persistent and WAL storage commit the deletion marker synchronously; hybrid storage retains its periodic-flush durability. Missing dump files are treated as already removed; untrusted paths are preserved and logged. Cross-Region copy remains metadata only.
- **Snapshots dump the database.** While the namespace's workgroup is running, `CreateSnapshot` runs `pg_dump` on its container and stores the dump under `<persistent-path>/redshift-serverless-dumps/<account>/<region>/`. `RestoreFromSnapshot` drops every user schema (the catalog bootstrap schema excepted) and replays the dump with `psql`, stopping at the first failing statement, so rows written after the snapshot are gone. The current contents are dumped first and put back if replay or credential changes fail, and a restore whose recorded dump file has gone missing fails instead of reporting success. A snapshot taken with no running workgroup is metadata only, and restoring it leaves the database untouched. `DeleteSnapshot` removes the dump. Snapshot ARNs use the snapshot name as their id, snapshot names are 3-255 lowercase letters, digits and hyphens, and `retentionPeriod` is `-1` (indefinite, the default) or 1 to 3653 days. Snapshots are taggable by ARN. `snapshotName` and `snapshotArn` cannot be sent together. Floci's own `floci_internal` bootstrap schema, which feeds the `svv_external_*` views from the Glue catalog, is left out of both the dump and the reset, matching AWS where the Glue catalog is outside a namespace snapshot, so a client schema with that exact name is not captured. Snapshots with finite retention expire at their creation time plus the retention period. A dedicated background worker removes expired metadata, dumps and resource policies across all accounts and Regions. It runs every `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_EXPIRATION_SWEEP_INTERVAL_SECONDS` (60 by default) and can be disabled with `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_EXPIRATION_ENABLED=false`. Indefinite snapshots are preserved. Cleanup serializes with restore and retention updates. A failed cleanup remains `DELETED`, rejects restore and retention updates, and is retried on later sweeps, including after restart. Persistent and WAL storage commit the deletion marker synchronously; hybrid storage retains its periodic-flush durability. Missing dump files are treated as already removed; untrusted paths are preserved and logged. Cross-Region copies are described under snapshot copy configurations below, and an expired copy is removed like any other snapshot.
- **`UpdateSnapshot` changes only `retentionPeriod`.** It is validated like `CreateSnapshot` (`-1` or 1 to 3653 days), `-1` makes the snapshot indefinite, and an omitted period leaves the snapshot unchanged. `snapshotRemainingDays` keeps counting from the creation time, because Floci stores no separate retention start.
- **Resource policies are recorded, not acted on.** A policy is stored per account and Region, echoed in the shape of the API model, and dropped on read once the snapshot it belongs to is gone. A snapshot recreated under the same name is a different snapshot: the record keeps the snapshot's creation time, so the policy is not inherited. `PutResourcePolicy` accepts a JSON object for a snapshot ARN of this account and Region; no principal in it gains access. A foreign or non-snapshot ARN is a `ValidationException`.
- **Endpoint access is recorded, not acted on.** An endpoint is stored per account and Region, echoed in the shape of the API model, and dropped on read once its workgroup is gone; a workgroup recreated under the same name is a different workgroup and does not inherit it. `CreateEndpointAccess` creates no VPC endpoint. `address` and `port` are the workgroup's own, so a client can connect; `vpcEndpoint` carries a generated id and one network interface per subnet, without a `vpcId`, and `ListEndpointAccess` with a `vpcId` returns nothing. `vpcSecurityGroupIds` is optional. Endpoint names are 1 to 30 letters, digits or hyphens, start with a letter, and contain no consecutive or trailing hyphens. Security groups are the only member `UpdateEndpointAccess` changes.
- **Custom domain associations are recorded, not acted on.** An association is stored per account and Region and dropped on read once its workgroup is gone; a workgroup recreated under the same name does not inherit it. A workgroup has at most one custom domain association. The certificate expiry time comes from ACM when the certificate exists in the emulator.
- **Snapshot copy configurations are recorded, not acted on.** `CreateSnapshotCopyConfiguration` copies no snapshot. A configuration is stored per account and Region and dropped on read once its namespace is gone; a namespace recreated under the same name does not inherit it. The destination Region must differ from the namespace's, and a namespace has only one configuration at a time (`ConflictException`). Delete the existing configuration before choosing another destination Region.
- **Snapshot copy configurations copy snapshots.** A background sweep copies every `AVAILABLE` snapshot of the namespace that was taken at or after the configuration's creation into the destination Region, with its dump and metadata. It runs every `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_COPY_SWEEP_INTERVAL_SECONDS` (60 by default) and can be disabled with `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_COPY_ENABLED=false`. The copy is a snapshot of its own: it keeps the name, namespace name, owner, tags and admin user of the source, gets an ARN in the destination Region, uses `destinationKmsKeyId` as its key, and counts its `snapshotRetentionPeriod` (indefinite when omitted or `-1`) from the moment it is copied. Describe, restore, delete and expiration treat it like any other snapshot, and restoring it needs an existing namespace and workgroup in the destination Region. A copy is never copied on. The source records where it has been copied, so deleting or expiring the copy does not bring it back, and a retry or restart after a crash makes no second copy. If a snapshot of the same name that is not a copy of this source already exists in the destination Region, Floci keeps it, logs a warning and does not copy. A snapshot deleted and taken again under the same name is copied again and replaces the earlier copy of that name; each copy has its own dump file, and the earlier one is removed only after the replacement is saved, so a failed replacement leaves the earlier copy restorable. A failed copy, such as a missing dump file, leaves the source untouched and is retried by the next sweep. A crash in the middle of a copy can leave an unreferenced dump file in the destination directory, which a reset removes. `UpdateSnapshotCopyConfiguration` changes the retention of copies made afterwards, not of existing ones. Deleting the configuration stops further copies and keeps the copies already made. These are Floci choices where AWS does not say otherwise. A configuration is stored per account and Region and dropped on read once its namespace is gone; a namespace recreated under the same name does not inherit it. The destination must be a known Region in the same partition as the namespace's and must differ from it, and a namespace has only one configuration at a time (`ConflictException`). Delete the existing configuration before choosing another destination Region.
- **Scheduled actions run.** A background sweep (every `FLOCI_SERVICES_REDSHIFT_SERVERLESS_SCHEDULED_ACTION_SWEEP_INTERVAL_SECONDS`, 60 by default) takes the `createSnapshot` of each enabled action whose `at` or six-field `cron` schedule came due, in UTC and inside the `startTime` to `endTime` window. A cron expression may be wrapped as `cron(...)` and must fire at most once an hour; AWS day-of-week numbering applies (1 is Sunday). The snapshot is named `<snapshotNamePrefix>-yyyy-MM-dd-HH-mm-ss` after the scheduled time (lowercased) and keeps the action's `retentionPeriod` and tags. `nextInvocations` reports the next eligible time for both schedule types, and is empty once none remains. Floci records the invocation checkpoint with a normal atomic write after attempting the snapshot. A failure (an existing snapshot of that name, a missing namespace, a refused role) is logged and skipped while that checkpoint is retained. A crash before the checkpoint write, or before a hybrid flush, can cause the invocation to be retried; the scheduled-time snapshot name and the existing-name check prevent a duplicate snapshot. This is not exactly-once delivery. After downtime only the latest due time runs, and nothing before the action was created, rescheduled or re-enabled is replayed. That is a Floci choice, not a statement about AWS. Persistent and WAL storage commit checkpoints synchronously; hybrid storage persists them on its normal periodic flush. In memory mode actions are lost on restart. With IAM enforcement on, `roleArn` must be a role of the action's account that trusts `scheduler.redshift.amazonaws.com` and allows `redshift-serverless:CreateSnapshot` on the target namespace; otherwise nothing is created. An action is stored per account and Region and dropped on read once its namespace is gone; a namespace recreated under the same name does not inherit it. The owning `namespaceName` and the `targetAction.createSnapshot.namespaceName` must each exist but are not required to match. `startTime`, `endTime` and `at` are epoch seconds. Recovery points, snapshot expiration and cross-Region copy are not part of a scheduled action.
@@ -1917,6 +1917,12 @@ public interface EmulatorConfig {
@WithDefault("60")
int snapshotExpirationSweepIntervalSeconds();
@WithDefault("true")
boolean snapshotCopyEnabled();
@WithDefault("60")
int snapshotCopySweepIntervalSeconds();
@WithDefault("true")
boolean scheduledActionsEnabled();
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.redshift.TempCredential;
import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessSnapshotCopyService.CopyRule;
import io.github.hectorvent.floci.services.redshiftserverless.model.ConfigParameter;
import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace;
import io.github.hectorvent.floci.services.redshiftserverless.model.PricePerformanceTarget;
@@ -30,9 +31,11 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -44,6 +47,7 @@ import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ApplicationScoped
public class RedshiftServerlessService implements Resettable {
@@ -641,6 +645,12 @@ public class RedshiftServerlessService implements Resettable {
return namespaceName == null ? Optional.empty() : namespaces.get(storageKey(region, namespaceName));
}
/** Like {@link #findNamespace}, for a background sweep that acts for an account other than the ambient one. */
Optional<Namespace> findNamespaceForAccount(String accountId, String namespaceName, String region) {
return namespaceName == null ? Optional.empty()
: namespaces.getForAccount(accountId, storageKey(region, namespaceName));
}
/** The snapshot called {@code snapshotName} in {@code region}, empty when there is none. */
public Optional<RedshiftServerlessSnapshot> findSnapshot(String snapshotName, String region) {
return snapshotName == null ? Optional.empty() : snapshots.get(storageKey(region, snapshotName));
@@ -698,6 +708,151 @@ public class RedshiftServerlessService implements Resettable {
}
}
/**
* Copies the snapshots each rule has not yet carried to its destination Region. One snapshot
* failing is logged and retried by the next sweep without stopping the rest. The monitor keeps
* a copy from racing a delete, a retention change or an expiration of the same snapshot.
*/
synchronized void copySnapshots(Instant now, List<CopyRule> rules) {
for (CopyRule rule : rules) {
boolean sameNamespace = findNamespaceForAccount(rule.accountId(), rule.namespaceName(), rule.sourceRegion())
.map(namespace -> Objects.equals(namespace.getNamespaceId(), rule.namespaceId())).orElse(false);
if (!sameNamespace) {
continue;
}
for (RedshiftServerlessSnapshot snapshot : snapshots.scanForAccount(rule.accountId(),
key -> key.startsWith(rule.sourceRegion() + "::"))) {
if (!isCopyCandidate(snapshot, rule)) {
continue;
}
try {
copyToRegion(snapshot, rule, now);
} catch (IOException | RuntimeException e) {
// Without the stack: a snapshot that cannot be copied fails again every sweep.
LOG.warnv("Could not copy Redshift Serverless snapshot {0} of account {1} to {2}; will retry: {3}",
snapshot.getSnapshotName(), rule.accountId(), rule.destinationRegion(), e.getMessage());
LOG.debugv(e, "Copy failure of snapshot {0}", snapshot.getSnapshotName());
}
}
}
}
/** A copy is never copied on, and a snapshot taken before the configuration existed stays where it is. */
private static boolean isCopyCandidate(RedshiftServerlessSnapshot snapshot, CopyRule rule) {
return "AVAILABLE".equals(snapshot.getStatus())
&& snapshot.getCopiedFromSnapshotArn() == null
&& rule.namespaceName().equals(snapshot.getNamespaceName())
&& !snapshot.getCopiedToRegions().contains(rule.destinationRegion())
&& (rule.createdAt() == null || (snapshot.getSnapshotCreateTime() != null
&& !snapshot.getSnapshotCreateTime().isBefore(rule.createdAt())));
}
private void copyToRegion(RedshiftServerlessSnapshot source, CopyRule rule, Instant now) throws IOException {
String name = source.getSnapshotName();
String destinationKey = storageKey(rule.destinationRegion(), name);
RedshiftServerlessSnapshot existing = snapshots.getForAccount(rule.accountId(), destinationKey).orElse(null);
if (existing != null) {
boolean copyOfThisName = source.getSnapshotArn().equals(existing.getCopiedFromSnapshotArn());
if (copyOfThisName && Objects.equals(source.getSnapshotCreateTime(),
existing.getCopiedFromSnapshotCreateTime())) {
// A previous sweep committed this very copy and died before marking the source.
markCopied(rule, name);
return;
}
if (!copyOfThisName) {
// The name belongs to a snapshot someone else made there, which the copy must not overwrite.
LOG.warnv("Snapshot {0} of account {1} was not copied to {2}: a snapshot of that name is already there",
name, rule.accountId(), rule.destinationRegion());
markCopied(rule, name);
return;
}
// Otherwise it is the copy of an earlier snapshot that had the same name: replace it.
}
Path destinationDump = copyDump(source, rule);
RedshiftServerlessSnapshot copy = new RedshiftServerlessSnapshot(source);
copy.setRegion(rule.destinationRegion());
copy.setSnapshotArn(AwsArnUtils.Arn.of("redshift-serverless", rule.destinationRegion(), rule.accountId(),
"snapshot/" + name).toString());
copy.setStatus("AVAILABLE");
copy.setSnapshotCreateTime(now);
copy.setKmsKeyId(rule.destinationKmsKeyId());
copy.setRetentionPeriod(rule.retentionPeriod() == null || rule.retentionPeriod() == -1
? null : rule.retentionPeriod());
copy.setSqlDump(destinationDump == null ? null : destinationDump.toString());
copy.setCopiedFromSnapshotArn(source.getSnapshotArn());
copy.setCopiedFromSnapshotCreateTime(source.getSnapshotCreateTime());
copy.setCopiedToRegions(Set.of());
try {
snapshots.putAllAtomicallyForAccount(rule.accountId(), Map.of(destinationKey, copy));
} catch (RuntimeException e) {
if (destinationDump != null) {
deleteDumpQuietly(destinationDump);
}
throw e;
}
if (existing != null) {
// Only now that the new record is saved is the replaced copy's dump unreferenced.
deleteReplacedDump(existing, rule, destinationDump);
}
markCopied(rule, name);
}
/** Removes the dump of a replaced copy, if it still lies in the rule account's destination directory. */
private void deleteReplacedDump(RedshiftServerlessSnapshot replaced, CopyRule rule, Path keep) {
String stored = replaced.getSqlDump();
if (stored == null || stored.isBlank()) {
return;
}
Path old = Paths.get(stored).toAbsolutePath().normalize();
if (old.startsWith(dumpDir(rule.accountId(), rule.destinationRegion())) && !old.equals(keep)) {
deleteDumpQuietly(old);
}
}
/** Copies the source dump beside the destination snapshot, or returns {@code null} for a metadata-only snapshot. */
private Path copyDump(RedshiftServerlessSnapshot source, CopyRule rule) throws IOException {
String stored = source.getSqlDump();
if (stored == null || stored.isBlank()) {
return null;
}
Path sourceDirectory = dumpDir(rule.accountId(), rule.sourceRegion());
Path from = Paths.get(stored).toAbsolutePath().normalize();
if (!from.startsWith(sourceDirectory) || from.equals(sourceDirectory) || !Files.isRegularFile(from)) {
throw new IOException("Snapshot dump is missing or outside its account and Region directory: " + from);
}
Path destinationDirectory = dumpDir(rule.accountId(), rule.destinationRegion());
// Each copy gets its own file, so replacing an earlier copy never touches the dump it still points to.
// The name is left out: a 255-character snapshot name plus a suffix would exceed filesystem filename limits.
String copyFileName = UUID.randomUUID().toString();
Path to = destinationDirectory.resolve(copyFileName + ".sql").normalize();
Path staging = destinationDirectory.resolve(copyFileName + ".sql.copying").normalize();
if (!to.startsWith(destinationDirectory) || !staging.startsWith(destinationDirectory)) {
throw new IOException("Invalid snapshot name: " + source.getSnapshotName());
}
Files.createDirectories(destinationDirectory);
try {
Files.copy(from, staging, StandardCopyOption.REPLACE_EXISTING);
Files.move(staging, to, StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) {
deleteDumpQuietly(staging);
throw e;
}
return to;
}
/** Records that the snapshot has been carried to the rule's Region, so a deleted or expired copy stays gone. */
private void markCopied(CopyRule rule, String snapshotName) {
String key = storageKey(rule.sourceRegion(), snapshotName);
RedshiftServerlessSnapshot current = snapshots.getForAccount(rule.accountId(), key).orElse(null);
if (current == null || !"AVAILABLE".equals(current.getStatus())) {
return;
}
RedshiftServerlessSnapshot marked = new RedshiftServerlessSnapshot(current);
marked.getCopiedToRegions().add(rule.destinationRegion());
snapshots.putAllAtomicallyForAccount(rule.accountId(), Map.of(key, marked));
}
private static boolean isExpired(RedshiftServerlessSnapshot snapshot, Instant now) {
if ("DELETED".equals(snapshot.getStatus())) {
return true;
@@ -1225,6 +1380,26 @@ public class RedshiftServerlessService implements Resettable {
}
}
snapshots.clear();
deleteDumpTree();
}
/**
* Reset empties the stores before it calls {@link #clear()}, so the loop above finds no snapshot
* left to name a dump. Every dump lives under this one directory, copies included.
*/
private void deleteDumpTree() {
Path root = Paths.get(config.storage().persistentPath()).resolve("redshift-serverless-dumps")
.toAbsolutePath().normalize();
if (!Files.isDirectory(root)) {
return;
}
try (Stream<Path> paths = Files.walk(root)) {
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) {
Files.deleteIfExists(path);
}
} catch (IOException e) {
LOG.warnv(e, "Could not delete the snapshot dump directory {0} while clearing state", root);
}
}
private static void requireSnapshotName(String snapshotName) {
@@ -0,0 +1,63 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.SweepWorker;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
import jakarta.annotation.Priority;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import java.time.Instant;
/** Drives Serverless snapshot copies outside AWS request threads, one sweep at a time. */
@ApplicationScoped
public class RedshiftServerlessSnapshotCopyScheduler implements Resettable {
private final SweepWorker worker;
@Inject
public RedshiftServerlessSnapshotCopyScheduler(RedshiftServerlessSnapshotCopyService copies,
EmulatorConfig config) {
EmulatorConfig.RedshiftServerlessServiceConfig serverless = config.services().redshiftServerless();
this.worker = new SweepWorker("redshift-serverless-snapshot-copy",
serverless.enabled() && serverless.snapshotCopyEnabled(),
serverless.snapshotCopySweepIntervalSeconds(), true,
copies::runCopySweep);
}
void onStart(@Observes StartupEvent ignored) {
worker.start();
}
// Priority below APPLICATION (2000) so the worker drains before EmulatorLifecycle.onStop flushes storage.
void onStop(@Observes @Priority(1000) ShutdownEvent ignored) {
worker.stop();
}
/** Whether a background worker exists, which the two configuration switches decide. */
boolean active() {
return worker.active();
}
public void tick(Instant now) {
worker.tick(now);
}
/** Drains a running sweep so it cannot write a copy back into storage that reset is about to clear. */
@Override
public void beforeReset() {
worker.pause();
}
@Override
public void clear() {
// Copies live in RedshiftServerlessService storage, which reset wipes.
}
@Override
public void afterReset() {
worker.resume();
}
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -12,6 +13,8 @@ import io.github.hectorvent.floci.services.redshiftserverless.model.SnapshotCopy
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
@@ -57,6 +60,12 @@ public class RedshiftServerlessSnapshotCopyService implements Resettable {
if (destinationRegion.equals(region)) {
throw ServerlessSupport.validation("destinationRegion must differ from the namespace's Region.");
}
if (!AwsRegions.isRegionId(destinationRegion)) {
throw ServerlessSupport.validation("destinationRegion " + destinationRegion + " is not a known Region.");
}
if (!AwsRegions.partitionFor(destinationRegion).equals(AwsRegions.partitionFor(region))) {
throw ServerlessSupport.validation("destinationRegion must be in the same partition as the namespace's Region.");
}
validateRetention(snapshotRetentionPeriod);
Namespace namespace = serverless.findNamespace(namespaceName, region)
.orElseThrow(() -> ServerlessSupport.notFound("The namespace " + namespaceName + " was not found."));
@@ -76,6 +85,7 @@ public class RedshiftServerlessSnapshotCopyService implements Resettable {
configuration.setDestinationRegion(destinationRegion);
configuration.setDestinationKmsKeyId(destinationKmsKeyId);
configuration.setSnapshotRetentionPeriod(snapshotRetentionPeriod);
configuration.setCreatedAt(Instant.now());
configurations.put(storageKey(region, configuration.getSnapshotCopyConfigurationId()), configuration);
return new SnapshotCopyConfiguration(configuration);
}
@@ -114,6 +124,55 @@ public class RedshiftServerlessSnapshotCopyService implements Resettable {
return existing;
}
/**
* One configuration as the copy sweep needs it, with the account and Region it lives in. The
* sweep runs outside any request, so it cannot rely on the ambient account.
*/
public record CopyRule(String accountId, String sourceRegion, String namespaceName, String namespaceId,
String destinationRegion, String destinationKmsKeyId, Integer retentionPeriod,
Instant createdAt) {}
/**
* Runs one copy sweep. The monitor is held from listing the rules to the last copy, so
* deleting a configuration returns only once no copy of it is still on its way; a namespace
* recreated meanwhile is caught by the id each rule carries.
*/
public synchronized void runCopySweep(Instant now) {
serverless.copySnapshots(now, activeRules());
}
/**
* The configurations of every account whose namespace is still the one they were made for. A
* configuration left behind by a deleted or recreated namespace is skipped here and dropped by
* the next read in its own Region.
*/
public synchronized List<CopyRule> activeRules() {
List<CopyRule> rules = new ArrayList<>();
for (AccountAwareStorageBackend.AccountEntry<SnapshotCopyConfiguration> entry
: configurations.scanAllAccountEntries(key -> true)) {
SnapshotCopyConfiguration stored = entry.value();
String sourceRegion = entry.key().substring(0, entry.key().indexOf("::"));
boolean current = serverless.findNamespaceForAccount(entry.accountId(),
stored.getNamespaceName(), sourceRegion)
.map(namespace -> Objects.equals(namespace.getNamespaceId(), stored.getOwnerId()))
.orElse(false);
if (current) {
SnapshotCopyConfiguration configuration = stored;
if (configuration.getCreatedAt() == null) {
// Made before the creation time was recorded: copy from now on rather than the whole history.
configuration = new SnapshotCopyConfiguration(stored);
configuration.setCreatedAt(Instant.now());
configurations.putForAccount(entry.accountId(), entry.key(), configuration);
}
rules.add(new CopyRule(entry.accountId(), sourceRegion, configuration.getNamespaceName(),
configuration.getOwnerId(), configuration.getDestinationRegion(),
configuration.getDestinationKmsKeyId(), configuration.getSnapshotRetentionPeriod(),
configuration.getCreatedAt()));
}
}
return rules;
}
@Override
public void clear() {
configurations.clear();
@@ -5,13 +5,13 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* A Redshift Serverless snapshot. Floci stores snapshot metadata only and does not model async
* cross-region copy: a snapshot created via {@code CreateSnapshot} in the standby region is
* immediately {@code AVAILABLE} there, standing in for what a real
* {@code SnapshotCopyConfiguration} would eventually produce.
* A Redshift Serverless snapshot. A cross-region copy made for a {@code SnapshotCopyConfiguration}
* is a snapshot of its own in the destination Region, immediately {@code AVAILABLE} there.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@@ -32,6 +32,9 @@ public class RedshiftServerlessSnapshot {
private Integer retentionPeriod;
private String sqlDump;
private Map<String, String> tags = new LinkedHashMap<>();
private String copiedFromSnapshotArn;
private Instant copiedFromSnapshotCreateTime;
private Set<String> copiedToRegions = new LinkedHashSet<>();
public RedshiftServerlessSnapshot() {
}
@@ -52,6 +55,9 @@ public class RedshiftServerlessSnapshot {
this.retentionPeriod = other.retentionPeriod;
this.sqlDump = other.sqlDump;
this.tags = new LinkedHashMap<>(other.tags);
this.copiedFromSnapshotArn = other.copiedFromSnapshotArn;
this.copiedFromSnapshotCreateTime = other.copiedFromSnapshotCreateTime;
this.copiedToRegions = new LinkedHashSet<>(other.copiedToRegions);
}
public String getSnapshotName() {
@@ -175,4 +181,35 @@ public class RedshiftServerlessSnapshot {
public void setTags(Map<String, String> tags) {
this.tags = tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags);
}
/** ARN of the snapshot this one was copied from, or {@code null} for a snapshot taken here. Never in a response. */
public String getCopiedFromSnapshotArn() {
return copiedFromSnapshotArn;
}
public void setCopiedFromSnapshotArn(String copiedFromSnapshotArn) {
this.copiedFromSnapshotArn = copiedFromSnapshotArn;
}
/**
* Creation time of the source snapshot at the moment of the copy. A snapshot ARN is built from
* the name alone, so this is what tells a copy of the current source from a copy of an earlier
* snapshot that had the same name.
*/
public Instant getCopiedFromSnapshotCreateTime() {
return copiedFromSnapshotCreateTime;
}
public void setCopiedFromSnapshotCreateTime(Instant copiedFromSnapshotCreateTime) {
this.copiedFromSnapshotCreateTime = copiedFromSnapshotCreateTime;
}
/** Regions this snapshot has already been copied to, so a deleted or expired copy is not made again. */
public Set<String> getCopiedToRegions() {
return copiedToRegions;
}
public void setCopiedToRegions(Set<String> copiedToRegions) {
this.copiedToRegions = copiedToRegions == null ? new LinkedHashSet<>() : new LinkedHashSet<>(copiedToRegions);
}
}
@@ -3,9 +3,11 @@ package io.github.hectorvent.floci.services.redshiftserverless.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
/**
* A Redshift Serverless snapshot copy configuration. Floci records it but copies nothing: a snapshot
* that should appear in another Region is created there directly.
* A Redshift Serverless snapshot copy configuration. The copy sweep copies the namespace's snapshots
* into the destination Region.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@@ -18,12 +20,14 @@ public class SnapshotCopyConfiguration {
private String destinationKmsKeyId;
private Integer snapshotRetentionPeriod;
private String ownerId;
private Instant createdAt;
public SnapshotCopyConfiguration() {
}
public SnapshotCopyConfiguration(SnapshotCopyConfiguration other) {
this.ownerId = other.ownerId;
this.createdAt = other.createdAt;
this.snapshotCopyConfigurationId = other.snapshotCopyConfigurationId;
this.snapshotCopyConfigurationArn = other.snapshotCopyConfigurationArn;
this.namespaceName = other.namespaceName;
@@ -87,4 +91,13 @@ public class SnapshotCopyConfiguration {
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
/** When the configuration was created; only snapshots taken from then on are copied. Never in a response. */
public Instant getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Instant createdAt) {
this.createdAt = createdAt;
}
}
+2
View File
@@ -585,6 +585,8 @@ floci:
enabled: true
snapshot-expiration-enabled: ${FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_EXPIRATION_ENABLED:true}
snapshot-expiration-sweep-interval-seconds: ${FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_EXPIRATION_SWEEP_INTERVAL_SECONDS:60}
snapshot-copy-enabled: ${FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_COPY_ENABLED:true}
snapshot-copy-sweep-interval-seconds: ${FLOCI_SERVICES_REDSHIFT_SERVERLESS_SNAPSHOT_COPY_SWEEP_INTERVAL_SECONDS:60}
scheduled-actions-enabled: ${FLOCI_SERVICES_REDSHIFT_SERVERLESS_SCHEDULED_ACTIONS_ENABLED:true}
scheduled-action-sweep-interval-seconds: ${FLOCI_SERVICES_REDSHIFT_SERVERLESS_SCHEDULED_ACTION_SWEEP_INTERVAL_SECONDS:60}
neptune:
@@ -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());
}
}
+2
View File
@@ -253,6 +253,8 @@ floci:
enabled: true
snapshot-expiration-enabled: false
snapshot-expiration-sweep-interval-seconds: 60
snapshot-copy-enabled: false
snapshot-copy-sweep-interval-seconds: 60
scheduled-actions-enabled: false
scheduled-action-sweep-interval-seconds: 60
neptune: