Created
June 24, 2025 08:38
-
-
Save manmal/b612794be8229e9ca9c9b57cddcd5da7 to your computer and use it in GitHub Desktop.
ClockDriftDetectingStream - needs to "open" clock existential
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// `some` opens the existential clock and instants | |
func clockDriftDetectingStream( | |
_ clock: some Clock<Duration>, | |
checkEverySeconds: Double, | |
toleranceSeconds: Double | |
) -> AsyncStream<Void> { | |
let startInstant = clock.now | |
let period = Duration.seconds(checkEverySeconds) | |
let tolerance = Duration.seconds(toleranceSeconds) | |
precondition(tolerance < period, "tolerance must be less than the period") | |
let (stream, continuation) = AsyncStream<Void>.makeStream() | |
let task = Task { | |
var expectedInstant = startInstant | |
while !Task.isCancelled { | |
do { | |
try await clock.sleep(for: period) | |
} catch { | |
break | |
} | |
expectedInstant = expectedInstant.advanced(by: period) | |
let now = clock.now | |
// ❌ This wouldn't compile without opening `clock` | |
let drift = expectedInstant.duration(to: now) | |
let negativeTolerance = Duration.zero - tolerance | |
if drift > tolerance || drift < negativeTolerance { | |
continuation.yield(()) | |
} | |
} | |
continuation.finish() | |
} | |
continuation.onTermination = { _ in | |
task.cancel() | |
} | |
return stream | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment