|
| 1 | +import Foundation |
| 2 | + |
| 3 | +/// Struct that has time + related metadata |
| 4 | +public typealias AnnotatedTime = ( |
| 5 | + |
| 6 | + /// Time that is being annotated |
| 7 | + date: Date, |
| 8 | + |
| 9 | + /// Amount of time that has passed since the last NTP sync; in other words, the NTP response age. |
| 10 | + timeSinceLastNtpSync: TimeInterval |
| 11 | +) |
| 12 | + |
| 13 | +/// High level implementation for clock synchronization using NTP. All returned dates use the most accurate |
| 14 | +/// synchronization and it's not affected by clock changes. The NTP synchronization implementation has sub- |
| 15 | +/// second accuracy but given that Darwin doesn't support microseconds on bootTime, dates don't have sub- |
| 16 | +/// second accuracy. |
| 17 | +/// |
| 18 | +/// Example usage: |
| 19 | +/// |
| 20 | +/// ```swift |
| 21 | +/// Clock.sync { date, offset in |
| 22 | +/// print(date) |
| 23 | +/// } |
| 24 | +/// // (... later on ...) |
| 25 | +/// print(Clock.now) |
| 26 | +/// ``` |
| 27 | +public struct Clock { |
| 28 | + private static var stableTime: TimeFreeze? { |
| 29 | + didSet { |
| 30 | + self.storage.stableTime = self.stableTime |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + /// Determines where the most current stable time is stored. Use TimeStoragePolicy.appGroup to share |
| 35 | + /// between your app and an extension. |
| 36 | + public static var storage = TimeStorage(storagePolicy: .standard) |
| 37 | + |
| 38 | + /// The most accurate timestamp that we have so far (nil if no synchronization was done yet) |
| 39 | + public static var timestamp: TimeInterval? { |
| 40 | + return self.stableTime?.adjustedTimestamp |
| 41 | + } |
| 42 | + |
| 43 | + /// The most accurate date that we have so far (nil if no synchronization was done yet) |
| 44 | + public static var now: Date? { |
| 45 | + return self.annotatedNow?.date |
| 46 | + } |
| 47 | + |
| 48 | + /// Same as `now` except with analytic metadata about the time |
| 49 | + public static var annotatedNow: AnnotatedTime? { |
| 50 | + guard let stableTime = self.stableTime else { |
| 51 | + return nil |
| 52 | + } |
| 53 | + |
| 54 | + return AnnotatedTime(date: Date(timeIntervalSince1970: stableTime.adjustedTimestamp), |
| 55 | + timeSinceLastNtpSync: stableTime.timeSinceLastNtpSync) |
| 56 | + } |
| 57 | + |
| 58 | + /// Syncs the clock using NTP. Note that the full synchronization could take a few seconds. The given |
| 59 | + /// closure will be called with the first valid NTP response which accuracy should be good enough for the |
| 60 | + /// initial clock adjustment but it might not be the most accurate representation. After calling the |
| 61 | + /// closure this method will continue syncing with multiple servers and multiple passes. |
| 62 | + /// |
| 63 | + /// - parameter pool: NTP pool that will be resolved into multiple NTP servers that will be used for |
| 64 | + /// the synchronization. |
| 65 | + /// - parameter samples: The number of samples to be acquired from each server (default 4). |
| 66 | + /// - parameter completion: A closure that will be called after _all_ the NTP calls are finished. |
| 67 | + /// - parameter first: A closure that will be called after the first valid date is calculated. |
| 68 | + public static func sync(from pool: String = "time.apple.com", samples: Int = 4, |
| 69 | + first: ((Date, TimeInterval) -> Void)? = nil, |
| 70 | + completion: ((Date?, TimeInterval?) -> Void)? = nil) |
| 71 | + { |
| 72 | + self.loadFromDefaults() |
| 73 | + |
| 74 | + NTPClient().query(pool: pool, numberOfSamples: samples) { offset, done, total in |
| 75 | + if let offset = offset { |
| 76 | + self.stableTime = TimeFreeze(offset: offset) |
| 77 | + |
| 78 | + if done == 1, let now = self.now { |
| 79 | + first?(now, offset) |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + if done == total { |
| 84 | + completion?(self.now, offset) |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + /// Resets all state of the monotonic clock. Note that you won't be able to access `now` until you `sync` |
| 90 | + /// again. |
| 91 | + public static func reset() { |
| 92 | + self.stableTime = nil |
| 93 | + } |
| 94 | + |
| 95 | + private static func loadFromDefaults() { |
| 96 | + guard let previousStableTime = self.storage.stableTime else { |
| 97 | + self.stableTime = nil |
| 98 | + return |
| 99 | + } |
| 100 | + self.stableTime = previousStableTime |
| 101 | + } |
| 102 | +} |
0 commit comments