|
| 1 | +import Foundation |
| 2 | + |
| 3 | +// MARK: - ManualClock |
| 4 | + |
| 5 | +/// A deterministic test clock whose time only advances when the test calls |
| 6 | +/// `advance(by:)`. Sleepers are suspended on continuations and resumed once |
| 7 | +/// their deadline is crossed. |
| 8 | +/// |
| 9 | +/// Typical usage in a `@MainActor` Swift Testing test: |
| 10 | +/// |
| 11 | +/// ```swift |
| 12 | +/// let clock = ManualClock() |
| 13 | +/// let scheduler = SyncScheduler(provider: spy, interval: .seconds(1), clock: clock) |
| 14 | +/// scheduler.setSceneActive(true) |
| 15 | +/// |
| 16 | +/// // Wait for the loop to actually suspend in clock.sleep before advancing. |
| 17 | +/// await clock.waitForSleeper() |
| 18 | +/// await clock.advance(by: .seconds(1)) |
| 19 | +/// #expect(spy.callCount >= 1) |
| 20 | +/// ``` |
| 21 | +/// |
| 22 | +/// `waitForSleeper()` is the key — without it, `advance()` would run before |
| 23 | +/// the loop task has had a chance to call `sleep(until:)`, so there would be |
| 24 | +/// no sleepers to wake. |
| 25 | +final class ManualClock: Clock, @unchecked Sendable { |
| 26 | + |
| 27 | + // MARK: - Instant |
| 28 | + |
| 29 | + struct Instant: InstantProtocol { |
| 30 | + var offset: Duration |
| 31 | + |
| 32 | + static var zero: Instant { Instant(offset: .zero) } |
| 33 | + |
| 34 | + func advanced(by duration: Duration) -> Instant { |
| 35 | + Instant(offset: offset + duration) |
| 36 | + } |
| 37 | + |
| 38 | + func duration(to other: Instant) -> Duration { |
| 39 | + other.offset - offset |
| 40 | + } |
| 41 | + |
| 42 | + static func < (lhs: Instant, rhs: Instant) -> Bool { |
| 43 | + lhs.offset < rhs.offset |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + // MARK: - Clock conformance |
| 48 | + |
| 49 | + var now: Instant { |
| 50 | + lock.withLock { _now } |
| 51 | + } |
| 52 | + |
| 53 | + var minimumResolution: Duration { .nanoseconds(1) } |
| 54 | + |
| 55 | + func sleep(until deadline: Instant, tolerance: Duration? = nil) async throws { |
| 56 | + try Task.checkCancellation() |
| 57 | + |
| 58 | + // Fast path: already past deadline. |
| 59 | + if lock.withLock({ _now }) >= deadline { |
| 60 | + await Task.yield() |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + // Register a continuation keyed to a stable UUID owned by this call. |
| 65 | + let id = UUID() |
| 66 | + try await withTaskCancellationHandler { |
| 67 | + try await withCheckedThrowingContinuation { (cont: CheckedContinuation<Void, Error>) in |
| 68 | + // Take the lock once; handle both the double-check and the |
| 69 | + // sleeper-waiter notification inside it. |
| 70 | + var waitersToResume: [CheckedContinuation<Void, Never>] = [] |
| 71 | + lock.withLock { |
| 72 | + if _now >= deadline { |
| 73 | + cont.resume() |
| 74 | + } else { |
| 75 | + sleepers[id] = Sleeper(deadline: deadline, continuation: cont) |
| 76 | + // Collect waiters to resume outside the lock. |
| 77 | + waitersToResume = sleeperWaiters |
| 78 | + sleeperWaiters.removeAll() |
| 79 | + } |
| 80 | + } |
| 81 | + // Resume sleeperWaiters outside the lock (safe: NSLock is not reentrant). |
| 82 | + for waiter in waitersToResume { |
| 83 | + waiter.resume() |
| 84 | + } |
| 85 | + } |
| 86 | + } onCancel: { |
| 87 | + let sleeper = lock.withLock { sleepers.removeValue(forKey: id) } |
| 88 | + sleeper?.continuation.resume(throwing: CancellationError()) |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + // MARK: - Time advancement |
| 93 | + |
| 94 | + /// Advance `now` by `duration`, waking all sleepers whose deadline is |
| 95 | + /// ≤ the new `now`. Yields several times after resuming so woken tasks |
| 96 | + /// have time to run before the caller continues asserting. |
| 97 | + func advance(by duration: Duration) async { |
| 98 | + let woken: [Sleeper] = lock.withLock { |
| 99 | + _now = _now.advanced(by: duration) |
| 100 | + let threshold = _now |
| 101 | + var woken: [Sleeper] = [] |
| 102 | + for (key, sleeper) in sleepers where sleeper.deadline <= threshold { |
| 103 | + woken.append(sleeper) |
| 104 | + sleepers.removeValue(forKey: key) |
| 105 | + } |
| 106 | + return woken |
| 107 | + } |
| 108 | + |
| 109 | + for sleeper in woken { |
| 110 | + sleeper.continuation.resume() |
| 111 | + } |
| 112 | + |
| 113 | + // Multiple yields give resumed tasks (and their downstream MainActor |
| 114 | + // work) time to complete before the caller's assertion. |
| 115 | + for _ in 0..<8 { |
| 116 | + await Task.yield() |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + // MARK: - Test synchronisation |
| 121 | + |
| 122 | + /// Suspend until at least one task has registered a sleep with this clock. |
| 123 | + /// |
| 124 | + /// Call this after starting the scheduler and before calling `advance(by:)` |
| 125 | + /// to guarantee the loop has actually suspended in `sleep(until:)`. |
| 126 | + func waitForSleeper() async { |
| 127 | + // Fast path: already have a sleeper. |
| 128 | + if lock.withLock({ !sleepers.isEmpty }) { return } |
| 129 | + |
| 130 | + await withCheckedContinuation { (cont: CheckedContinuation<Void, Never>) in |
| 131 | + lock.withLock { |
| 132 | + // Double-check under the lock. |
| 133 | + if sleepers.isEmpty { |
| 134 | + sleeperWaiters.append(cont) |
| 135 | + } else { |
| 136 | + cont.resume() |
| 137 | + } |
| 138 | + } |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + // MARK: - Private |
| 143 | + |
| 144 | + private var _now: Instant = .zero |
| 145 | + private let lock = NSLock() |
| 146 | + private var sleepers: [UUID: Sleeper] = [:] |
| 147 | + private var sleeperWaiters: [CheckedContinuation<Void, Never>] = [] |
| 148 | + |
| 149 | + private struct Sleeper { |
| 150 | + let deadline: Instant |
| 151 | + let continuation: CheckedContinuation<Void, Error> |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +// MARK: - NSLock helper |
| 156 | + |
| 157 | +private extension NSLock { |
| 158 | + @discardableResult |
| 159 | + func withLock<T>(_ body: () throws -> T) rethrows -> T { |
| 160 | + lock() |
| 161 | + defer { unlock() } |
| 162 | + return try body() |
| 163 | + } |
| 164 | +} |
0 commit comments