diff --git a/src/main/java/io/floci/aws/core/common/SweepWorker.java b/src/main/java/io/floci/aws/core/common/SweepWorker.java index 0d39bd46b7..7560d61bb3 100644 --- a/src/main/java/io/floci/aws/core/common/SweepWorker.java +++ b/src/main/java/io/floci/aws/core/common/SweepWorker.java @@ -2,6 +2,7 @@ package io.floci.aws.core.common; import org.jboss.logging.Logger; +import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.concurrent.Executors; @@ -25,6 +26,7 @@ public final class SweepWorker { private final boolean sweepAtStart; private final long shutdownTimeoutNanos; private final ScheduledExecutorService executor; + private final Clock clock; private final ReentrantLock sweepLock = new ReentrantLock(); private volatile boolean paused; private volatile Thread workerThread; @@ -49,6 +51,7 @@ public final class SweepWorker { this.intervalSeconds = Math.max(1, intervalSeconds); this.sweepAtStart = sweepAtStart; this.shutdownTimeoutNanos = shutdownTimeout.toNanos(); + this.clock = Clock.systemUTC(); this.executor = threadFactory == null ? null : Executors.newSingleThreadScheduledExecutor(task -> { Thread thread = threadFactory.newThread(task); workerThread = thread; @@ -56,6 +59,23 @@ public final class SweepWorker { }); } + /** + * A worker whose timer and clock the caller supplies, so a test can move time itself. + * + * @param executor runs the sweeps and is shut down by {@link #stop}; {@code null} disables scheduling + * @param clock read once per scheduled sweep for the instant handed to it + */ + public SweepWorker(String name, long intervalSeconds, boolean sweepAtStart, Consumer sweep, + ScheduledExecutorService executor, Clock clock) { + this.name = name; + this.sweep = sweep; + this.intervalSeconds = Math.max(1, intervalSeconds); + this.sweepAtStart = sweepAtStart; + this.shutdownTimeoutNanos = SHUTDOWN_TIMEOUT.toNanos(); + this.executor = executor; + this.clock = clock; + } + public void start() { if (executor != null) { executor.scheduleWithFixedDelay(this::tickSafely, sweepAtStart ? 0 : intervalSeconds, intervalSeconds, TimeUnit.SECONDS); @@ -122,7 +142,7 @@ public final class SweepWorker { private void tickSafely() { try { - tick(Instant.now()); + tick(clock.instant()); } catch (RuntimeException e) { LOG.warnv(e, "The {0} sweep failed", name); } diff --git a/src/test/java/io/floci/aws/core/common/SweepWorkerTest.java b/src/test/java/io/floci/aws/core/common/SweepWorkerTest.java index d925154e35..aeaca1f2b4 100644 --- a/src/test/java/io/floci/aws/core/common/SweepWorkerTest.java +++ b/src/test/java/io/floci/aws/core/common/SweepWorkerTest.java @@ -1,7 +1,9 @@ package io.floci.aws.core.common; +import io.floci.aws.testing.TestTime; import org.junit.jupiter.api.Test; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.List; @@ -174,4 +176,122 @@ class SweepWorkerTest { worker.stop(); assertTrue(swept.isEmpty()); } + private static SweepWorker timed(TestTime time, long intervalSeconds, boolean sweepAtStart, + Consumer sweep) { + return new SweepWorker("test-sweep", intervalSeconds, sweepAtStart, sweep, time.scheduler(), time.clock()); + } + + @Test + void controlledSchedulerWaitsOneIntervalBeforeTheFirstSweep() { + TestTime time = TestTime.create(); + SweepWorker worker = timed(time, 3600, false, swept::add); + Instant started = time.now(); + worker.start(); + + time.advance(Duration.ofSeconds(3599)); + assertTrue(swept.isEmpty(), "the first sweep ran before one interval had passed"); + + time.advance(Duration.ofSeconds(1)); + assertEquals(List.of(started.plusSeconds(3600)), swept); + } + + @Test + void aWorkerAskedToSweepAtStartStillWaitsAFullIntervalForTheSecondSweep() { + TestTime time = TestTime.create(); + SweepWorker worker = timed(time, 3600, true, swept::add); + Instant started = time.now(); + worker.start(); + + time.runDue(); + assertEquals(List.of(started), swept); + + time.advance(Duration.ofSeconds(3599)); + assertEquals(List.of(started), swept); + + time.advance(Duration.ofSeconds(1)); + assertEquals(List.of(started, started.plusSeconds(3600)), swept); + } + + @Test + void sweepsRepeatEveryIntervalAtTheInstantTheClockShows() { + TestTime time = TestTime.create(); + SweepWorker worker = timed(time, 60, false, swept::add); + Instant started = time.now(); + worker.start(); + + time.advance(Duration.ofSeconds(179)); + assertEquals(List.of(started.plusSeconds(60), started.plusSeconds(120)), swept); + + time.advance(Duration.ofSeconds(1)); + assertEquals(List.of(started.plusSeconds(60), started.plusSeconds(120), started.plusSeconds(180)), swept); + } + + @Test + void anIntervalBelowOneSecondIsRaisedToOneSecond() { + TestTime time = TestTime.create(); + SweepWorker worker = timed(time, 0, false, swept::add); + Instant started = time.now(); + worker.start(); + + time.advance(Duration.ofMillis(999)); + assertTrue(swept.isEmpty(), "a zero interval must not sweep faster than once a second"); + + time.advance(Duration.ofMillis(1)); + assertEquals(List.of(started.plusSeconds(1)), swept); + } + + @Test + void aFailedScheduledSweepDoesNotStopTheLaterOnes() { + TestTime time = TestTime.create(); + List attempts = new ArrayList<>(); + SweepWorker worker = timed(time, 60, false, now -> { + attempts.add(now); + if (attempts.size() == 1) { + throw new IllegalStateException("boom"); + } + }); + Instant started = time.now(); + worker.start(); + + time.advance(Duration.ofSeconds(60)); + assertEquals(List.of(started.plusSeconds(60)), attempts); + + time.advance(Duration.ofSeconds(60)); + assertEquals(List.of(started.plusSeconds(60), started.plusSeconds(120)), attempts); + } + + @Test + void scheduledSweepsAreSkippedBetweenPauseAndResume() { + TestTime time = TestTime.create(); + SweepWorker worker = timed(time, 60, false, swept::add); + Instant started = time.now(); + worker.start(); + + worker.pause(); + time.advance(Duration.ofSeconds(120)); + assertTrue(swept.isEmpty()); + + worker.resume(); + time.advance(Duration.ofSeconds(59)); + assertTrue(swept.isEmpty(), "resuming must not run a sweep before the next interval ends"); + + time.advance(Duration.ofSeconds(1)); + assertEquals(List.of(started.plusSeconds(180)), swept); + } + + @Test + void stopCancelsTheSweepsStillToCome() { + TestTime time = TestTime.create(); + SweepWorker worker = timed(time, 60, false, swept::add); + Instant started = time.now(); + worker.start(); + time.advance(Duration.ofSeconds(60)); + + worker.stop(); + time.advance(Duration.ofSeconds(3600)); + + assertEquals(List.of(started.plusSeconds(60)), swept); + assertEquals(0, time.pendingTasks()); + } + } diff --git a/src/test/java/io/floci/aws/testing/TestTime.java b/src/test/java/io/floci/aws/testing/TestTime.java new file mode 100644 index 0000000000..2511bee99e --- /dev/null +++ b/src/test/java/io/floci/aws/testing/TestTime.java @@ -0,0 +1,927 @@ +package io.floci.aws.testing; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.PriorityQueue; +import java.util.Set; +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Delayed; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.LockSupport; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.BooleanSupplier; + +/** + * Time a test controls: a clock, a scheduler and a sleep that share one timeline, which moves only + * when the test advances it. + * + *
{@code
+ * TestTime time = TestTime.create();
+ * Worker worker = new Worker(service, time.clock(), time.scheduler());
+ *
+ * time.advance(Duration.ofSeconds(59));
+ * assertDeploymentIsInProgress();
+ *
+ * time.advance(Duration.ofSeconds(1));
+ * assertDeploymentIsBaking();
+ * }
+ * + *

{@link #advance} does more than move the clock. It walks the timeline in order and, at each + * instant something is due, sets the clock to that instant and then: + *

    + *
  • runs the scheduled task on the advancing thread, re-queueing a periodic one, so a task that + * reads the clock sees the time it was scheduled for;
  • + *
  • wakes a thread parked in {@link #sleep}, and waits for that thread to park again or finish + * before moving on, so a polling loop takes one turn per interval however far the test jumps.
  • + *
+ * Nothing runs between calls: work handed to the scheduler waits for the next {@code advance}, even + * with no delay ({@link #runDue} runs just that). The production code keeps its configured + * durations; the test decides when they elapse. + * + *

Timed waits the code makes on its own ({@code Thread.sleep}, {@code get(timeout)}, + * {@code poll(timeout)}, {@code awaitNanos}) are outside this timeline. Give that code a seam to call + * instead and pass the stand-in: + *

    + *
  • {@code Thread.sleep} becomes {@link #sleep};
  • + *
  • a delayed or periodic task goes to {@link #scheduler()};
  • + *
  • {@code future.get(timeout)} becomes {@link #get}, {@code queue.poll(timeout)} becomes + * {@link #poll}, and any other timed wait ({@code monitor.wait(timeout)}, + * {@code condition.awaitNanos}, {@code latch.await(timeout)}) becomes {@link #within} around + * its untimed form.
  • + *
+ * A thread in one of those waits is released by whatever it waits for, as in production, or by the + * {@code advance} that reaches its deadline, which then waits for the thread to come to rest again. + * + *

Code the test calls on its own thread cannot park for an {@code advance} nobody is left to + * make: give it {@link #sleepAdvancing} and {@link #getAdvancing}, which move the timeline on + * themselves, or step through its work with {@link #advanceUntil}. + */ +public final class TestTime { + + /** Where a timeline starts unless the test says otherwise. */ + public static final Instant DEFAULT_START = Instant.parse("2026-01-01T00:00:00Z"); + + /** + * A blocking call with no time limit of its own, such as {@code queue::take} or + * {@code future::get}, for {@link #within} to bound on the timeline. + */ + @FunctionalInterface + public interface BlockingCall { + T call() throws X, InterruptedException; + } + + private static final Duration DEFAULT_SETTLE_TIMEOUT = Duration.ofSeconds(10); + /** Keeps {@link #nanoTime} visibly unrelated to the epoch, like {@link System#nanoTime}. */ + private static final long NANO_ORIGIN = TimeUnit.HOURS.toNanos(7); + private static final int SETTLED_SAMPLES = 2; + /** Earliest first, and for the same instant, whichever was queued first. */ + private static final Comparator IN_DUE_ORDER = + Comparator.comparing(entry -> entry.due).thenComparingLong(entry -> entry.sequence); + + /** Held by the thread walking the timeline; a task it runs may advance further. */ + private final ReentrantLock advancing = new ReentrantLock(); + /** Guards the queue, the sequence and every entry's state. */ + private final ReentrantLock lock = new ReentrantLock(); + private final Condition changed = lock.newCondition(); + private final PriorityQueue queue = new PriorityQueue<>(IN_DUE_ORDER); + private final Instant start; + private final Clock clock = new TimelineClock(ZoneOffset.UTC); + private final ScheduledExecutorService scheduler = new TimelineScheduler(); + private volatile Instant now; + private volatile Duration settleTimeout = DEFAULT_SETTLE_TIMEOUT; + private long nextSequence; + + private TestTime(Instant start) { + this.start = Objects.requireNonNull(start, "start"); + this.now = start; + } + + /** A timeline starting at {@link #DEFAULT_START}. */ + public static TestTime create() { + return new TestTime(DEFAULT_START); + } + + /** A timeline starting at {@code start}. */ + public static TestTime startingAt(Instant start) { + return new TestTime(start); + } + + /** The clock for this timeline, in UTC. Zoned views of it move with it. */ + public Clock clock() { + return clock; + } + + /** The current instant on this timeline. */ + public Instant now() { + return now; + } + + /** Milliseconds since the epoch on this timeline, for a seam shaped like {@code System::currentTimeMillis}. */ + public long currentTimeMillis() { + return now.toEpochMilli(); + } + + /** A monotonic reading of this timeline, for a seam shaped like {@code System::nanoTime}. */ + public long nanoTime() { + return NANO_ORIGIN + Duration.between(start, now).toNanos(); + } + + /** + * The scheduler for this timeline. Its tasks run on the thread that calls {@link #advance}, in + * due order and then in the order they were submitted. + */ + public ScheduledExecutorService scheduler() { + return scheduler; + } + + /** + * Another scheduler on the same timeline, for code that owns and shuts down its own. Shutting one + * down leaves the others running. + */ + public ScheduledExecutorService newScheduler() { + return new TimelineScheduler(); + } + + /** + * Parks the calling thread until the timeline has moved {@code duration} on, the way + * {@code Thread.sleep} would on a real clock. Returns at once for a zero or negative duration. + * Called from a task {@link #advance} is running, it moves the timeline itself instead of parking, + * since nothing else could. + */ + public void sleep(Duration duration) throws InterruptedException { + Objects.requireNonNull(duration, "duration"); + if (Thread.interrupted()) { + throw new InterruptedException(); + } + if (duration.isZero() || duration.isNegative()) { + return; + } + if (advancing.isHeldByCurrentThread()) { + advance(duration); + return; + } + lock.lockInterruptibly(); + try { + Parked sleep = new Parked(now.plus(duration), nextSequence++, Thread.currentThread(), false); + queue.add(sleep); + changed.signalAll(); + try { + while (!sleep.woken) { + changed.await(); + } + } finally { + queue.remove(sleep); + sleep.returned = true; + changed.signalAll(); + } + } finally { + lock.unlock(); + } + } + + /** {@link #sleep(Duration)} for a seam that counts in milliseconds. */ + public void sleepMillis(long millis) throws InterruptedException { + sleep(Duration.ofMillis(millis)); + } + + /** {@link #sleep(Duration)} for a seam that counts in nanoseconds. */ + public void sleepNanos(long nanos) throws InterruptedException { + sleep(Duration.ofNanos(nanos)); + } + + /** + * A sleep that passes by itself: moves the timeline {@code duration} on from the calling thread, + * running whatever comes due on the way. For code that sleeps on the test's own thread, such as a + * retry loop called directly, where nobody else is left to call {@link #advance}. + */ + public void sleepAdvancing(Duration duration) { + Objects.requireNonNull(duration, "duration"); + if (!duration.isNegative()) { + advance(duration); + } + } + + /** + * Runs {@code call}, a blocking call with no time limit of its own, with {@code timeout} measured + * on this timeline: the stand-in for any timed wait, such as + * {@code within(timeout, () -> condition.await())} for {@code condition.awaitNanos}. Returns what + * the call returns if it comes back by itself. If {@link #advance} reaches the deadline first, the + * waiting thread is interrupted out of the call and this throws {@link TimeoutException}; the + * advance goes on once the thread has parked again or finished. A call that returns just as the + * deadline is reached wins. The waiting thread counts among the {@link #waiters}. + * + *

Times out at once, without calling, for a zero or negative timeout. Not for a task the + * timeline itself is running, which would stop the timeline: use {@link #getAdvancing} there. + */ + public T within(Duration timeout, BlockingCall call) + throws X, InterruptedException, TimeoutException { + Objects.requireNonNull(timeout, "timeout"); + Objects.requireNonNull(call, "call"); + if (Thread.interrupted()) { + throw new InterruptedException(); + } + if (timeout.isZero() || timeout.isNegative()) { + throw new TimeoutException(); + } + if (advancing.isHeldByCurrentThread()) { + throw new IllegalStateException("a blocking wait inside a task the timeline is running would stop " + + "the timeline; use getAdvancing or advanceUntil"); + } + Parked wait; + lock.lockInterruptibly(); + try { + wait = new Parked(now.plus(timeout), nextSequence++, Thread.currentThread(), true); + queue.add(wait); + changed.signalAll(); + } finally { + lock.unlock(); + } + T result = null; + InterruptedException interruption = null; + boolean timedOut; + try { + result = call.call(); + } catch (InterruptedException e) { + interruption = e; + } finally { + timedOut = leave(wait, interruption != null); + } + if (interruption == null) { + return result; + } + if (timedOut) { + throw new TimeoutException(); + } + throw interruption; + } + + /** + * {@code future.get(timeout)} with the timeout on this timeline: returns when the future completes, + * and throws {@link TimeoutException} when {@link #advance} reaches the deadline first. See + * {@link #within}. Called from a task the timeline is running, it is {@link #getAdvancing}. + */ + public T get(Future future, Duration timeout) + throws InterruptedException, ExecutionException, TimeoutException { + Objects.requireNonNull(future, "future"); + Objects.requireNonNull(timeout, "timeout"); + if (future.isDone() || timeout.isZero() || timeout.isNegative()) { + return future.get(0, TimeUnit.NANOSECONDS); + } + if (advancing.isHeldByCurrentThread()) { + return getAdvancing(future, timeout); + } + return this.within(timeout, future::get); + } + + /** + * A {@code future.get(timeout)} that passes by itself: moves the timeline on from the calling + * thread, one due instant at a time, until the future is done or {@code timeout} has passed, so + * the clock stops where the future completed. For code that waits on the test's own thread for + * something the timeline's own tasks will complete. + */ + public T getAdvancing(Future future, Duration timeout) + throws InterruptedException, ExecutionException, TimeoutException { + Objects.requireNonNull(future, "future"); + Objects.requireNonNull(timeout, "timeout"); + if (!timeout.isNegative()) { + advanceUntil(future::isDone, timeout); + } + return future.get(0, TimeUnit.NANOSECONDS); + } + + /** + * {@code queue.poll(timeout)} with the timeout on this timeline: the next element once there is + * one, or {@code null} when {@link #advance} reaches the deadline first. See {@link #within}. + */ + public T poll(BlockingQueue queue, Duration timeout) throws InterruptedException { + Objects.requireNonNull(queue, "queue"); + Objects.requireNonNull(timeout, "timeout"); + if (Thread.interrupted()) { + throw new InterruptedException(); + } + T head = queue.poll(); + if (head != null || timeout.isZero() || timeout.isNegative()) { + return head; + } + if (advancing.isHeldByCurrentThread()) { + advanceUntil(() -> !queue.isEmpty(), timeout); + return queue.poll(); + } + try { + return this.within(timeout, queue::take); + } catch (TimeoutException expired) { + return null; + } + } + + /** + * Moves the timeline {@code duration} on, running every scheduled task and waking every sleeper + * that comes due on the way, each with the clock at its own due time. Work a task schedules inside + * the window runs in the same call. Returns with the clock at the target, or later if a task + * slept past it. + */ + public void advance(Duration duration) { + Objects.requireNonNull(duration, "duration"); + if (duration.isNegative()) { + throw new IllegalArgumentException("time only moves forward, not by " + duration); + } + advancing.lock(); + try { + Instant target = now.plus(duration); + Entry due; + while ((due = takeDue(target)) != null) { + due.fire(); + } + lock.lock(); + try { + if (target.isAfter(now)) { + now = target; + } + } finally { + lock.unlock(); + } + } finally { + advancing.unlock(); + } + } + + /** {@link #advance} up to {@code instant}, which must not be in this timeline's past. */ + public void advanceTo(Instant instant) { + advancing.lock(); + try { + advance(Duration.between(now, instant)); + } finally { + advancing.unlock(); + } + } + + /** Runs what is due now, without moving the clock: work submitted with no delay, mostly. */ + public void runDue() { + advance(Duration.ZERO); + } + + /** + * Moves the timeline on one due instant at a time, running what is due there, until + * {@code condition} holds or {@code limit} has passed, whichever comes first. Returns whether the + * condition holds, with the clock at the instant it first did, or at the limit. + * + *

{@code
+     * assertTrue(time.advanceUntil(() -> deployment.state() == BAKING, Duration.ofMinutes(10)));
+     * assertEquals(start.plusSeconds(60), time.now());
+     * }
+ */ + public boolean advanceUntil(BooleanSupplier condition, Duration limit) { + Objects.requireNonNull(condition, "condition"); + Objects.requireNonNull(limit, "limit"); + if (limit.isNegative()) { + throw new IllegalArgumentException("time only moves forward, not by " + limit); + } + advancing.lock(); + try { + Instant deadline = now.plus(limit); + while (!condition.getAsBoolean()) { + Instant next = nextDue().filter(due -> !due.isAfter(deadline)).orElse(deadline); + advanceTo(next.isAfter(now) ? next : now); + if (next.equals(deadline)) { + return condition.getAsBoolean(); + } + } + return true; + } finally { + advancing.unlock(); + } + } + + /** How many scheduled tasks are waiting for their time, periodic ones counted once. */ + public int pendingTasks() { + lock.lock(); + try { + return (int) queue.stream().filter(entry -> entry instanceof Task).count(); + } finally { + lock.unlock(); + } + } + + /** When the next scheduled task is due, if any is waiting. */ + public Optional nextTaskDue() { + lock.lock(); + try { + return queue.stream().filter(entry -> entry instanceof Task).min(IN_DUE_ORDER) + .map(entry -> entry.due); + } finally { + lock.unlock(); + } + } + + /** + * When the next thing on this timeline is due, if anything is waiting: a scheduled task, the end + * of a sleep or the deadline of a timed wait. + */ + public Optional nextDue() { + lock.lock(); + try { + return Optional.ofNullable(queue.peek()).map(entry -> entry.due); + } finally { + lock.unlock(); + } + } + + /** How many threads are parked in {@link #sleep} right now. */ + public int sleepers() { + lock.lock(); + try { + return parkedCount(false); + } finally { + lock.unlock(); + } + } + + /** How many threads are in a timed wait right now: {@link #within}, {@link #get} or {@link #poll}. */ + public int waiters() { + lock.lock(); + try { + return parkedCount(true); + } finally { + lock.unlock(); + } + } + + /** + * Waits, in real time, until at least {@code count} threads are parked in {@link #sleep}. Call it + * before advancing past a sleep a background thread is about to take: a thread that has not + * reached its sleep yet would otherwise measure it from the later time. Fails after the settle + * timeout. + */ + public void awaitSleepers(int count) { + awaitParked(count, false, "sleeping"); + } + + /** + * {@link #awaitSleepers} for timed waits: waits, in real time, until at least {@code count} + * threads have their deadline on the timeline, so that the advance that follows measures it from + * now. Such a thread may not have blocked yet; the deadline reaches it either way. + */ + public void awaitWaiters(int count) { + awaitParked(count, true, "waiting"); + } + + private void awaitParked(int count, boolean timedWaits, String doing) { + long deadline = System.nanoTime() + settleTimeout.toNanos(); + lock.lock(); + try { + while (parkedCount(timedWaits) < count) { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + throw new AssertionError("expected " + count + " " + doing + " thread(s) within " + + settleTimeout + ", found " + parkedCount(timedWaits)); + } + changed.awaitNanos(remaining); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError("interrupted waiting for " + count + " " + doing + " thread(s)", e); + } finally { + lock.unlock(); + } + } + + /** + * How long, in real time, {@link #advance} waits for a woken thread to park again or finish, and + * {@link #awaitSleepers} and {@link #awaitWaiters} for threads to arrive, before failing the test. + * Ten seconds by default. + */ + public TestTime settleTimeout(Duration timeout) { + this.settleTimeout = Objects.requireNonNull(timeout, "timeout"); + return this; + } + + @Override + public String toString() { + return "TestTime[" + now + "]"; + } + + private int parkedCount(boolean timedWaits) { + return (int) queue.stream() + .filter(entry -> entry instanceof Parked parked && parked.interrupts == timedWaits).count(); + } + + /** Removes the earliest entry due by {@code target} and moves the clock up to it. */ + private Entry takeDue(Instant target) { + lock.lock(); + try { + Entry head = queue.peek(); + if (head == null || head.due.isAfter(target)) { + return null; + } + queue.remove(); + if (head.due.isAfter(now)) { + now = head.due; + } + return head; + } finally { + lock.unlock(); + } + } + + private boolean isParked(Thread thread) { + lock.lock(); + try { + return queue.stream().anyMatch(entry -> entry instanceof Parked parked && parked.thread == thread); + } finally { + lock.unlock(); + } + } + + /** + * Ends a timed wait and says whether its deadline was reached. A deadline that fired while the + * call was returning on its own left an interrupt nobody consumed; it belongs to this wait, so it + * is cleared here. + */ + private boolean leave(Parked wait, boolean interruptConsumed) { + lock.lock(); + try { + queue.remove(wait); + wait.returned = true; + changed.signalAll(); + if (wait.woken && !interruptConsumed) { + Thread.interrupted(); + } + return wait.woken; + } finally { + lock.unlock(); + } + } + + /** Something due at a point on the timeline: a scheduled task or a sleeping thread. */ + private abstract static class Entry { + Instant due; + long sequence; + + Entry(Instant due, long sequence) { + this.due = due; + this.sequence = sequence; + } + + abstract void fire(); + } + + /** A thread waiting for an instant: asleep in {@link #sleep}, or blocked elsewhere in a timed wait. */ + private final class Parked extends Entry { + final Thread thread; + /** Whether the thread is blocked outside this class, where only an interrupt reaches it. */ + final boolean interrupts; + boolean woken; + boolean returned; + + Parked(Instant due, long sequence, Thread thread, boolean interrupts) { + super(due, sequence); + this.thread = thread; + this.interrupts = interrupts; + } + + /** + * Wakes the thread, then holds the timeline still until it has stopped running again: back + * on the timeline, blocked somewhere else, or finished. + */ + @Override + void fire() { + long deadline = System.nanoTime() + settleTimeout.toNanos(); + lock.lock(); + try { + if (returned) { + return; + } + woken = true; + if (interrupts) { + thread.interrupt(); + } + changed.signalAll(); + while (!returned) { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + throw stillRunning(); + } + changed.awaitNanos(remaining); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError("interrupted waking " + thread.getName(), e); + } finally { + lock.unlock(); + } + int parkedSamples = 0; + while (thread.isAlive()) { + boolean blockedElsewhere; + lock.lock(); + try { + if (isParked(thread)) { + return; + } + // Queued for this lock, the thread is on its way into its next sleep or wait: + // it looks parked but has not come to rest. Read with the lock held, it cannot + // leave that queue in between. + blockedElsewhere = ThreadStates.PARKED_OR_DONE.contains(thread.getState()) + && !lock.hasQueuedThread(thread); + } finally { + lock.unlock(); + } + parkedSamples = blockedElsewhere ? parkedSamples + 1 : 0; + if (parkedSamples >= SETTLED_SAMPLES) { + return; + } + if (System.nanoTime() - deadline > 0) { + throw stillRunning(); + } + LockSupport.parkNanos(TimeUnit.MICROSECONDS.toNanos(parkedSamples == 0 ? 50 : 500)); + } + } + + private AssertionError stillRunning() { + AssertionError error = new AssertionError(thread.getName() + " was still running " + settleTimeout + + " after its " + (interrupts ? "timed wait" : "sleep") + " ended at " + due + + "; it must sleep again, block or finish"); + error.setStackTrace(thread.getStackTrace()); + return error; + } + } + + private final class Task extends Entry implements ScheduledFuture { + private final TimelineScheduler owner; + private final Callable body; + /** Zero for a one-shot, positive for a fixed rate, negative for a fixed delay. */ + private final long periodNanos; + private final CompletableFuture result = new CompletableFuture<>(); + + Task(TimelineScheduler owner, Callable body, Instant due, long sequence, long periodNanos) { + super(due, sequence); + this.owner = owner; + this.body = body; + this.periodNanos = periodNanos; + } + + @Override + void fire() { + if (result.isDone()) { + owner.finished(this); + return; + } + try { + V value = body.call(); + if (periodNanos == 0) { + result.complete(value); + } + } catch (Throwable failure) { + // What a real scheduler does: the failure goes to the future and a periodic task stops. + result.completeExceptionally(failure); + } + lock.lock(); + try { + if (!result.isDone() && !owner.shutdown) { + due = periodNanos > 0 ? due.plusNanos(periodNanos) : now.plusNanos(-periodNanos); + sequence = nextSequence++; + queue.add(this); + return; + } + } finally { + lock.unlock(); + } + result.cancel(false); + owner.finished(this); + } + + @Override + public long getDelay(TimeUnit unit) { + lock.lock(); + try { + return unit.convert(Duration.between(now, due)); + } finally { + lock.unlock(); + } + } + + @Override + public int compareTo(Delayed other) { + if (other instanceof Entry entry) { + return IN_DUE_ORDER.compare(this, entry); + } + return Long.compare(getDelay(TimeUnit.NANOSECONDS), other.getDelay(TimeUnit.NANOSECONDS)); + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + boolean cancelled = result.cancel(false); + lock.lock(); + try { + if (queue.remove(this)) { + owner.finished(this); + } + } finally { + lock.unlock(); + } + return cancelled; + } + + @Override + public boolean isCancelled() { + return result.isCancelled(); + } + + @Override + public boolean isDone() { + return result.isDone(); + } + + @Override + public V get() throws InterruptedException, ExecutionException { + return result.get(); + } + + @Override + public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return result.get(timeout, unit); + } + } + + private final class TimelineScheduler extends AbstractExecutorService implements ScheduledExecutorService { + /** Tasks queued or running; guarded by {@link TestTime#lock}. */ + private final Set> tasks = new HashSet<>(); + private volatile boolean shutdown; + + @Override + public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { + Objects.requireNonNull(command, "command"); + return enqueue(Executors.callable(command), unit.toNanos(delay), 0); + } + + @Override + public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { + return enqueue(Objects.requireNonNull(callable, "callable"), unit.toNanos(delay), 0); + } + + @Override + public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, + TimeUnit unit) { + Objects.requireNonNull(command, "command"); + if (period <= 0) { + throw new IllegalArgumentException("period must be positive"); + } + return enqueue(Executors.callable(command), unit.toNanos(initialDelay), unit.toNanos(period)); + } + + @Override + public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, + TimeUnit unit) { + Objects.requireNonNull(command, "command"); + if (delay <= 0) { + throw new IllegalArgumentException("delay must be positive"); + } + return enqueue(Executors.callable(command), unit.toNanos(initialDelay), -unit.toNanos(delay)); + } + + @Override + public void execute(Runnable command) { + schedule(command, 0, TimeUnit.NANOSECONDS); + } + + private Task enqueue(Callable body, long delayNanos, long periodNanos) { + lock.lock(); + try { + if (shutdown) { + throw new RejectedExecutionException("scheduler is shut down"); + } + Task task = new Task<>(this, body, now.plusNanos(Math.max(delayNanos, 0)), nextSequence++, + periodNanos); + tasks.add(task); + queue.add(task); + return task; + } finally { + lock.unlock(); + } + } + + void finished(Task task) { + lock.lock(); + try { + tasks.remove(task); + changed.signalAll(); + } finally { + lock.unlock(); + } + } + + /** As a real scheduler does by default: periodic work stops, delayed one-shots still run. */ + @Override + public void shutdown() { + lock.lock(); + try { + shutdown = true; + for (Task task : List.copyOf(tasks)) { + if (task.periodNanos != 0 && queue.remove(task)) { + task.result.cancel(false); + tasks.remove(task); + } + } + } finally { + lock.unlock(); + } + } + + @Override + public List shutdownNow() { + List dropped = new ArrayList<>(); + lock.lock(); + try { + shutdown = true; + for (Task task : List.copyOf(tasks)) { + if (queue.remove(task)) { + tasks.remove(task); + dropped.add(() -> { + try { + task.body.call(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }); + } + } + } finally { + lock.unlock(); + } + return dropped; + } + + @Override + public boolean isShutdown() { + return shutdown; + } + + @Override + public boolean isTerminated() { + lock.lock(); + try { + return shutdown && tasks.isEmpty(); + } finally { + lock.unlock(); + } + } + + /** Answers at once: waiting in real time for work that only virtual time can finish would hang. */ + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return isTerminated(); + } + + @Override + public String toString() { + return "TestTime.scheduler[" + now + "]"; + } + } + + private final class TimelineClock extends Clock { + private final ZoneId zone; + + TimelineClock(ZoneId zone) { + this.zone = Objects.requireNonNull(zone, "zone"); + } + + @Override + public ZoneId getZone() { + return zone; + } + + @Override + public Clock withZone(ZoneId zone) { + return new TimelineClock(zone); + } + + @Override + public Instant instant() { + return now; + } + + @Override + public long millis() { + return now.toEpochMilli(); + } + } +} diff --git a/src/test/java/io/floci/aws/testing/TestTimeTest.java b/src/test/java/io/floci/aws/testing/TestTimeTest.java new file mode 100644 index 0000000000..3462254014 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/TestTimeTest.java @@ -0,0 +1,720 @@ +package io.floci.aws.testing; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.lang.reflect.Method; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Timeout(30) +class TestTimeTest { + + private static final Instant START = Instant.parse("2026-10-29T00:00:00Z"); + + private final TestTime time = TestTime.startingAt(START); + + @Test + void theClockMovesOnlyWhenAdvanced() { + Clock zoned = time.clock().withZone(ZoneOffset.ofHours(7)); + + assertEquals(START, time.clock().instant()); + assertEquals(START, time.clock().instant()); + + time.advance(Duration.ofSeconds(90)); + + assertEquals(START.plusSeconds(90), time.now()); + assertEquals(START.plusSeconds(90), time.clock().instant()); + assertEquals(START.plusSeconds(90), zoned.instant()); + assertEquals(ZoneOffset.ofHours(7), zoned.getZone()); + assertEquals(START.plusSeconds(90).toEpochMilli(), time.currentTimeMillis()); + } + + @Test + void theMonotonicReadingAdvancesWithTheClock() { + long before = time.nanoTime(); + + time.advance(Duration.ofMillis(1500)); + + assertEquals(Duration.ofMillis(1500).toNanos(), time.nanoTime() - before); + } + + @Test + void timeDoesNotMoveBackwards() { + assertThrows(IllegalArgumentException.class, () -> time.advance(Duration.ofNanos(-1))); + assertThrows(IllegalArgumentException.class, () -> time.advanceTo(START.minusNanos(1))); + assertEquals(START, time.now()); + } + + @Test + void aDelayedTaskRunsExactlyWhenItsDelayHasPassed() { + AtomicInteger runs = new AtomicInteger(); + ScheduledFuture future = time.scheduler().schedule(runs::incrementAndGet, 60, TimeUnit.SECONDS); + + time.advance(Duration.ofSeconds(59)); + assertEquals(0, runs.get()); + assertFalse(future.isDone()); + assertEquals(1, future.getDelay(TimeUnit.SECONDS)); + + time.advance(Duration.ofSeconds(1)); + assertEquals(1, runs.get()); + assertTrue(future.isDone()); + assertEquals(0, time.pendingTasks()); + } + + @Test + void aTaskSeesTheClockAtItsOwnDueTimeHoweverFarTheTestJumps() { + List seen = new ArrayList<>(); + time.scheduler().schedule(() -> seen.add(time.now()), 10, TimeUnit.SECONDS); + time.scheduler().schedule(() -> seen.add(time.now()), 3, TimeUnit.SECONDS); + + time.advance(Duration.ofHours(1)); + + assertEquals(List.of(START.plusSeconds(3), START.plusSeconds(10)), seen); + assertEquals(START.plus(Duration.ofHours(1)), time.now()); + } + + @Test + void tasksDueAtTheSameInstantRunInSubmissionOrder() { + List order = new ArrayList<>(); + time.scheduler().schedule(() -> order.add("first"), 1, TimeUnit.SECONDS); + time.newScheduler().schedule(() -> order.add("second"), 1, TimeUnit.SECONDS); + time.scheduler().schedule(() -> order.add("third"), 1, TimeUnit.SECONDS); + + time.advance(Duration.ofSeconds(1)); + + assertEquals(List.of("first", "second", "third"), order); + } + + @Test + void submittedWorkWaitsForTheTestToRunIt() throws Exception { + AtomicBoolean ran = new AtomicBoolean(); + Future future = time.scheduler().submit(() -> { + ran.set(true); + return "done"; + }); + + assertFalse(ran.get()); + + time.runDue(); + + assertTrue(ran.get()); + assertEquals("done", future.get()); + assertEquals(START, time.now()); + } + + @Test + void aFixedRateTaskRunsOncePerPeriod() { + List ticks = new ArrayList<>(); + time.scheduler().scheduleAtFixedRate(() -> ticks.add(time.now()), 5, 10, TimeUnit.SECONDS); + + time.advance(Duration.ofSeconds(4)); + assertEquals(List.of(), ticks); + + time.advance(Duration.ofSeconds(31)); + assertEquals(List.of(START.plusSeconds(5), START.plusSeconds(15), START.plusSeconds(25), + START.plusSeconds(35)), ticks); + assertEquals(1, time.pendingTasks()); + assertEquals(START.plusSeconds(45), time.nextTaskDue().orElseThrow()); + } + + @Test + void aFixedDelayTaskWaitsItsDelayAfterEachRunEnds() { + List ticks = new ArrayList<>(); + time.scheduler().scheduleWithFixedDelay(() -> { + ticks.add(time.now()); + time.sleepAdvancing(Duration.ofSeconds(2)); + }, 1, 10, TimeUnit.SECONDS); + + time.advance(Duration.ofSeconds(30)); + + assertEquals(List.of(START.plusSeconds(1), START.plusSeconds(13), START.plusSeconds(25)), ticks); + } + + @Test + void aTaskScheduledInsideTheWindowRunsInTheSameAdvance() { + List order = new ArrayList<>(); + ScheduledExecutorService scheduler = time.scheduler(); + scheduler.schedule(() -> { + order.add("retry scheduled at " + time.now()); + scheduler.schedule(() -> order.add("retry ran at " + time.now()), 2, TimeUnit.SECONDS); + }, 1, TimeUnit.SECONDS); + + time.advance(Duration.ofSeconds(3)); + + assertEquals(List.of("retry scheduled at " + START.plusSeconds(1), "retry ran at " + START.plusSeconds(3)), + order); + } + + @Test + void aCancelledTaskNeverRuns() { + AtomicInteger runs = new AtomicInteger(); + ScheduledFuture oneShot = time.scheduler().schedule(runs::incrementAndGet, 1, TimeUnit.SECONDS); + ScheduledFuture periodic = time.scheduler().scheduleAtFixedRate(runs::incrementAndGet, 1, 1, + TimeUnit.SECONDS); + + assertTrue(oneShot.cancel(false)); + time.advance(Duration.ofSeconds(1)); + assertEquals(1, runs.get()); + + assertTrue(periodic.cancel(false)); + time.advance(Duration.ofMinutes(1)); + + assertEquals(1, runs.get()); + assertTrue(oneShot.isCancelled()); + assertThrows(CancellationException.class, periodic::get); + assertEquals(0, time.pendingTasks()); + } + + @Test + void aPeriodicTaskThatThrowsStopsLikeARealOne() { + AtomicInteger runs = new AtomicInteger(); + ScheduledFuture future = time.scheduler().scheduleAtFixedRate(() -> { + if (runs.incrementAndGet() == 2) { + throw new IllegalStateException("boom"); + } + }, 1, 1, TimeUnit.SECONDS); + + time.advance(Duration.ofSeconds(10)); + + assertEquals(2, runs.get()); + ExecutionException failure = assertThrows(ExecutionException.class, future::get); + assertInstanceOf(IllegalStateException.class, failure.getCause()); + } + + @Test + void shutdownStopsPeriodicWorkAndKeepsDelayedWork() throws Exception { + ScheduledExecutorService scheduler = time.newScheduler(); + AtomicInteger periodic = new AtomicInteger(); + AtomicInteger delayed = new AtomicInteger(); + scheduler.scheduleAtFixedRate(periodic::incrementAndGet, 1, 1, TimeUnit.SECONDS); + scheduler.schedule(delayed::incrementAndGet, 5, TimeUnit.SECONDS); + time.advance(Duration.ofSeconds(2)); + + scheduler.shutdown(); + + assertTrue(scheduler.isShutdown()); + assertFalse(scheduler.isTerminated()); + assertThrows(RejectedExecutionException.class, () -> scheduler.execute(() -> { })); + time.advance(Duration.ofSeconds(10)); + assertEquals(2, periodic.get()); + assertEquals(1, delayed.get()); + assertTrue(scheduler.isTerminated()); + assertTrue(scheduler.awaitTermination(1, TimeUnit.HOURS)); + } + + @Test + void shutdownNowDropsEverythingAndLeavesOtherSchedulersAlone() { + ScheduledExecutorService stopped = time.newScheduler(); + AtomicInteger dropped = new AtomicInteger(); + AtomicInteger kept = new AtomicInteger(); + stopped.schedule(dropped::incrementAndGet, 1, TimeUnit.SECONDS); + stopped.scheduleWithFixedDelay(dropped::incrementAndGet, 1, 1, TimeUnit.SECONDS); + time.scheduler().schedule(kept::incrementAndGet, 1, TimeUnit.SECONDS); + + assertEquals(2, stopped.shutdownNow().size()); + + assertTrue(stopped.isTerminated()); + time.advance(Duration.ofSeconds(5)); + assertEquals(0, dropped.get()); + assertEquals(1, kept.get()); + } + + @Test + void aSleepingThreadWakesExactlyWhenItsSleepHasPassed() throws Exception { + AtomicBoolean woke = new AtomicBoolean(); + Thread sleeper = Thread.ofPlatform().name("sleeper").start(() -> { + try { + time.sleep(Duration.ofSeconds(60)); + woke.set(true); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + time.awaitSleepers(1); + + time.advance(Duration.ofSeconds(59)); + assertFalse(woke.get()); + assertEquals(1, time.sleepers()); + + time.advance(Duration.ofSeconds(1)); + assertTrue(woke.get()); + assertEquals(0, time.sleepers()); + sleeper.join(); + } + + @Test + void aPollingLoopTakesOneTurnPerIntervalHoweverFarTheTestJumps() throws Exception { + List polls = new CopyOnWriteArrayList<>(); + Thread poller = Thread.ofVirtual().name("poller").start(() -> { + try { + for (int turn = 0; turn < 5; turn++) { + time.sleepMillis(200); + polls.add(time.now()); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + time.awaitSleepers(1); + + time.advance(Duration.ofMillis(650)); + assertEquals(List.of(START.plusMillis(200), START.plusMillis(400), START.plusMillis(600)), polls); + + time.advance(Duration.ofMinutes(5)); + assertEquals(5, polls.size()); + assertEquals(START.plusMillis(1000), polls.get(4)); + poller.join(); + } + + @Test + void sleepersAndTasksInterleaveInDueOrder() throws Exception { + List order = new CopyOnWriteArrayList<>(); + Thread sleeper = Thread.ofPlatform().name("sleeper").start(() -> { + try { + time.sleep(Duration.ofSeconds(2)); + order.add("sleeper"); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + time.awaitSleepers(1); + time.scheduler().schedule(() -> order.add("before"), 1, TimeUnit.SECONDS); + time.scheduler().schedule(() -> order.add("after"), 3, TimeUnit.SECONDS); + + time.advance(Duration.ofSeconds(3)); + + sleeper.join(); + assertEquals(List.of("before", "sleeper", "after"), order); + } + + @Test + void anInterruptedSleeperLeavesTheTimeline() throws Exception { + AtomicBoolean interrupted = new AtomicBoolean(); + Thread sleeper = Thread.ofPlatform().name("sleeper").start(() -> { + try { + time.sleep(Duration.ofSeconds(60)); + } catch (InterruptedException e) { + interrupted.set(true); + } + }); + time.awaitSleepers(1); + + sleeper.interrupt(); + sleeper.join(); + + assertTrue(interrupted.get()); + assertEquals(0, time.sleepers()); + time.advance(Duration.ofMinutes(2)); + } + + @Test + void aTaskThatSleepsMovesTheTimelineItself() { + List order = new ArrayList<>(); + time.scheduler().schedule(() -> { + order.add("start " + time.now()); + try { + time.sleep(Duration.ofSeconds(5)); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } + order.add("end " + time.now()); + }, 1, TimeUnit.SECONDS); + time.scheduler().schedule(() -> order.add("other " + time.now()), 3, TimeUnit.SECONDS); + + time.advance(Duration.ofSeconds(2)); + + assertEquals(List.of("start " + START.plusSeconds(1), "other " + START.plusSeconds(3), + "end " + START.plusSeconds(6)), order); + assertEquals(START.plusSeconds(6), time.now()); + } + + @Test + void aSleepOnTheTestThreadCanPassByItself() { + AtomicInteger ticks = new AtomicInteger(); + time.scheduler().scheduleAtFixedRate(ticks::incrementAndGet, 1, 1, TimeUnit.SECONDS); + + time.sleepAdvancing(Duration.ofSeconds(3)); + + assertEquals(3, ticks.get()); + assertEquals(START.plusSeconds(3), time.now()); + } + + @Test + void waitingForASleeperThatNeverArrivesFails() { + time.settleTimeout(Duration.ofMillis(50)); + + AssertionError error = assertThrows(AssertionError.class, () -> time.awaitSleepers(1)); + + assertTrue(error.getMessage().contains("expected 1 sleeping thread(s)"), error.getMessage()); + } + + @Test + void aTimedGetTimesOutExactlyWhenItsTimeoutHasPassed() throws Exception { + CompletableFuture never = new CompletableFuture<>(); + AtomicReference outcome = new AtomicReference<>(); + AtomicBoolean interruptLeftBehind = new AtomicBoolean(); + Thread waiter = Thread.ofPlatform().name("waiter").start(() -> { + try { + outcome.set(time.get(never, Duration.ofMinutes(5))); + } catch (TimeoutException | InterruptedException | ExecutionException e) { + outcome.set(e); + } + interruptLeftBehind.set(Thread.currentThread().isInterrupted()); + }); + time.awaitWaiters(1); + + time.advance(Duration.ofMinutes(5).minusNanos(1)); + assertNull(outcome.get()); + assertEquals(1, time.waiters()); + + time.advance(Duration.ofNanos(1)); + assertInstanceOf(TimeoutException.class, outcome.get()); + assertEquals(0, time.waiters()); + waiter.join(); + assertFalse(interruptLeftBehind.get()); + } + + @Test + void aTimedGetReturnsWhatArrivesBeforeItsDeadline() throws Exception { + CompletableFuture answer = new CompletableFuture<>(); + CompletableFuture failure = new CompletableFuture<>(); + AtomicReference answered = new AtomicReference<>(); + AtomicReference failed = new AtomicReference<>(); + Thread first = Thread.ofVirtual().name("first").start(() -> answered.set(timedGet(answer))); + Thread second = Thread.ofPlatform().name("second").start(() -> failed.set(timedGet(failure))); + time.awaitWaiters(2); + time.advance(Duration.ofMinutes(5).minusNanos(1)); + + answer.complete("signalled"); + failure.completeExceptionally(new IllegalStateException("boom")); + first.join(); + second.join(); + + assertEquals("signalled", answered.get()); + assertInstanceOf(IllegalStateException.class, ((ExecutionException) failed.get()).getCause()); + assertEquals(0, time.waiters()); + time.advance(Duration.ofMinutes(1)); + assertEquals("signalled", answered.get()); + } + + @Test + void aTimedPollTakesOneTurnPerTimeoutHoweverFarTheTestJumps() throws Exception { + LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); + List polled = new CopyOnWriteArrayList<>(); + Thread poller = Thread.ofVirtual().name("poller").start(() -> { + try { + for (int turn = 0; turn < 4; turn++) { + polled.add(time.poll(queue, Duration.ofSeconds(20)) + " at " + time.now()); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + time.awaitWaiters(1); + + time.advance(Duration.ofSeconds(50)); + assertEquals(List.of("null at " + START.plusSeconds(20), "null at " + START.plusSeconds(40)), polled); + + queue.add("message"); + queue.add("another"); + poller.join(); + assertEquals(List.of("message at " + START.plusSeconds(50), "another at " + START.plusSeconds(50)), + polled.subList(2, 4)); + assertEquals(0, time.waiters()); + } + + @Test + void aCallReturningAfterDeadlineSelectionIsNotInterruptedByItsWake() throws Exception { + CompletableFuture response = new CompletableFuture<>(); + CompletableFuture result = new CompletableFuture<>(); + CountDownLatch returned = new CountDownLatch(1); + Semaphore continueAfterWake = new Semaphore(0); + AtomicBoolean staleInterrupt = new AtomicBoolean(); + Thread waiter = Thread.ofPlatform().name("returned-before-wake").start(() -> { + try { + result.complete(time.within(Duration.ofSeconds(1), response::get)); + returned.countDown(); + continueAfterWake.acquireUninterruptibly(); + staleInterrupt.set(Thread.currentThread().isInterrupted()); + } catch (Exception e) { + result.completeExceptionally(e); + } + }); + try { + time.awaitWaiters(1); + // Split selection from firing to force the return between these two real timeline steps. + Method takeDue = TestTime.class.getDeclaredMethod("takeDue", Instant.class); + takeDue.setAccessible(true); + Object due = takeDue.invoke(time, START.plusSeconds(1)); + response.complete("returned normally"); + assertTrue(returned.await(5, TimeUnit.SECONDS)); + assertEquals("returned normally", result.get(5, TimeUnit.SECONDS)); + Method fire = due.getClass().getDeclaredMethod("fire"); + fire.setAccessible(true); + fire.invoke(due); + continueAfterWake.release(); + waiter.join(5000); + assertFalse(waiter.isAlive()); + assertFalse(staleInterrupt.get(), "the selected deadline must not interrupt a call that already returned"); + assertEquals(0, time.waiters()); + } finally { + response.complete("cleanup"); + continueAfterWake.release(); + waiter.interrupt(); + waiter.join(5000); + } + } + + @Test + void anyBlockingCallCanBeBoundedOnTheTimeline() throws Exception { + Object monitor = new Object(); + CountDownLatch latch = new CountDownLatch(1); + List order = new CopyOnWriteArrayList<>(); + Thread onMonitor = Thread.ofPlatform().name("on-monitor").start(() -> { + synchronized (monitor) { + try { + time.within(Duration.ofSeconds(30), () -> { + monitor.wait(); + return null; + }); + order.add("notified"); + } catch (TimeoutException e) { + order.add("monitor timed out at " + time.now()); + } catch (InterruptedException e) { + order.add("interrupted"); + } + } + }); + Thread onLatch = Thread.ofPlatform().name("on-latch").start(() -> { + try { + time.within(Duration.ofSeconds(10), () -> { + latch.await(); + return null; + }); + order.add("released"); + } catch (TimeoutException e) { + order.add("latch timed out at " + time.now()); + } catch (InterruptedException e) { + order.add("interrupted"); + } + }); + time.awaitWaiters(2); + + time.advance(Duration.ofMinutes(1)); + + onMonitor.join(); + onLatch.join(); + assertEquals(List.of("latch timed out at " + START.plusSeconds(10), + "monitor timed out at " + START.plusSeconds(30)), order); + } + + @Test + void aThreadInterruptedInATimedWaitSeesTheInterruptNotATimeout() throws Exception { + AtomicReference outcome = new AtomicReference<>(); + Thread waiter = Thread.ofPlatform().name("waiter").start( + () -> outcome.set(timedGet(new CompletableFuture<>()))); + time.awaitWaiters(1); + + waiter.interrupt(); + waiter.join(); + + assertInstanceOf(InterruptedException.class, outcome.get()); + assertEquals(0, time.waiters()); + time.advance(Duration.ofMinutes(10)); + } + + @Test + void aTimedWaitWithNoTimeLeftNeverBlocks() throws Exception { + CompletableFuture pending = new CompletableFuture<>(); + LinkedBlockingQueue queue = new LinkedBlockingQueue<>(List.of("ready")); + + assertThrows(TimeoutException.class, () -> time.get(pending, Duration.ZERO)); + assertThrows(TimeoutException.class, () -> time.within(Duration.ofSeconds(-1), () -> pending.get())); + assertEquals("done", time.get(CompletableFuture.completedFuture("done"), Duration.ZERO)); + assertEquals("ready", time.poll(queue, Duration.ZERO)); + assertNull(time.poll(queue, Duration.ZERO)); + assertEquals(START, time.now()); + } + + @Test + void aTimedGetOnTheTestThreadCanPassByItself() throws Exception { + CompletableFuture response = new CompletableFuture<>(); + AtomicInteger ticks = new AtomicInteger(); + time.scheduler().scheduleAtFixedRate(ticks::incrementAndGet, 1, 1, TimeUnit.SECONDS); + time.scheduler().schedule(() -> response.complete("late answer"), 3, TimeUnit.SECONDS); + + assertEquals("late answer", time.getAdvancing(response, Duration.ofSeconds(10))); + assertEquals(START.plusSeconds(3), time.now()); + assertEquals(3, ticks.get()); + + assertThrows(TimeoutException.class, + () -> time.getAdvancing(new CompletableFuture<>(), Duration.ofSeconds(10))); + assertEquals(START.plusSeconds(13), time.now()); + assertEquals(13, ticks.get()); + } + + @Test + void aTimedGetInsideATaskMovesTheTimelineItself() { + CompletableFuture response = new CompletableFuture<>(); + List order = new ArrayList<>(); + time.scheduler().schedule(() -> { + try { + order.add(time.get(response, Duration.ofSeconds(30)) + " at " + time.now()); + } catch (InterruptedException | ExecutionException | TimeoutException e) { + order.add(e.toString()); + } + }, 1, TimeUnit.SECONDS); + time.scheduler().schedule(() -> response.complete("answer"), 5, TimeUnit.SECONDS); + + time.advance(Duration.ofSeconds(1)); + + assertEquals(List.of("answer at " + START.plusSeconds(5)), order); + IllegalStateException refused = assertThrows(IllegalStateException.class, () -> { + Future task = time.scheduler().submit(() -> time.within(Duration.ofSeconds(1), () -> response.get())); + time.runDue(); + try { + task.get(); + } catch (ExecutionException e) { + throw (RuntimeException) e.getCause(); + } + }); + assertTrue(refused.getMessage().contains("would stop the timeline"), refused.getMessage()); + } + + @Test + void advanceUntilStopsAtTheInstantTheConditionFirstHolds() throws Exception { + AtomicInteger polls = new AtomicInteger(); + Thread poller = Thread.ofVirtual().name("poller").start(() -> { + try { + while (true) { + time.sleepMillis(250); + polls.incrementAndGet(); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + time.awaitSleepers(1); + + assertTrue(time.advanceUntil(() -> polls.get() == 7, Duration.ofMinutes(5))); + assertEquals(START.plusMillis(1750), time.now()); + + assertFalse(time.advanceUntil(() -> polls.get() == 12, Duration.ofSeconds(1))); + assertEquals(START.plusMillis(2750), time.now()); + assertEquals(11, polls.get()); + + assertTrue(time.advanceUntil(() -> true, Duration.ofHours(1))); + assertEquals(START.plusMillis(2750), time.now()); + assertThrows(IllegalArgumentException.class, () -> time.advanceUntil(() -> true, Duration.ofNanos(-1))); + poller.interrupt(); + poller.join(); + } + + /** What a five-minute timed get of {@code future} ends with: its value, or what it threw. */ + private Object timedGet(CompletableFuture future) { + try { + return time.get(future, Duration.ofMinutes(5)); + } catch (TimeoutException | InterruptedException | ExecutionException e) { + return e; + } + } + + @Test + void sleepersAndTimedWaitersAreCountedApart() throws Exception { + Thread sleeper = Thread.ofVirtual().name("sleeper").start(() -> { + try { + time.sleep(Duration.ofMinutes(1)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + Thread waiter = Thread.ofVirtual().name("waiter").start(() -> timedGet(new CompletableFuture<>())); + time.awaitSleepers(1); + time.awaitWaiters(1); + + assertEquals(1, time.sleepers()); + assertEquals(1, time.waiters()); + + time.advance(Duration.ofMinutes(1)); + sleeper.join(); + assertEquals(0, time.sleepers()); + assertEquals(1, time.waiters()); + + time.advance(Duration.ofMinutes(4)); + waiter.join(); + assertEquals(0, time.waiters()); + time.settleTimeout(Duration.ofMillis(50)); + AssertionError error = assertThrows(AssertionError.class, () -> time.awaitWaiters(1)); + assertTrue(error.getMessage().contains("expected 1 waiting thread(s)"), error.getMessage()); + } + + @Test + void aSleeperQueuedForTheTimelinesOwnLockHasNotSettled() throws Exception { + // Other threads reading the timeline keep its lock busy, so the poller often has to queue + // for it on the way back into its next sleep. Queued there it looks parked, but it is still + // on its way: the advance must wait for it, or it leaves polls behind. + AtomicBoolean reading = new AtomicBoolean(true); + List readers = new ArrayList<>(); + for (int i = 0; i < 4; i++) { + readers.add(Thread.ofPlatform().daemon().name("reader-" + i).start(() -> { + while (reading.get()) { + time.sleepers(); + } + })); + } + AtomicInteger polls = new AtomicInteger(); + Thread poller = Thread.ofPlatform().daemon().name("poller").start(() -> { + try { + while (true) { + time.sleep(Duration.ofMillis(100)); + polls.incrementAndGet(); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + try { + time.awaitSleepers(1); + + time.advance(Duration.ofSeconds(50).minusNanos(1)); + + assertEquals(499, polls.get()); + assertEquals(1, time.sleepers()); + } finally { + reading.set(false); + poller.interrupt(); + poller.join(); + for (Thread reader : readers) { + reader.join(); + } + } + } +}