SPB Git

Repository Public

Connectivity.swift 2.6 KB 68 lines swift

1import Foundation2import Network3import Observation45/// Whether the server can be reached, as observed by the requests themselves (a transport failure flips it to6/// unreachable, any HTTP response flips it back) and combined with the network path. Shared, thread-safe.7public final class Connectivity: @unchecked Sendable {8    public struct State: Sendable, Equatable {9        public var serverReachable = true10        public var pathSatisfied = true11        /// When the client last lost the server (or the network); nil while online.12        public var offlineSince: Date?13        public var isOffline: Bool { !serverReachable || !pathSatisfied }14    }1516    private let lock = NSLock()17    private var state = State()18    private var observers: [UUID: AsyncStream<State>.Continuation] = [:]1920    public init() {}2122    public var current: State { lock.withLock { state } }23    public var isOffline: Bool { current.isOffline }2425    public func recordResponse() { mutate { $0.serverReachable = true } }26    public func recordTransportFailure() { mutate { $0.serverReachable = false } }27    public func setPathSatisfied(_ ok: Bool) { mutate { $0.pathSatisfied = ok } }2829    private func mutate(_ f: (inout State) -> Void) {30        let (changed, new, conts): (Bool, State, [AsyncStream<State>.Continuation]) = lock.withLock {31            var s = state32            f(&s)33            if s.isOffline && !state.isOffline { s.offlineSince = Date() }34            if !s.isOffline { s.offlineSince = nil }35            let changed = s != state36            state = s37            return (changed, s, Array(observers.values))38        }39        if changed { conts.forEach { $0.yield(new) } }40    }4142    /// Every state change, starting with the current state.43    public func updates() -> AsyncStream<State> {44        AsyncStream { cont in45            let id = UUID()46            let now: State = lock.withLock { observers[id] = cont; return state }47            cont.yield(now)48            cont.onTermination = { [weak self] _ in self?.lock.withLock { self?.observers[id] = nil } }49        }50    }51}5253/// Network path monitoring (Network framework) feeding `Connectivity`.54public final class PathObserver: @unchecked Sendable {55    private let monitor = NWPathMonitor()56    private let queue = DispatchQueue(label: "ai.spboucher.clustr.path")57    public init() {}58    public func start(connectivity: Connectivity, onChange: (@Sendable (Bool) -> Void)? = nil) {59        monitor.pathUpdateHandler = { path in60            let ok = path.status == .satisfied61            connectivity.setPathSatisfied(ok)62            onChange?(ok)63        }64        monitor.start(queue: queue)65    }66    public func stop() { monitor.cancel() }67}68
Files main
Menu

Theme