diff --git a/.github/workflows/swiftpm.yml b/.github/workflows/swiftpm.yml new file mode 100644 index 0000000..721a97f --- /dev/null +++ b/.github/workflows/swiftpm.yml @@ -0,0 +1,31 @@ +name: SwiftPM + +on: + pull_request: + branches: [master] + push: + branches: [master] + +permissions: + contents: read + +concurrency: + group: swiftpm-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + macos: + name: macOS debug and release tests + runs-on: macos-15 + timeout-minutes: 15 + steps: + - name: Check out source + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - name: Show Swift version + run: swift --version + - name: Test debug build + run: swift test --jobs 2 + - name: Test release build + run: swift test --configuration release --jobs 2 diff --git a/.gitignore b/.gitignore index 021f2f2..61b5757 100644 --- a/.gitignore +++ b/.gitignore @@ -40,6 +40,7 @@ playground.xcworkspace # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. # Packages/ .build/ +.swiftpm/ # CocoaPods # @@ -66,4 +67,4 @@ Carthage/Build fastlane/report.xml fastlane/Preview.html fastlane/screenshots -fastlane/test_output \ No newline at end of file +fastlane/test_output diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..d4cb338 --- /dev/null +++ b/Package.swift @@ -0,0 +1,34 @@ +// swift-tools-version:5.0 + +import PackageDescription + +let package = Package( + name: "SwiftTimer", + platforms: [ + .iOS(.v8), + .macOS(.v10_11), + .tvOS(.v10), + .watchOS(.v3) + ], + products: [ + .library(name: "SwiftTimer", targets: ["SwiftTimer"]) + ], + targets: [ + .target( + name: "SwiftTimer", + path: "Sources", + exclude: [ + "Info-iOS.plist", + "Info-macOS.plist", + "Info-tvOS.plist", + "Info-watchOS.plist", + "SwiftTimer.h" + ] + ), + .testTarget( + name: "SwiftTimerTests", + dependencies: ["SwiftTimer"] + ) + ], + swiftLanguageVersions: [.v5] +) diff --git a/README.md b/README.md index 742feb0..f034f3e 100644 --- a/README.md +++ b/README.md @@ -84,8 +84,62 @@ timer.start() ## Installation -Carthage: +### Swift Package Manager + +SwiftTimer can be added as a Swift Package Manager dependency with Swift 5.0 or later. +The package exposes the `SwiftTimer` library and keeps the existing deployment targets: +iOS 8, macOS 10.11, tvOS 10, and watchOS 3. Your Xcode version may require a newer +deployment target. The package also builds on Linux using Foundation and Dispatch. + +In Xcode, choose **File > Add Package Dependencies**, enter +`https://github.com/100mango/SwiftTimer.git`, and add the `SwiftTimer` product to your target. +Select **Up to Next Major Version** starting at **1.2.0**. Version 1.2.0 is the +first release with a package manifest; the older `v1.0` and `1.1` tags do not +support Swift Package Manager. + +For a `Package.swift` dependency: + +~~~swift +dependencies: [ + .package(url: "https://github.com/100mango/SwiftTimer.git", from: "1.2.0") +], +targets: [ + .target(name: "YourTarget", dependencies: ["SwiftTimer"]) +] +~~~ + +Then use `import SwiftTimer` in your Swift files. The package compiles in Swift 5 +language mode, including when used with a Swift 6 toolchain. + +### Queue and cancellation behavior + +Use each timer instance from a single serial queue. `fire()` calls its handler +synchronously on the caller's queue; scheduled events use the queue passed to the +initializer. Keep a strong reference to a timer for as long as it is needed. + +Debounce and throttle registration and cancellation are safe to call concurrently. +Identifiers share one registry across both operations. A pending throttle ignores +the same identifier; debounce replaces any pending work with that identifier. +The identifier becomes available before its handler runs, so handlers may schedule +or cancel new work with the same identifier. Cancellation prevents pending work +from starting; it does not interrupt a handler that has already started. + +### Carthage ~~~ github "100mango/SwiftTimer" ~~~ + +## Testing + +Run the cross-platform package tests with a current Swift toolchain: + +~~~sh +swift test +swift test -c release +~~~ + +The package tests cover timers, countdowns, debounce, and throttle without UIKit, +including lifecycle, reentrant handlers, concurrent cancellation, and input boundaries. +The existing Xcode project and its iOS tests remain available for Apple-platform +validation; Linux package tests do not replace Apple SDK or device testing. diff --git a/Sources/SwiftTimer.swift b/Sources/SwiftTimer.swift index 850ba3c..feef7a7 100644 --- a/Sources/SwiftTimer.swift +++ b/Sources/SwiftTimer.swift @@ -7,6 +7,7 @@ // import Foundation +import Dispatch public class SwiftTimer { @@ -92,52 +93,60 @@ public class SwiftTimer { //MARK: Throttle public extension SwiftTimer { - private static var workItems = [String:DispatchWorkItem]() + private static var workItems = [String: (item: DispatchWorkItem, token: UUID)]() + private static let workItemsLock = NSLock() ///The Handler will be called after interval you specified ///Calling again in the interval cancels the previous call static func debounce(interval: DispatchTimeInterval, identifier: String, queue: DispatchQueue = .main , handler: @escaping () -> Void ) { - //if already exist - if let item = workItems[identifier] { - item.cancel() - } - - let item = DispatchWorkItem { - handler(); - workItems.removeValue(forKey: identifier) - }; - workItems[identifier] = item - queue.asyncAfter(deadline: .now() + interval, execute: item); + scheduleWork(interval: interval, identifier: identifier, queue: queue, replacing: true, handler: handler) } ///The Handler will be called after interval you specified ///It is invalid to call again in the interval static func throttle(interval: DispatchTimeInterval, identifier: String, queue: DispatchQueue = .main , handler: @escaping () -> Void ) { - //if already exist - if workItems[identifier] != nil { - return; - } - - let item = DispatchWorkItem { - handler(); - workItems.removeValue(forKey: identifier) - }; - workItems[identifier] = item - queue.asyncAfter(deadline: .now() + interval, execute: item); - + scheduleWork(interval: interval, identifier: identifier, queue: queue, replacing: false, handler: handler) } static func cancelThrottlingTimer(identifier: String) { - if let item = workItems[identifier] { - item.cancel() - workItems.removeValue(forKey: identifier) + workItemsLock.lock() + let pending = workItems.removeValue(forKey: identifier) + workItemsLock.unlock() + pending?.item.cancel() + } + + private static func scheduleWork(interval: DispatchTimeInterval, identifier: String, queue: DispatchQueue, replacing: Bool, handler: @escaping () -> Void) { + workItemsLock.lock() + let previous = workItems[identifier] + if previous != nil && !replacing { + workItemsLock.unlock() + return } + + let token = UUID() + let item = DispatchWorkItem { + workItemsLock.lock() + guard workItems[identifier]?.token == token else { + workItemsLock.unlock() + return + } + // Remove only this generation before invoking user code. A handler may + // immediately schedule or cancel work with the same identifier. + let pending = workItems.removeValue(forKey: identifier) + workItemsLock.unlock() + withExtendedLifetime(pending) { + handler() + } + } + workItems[identifier] = (item, token) + workItemsLock.unlock() + // Keep replaced captures alive until after unlocking; their deinitializers + // may themselves register or cancel work. + previous?.item.cancel() + queue.asyncAfter(deadline: .now() + interval, execute: item) } - - - } //MARK: Count Down diff --git a/Tests/SwiftTimerTests/SwiftTimerTests.swift b/Tests/SwiftTimerTests/SwiftTimerTests.swift new file mode 100644 index 0000000..f105def --- /dev/null +++ b/Tests/SwiftTimerTests/SwiftTimerTests.swift @@ -0,0 +1,522 @@ +import Dispatch +import Foundation +import XCTest +import SwiftTimer + +final class SwiftTimerTests: XCTestCase { + func testSingleTimerFiresOnce() { + let fired = expectation(description: "Single timer fires") + fired.assertForOverFulfill = true + var count = 0 + let timer = SwiftTimer(interval: .milliseconds(10)) { _ in + count += 1 + fired.fulfill() + } + + XCTAssertFalse(timer.repeats) + timer.start() + wait(for: [fired], timeout: 2) + waitForMainQueue(milliseconds: 50) + XCTAssertEqual(count, 1) + withExtendedLifetime(timer) {} + } + + func testTimerWaitsForStart() { + var count = 0 + let fired = expectation(description: "Timer starts after suspension") + let timer = SwiftTimer(interval: .milliseconds(10)) { _ in + count += 1 + fired.fulfill() + } + + waitForMainQueue(milliseconds: 50) + XCTAssertEqual(count, 0) + timer.start() + wait(for: [fired], timeout: 2) + withExtendedLifetime(timer) {} + } + + func testRepeatingTimerCanSuspendAndResume() { + let firstRun = expectation(description: "First repeated events") + let resumed = expectation(description: "Timer resumes") + var count = 0 + let timer = SwiftTimer.repeaticTimer(interval: .milliseconds(10)) { timer in + count += 1 + if count == 2 { + timer.suspend() + firstRun.fulfill() + } else if count == 3 { + timer.suspend() + resumed.fulfill() + } + } + + XCTAssertTrue(timer.repeats) + timer.start() + timer.start() // Repeated starts must not over-resume the dispatch source. + wait(for: [firstRun], timeout: 2) + timer.suspend() // Repeated suspensions must not over-suspend it either. + waitForMainQueue(milliseconds: 50) + XCTAssertEqual(count, 2) + timer.start() + wait(for: [resumed], timeout: 2) + XCTAssertEqual(count, 3) + withExtendedLifetime(timer) {} + } + + func testManualFireUsesCurrentHandler() { + var originalCount = 0 + var replacementCount = 0 + let timer = SwiftTimer.repeaticTimer(interval: .seconds(60)) { _ in + originalCount += 1 + } + + timer.fire() + timer.rescheduleHandler { _ in replacementCount += 1 } + timer.fire() + XCTAssertEqual(originalCount, 1) + XCTAssertEqual(replacementCount, 1) + } + + func testManualFireCancelsScheduledSingleTimer() { + var count = 0 + let timer = SwiftTimer(interval: .milliseconds(10)) { _ in count += 1 } + + timer.fire() + timer.start() + waitForMainQueue(milliseconds: 50) + XCTAssertEqual(count, 1) + withExtendedLifetime(timer) {} + } + + func testRescheduledHandlerReceivesScheduledEvent() { + let fired = expectation(description: "Replacement handler receives event") + let timer = SwiftTimer(interval: .milliseconds(10)) { _ in + XCTFail("The original handler must be replaced") + } + timer.rescheduleHandler { _ in fired.fulfill() } + + timer.start() + wait(for: [fired], timeout: 2) + withExtendedLifetime(timer) {} + } + + func testRepeatingIntervalCanBeRescheduled() { + let fired = expectation(description: "Rescheduled timer fires") + let timer = SwiftTimer.repeaticTimer(interval: .seconds(60)) { timer in + timer.suspend() + fired.fulfill() + } + + timer.start() + timer.rescheduleRepeating(interval: .milliseconds(10)) + wait(for: [fired], timeout: 2) + withExtendedLifetime(timer) {} + } + + func testTimerDoesNotRetainItselfWhileRunningOrSuspended() { + for shouldStart in [false, true] { + weak var reference: SwiftTimer? + do { + let timer = SwiftTimer.repeaticTimer(interval: .seconds(60)) { _ in } + reference = timer + if shouldStart { + timer.start() + } + } + XCTAssertNil(reference) + } + } + + func testTimerUsesRequestedQueue() { + let queue = DispatchQueue(label: "SwiftTimerTests.custom") + let key = DispatchSpecificKey() + queue.setSpecific(key: key, value: "custom") + let fired = expectation(description: "Timer fires on requested queue") + let timer = SwiftTimer(interval: .milliseconds(10), queue: queue) { _ in + XCTAssertEqual(DispatchQueue.getSpecific(key: key), "custom") + fired.fulfill() + } + + timer.start() + wait(for: [fired], timeout: 2) + withExtendedLifetime(timer) {} + } + + func testDebounceOnlyInvokesLatestHandler() { + let identifier = UUID().uuidString + defer { SwiftTimer.cancelThrottlingTimer(identifier: identifier) } + let fired = expectation(description: "Latest debounced handler fires") + fired.assertForOverFulfill = true + + for _ in 0..<3 { + SwiftTimer.debounce(interval: .milliseconds(10), identifier: identifier) { + XCTFail("Earlier debounce handlers must be cancelled") + } + } + SwiftTimer.debounce(interval: .milliseconds(10), identifier: identifier) { + fired.fulfill() + } + + wait(for: [fired], timeout: 2) + waitForMainQueue(milliseconds: 50) + } + + func testThrottleOnlyInvokesFirstHandlerWithinWindowAndCanBeReused() { + let identifier = UUID().uuidString + defer { SwiftTimer.cancelThrottlingTimer(identifier: identifier) } + let first = expectation(description: "First throttled handler fires") + let second = expectation(description: "Identifier is reusable after firing") + + SwiftTimer.throttle(interval: .milliseconds(10), identifier: identifier) { + first.fulfill() + } + for _ in 0..<3 { + SwiftTimer.throttle(interval: .milliseconds(10), identifier: identifier) { + XCTFail("Calls within the throttle window must be ignored") + } + } + wait(for: [first], timeout: 2) + + SwiftTimer.throttle(interval: .milliseconds(10), identifier: identifier) { + second.fulfill() + } + wait(for: [second], timeout: 2) + } + + func testCancellingPendingDebounceAndThrottlePreventsDelivery() { + let debounceID = UUID().uuidString + let throttleID = UUID().uuidString + let cancelled = expectation(description: "Cancelled handlers do not fire") + cancelled.isInverted = true + + SwiftTimer.debounce(interval: .milliseconds(10), identifier: debounceID) { + cancelled.fulfill() + } + SwiftTimer.throttle(interval: .milliseconds(10), identifier: throttleID) { + cancelled.fulfill() + } + SwiftTimer.cancelThrottlingTimer(identifier: debounceID) + SwiftTimer.cancelThrottlingTimer(identifier: throttleID) + SwiftTimer.cancelThrottlingTimer(identifier: "missing") + + wait(for: [cancelled], timeout: 0.1) + } + + func testCountdownStopsAtZeroAndCanRestart() { + let first = expectation(description: "Countdown reaches zero") + let second = expectation(description: "Reset countdown reaches zero") + var values: [Int] = [] + var restarted = false + let timer = SwiftCountDownTimer(interval: .milliseconds(10), times: 3) { _, remaining in + values.append(remaining) + if remaining == 0 { + (restarted ? second : first).fulfill() + } + } + + timer.start() + wait(for: [first], timeout: 2) + waitForMainQueue(milliseconds: 50) + XCTAssertEqual(values, [2, 1, 0]) + + restarted = true + timer.reCountDown() + timer.start() + wait(for: [second], timeout: 2) + timer.suspend() + XCTAssertEqual(values, [2, 1, 0, 2, 1, 0]) + withExtendedLifetime(timer) {} + } + + func testSecondsConversionUsesMilliseconds() { + switch DispatchTimeInterval.fromSeconds(1.25) { + case .milliseconds(let value): + XCTAssertEqual(value, 1_250) + default: + XCTFail("Seconds must be represented as milliseconds") + } + } + + func testThrottleCanScheduleSameIdentifierFromItsHandler() { + let identifier = UUID().uuidString + defer { SwiftTimer.cancelThrottlingTimer(identifier: identifier) } + let completed = expectation(description: "Reentrant throttle fires three times") + var count = 0 + func schedule() { + SwiftTimer.throttle(interval: .milliseconds(0), identifier: identifier) { + count += 1 + if count < 3 { + schedule() + } else { + completed.fulfill() + } + } + } + + schedule() + wait(for: [completed], timeout: 2) + XCTAssertEqual(count, 3) + } + + func testReentrantDebounceRemainsCancellableAfterOriginalHandlerReturns() { + let identifier = UUID().uuidString + let queue = DispatchQueue(label: "SwiftTimerTests.reentrantDebounce") + queue.suspend() + let cancelled = expectation(description: "Replacement remains cancellable") + cancelled.isInverted = true + let drained = expectation(description: "Replacement queue runs") + SwiftTimer.debounce(interval: .milliseconds(0), identifier: identifier) { + SwiftTimer.debounce(interval: .milliseconds(0), identifier: identifier, queue: queue) { + cancelled.fulfill() + } + DispatchQueue.main.async { + SwiftTimer.cancelThrottlingTimer(identifier: identifier) + queue.resume() + queue.async { drained.fulfill() } + } + } + + wait(for: [drained, cancelled], timeout: 0.2) + SwiftTimer.cancelThrottlingTimer(identifier: identifier) + } + + func testConcurrentIdentifiersAndCancellationAreIndependent() { + let prefix = UUID().uuidString + let completed = expectation(description: "All uncancelled callbacks fire") + completed.expectedFulfillmentCount = 50 + completed.assertForOverFulfill = true + var values = Set() + + // Callbacks use the main queue, which cannot run until registration returns. + // This makes cancellation deterministic while registrations overlap on workers. + DispatchQueue.concurrentPerform(iterations: 100) { index in + let identifier = "\(prefix)-\(index)" + SwiftTimer.debounce(interval: .milliseconds(0), identifier: identifier) { + XCTAssertEqual(index % 2, 0) + values.insert(index) + completed.fulfill() + } + if index % 2 != 0 { + SwiftTimer.cancelThrottlingTimer(identifier: identifier) + } + } + + wait(for: [completed], timeout: 2) + XCTAssertEqual(values, Set(stride(from: 0, to: 100, by: 2))) + for index in 0..<100 { + SwiftTimer.cancelThrottlingTimer(identifier: "\(prefix)-\(index)") + } + } + + func testDebounceAndThrottleUseRequestedQueue() { + let queue = DispatchQueue(label: "SwiftTimerTests.workItems") + let key = DispatchSpecificKey() + queue.setSpecific(key: key, value: "workItems") + let completed = expectation(description: "Callbacks use requested queue") + completed.expectedFulfillmentCount = 2 + let handler = { + XCTAssertEqual(DispatchQueue.getSpecific(key: key), "workItems") + completed.fulfill() + } + + SwiftTimer.debounce(interval: .milliseconds(0), identifier: UUID().uuidString, queue: queue, handler: handler) + SwiftTimer.throttle(interval: .milliseconds(0), identifier: UUID().uuidString, queue: queue, handler: handler) + wait(for: [completed], timeout: 2) + } + + func testConcurrentDebounceWithSameIdentifierOnlyRunsLatestRegistration() { + assertConcurrentRegistrationsOnlyFireOnce(replacing: true) + } + + func testConcurrentThrottleWithSameIdentifierOnlyRunsFirstRegistration() { + assertConcurrentRegistrationsOnlyFireOnce(replacing: false) + } + + private func assertConcurrentRegistrationsOnlyFireOnce(replacing: Bool) { + let identifier = UUID().uuidString + let queue = DispatchQueue(label: "SwiftTimerTests.sameIdentifier") + queue.suspend() + let fired = expectation(description: "One registration wins") + fired.assertForOverFulfill = true + var count = 0 + let selectedHandler = { + count += 1 + fired.fulfill() + } + if !replacing { + SwiftTimer.throttle(interval: .milliseconds(0), identifier: identifier, queue: queue, handler: selectedHandler) + } + DispatchQueue.concurrentPerform(iterations: 64) { _ in + let handler = { + XCTFail("A superseded or throttled registration must not fire") + } + if replacing { + SwiftTimer.debounce(interval: .milliseconds(0), identifier: identifier, queue: queue, handler: handler) + } else { + SwiftTimer.throttle(interval: .milliseconds(0), identifier: identifier, queue: queue, handler: handler) + } + } + if replacing { + SwiftTimer.debounce(interval: .milliseconds(0), identifier: identifier, queue: queue, handler: selectedHandler) + } + queue.resume() + wait(for: [fired], timeout: 2) + queue.sync { XCTAssertEqual(count, 1) } + SwiftTimer.cancelThrottlingTimer(identifier: identifier) + } + + func testRescheduleRepeatingDoesNotChangeSingleTimer() { + let completed = expectation(description: "Single timer keeps its deadline") + let timer = SwiftTimer(interval: .milliseconds(0)) { _ in completed.fulfill() } + timer.rescheduleRepeating(interval: .seconds(60)) + timer.start() + wait(for: [completed], timeout: 2) + withExtendedLifetime(timer) {} + } + + func testRepeatingTimerCanFireReentrantly() { + var count = 0 + let timer = SwiftTimer.repeaticTimer(interval: .seconds(60)) { timer in + count += 1 + if count < 3 { + timer.fire() + } + } + + timer.fire() + XCTAssertEqual(count, 3) + } + + func testTimerCanReleaseLastReferenceFromCallback() { + let completed = expectation(description: "Timer releases itself from callback") + var timer: SwiftTimer? + weak var reference: SwiftTimer? + timer = SwiftTimer.repeaticTimer(interval: .milliseconds(10)) { firingTimer in + firingTimer.suspend() + timer = nil + completed.fulfill() + } + reference = timer + timer?.start() + + wait(for: [completed], timeout: 2) + XCTAssertNil(reference) + } + + func testReplacingHandlerReleasesItsCapturedObject() { + let released = expectation(description: "Old handler releases its capture") + var timer: SwiftTimer? + do { + let probe = LifetimeProbe { released.fulfill() } + timer = SwiftTimer(interval: .seconds(60)) { [probe] _ in + withExtendedLifetime(probe) {} + } + } + timer?.rescheduleHandler { _ in } + + wait(for: [released], timeout: 2) + withExtendedLifetime(timer) {} + } + + func testNonPositiveCountdownNeverCallsHandler() { + let unexpected = expectation(description: "Nonpositive countdown stays silent") + unexpected.isInverted = true + let zero = SwiftCountDownTimer(interval: .milliseconds(0), times: 0) { _, _ in unexpected.fulfill() } + let negative = SwiftCountDownTimer(interval: .milliseconds(0), times: -1) { _, _ in unexpected.fulfill() } + zero.start() + negative.start() + + wait(for: [unexpected], timeout: 0.1) + zero.suspend() + negative.suspend() + withExtendedLifetime((zero, negative)) {} + } + + func testCountdownCanSuspendInHandlerAndResumeWithoutResetting() { + let paused = expectation(description: "Countdown pauses after first event") + let completed = expectation(description: "Countdown resumes from remaining count") + var values: [Int] = [] + let timer = SwiftCountDownTimer(interval: .milliseconds(10), times: 3) { timer, remaining in + values.append(remaining) + if remaining == 2 { + timer.suspend() + paused.fulfill() + } else if remaining == 0 { + timer.suspend() + completed.fulfill() + } + } + timer.start() + wait(for: [paused], timeout: 2) + XCTAssertEqual(values, [2]) + timer.start() + wait(for: [completed], timeout: 2) + XCTAssertEqual(values, [2, 1, 0]) + withExtendedLifetime(timer) {} + } + + func testCountdownCanResetFromItsCompletionHandler() { + let completed = expectation(description: "Countdown resets from callback") + var values: [Int] = [] + let timer = SwiftCountDownTimer(interval: .milliseconds(10), times: 2) { timer, remaining in + values.append(remaining) + if values == [1, 0] { + timer.reCountDown() + } else if values == [1, 0, 1, 0] { + timer.suspend() + completed.fulfill() + } + } + timer.start() + wait(for: [completed], timeout: 2) + XCTAssertEqual(values, [1, 0, 1, 0]) + withExtendedLifetime(timer) {} + } + + func testCountdownCanReleaseLastReferenceFromCallback() { + let completed = expectation(description: "Countdown releases itself from callback") + var timer: SwiftCountDownTimer? + weak var reference: SwiftCountDownTimer? + timer = SwiftCountDownTimer(interval: .milliseconds(10), times: 1) { _, remaining in + XCTAssertEqual(remaining, 0) + timer = nil + completed.fulfill() + } + reference = timer + timer?.start() + wait(for: [completed], timeout: 2) + XCTAssertNil(reference) + } + + func testSecondsConversionHandlesZeroSubmillisecondAndNegativeValues() { + for (input, expected) in [(0.0, 0), (0.0009, 0), (1.9999, 1999), (-1.25, -1250)] { + switch DispatchTimeInterval.fromSeconds(input) { + case .milliseconds(let value): + XCTAssertEqual(value, expected) + default: + XCTFail("Seconds must be represented as milliseconds") + } + } + } + + private func waitForMainQueue(milliseconds: Int) { + let elapsed = expectation(description: "Main queue observation window") + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { + elapsed.fulfill() + } + wait(for: [elapsed], timeout: 2) + } +} + +private final class LifetimeProbe { + private let onDeinit: () -> Void + + init(onDeinit: @escaping () -> Void) { + self.onDeinit = onDeinit + } + + deinit { + onDeinit() + } +}