feat(redshift-serverless): expire snapshots after their retention period (#6966)

* feat(redshift-serverless): expire snapshots after their retention period

* fix(redshift-serverless): stop the snapshot expiration worker before storage closes

* fix(redshift-serverless): mark pending snapshot cleanup DELETED and test the sweep lock without timing

* refactor(redshift-serverless): run snapshot expiration on a shared sweep worker
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-29 23:29:50 -04:00
1 parent 9c00c8c70e
commit 80edd853de
14 files changed
+958 -3

No files matched your search

+1 -1
View File
@@ -141,7 +141,7 @@ 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. A real snapshot expires after its retention period; Floci reports `snapshotRemainingDays` but does not expire snapshots.
- **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.
- **`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.
@@ -1909,6 +1909,12 @@ public interface EmulatorConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("true")
boolean snapshotExpirationEnabled();
@WithDefault("60")
int snapshotExpirationSweepIntervalSeconds();
@WithDefault("true")
boolean scheduledActionsEnabled();
@@ -0,0 +1,109 @@
package io.github.hectorvent.floci.core.common;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
/**
* Runs a periodic sweep on its own daemon thread, one sweep at a time. A service owns one worker and
* forwards its startup, shutdown and reset events to it; the worker has no CDI wiring of its own.
*/
public final class SweepWorker {
private static final Logger LOG = Logger.getLogger(SweepWorker.class);
private final String name;
private final Consumer<Instant> sweep;
private final long intervalSeconds;
private final boolean sweepAtStart;
private final ScheduledExecutorService executor;
private final ReentrantLock sweepLock = new ReentrantLock();
private volatile boolean paused;
/**
* @param name display name used in the thread name and log messages
* @param enabled whether a background thread exists; a disabled worker still runs {@link #tick}
* @param intervalSeconds delay between sweeps, at least one second
* @param sweepAtStart whether the first sweep runs at startup, not after one interval
* @param sweep the work, run under the sweep lock and skipped while paused
*/
public SweepWorker(String name, boolean enabled, long intervalSeconds, boolean sweepAtStart,
Consumer<Instant> sweep) {
this.name = name;
this.sweep = sweep;
this.intervalSeconds = Math.max(1, intervalSeconds);
this.sweepAtStart = sweepAtStart;
this.executor = enabled
? Executors.newSingleThreadScheduledExecutor(task -> {
Thread thread = new Thread(task, name);
thread.setDaemon(true);
return thread;
}) : null;
}
public void start() {
if (executor != null) {
executor.scheduleWithFixedDelay(this::tickSafely, sweepAtStart ? 0 : intervalSeconds, intervalSeconds, TimeUnit.SECONDS);
}
}
/** Interrupts a running sweep and waits briefly for it to end. */
public void stop() {
if (executor == null) {
return;
}
executor.shutdownNow();
try {
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
LOG.warnv("The {0} worker is still finishing a sweep during shutdown", name);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOG.debugv(e, "Interrupted while stopping the {0} worker", name);
}
}
/** Whether a background thread exists, which the owner's configuration switches decide. */
public boolean active() {
return executor != null;
}
public void tick(Instant now) {
sweepLock.lock();
try {
if (!paused) {
sweep.accept(now);
}
} finally {
sweepLock.unlock();
}
}
/** Stops new sweeps and waits for a running one, so it cannot write into storage that reset is about to clear. */
public void pause() {
paused = true;
sweepLock.lock();
sweepLock.unlock();
}
public void resume() {
paused = false;
}
/** Threads waiting for the running sweep, which lets tests observe blocking without timing. */
public int queuedSweeps() {
return sweepLock.getQueueLength();
}
private void tickSafely() {
try {
tick(Instant.now());
} catch (RuntimeException e) {
LOG.warnv(e, "The {0} sweep failed", name);
}
}
}
@@ -17,6 +17,7 @@ import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/**
* Resource policies for Redshift Serverless snapshots. A policy is stored and echoed, not
@@ -47,6 +48,9 @@ public class RedshiftServerlessResourcePolicyService implements Resettable {
requireJsonObject(policy);
RedshiftServerlessSnapshot snapshot = findSnapshot(resourceArn, region)
.orElseThrow(() -> ServerlessSupport.notFound("The resource " + resourceArn + " was not found."));
if (!"AVAILABLE".equals(snapshot.getStatus())) {
throw ServerlessSupport.conflict("The snapshot is not available.");
}
ResourcePolicy stored = new ResourcePolicy(resourceArn, policy);
stored.setSnapshotCreateTime(snapshot.getSnapshotCreateTime());
policies.put(storageKey(region, resourceArn), stored);
@@ -63,6 +67,17 @@ public class RedshiftServerlessResourcePolicyService implements Resettable {
policies.delete(storageKey(region, resourceArn));
}
synchronized void deleteExpiredSnapshotPolicy(
AccountAwareStorageBackend.AccountEntry<RedshiftServerlessSnapshot> entry) {
RedshiftServerlessSnapshot snapshot = entry.value();
String region = entry.key().substring(0, entry.key().indexOf("::"));
String key = storageKey(region, snapshot.getSnapshotArn());
policies.getForAccountMigratingLegacy(entry.accountId(), key,
legacy -> policies.getLegacyForAccount(entry.accountId(), key).isPresent())
.filter(policy -> Objects.equals(policy.getSnapshotCreateTime(), snapshot.getSnapshotCreateTime()))
.ifPresent(policy -> policies.deleteAllAtomicallyForAccounts(Map.of(entry.accountId(), Set.of(key))));
}
@Override
public void clear() {
policies.clear();
@@ -31,6 +31,7 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@@ -564,9 +565,13 @@ public class RedshiftServerlessService implements Resettable {
/** Absolute, normalised {@code <persistentPath>/redshift-serverless-dumps/<accountId>/<region>} directory. */
private Path dumpDir(String region) {
return dumpDir(workgroups.accountId(), region);
}
private Path dumpDir(String accountId, String region) {
return Paths.get(config.storage().persistentPath())
.resolve("redshift-serverless-dumps")
.resolve(workgroups.accountId())
.resolve(accountId)
.resolve(region)
.toAbsolutePath()
.normalize();
@@ -649,6 +654,7 @@ public class RedshiftServerlessService implements Resettable {
public synchronized RedshiftServerlessSnapshot updateSnapshot(String snapshotName, Integer retentionPeriod,
String region) {
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot(getSnapshot(snapshotName, region));
requireAvailableSnapshot(snapshot);
if (retentionPeriod != null) {
snapshot.setRetentionPeriod(validateRetentionPeriod(retentionPeriod));
snapshots.put(storageKey(region, snapshotName), snapshot);
@@ -658,11 +664,70 @@ public class RedshiftServerlessService implements Resettable {
public synchronized RedshiftServerlessSnapshot deleteSnapshot(String snapshotName, String region) {
RedshiftServerlessSnapshot deleted = getSnapshot(snapshotName, region);
requireAvailableSnapshot(deleted);
snapshots.delete(storageKey(region, snapshotName));
trustedDump(deleted, region).ifPresent(RedshiftServerlessService::deleteDumpQuietly);
return deleted;
}
/** The monitor also protects restore, retention changes and snapshot creation from cleanup. */
synchronized void expireSnapshots(Instant now,
Consumer<AccountAwareStorageBackend.AccountEntry<RedshiftServerlessSnapshot>> deletePolicy) {
for (AccountAwareStorageBackend.AccountEntry<RedshiftServerlessSnapshot> entry
: snapshots.scanAllAccountEntries(key -> true)) {
try {
// The scan assigns unprefixed entries to the default account; never claim them for another account.
RedshiftServerlessSnapshot snapshot = snapshots.getForAccountMigratingLegacy(
entry.accountId(), entry.key(), legacy -> snapshots
.getLegacyForAccount(entry.accountId(), entry.key()).isPresent())
.orElse(null);
if (snapshot == null || !isExpired(snapshot, now)) {
continue;
}
RedshiftServerlessSnapshot deleting = new RedshiftServerlessSnapshot(snapshot);
deleting.setStatus("DELETED");
snapshots.putAllAtomicallyForAccount(entry.accountId(), Map.of(entry.key(), deleting));
deleteExpiredDump(deleting, entry.accountId(), regionOf(entry.key()));
deletePolicy.accept(new AccountAwareStorageBackend.AccountEntry<>(
entry.accountId(), entry.key(), deleting));
snapshots.deleteAllAtomicallyForAccounts(Map.of(entry.accountId(), Set.of(entry.key())));
} catch (IOException | RuntimeException e) {
LOG.warnv(e, "Could not expire Redshift Serverless snapshot {0} for account {1}; will retry",
entry.key(), entry.accountId());
}
}
}
private static boolean isExpired(RedshiftServerlessSnapshot snapshot, Instant now) {
if ("DELETED".equals(snapshot.getStatus())) {
return true;
}
Integer retention = snapshot.getRetentionPeriod();
return "AVAILABLE".equals(snapshot.getStatus()) && retention != null && retention > 0
&& snapshot.getSnapshotCreateTime() != null
&& !now.isBefore(snapshot.getSnapshotCreateTime().plus(retention, ChronoUnit.DAYS));
}
private void deleteExpiredDump(RedshiftServerlessSnapshot snapshot, String accountId, String region)
throws IOException {
String stored = snapshot.getSqlDump();
if (stored == null || stored.isBlank()) {
return;
}
Path dump = Paths.get(stored).toAbsolutePath().normalize();
Path directory = dumpDir(accountId, region);
if (!dump.startsWith(directory) || dump.equals(directory)) {
throw new IOException("Snapshot dump is outside its account and Region directory: " + dump);
}
Files.deleteIfExists(dump);
}
private static void requireAvailableSnapshot(RedshiftServerlessSnapshot snapshot) {
if (!"AVAILABLE".equals(snapshot.getStatus())) {
throw ServerlessSupport.conflict("The snapshot " + snapshot.getSnapshotName() + " is not available.");
}
}
/**
* Lists the Region's snapshots, narrowed by every filter that is supplied: the namespace by
* name or ARN, the owning account, and a creation-time window that includes both ends.
@@ -704,6 +769,7 @@ public class RedshiftServerlessService implements Resettable {
validateManagedPassword(manageAdminPassword, null, adminPasswordSecretKmsKeyId);
validateNamespaceName(namespaceName);
RedshiftServerlessSnapshot snapshot = getSnapshot(snapshotName, region);
requireAvailableSnapshot(snapshot);
if (ownerAccount != null && !ownerAccount.isBlank() && !ownerAccount.equals(snapshot.getOwnerAccount())) {
throw snapshotNotFound(snapshotName);
}
@@ -0,0 +1,64 @@
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 expirations outside AWS request threads, one sweep at a time. */
@ApplicationScoped
public class RedshiftServerlessSnapshotExpirationScheduler implements Resettable {
private final SweepWorker worker;
@Inject
public RedshiftServerlessSnapshotExpirationScheduler(RedshiftServerlessService service,
RedshiftServerlessResourcePolicyService policies,
EmulatorConfig config) {
EmulatorConfig.RedshiftServerlessServiceConfig serverless = config.services().redshiftServerless();
this.worker = new SweepWorker("redshift-serverless-snapshot-expiration",
serverless.enabled() && serverless.snapshotExpirationEnabled(),
serverless.snapshotExpirationSweepIntervalSeconds(), true,
now -> service.expireSnapshots(now, policies::deleteExpiredSnapshotPolicy));
}
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 snapshot back into storage that reset is about to clear. */
@Override
public void beforeReset() {
worker.pause();
}
@Override
public void clear() {
// Snapshot state lives in RedshiftServerlessService storage, which reset wipes.
}
@Override
public void afterReset() {
worker.resume();
}
}
+2
View File
@@ -583,6 +583,8 @@ floci:
shutdown-timeout-seconds: ${FLOCI_SERVICES_REDSHIFT_DATA_SHUTDOWN_TIMEOUT_SECONDS:10}
redshift-serverless:
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}
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,177 @@
package io.github.hectorvent.floci.core.common;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.*;
class SweepWorkerTest {
private static final Instant NOW = Instant.parse("2030-01-07T02:00:00Z");
private final List<Instant> swept = new CopyOnWriteArrayList<>();
private SweepWorker worker(boolean enabled, Consumer<Instant> sweep) {
return new SweepWorker("test-sweep", enabled, 60, false, sweep);
}
private static void awaitQueuedSweeps(SweepWorker worker, int expected) {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (worker.queuedSweeps() < expected) {
assertTrue(System.nanoTime() < deadline, "Expected " + expected + " thread(s) waiting for the sweep");
Thread.onSpinWait();
}
}
@Test
void backgroundThreadExistsOnlyWhenEnabled() {
assertTrue(worker(true, swept::add).active());
assertFalse(worker(false, swept::add).active());
}
@Test
void tickRunsTheSweepAtTheGivenInstantEvenWithoutABackgroundThread() {
worker(false, swept::add).tick(NOW);
assertEquals(List.of(NOW), swept);
}
@Test
void tickIsSkippedBetweenPauseAndResume() {
SweepWorker worker = worker(false, swept::add);
worker.pause();
worker.tick(NOW);
assertTrue(swept.isEmpty());
worker.resume();
worker.tick(NOW);
assertEquals(List.of(NOW), swept);
}
@Test
void pauseDrainsARunningSweepAndHoldsLaterOnesUntilResume() throws Exception {
CountDownLatch running = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
SweepWorker worker = worker(false, now -> {
swept.add(now);
running.countDown();
try {
release.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Future<?> sweep = executor.submit(() -> worker.tick(NOW));
assertTrue(running.await(5, TimeUnit.SECONDS));
Future<?> pause = executor.submit(worker::pause);
awaitQueuedSweeps(worker, 1);
assertFalse(pause.isDone());
release.countDown();
pause.get(5, TimeUnit.SECONDS);
sweep.get(5, TimeUnit.SECONDS);
worker.tick(NOW.plusSeconds(60));
assertEquals(List.of(NOW), swept);
worker.resume();
worker.tick(NOW.plusSeconds(120));
assertEquals(List.of(NOW, NOW.plusSeconds(120)), swept);
} finally {
release.countDown();
executor.shutdownNow();
}
}
@Test
void overlappingTicksNeverRunTheSweepConcurrently() throws Exception {
AtomicInteger concurrent = new AtomicInteger();
AtomicInteger peak = new AtomicInteger();
CountDownLatch running = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
SweepWorker worker = worker(false, now -> {
peak.accumulateAndGet(concurrent.incrementAndGet(), Math::max);
running.countDown();
try {
release.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
concurrent.decrementAndGet();
});
ExecutorService executor = Executors.newFixedThreadPool(3);
try {
Future<?> first = executor.submit(() -> worker.tick(NOW));
assertTrue(running.await(5, TimeUnit.SECONDS));
Future<?> second = executor.submit(() -> worker.tick(NOW));
Future<?> third = executor.submit(() -> worker.tick(NOW));
awaitQueuedSweeps(worker, 2);
assertEquals(1, concurrent.get());
release.countDown();
first.get(5, TimeUnit.SECONDS);
second.get(5, TimeUnit.SECONDS);
third.get(5, TimeUnit.SECONDS);
} finally {
release.countDown();
executor.shutdownNow();
}
assertEquals(1, peak.get());
}
@Test
void aFailedSweepReleasesTheLock() {
List<Instant> attempts = new ArrayList<>();
SweepWorker worker = worker(false, now -> {
attempts.add(now);
if (attempts.size() == 1) {
throw new IllegalStateException("boom");
}
});
assertThrows(IllegalStateException.class, () -> worker.tick(NOW));
worker.tick(NOW.plusSeconds(60));
assertEquals(List.of(NOW, NOW.plusSeconds(60)), attempts);
}
@Test
void startRunsTheFirstSweepAtOnceWhenAskedTo() throws Exception {
CountDownLatch first = new CountDownLatch(1);
SweepWorker worker = new SweepWorker("test-sweep", true, 3600, true, now -> first.countDown());
try {
worker.start();
assertTrue(first.await(5, TimeUnit.SECONDS));
} finally {
worker.stop();
}
}
@Test
void startWaitsOneIntervalBeforeTheFirstSweepByDefault() throws Exception {
CountDownLatch first = new CountDownLatch(1);
SweepWorker worker = new SweepWorker("test-sweep", true, 3600, false, now -> first.countDown());
try {
worker.start();
assertEquals(1, first.getCount());
} finally {
worker.stop();
}
}
@Test
void stopWithoutABackgroundThreadDoesNothing() {
SweepWorker worker = worker(false, swept::add);
worker.start();
worker.stop();
assertTrue(swept.isEmpty());
}
}
@@ -0,0 +1,98 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
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.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.redshiftserverless.model.RedshiftServerlessSnapshot;
import io.github.hectorvent.floci.services.redshiftserverless.model.ResourcePolicy;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.Instant;
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.mock;
import static org.mockito.Mockito.when;
class RedshiftServerlessResourcePolicyExpirationTest {
@ParameterizedTest
@ValueSource(booleans = {false, true})
@SuppressWarnings({"unchecked", "rawtypes"})
void expirationRemovesLegacySnapshotAndPolicyWithoutAnApiReadFirst(boolean scopedSnapshot) {
String account = "123456789012";
String region = "us-east-1";
String arn = "arn:aws:redshift-serverless:us-east-1:123456789012:snapshot/legacy-snap";
InMemoryStorage<String, RedshiftServerlessSnapshot> rawSnapshots = new InMemoryStorage<>();
InMemoryStorage<String, ResourcePolicy> rawPolicies = new InMemoryStorage<>();
AccountAwareStorageBackend<RedshiftServerlessSnapshot> snapshots =
new AccountAwareStorageBackend<>(rawSnapshots, null, account);
AccountAwareStorageBackend<ResourcePolicy> policies = new AccountAwareStorageBackend<>(rawPolicies, null, account);
StorageFactory factory = mock(StorageFactory.class);
when(factory.create(eq("redshiftserverless"), eq("redshiftserverless-snapshots.json"),
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) snapshots);
when(factory.create(eq("redshiftserverless"), eq("redshiftserverless-resourcepolicies.json"),
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) policies);
RedshiftServerlessService serverless = new RedshiftServerlessService(factory,
new RegionResolver(region, account), mock(RedshiftServerlessEndpoints.class),
mock(RedshiftServerlessRuntime.class), mock(EmulatorConfig.class));
RedshiftServerlessResourcePolicyService service = new RedshiftServerlessResourcePolicyService(
factory, serverless, new ObjectMapper());
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot();
snapshot.setSnapshotName("legacy-snap");
snapshot.setSnapshotArn(arn);
snapshot.setSnapshotCreateTime(Instant.EPOCH);
snapshot.setRetentionPeriod(1);
ResourcePolicy policy = new ResourcePolicy(arn, "{}");
policy.setSnapshotCreateTime(Instant.EPOCH);
rawSnapshots.put((scopedSnapshot ? account + "/" : "") + region + "::legacy-snap", snapshot);
rawPolicies.put(region + "::" + arn, policy);
serverless.expireSnapshots(Instant.EPOCH.plusSeconds(86400), service::deleteExpiredSnapshotPolicy);
assertTrue(rawSnapshots.keys().isEmpty());
assertTrue(rawPolicies.keys().isEmpty());
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void expirationRemovesOnlyThePolicyOfThatAccountAndSnapshotGeneration() {
String account = "123456789012";
String otherAccount = "999999999999";
String region = "us-east-1";
String arn = "arn:aws:redshift-serverless:us-east-1:123456789012:snapshot/expiry-snap";
String key = region + "::" + arn;
Instant created = Instant.parse("2030-01-01T00:00:00Z");
AccountAwareStorageBackend<ResourcePolicy> store = AccountAwareStorageBackend.inMemory(account);
StorageFactory factory = mock(StorageFactory.class);
when(factory.create(eq("redshiftserverless"), eq("redshiftserverless-resourcepolicies.json"),
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) store);
RedshiftServerlessResourcePolicyService service = new RedshiftServerlessResourcePolicyService(
factory, mock(RedshiftServerlessService.class), new ObjectMapper());
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot();
snapshot.setSnapshotArn(arn);
snapshot.setSnapshotCreateTime(created);
ResourcePolicy policy = new ResourcePolicy(arn, "{}");
policy.setSnapshotCreateTime(created);
store.putForAccount(account, key, policy);
store.putForAccount(otherAccount, key, policy);
AccountAwareStorageBackend.AccountEntry<RedshiftServerlessSnapshot> entry =
new AccountAwareStorageBackend.AccountEntry<>(account, region + "::expiry-snap", snapshot);
service.deleteExpiredSnapshotPolicy(entry);
service.deleteExpiredSnapshotPolicy(entry);
assertTrue(store.getForAccount(account, key).isEmpty());
assertTrue(store.getForAccount(otherAccount, key).isPresent());
ResourcePolicy replacement = new ResourcePolicy(arn, "{}");
replacement.setSnapshotCreateTime(created.plusSeconds(1));
store.putForAccount(account, key, replacement);
service.deleteExpiredSnapshotPolicy(entry);
assertTrue(store.getForAccount(account, key).isPresent());
}
}
@@ -27,7 +27,14 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -56,6 +63,7 @@ class RedshiftServerlessServiceTest {
private RedshiftServerlessService service;
private AccountAwareStorageBackend<Namespace> store;
private AccountAwareStorageBackend<Workgroup> workgroupStore;
private AccountAwareStorageBackend<RedshiftServerlessSnapshot> snapshotStore;
private RedshiftServerlessEndpoints endpoints;
private RedshiftServerlessRuntime runtime;
private int nextPort;
@@ -78,8 +86,9 @@ class RedshiftServerlessServiceTest {
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-workgroups.json"),
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) workgroupStore);
snapshotStore = spy(AccountAwareStorageBackend.inMemory(ACCOUNT_ID));
when(storageFactory.create(eq("redshiftserverless"), eq("redshiftserverless-snapshots.json"),
any(TypeReference.class))).thenReturn(AccountAwareStorageBackend.inMemory(ACCOUNT_ID));
any(TypeReference.class))).thenReturn((AccountAwareStorageBackend) snapshotStore);
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
@@ -104,6 +113,180 @@ class RedshiftServerlessServiceTest {
service = new RedshiftServerlessService(storageFactory, regionResolver, endpoints, runtime, config);
}
@Test
void expirationHonorsTheExactBoundaryAndIndefiniteRetention() {
create("expiry-ns");
RedshiftServerlessSnapshot finite = service.createSnapshot("finite-snap", "expiry-ns", 1, null, REGION);
service.createSnapshot("default-snap", "expiry-ns", null, null, REGION);
service.createSnapshot("indefinite-snap", "expiry-ns", -1, null, REGION);
Instant deadline = finite.getSnapshotCreateTime().plusSeconds(86400);
service.expireSnapshots(deadline.minusNanos(1), entry -> { });
assertTrue(service.findSnapshot("finite-snap", REGION).isPresent());
service.expireSnapshots(deadline, entry -> { });
assertTrue(service.findSnapshot("finite-snap", REGION).isEmpty());
service.expireSnapshots(deadline.plusSeconds(86400 * 4000L), entry -> { });
assertTrue(service.findSnapshot("default-snap", REGION).isPresent());
assertTrue(service.findSnapshot("indefinite-snap", REGION).isPresent());
}
@Test
void expirationUsesUpdatedRetentionFromTheOriginalCreationTime() {
create("expiry-ns");
RedshiftServerlessSnapshot snapshot = service.createSnapshot("extend-snap", "expiry-ns", 1, null, REGION);
Instant created = snapshot.getSnapshotCreateTime();
service.updateSnapshot("extend-snap", 3, REGION);
service.expireSnapshots(created.plusSeconds(86400), entry -> { });
assertTrue(service.findSnapshot("extend-snap", REGION).isPresent());
service.updateSnapshot("extend-snap", 1, REGION);
service.expireSnapshots(created.plusSeconds(86400), entry -> { });
assertTrue(service.findSnapshot("extend-snap", REGION).isEmpty());
}
@Test
void expirationDeletesDumpsAcrossAccountsAndRegionsAndIsIdempotent() throws Exception {
Instant created = Instant.parse("2030-01-01T00:00:00Z");
for (String account : List.of(ACCOUNT_ID, "999999999999")) {
for (String region : List.of(REGION, "cn-north-1")) {
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot();
snapshot.setSnapshotName("same-snap");
snapshot.setSnapshotCreateTime(created);
snapshot.setRetentionPeriod(1);
Path dump = dumpDir.resolve("redshift-serverless-dumps").resolve(account).resolve(region)
.resolve("same-snap.sql");
Files.createDirectories(dump.getParent());
Files.writeString(dump, "data");
snapshot.setSqlDump(dump.toString());
snapshotStore.putForAccount(account, region + "::same-snap", snapshot);
}
}
service.expireSnapshots(created.plusSeconds(86400), entry -> { });
service.expireSnapshots(created.plusSeconds(86400), entry -> { });
assertTrue(snapshotStore.scanAllAccounts().isEmpty());
try (Stream<Path> files = Files.walk(dumpDir)) {
assertEquals(0, files.filter(Files::isRegularFile).count());
}
}
@Test
void expirationRetriesAFailedDumpAndContinuesOtherSnapshots() throws Exception {
create("expiry-ns");
RedshiftServerlessSnapshot failed = service.createSnapshot("failed-snap", "expiry-ns", 1, null, REGION);
RedshiftServerlessSnapshot other = service.createSnapshot("other-snap", "expiry-ns", 1, null, REGION);
Path dump = dumpDir.resolve("redshift-serverless-dumps").resolve(ACCOUNT_ID).resolve(REGION)
.resolve("failed-snap.sql");
Files.createDirectories(dump);
Path blocker = Files.writeString(dump.resolve("blocker"), "not an empty directory");
failed.setSqlDump(dump.toString());
Instant now = other.getSnapshotCreateTime().plusSeconds(86400);
service.expireSnapshots(now, entry -> { });
assertEquals("DELETED", service.getSnapshot("failed-snap", REGION).getStatus());
assertTrue(service.findSnapshot("other-snap", REGION).isEmpty());
assertEquals("ConflictException", assertThrows(AwsException.class,
() -> service.updateSnapshot("failed-snap", -1, REGION)).getErrorCode());
assertEquals("ConflictException", assertThrows(AwsException.class,
() -> service.restoreFromSnapshot("expiry-ns", "any-workgroup", "failed-snap", null, REGION))
.getErrorCode());
Files.delete(blocker);
service.expireSnapshots(now, entry -> { });
assertTrue(service.findSnapshot("failed-snap", REGION).isEmpty());
assertFalse(Files.exists(dump));
}
@Test
void expirationRetriesPersistedDeletionAndPolicyFailures() {
create("expiry-ns");
RedshiftServerlessSnapshot snapshot = service.createSnapshot("retry-snap", "expiry-ns", null, null, REGION);
snapshot.setStatus("DELETED");
service.expireSnapshots(Instant.EPOCH, entry -> {
throw new IllegalStateException("policy store unavailable");
});
assertTrue(service.findSnapshot("retry-snap", REGION).isPresent());
service.expireSnapshots(Instant.EPOCH, entry -> { });
assertTrue(service.findSnapshot("retry-snap", REGION).isEmpty());
}
@Test
void expirationNeverDeletesAnUntrustedDump() throws Exception {
create("expiry-ns");
RedshiftServerlessSnapshot snapshot = service.createSnapshot("untrusted-snap", "expiry-ns", 1, null, REGION);
Path outside = Files.writeString(dumpDir.resolve("outside.sql"), "unrelated");
snapshot.setSqlDump(outside.toString());
service.expireSnapshots(snapshot.getSnapshotCreateTime().plusSeconds(86400), entry -> { });
assertTrue(Files.exists(outside));
assertTrue(service.findSnapshot("untrusted-snap", REGION).isPresent());
}
@Test
void expirationWaitsForAnInProgressRestore() throws Exception {
create("restore-expiry-ns");
createWorkgroup("restore-expiry-wg", "restore-expiry-ns");
doAnswer(invocation -> {
Files.writeString(invocation.getArgument(5, Path.class), "snapshot data");
return null;
}).when(runtime).takeSnapshot(any(), any(), any(), any(), any(), any());
RedshiftServerlessSnapshot snapshot = service.createSnapshot(
"restore-expiry-snap", "restore-expiry-ns", 1, null, REGION);
CountDownLatch restoring = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(invocation -> {
restoring.countDown();
assertTrue(release.await(10, TimeUnit.SECONDS));
assertTrue(Files.exists(invocation.getArgument(5, Path.class)));
return null;
}).when(runtime).restoreSnapshot(any(), any(), any(), any(), any(), any(), any());
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Future<?> restore = executor.submit(() -> service.restoreFromSnapshot(
"restore-expiry-ns", "restore-expiry-wg", "restore-expiry-snap", null, REGION));
assertTrue(restoring.await(5, TimeUnit.SECONDS));
Future<?> sweep = executor.submit(() -> service.expireSnapshots(
snapshot.getSnapshotCreateTime().plusSeconds(86400), entry -> { }));
assertThrows(TimeoutException.class, () -> sweep.get(200, TimeUnit.MILLISECONDS));
release.countDown();
restore.get(5, TimeUnit.SECONDS);
sweep.get(5, TimeUnit.SECONDS);
assertTrue(service.findSnapshot("restore-expiry-snap", REGION).isEmpty());
} finally {
release.countDown();
executor.shutdownNow();
}
}
@Test
void expirationRetainsMetadataWhenTheFinalStorageDeleteFails() {
create("expiry-ns");
RedshiftServerlessSnapshot snapshot = service.createSnapshot("store-fail-snap", "expiry-ns", 1, null, REGION);
doThrow(new IllegalStateException("storage unavailable")).doCallRealMethod()
.when(snapshotStore).deleteAllAtomicallyForAccounts(any());
Instant deadline = snapshot.getSnapshotCreateTime().plusSeconds(86400);
service.expireSnapshots(deadline, entry -> { });
assertEquals("DELETED", service.getSnapshot("store-fail-snap", REGION).getStatus());
service.expireSnapshots(deadline, entry -> { });
assertTrue(service.findSnapshot("store-fail-snap", REGION).isEmpty());
}
@Test
void expirationNeverDeletesDataWhenTheDeletionMarkerCannotBeStored() throws Exception {
create("expiry-ns");
RedshiftServerlessSnapshot snapshot = service.createSnapshot("marker-fail-snap", "expiry-ns", 1, null, REGION);
Path dump = dumpDir.resolve("redshift-serverless-dumps").resolve(ACCOUNT_ID).resolve(REGION)
.resolve("marker-fail-snap.sql");
Files.createDirectories(dump.getParent());
Files.writeString(dump, "data");
snapshot.setSqlDump(dump.toString());
doThrow(new IllegalStateException("storage unavailable")).when(snapshotStore)
.putAllAtomicallyForAccount(any(), any());
service.expireSnapshots(snapshot.getSnapshotCreateTime().plusSeconds(86400), entry -> {
throw new AssertionError("Policy cleanup must not run before the deletion marker is stored");
});
assertEquals("AVAILABLE", service.getSnapshot("marker-fail-snap", REGION).getStatus());
assertTrue(Files.exists(dump));
}
@Test
void createAppliesAwsDefaultsAndAUniqueNamespaceId() {
Namespace first = create("first-ns");
@@ -0,0 +1,76 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import io.github.hectorvent.floci.testing.PartitionCleanup;
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.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
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;
@QuarkusTest
class RedshiftServerlessSnapshotExpirationIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@InjectMock
RedshiftServerlessRuntime runtime;
@Inject
RedshiftServerlessSnapshotExpirationScheduler scheduler;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void sdkObservesExpirationAndRecreationWithoutInheritingPolicy() {
String namespace = "expiry-" + UUID.randomUUID().toString().substring(0, 8);
try (RedshiftServerlessClient client = RedshiftServerlessClient.builder().endpointOverride(endpoint)
.region(Region.US_EAST_1).credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("test", "test"))).build()) {
client.createNamespace(request -> request.namespaceName(namespace).adminUsername("admin")
.adminUserPassword("Password123!"));
Snapshot finite = client.createSnapshot(request -> request.namespaceName(namespace)
.snapshotName(namespace + "-finite").retentionPeriod(1)).snapshot();
Snapshot indefinite = client.createSnapshot(request -> request.namespaceName(namespace)
.snapshotName(namespace + "-indefinite").retentionPeriod(-1)).snapshot();
client.putResourcePolicy(request -> request.resourceArn(finite.snapshotArn()).policy("{}"));
Instant deadline = finite.snapshotCreateTime().plusSeconds(86400);
scheduler.tick(deadline.minusSeconds(1));
assertEquals("AVAILABLE", client.getSnapshot(request -> request.snapshotName(finite.snapshotName()))
.snapshot().statusAsString());
scheduler.tick(deadline.plusSeconds(1));
assertThrows(ResourceNotFoundException.class,
() -> client.getSnapshot(request -> request.snapshotName(finite.snapshotName())));
assertThrows(ResourceNotFoundException.class,
() -> client.getSnapshot(request -> request.snapshotArn(finite.snapshotArn())));
assertThrows(ResourceNotFoundException.class,
() -> client.updateSnapshot(request -> request.snapshotName(finite.snapshotName()).retentionPeriod(7)));
assertThrows(ResourceNotFoundException.class,
() -> client.getResourcePolicy(request -> request.resourceArn(finite.snapshotArn())));
assertTrue(client.listSnapshots(request -> request.namespaceName(namespace)).snapshots().stream()
.noneMatch(snapshot -> finite.snapshotName().equals(snapshot.snapshotName())));
assertEquals(indefinite.snapshotName(), client.getSnapshot(request -> request
.snapshotName(indefinite.snapshotName())).snapshot().snapshotName());
client.createSnapshot(request -> request.namespaceName(namespace).snapshotName(finite.snapshotName()));
assertThrows(ResourceNotFoundException.class,
() -> client.getResourcePolicy(request -> request.resourceArn(finite.snapshotArn())));
}
}
}
@@ -0,0 +1,71 @@
package io.github.hectorvent.floci.services.redshiftserverless;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.quarkus.runtime.ShutdownEvent;
import jakarta.annotation.Priority;
import jakarta.interceptor.Interceptor;
import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.time.Instant;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.*;
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 RedshiftServerlessSnapshotExpirationSchedulerTest {
private static final Instant NOW = Instant.parse("2030-01-07T02:00:00Z");
private final RedshiftServerlessService service = mock(RedshiftServerlessService.class);
private RedshiftServerlessSnapshotExpirationScheduler scheduler(boolean serviceEnabled, boolean actionsEnabled) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().redshiftServerless().enabled()).thenReturn(serviceEnabled);
when(config.services().redshiftServerless().snapshotExpirationEnabled()).thenReturn(actionsEnabled);
when(config.services().redshiftServerless().snapshotExpirationSweepIntervalSeconds()).thenReturn(60);
return new RedshiftServerlessSnapshotExpirationScheduler(service, mock(RedshiftServerlessResourcePolicyService.class), config);
}
@Test
void workerExistsOnlyWhenTheServiceAndTheSwitchAreBothOn() {
assertTrue(scheduler(true, true).active());
assertFalse(scheduler(true, false).active());
assertFalse(scheduler(false, true).active());
}
@Test
void shutdownObserverRunsBeforeStorageIsFlushedAndClosed() throws Exception {
Method onStop = RedshiftServerlessSnapshotExpirationScheduler.class
.getDeclaredMethod("onStop", ShutdownEvent.class);
Annotation priority = Arrays.stream(onStop.getParameterAnnotations()[0])
.filter(Priority.class::isInstance)
.findFirst()
.orElseThrow();
assertTrue(((Priority) priority).value() < Interceptor.Priority.APPLICATION);
}
@Test
void tickRunsTheSweepAtTheGivenInstant() {
scheduler(true, false).tick(NOW);
verify(service).expireSnapshots(eq(NOW), any());
}
@Test
void tickIsSkippedBetweenBeforeResetAndAfterReset() {
RedshiftServerlessSnapshotExpirationScheduler scheduler = scheduler(true, false);
scheduler.beforeReset();
scheduler.tick(NOW);
verify(service, never()).expireSnapshots(any(), any());
scheduler.afterReset();
scheduler.tick(NOW);
verify(service).expireSnapshots(eq(NOW), any());
}
}
@@ -0,0 +1,86 @@
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.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.redshiftserverless.model.RedshiftServerlessSnapshot;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class RedshiftServerlessSnapshotExpirationStorageTest {
private static final String ACCOUNT = "123456789012";
private static final String REGION = "us-east-1";
@TempDir
Path directory;
@ParameterizedTest
@ValueSource(strings = {"memory", "persistent", "hybrid", "wal"})
void deletionResumesAfterStorageReload(String mode) throws Exception {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.storage().persistentPath()).thenReturn(directory.toString());
when(config.defaultAccountId()).thenReturn(ACCOUNT);
when(config.storage().wal().compactionIntervalMs()).thenReturn(3600000L);
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
when(access.storageMode("redshiftserverless")).thenReturn(mode);
when(access.storageFlushInterval("redshiftserverless")).thenReturn(3600000L);
StorageFactory factory = new StorageFactory(config, access);
Path dump = directory.resolve("redshift-serverless-dumps").resolve(ACCOUNT).resolve(REGION)
.resolve("retry-snap.sql");
Files.createDirectories(dump);
Path blocker = Files.writeString(dump.resolve("blocker"), "partial dump");
try {
AccountAwareStorageBackend<RedshiftServerlessSnapshot> snapshots = factory.create(
"redshiftserverless", "redshiftserverless-snapshots.json", new TypeReference<>() { });
RedshiftServerlessSnapshot snapshot = new RedshiftServerlessSnapshot();
snapshot.setSnapshotName("retry-snap");
snapshot.setSnapshotCreateTime(Instant.EPOCH);
snapshot.setRetentionPeriod(1);
snapshot.setSqlDump(dump.toString());
snapshots.put(REGION + "::retry-snap", snapshot);
service(factory, config).expireSnapshots(Instant.EPOCH.plusSeconds(86400), entry -> { });
assertEquals("DELETED", snapshots.get(REGION + "::retry-snap").orElseThrow().getStatus());
if ("memory".equals(mode)) {
Files.delete(blocker);
service(factory, config).expireSnapshots(Instant.EPOCH, entry -> { });
assertTrue(snapshots.scanAllAccounts().isEmpty());
assertFalse(Files.exists(dump));
return;
}
} finally {
factory.shutdownAll();
}
StorageFactory reloaded = new StorageFactory(config, access);
try {
RedshiftServerlessService service = service(reloaded, config);
assertEquals("DELETED", service.getSnapshot("retry-snap", REGION).getStatus());
Files.delete(blocker);
service.expireSnapshots(Instant.EPOCH, entry -> { });
assertTrue(service.findSnapshot("retry-snap", REGION).isEmpty());
assertFalse(Files.exists(dump));
} finally {
reloaded.shutdownAll();
}
}
private RedshiftServerlessService service(StorageFactory factory, EmulatorConfig config) {
return new RedshiftServerlessService(factory, new RegionResolver(REGION, ACCOUNT),
mock(RedshiftServerlessEndpoints.class), mock(RedshiftServerlessRuntime.class), config);
}
}
+2
View File
@@ -251,6 +251,8 @@ floci:
shutdown-timeout-seconds: 10
redshift-serverless:
enabled: true
snapshot-expiration-enabled: false
snapshot-expiration-sweep-interval-seconds: 60
scheduled-actions-enabled: false
scheduled-action-sweep-interval-seconds: 60
neptune: