SPB Git

Repository Public

VQManualClock.swift 3.1 KB 71 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKitTesting/VQManualClock.swift3// Description: A clock a test moves by hand: sleeps suspend until `advance` passes their deadline.4import Foundation5import VQuantKit67public final class VQManualClock: VQClock, @unchecked Sendable {8    private let lock = NSLock()9    private var current: Date10    private var nextID = 011    private var sleepers: [Int: (deadline: Date, continuation: CheckedContinuation<Void, Error>)] = [:]12    private var history: [TimeInterval] = []1314    public init(now: Date = Date(timeIntervalSince1970: 1_795_000_000)) { current = now }1516    public func now() -> Date { lock.withLock { current } }1718    /// Every duration asked so far, in order (to assert a back-off sequence).19    public var recordedSleeps: [TimeInterval] { lock.withLock { history } }20    public var pendingSleepers: Int { lock.withLock { sleepers.count } }2122    public func sleep(seconds: TimeInterval) async throws {23        let id: Int = lock.withLock { nextID += 1; history.append(seconds); return nextID }24        try await withTaskCancellationHandler {25            try await withCheckedThrowingContinuation { (c: CheckedContinuation<Void, Error>) in26                let resumeNow: Bool = lock.withLock {27                    if Task.isCancelled { return true }28                    sleepers[id] = (current.addingTimeInterval(seconds), c)29                    return false30                }31                if resumeNow { c.resume(throwing: CancellationError()) }32            }33        } onCancel: {34            let c = lock.withLock { sleepers.removeValue(forKey: id)?.continuation }35            c?.resume(throwing: CancellationError())36        }37    }3839    /// Moves time forward and resumes the sleeps whose deadline has passed.40    public func advance(by seconds: TimeInterval) {41        let due: [CheckedContinuation<Void, Error>] = lock.withLock {42            current = current.addingTimeInterval(seconds)43            let ids = sleepers.filter { $0.value.deadline <= current }.map(\.key)44            return ids.compactMap { sleepers.removeValue(forKey: $0)?.continuation }45        }46        for c in due { c.resume() }47    }4849    /// Waits (in real time, briefly) until at least `count` tasks are asleep on this clock. Returns false on timeout.50    @discardableResult51    public func waitForSleepers(_ count: Int = 1, timeout: TimeInterval = 5) async -> Bool {52        let end = Date().addingTimeInterval(timeout)53        while Date() < end {54            if pendingSleepers >= count { return true }55            try? await Task.sleep(nanoseconds: 2_000_000)56        }57        return pendingSleepers >= count58    }59}6061/// Polls a condition in real time (for effects that cross tasks). Returns whether it became true.62@discardableResult63public func vqWaitUntil(timeout: TimeInterval = 5, _ condition: @Sendable () async -> Bool) async -> Bool {64    let end = Date().addingTimeInterval(timeout)65    while Date() < end {66        if await condition() { return true }67        try? await Task.sleep(nanoseconds: 2_000_000)68    }69    return await condition()70}71
Files main
Menu

Theme