Cotton code
52 lines · 2.0 KB · SwiftRaw
// WHETHER THIS PHONE'S NETWORK IS UNMETERED (assets/design/data/CONTRACT.md, iPhone brief 14): Wi-Fi or Ethernet// that is neither expensive (a phone's hotspot) nor constrained (Low Data Mode). Cotton Data passes it with// `personal.connect` (`unmetered`), so Keep everything's whole copy starts only on such a network; the core decides// the rest (`phone::data_app::keeps_everything`). Read from `NWPathMonitor`, watched from the first ask.import Foundationimport Networkpublic final class NetworkUnmetered: @unchecked Sendable {    public static let shared = NetworkUnmetered()    private let monitor = NWPathMonitor()    private let lock = NSLock()    private var path: NWPath?    private init() {        monitor.pathUpdateHandler = { [weak self] path in self?.took(path) }        monitor.start(queue: DispatchQueue(label: "com.cottondb.network.unmetered", qos: .utility))    }    private func took(_ path: NWPath) {        lock.lock()        self.path = path        lock.unlock()    }    /// Whether `path` is unmetered: satisfied, over Wi-Fi or wired Ethernet, not expensive, not constrained.    public static func unmetered(satisfied: Bool, wifiOrWired: Bool, expensive: Bool, constrained: Bool) -> Bool {        satisfied && wifiOrWired && !expensive && !constrained    }    private static func of(_ path: NWPath) -> Bool {        unmetered(satisfied: path.status == .satisfied,                  wifiOrWired: path.usesInterfaceType(.wifi) || path.usesInterfaceType(.wiredEthernet),                  expensive: path.isExpensive, constrained: path.isConstrained)    }    /// Whether the network is unmetered now; the first ask waits for the monitor's first reading (at most a second).    public func now() async -> Bool {        for _ in 0..<20 {            if let path = reading() { return Self.of(path) }            try? await Task.sleep(for: .milliseconds(50))        }        return reading().map(Self.of) ?? false    }    private func reading() -> NWPath? {        lock.lock()        defer { lock.unlock() }        return path    }}