diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotScheduler.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotScheduler.java index f3c590cc08..852081b04c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotScheduler.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotScheduler.java @@ -2,78 +2,46 @@ package io.github.hectorvent.floci.services.redshift; 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 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; /** Drives automated snapshots outside AWS request threads. */ @ApplicationScoped public class RedshiftSnapshotScheduler implements Resettable { - private static final Logger LOG = Logger.getLogger(RedshiftSnapshotScheduler.class); - private final RedshiftService service; - private final ScheduledExecutorService executor; - private final long intervalSeconds; - private final ReentrantLock sweepLock = new ReentrantLock(); - private volatile boolean paused; + private final SweepWorker worker; @Inject public RedshiftSnapshotScheduler(RedshiftService service, EmulatorConfig config) { - this.service = service; - this.intervalSeconds = Math.max(1, config.services().redshift().snapshotSweepIntervalSeconds()); - this.executor = config.services().redshift().enabled() && config.services().redshift().automatedSnapshotsEnabled() - ? Executors.newSingleThreadScheduledExecutor(task -> { - Thread thread = new Thread(task, "redshift-snapshot-scheduler"); - thread.setDaemon(true); - return thread; - }) : null; + EmulatorConfig.RedshiftServiceConfig redshift = config.services().redshift(); + this.worker = new SweepWorker("redshift-snapshot-scheduler", + redshift.enabled() && redshift.automatedSnapshotsEnabled(), + redshift.snapshotSweepIntervalSeconds(), false, service::runSnapshotSchedules); } void onStart(@Observes StartupEvent ignored) { - if (executor != null) { - executor.scheduleWithFixedDelay(this::tickSafely, intervalSeconds, intervalSeconds, TimeUnit.SECONDS); - } + worker.start(); } - void onStop(@Observes ShutdownEvent ignored) { - if (executor != null) { - executor.shutdownNow(); - try { - if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { - LOG.warn("Redshift snapshot scheduler is still finishing a dump during shutdown"); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - LOG.debugv(e, "Interrupted while stopping the Redshift snapshot scheduler"); - } - } + // Priority below APPLICATION (2000) so the worker drains before EmulatorLifecycle.onStop flushes storage. + void onStop(@Observes @Priority(1000) ShutdownEvent ignored) { + worker.stop(); } public void tick(Instant now) { - sweepLock.lock(); - try { - if (!paused) { - service.runSnapshotSchedules(now); - } - } finally { - sweepLock.unlock(); - } + worker.tick(now); } /** Drains a running sweep so it cannot write old snapshots back into storage that reset is about to clear. */ @Override public void beforeReset() { - paused = true; - sweepLock.lock(); - sweepLock.unlock(); + worker.pause(); } @Override @@ -83,14 +51,6 @@ public class RedshiftSnapshotScheduler implements Resettable { @Override public void afterReset() { - paused = false; - } - - private void tickSafely() { - try { - tick(Instant.now()); - } catch (RuntimeException e) { - LOG.warnv(e, "Redshift automated snapshot sweep failed"); - } + worker.resume(); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionScheduler.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionScheduler.java index 5bccc5bfa5..367d83061d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionScheduler.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionScheduler.java @@ -2,85 +2,52 @@ 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 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; /** Drives Serverless scheduled actions outside AWS request threads, one sweep at a time. */ @ApplicationScoped public class RedshiftServerlessScheduledActionScheduler implements Resettable { - private static final Logger LOG = Logger.getLogger(RedshiftServerlessScheduledActionScheduler.class); - private final RedshiftServerlessScheduledActionService service; - private final ScheduledExecutorService executor; - private final long intervalSeconds; - private final ReentrantLock sweepLock = new ReentrantLock(); - private volatile boolean paused; + private final SweepWorker worker; @Inject public RedshiftServerlessScheduledActionScheduler(RedshiftServerlessScheduledActionService service, EmulatorConfig config) { EmulatorConfig.RedshiftServerlessServiceConfig serverless = config.services().redshiftServerless(); - this.service = service; - this.intervalSeconds = Math.max(1, serverless.scheduledActionSweepIntervalSeconds()); - this.executor = serverless.enabled() && serverless.scheduledActionsEnabled() - ? Executors.newSingleThreadScheduledExecutor(task -> { - Thread thread = new Thread(task, "redshift-serverless-scheduled-actions"); - thread.setDaemon(true); - return thread; - }) : null; + this.worker = new SweepWorker("redshift-serverless-scheduled-actions", + serverless.enabled() && serverless.scheduledActionsEnabled(), + serverless.scheduledActionSweepIntervalSeconds(), false, service::runScheduledActions); } void onStart(@Observes StartupEvent ignored) { - if (executor != null) { - executor.scheduleWithFixedDelay(this::tickSafely, intervalSeconds, intervalSeconds, TimeUnit.SECONDS); - } + worker.start(); } - void onStop(@Observes ShutdownEvent ignored) { - if (executor != null) { - executor.shutdownNow(); - try { - if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { - LOG.warn("The Redshift Serverless scheduled action worker is still finishing a snapshot during shutdown"); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - LOG.debugv(e, "Interrupted while stopping the Redshift Serverless scheduled action worker"); - } - } + // 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 executor != null; + return worker.active(); } public void tick(Instant now) { - sweepLock.lock(); - try { - if (!paused) { - service.runScheduledActions(now); - } - } finally { - sweepLock.unlock(); - } + worker.tick(now); } /** Drains a running sweep so it cannot write a claim back into storage that reset is about to clear. */ @Override public void beforeReset() { - paused = true; - sweepLock.lock(); - sweepLock.unlock(); + worker.pause(); } @Override @@ -90,14 +57,6 @@ public class RedshiftServerlessScheduledActionScheduler implements Resettable { @Override public void afterReset() { - paused = false; - } - - private void tickSafely() { - try { - tick(Instant.now()); - } catch (RuntimeException e) { - LOG.warnv(e, "The Redshift Serverless scheduled action sweep failed"); - } + worker.resume(); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotSchedulerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotSchedulerTest.java index 49e1a693e1..dfb0222065 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotSchedulerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSnapshotSchedulerTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.redshift; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.testutil.ShutdownOrdering; import org.junit.jupiter.api.Test; import java.time.Instant; @@ -30,4 +31,9 @@ class RedshiftSnapshotSchedulerTest { scheduler.tick(NOW); verify(service).runSnapshotSchedules(NOW); } + + @Test + void shutdownObserverRunsBeforeStorageIsFlushedAndClosed() throws Exception { + ShutdownOrdering.assertStopsBeforeStorageCloses(RedshiftSnapshotScheduler.class); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionSchedulerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionSchedulerTest.java index 5cb8a88abe..b5d1c572eb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionSchedulerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessScheduledActionSchedulerTest.java @@ -1,21 +1,13 @@ 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 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.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -41,6 +33,11 @@ class RedshiftServerlessScheduledActionSchedulerTest { assertFalse(scheduler(false, true).active()); } + @Test + void shutdownObserverRunsBeforeStorageIsFlushedAndClosed() throws Exception { + ShutdownOrdering.assertStopsBeforeStorageCloses(RedshiftServerlessScheduledActionScheduler.class); + } + @Test void tickRunsTheSweepAtTheGivenInstant() { scheduler(true, false).tick(NOW); @@ -48,68 +45,14 @@ class RedshiftServerlessScheduledActionSchedulerTest { } @Test - void resetDrainsARunningSweepAndPausesUntilItEnds() throws Exception { + void tickIsSkippedBetweenBeforeResetAndAfterReset() { RedshiftServerlessScheduledActionScheduler scheduler = scheduler(true, false); - CountDownLatch running = new CountDownLatch(1); - CountDownLatch release = new CountDownLatch(1); - doAnswer(invocation -> { - running.countDown(); - release.await(10, TimeUnit.SECONDS); - return null; - }).when(service).runScheduledActions(NOW); - ExecutorService executor = Executors.newFixedThreadPool(2); - try { - Future sweep = executor.submit(() -> scheduler.tick(NOW)); - assertTrue(running.await(5, TimeUnit.SECONDS)); - Future reset = executor.submit(scheduler::beforeReset); - assertThrows(TimeoutException.class, () -> reset.get(300, TimeUnit.MILLISECONDS)); + scheduler.beforeReset(); + scheduler.tick(NOW); + verify(service, never()).runScheduledActions(NOW); - release.countDown(); - reset.get(5, TimeUnit.SECONDS); - sweep.get(5, TimeUnit.SECONDS); - scheduler.tick(NOW.plusSeconds(60)); - verify(service, never()).runScheduledActions(NOW.plusSeconds(60)); - - scheduler.afterReset(); - scheduler.tick(NOW.plusSeconds(120)); - verify(service).runScheduledActions(NOW.plusSeconds(120)); - } finally { - release.countDown(); - executor.shutdownNow(); - } - } - - @Test - void overlappingTicksNeverRunTheSweepConcurrently() throws Exception { - RedshiftServerlessScheduledActionScheduler scheduler = scheduler(true, false); - AtomicInteger concurrent = new AtomicInteger(); - AtomicInteger peak = new AtomicInteger(); - doAnswer(invocation -> { - peak.accumulateAndGet(concurrent.incrementAndGet(), Math::max); - Thread.sleep(100); - concurrent.decrementAndGet(); - return null; - }).when(service).runScheduledActions(NOW); - ExecutorService executor = Executors.newFixedThreadPool(3); - try { - Future first = executor.submit(() -> scheduler.tick(NOW)); - Future second = executor.submit(() -> scheduler.tick(NOW)); - Future third = executor.submit(() -> scheduler.tick(NOW)); - first.get(5, TimeUnit.SECONDS); - second.get(5, TimeUnit.SECONDS); - third.get(5, TimeUnit.SECONDS); - } finally { - executor.shutdownNow(); - } - assertEquals(1, peak.get()); - } - - @Test - void aFailedSweepReleasesTheLock() { - RedshiftServerlessScheduledActionScheduler scheduler = scheduler(true, false); - doThrow(new IllegalStateException("boom")).when(service).runScheduledActions(NOW); - assertThrows(IllegalStateException.class, () -> scheduler.tick(NOW)); - scheduler.tick(NOW.plusSeconds(60)); - verify(service).runScheduledActions(NOW.plusSeconds(60)); + scheduler.afterReset(); + scheduler.tick(NOW); + verify(service).runScheduledActions(NOW); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessSnapshotExpirationSchedulerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessSnapshotExpirationSchedulerTest.java index 7540f2d951..ec6e343e18 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessSnapshotExpirationSchedulerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessSnapshotExpirationSchedulerTest.java @@ -1,15 +1,10 @@ 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 io.github.hectorvent.floci.testutil.ShutdownOrdering; 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; @@ -42,13 +37,7 @@ class RedshiftServerlessSnapshotExpirationSchedulerTest { @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); + ShutdownOrdering.assertStopsBeforeStorageCloses(RedshiftServerlessSnapshotExpirationScheduler.class); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/testutil/ShutdownOrdering.java b/src/test/java/io/github/hectorvent/floci/testutil/ShutdownOrdering.java new file mode 100644 index 0000000000..f05b0de061 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testutil/ShutdownOrdering.java @@ -0,0 +1,28 @@ +package io.github.hectorvent.floci.testutil; + +import io.quarkus.runtime.ShutdownEvent; +import jakarta.annotation.Priority; +import jakarta.interceptor.Interceptor; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Checks that a background worker stops before EmulatorLifecycle.onStop flushes and closes storage. */ +public final class ShutdownOrdering { + private ShutdownOrdering() { + } + + /** The class's {@code onStop(ShutdownEvent)} observer must carry a priority below APPLICATION. */ + public static void assertStopsBeforeStorageCloses(Class owner) throws NoSuchMethodException { + Method onStop = owner.getDeclaredMethod("onStop", ShutdownEvent.class); + Annotation priority = Arrays.stream(onStop.getParameterAnnotations()[0]) + .filter(Priority.class::isInstance) + .findFirst() + .orElseThrow(() -> new AssertionError(owner.getSimpleName() + ".onStop has no @Priority")); + assertTrue(((Priority) priority).value() < Interceptor.Priority.APPLICATION, + owner.getSimpleName() + ".onStop must run before EmulatorLifecycle.onStop"); + } +}