SPB Git

Repository Public

Connectivity.swift 3.2 KB 72 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Networking/Connectivity.swift3// Description: Whether the cluster can be reached: network path, request outcomes, periodic probe, forced offline mode.4import Foundation5import Network67/// Whether the cluster can be reached right now. Fed by three sources: the system's network path, the outcome of8/// every API request, and a periodic probe while offline. The listener can also force offline mode, in which case9/// the app makes no request at all.10public final class Connectivity: @unchecked Sendable {11    private let lock = NSLock()12    private var reachable = true13    private var pathSatisfied = true14    private var forced = false15    private var continuations: [UUID: AsyncStream<Bool>.Continuation] = [:]16    private var monitor: NWPathMonitor?17    private var probeTask: Task<Void, Never>?1819    public init() {}20    deinit { monitor?.cancel(); probeTask?.cancel() }2122    /// True when requests may be attempted and the last evidence says the cluster answers.23    public var isOnline: Bool { lock.withLock { !forced && reachable && pathSatisfied } }24    public var forcedOffline: Bool {25        get { lock.withLock { forced } }26        set { update { forced = newValue } }27    }2829    private func update(_ change: () -> Void) {30        let (before, after, targets): (Bool, Bool, [AsyncStream<Bool>.Continuation]) = lock.withLock {31            let b = !forced && reachable && pathSatisfied32            change()33            return (b, !forced && reachable && pathSatisfied, Array(continuations.values))34        }35        if before != after { for c in targets { c.yield(after) } }36    }3738    public func noteSuccess() { update { reachable = true } }39    public func noteFailure() { update { reachable = false } }4041    /// Emits the online state now and at every change.42    public func states() -> AsyncStream<Bool> {43        let id = UUID()44        return AsyncStream(bufferingPolicy: .bufferingNewest(1)) { c in45            lock.withLock { continuations[id] = c }46            c.yield(isOnline)47            c.onTermination = { [weak self] _ in self?.lock.withLock { self?.continuations[id] = nil } }48        }49    }5051    /// Starts watching the network path and, while the cluster is unreachable, asks `probe` every few seconds.52    public func start(probe: @escaping @Sendable () async -> Bool, interval: TimeInterval = 8) {53        let m = NWPathMonitor()54        m.pathUpdateHandler = { [weak self] path in55            guard let self else { return }56            self.update { self.pathSatisfied = path.status == .satisfied }57        }58        m.start(queue: DispatchQueue(label: "spmusic.connectivity"))59        monitor = m60        probeTask?.cancel()61        probeTask = Task { [weak self] in62            while !Task.isCancelled {63                try? await Task.sleep(nanoseconds: UInt64(interval * 1_000_000_000))64                guard let self else { return }65                let needsProbe = self.lock.withLock { !self.forced && self.pathSatisfied && !self.reachable }66                if needsProbe, await probe() { self.noteSuccess() }67            }68        }69    }70    public func stop() { monitor?.cancel(); monitor = nil; probeTask?.cancel(); probeTask = nil }71}72
Files main
Menu

Theme