SPB Git

Repository Public

TransferPolicy.swift 5.0 KB 85 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sync/TransferPolicy.swift3// Description: Policies of the 2.0 transfer engine that do not depend on the network: retry delays (exponential back-off with jitter), priorities (what a person asked for goes before background work), and the power state of the machine (battery, Low Power Mode) with what it allows.4import Foundation5#if os(macOS)6import IOKit.ps7#endif89/// Delay before trying again: grows by `factor` at each failure up to `cap`, and is spread by ±`jitter` so that10/// many transfers (or many devices) that failed together do not come back together.11public struct RetryPolicy: Sendable, Equatable {12    public var base: Double13    public var factor: Double14    public var cap: Double15    /// Fraction of the delay that is randomised on each side (0.25 = between 75 % and 125 %).16    public var jitter: Double17    public init(base: Double, factor: Double = 2, cap: Double, jitter: Double = 0.25) { self.base = base; self.factor = factor; self.cap = cap; self.jitter = min(max(jitter, 0), 1) }18    /// Transfers: 2 s, 4 s, 8 s … 10 min.19    public static let transfers = RetryPolicy(base: 2, cap: 600)20    /// Event stream reconnection: 1 s … 60 s (contract §3).21    public static let reconnect = RetryPolicy(base: 1, cap: 60, jitter: 0.3)22    /// Delay without jitter for the nth consecutive failure (1 = first).23    public func nominal(attempt: Int) -> Double { min(cap, base * pow(factor, Double(min(max(attempt, 1), 40) - 1))) }24    /// - Parameter unit: a number in 0…1 that places the delay inside its jitter band (random by default; fixed in tests).25    public func delay(attempt: Int, unit: Double = .random(in: 0...1)) -> Double {26        let n = nominal(attempt: attempt), spread = n * jitter27        return min(cap, max(0, n - spread + 2 * spread * min(max(unit, 0), 1)))28    }29}3031/// Priorities of the transfer queue. Higher runs first; among equals, first queued first served.32public enum TransferPriority {33    /// Work nobody is waiting for (pre-fetching, housekeeping). Deferred in Low Power Mode and on a nearly empty battery.34    public static let background = 035    /// Something the person just asked for: an upload they dropped, a download they clicked.36    public static let userInitiated = 1037    /// "Send this one first", chosen in the transfer centre.38    public static let urgent = 2039}4041/// What the machine's power situation is right now.42public struct PowerState: Sendable, Equatable {43    public var onBattery: Bool44    public var lowPowerMode: Bool45    /// Charge between 0 and 1; nil on a Mac without a battery.46    public var level: Double?47    public init(onBattery: Bool = false, lowPowerMode: Bool = false, level: Double? = nil) { self.onBattery = onBattery; self.lowPowerMode = lowPowerMode; self.level = level }48    public static let unconstrained = PowerState()49    /// On battery with 10 % or less.50    public var isCritical: Bool { onBattery && (level ?? 1) <= 0.10 }51    /// On battery with 20 % or less.52    public var isLow: Bool { onBattery && (level ?? 1) <= 0.20 }53    /// Background transfers wait; what the person asked for still runs.54    public var defersBackground: Bool { lowPowerMode || isCritical }55    /// Upper bound on simultaneous transfers imposed by power alone.56    public var concurrencyCap: Int { defersBackground ? 1 : (isLow ? 2 : Int.max) }57}5859public protocol PowerSource: Sendable { var state: PowerState { get } }6061/// A power source with a fixed, settable state (tests, and Macs where nothing can be read).62public final class FixedPowerSource: PowerSource, @unchecked Sendable {63    private let lock = NSLock(); private var value: PowerState64    public init(_ state: PowerState = .unconstrained) { value = state }65    public var state: PowerState { get { lock.withLock { value } } set { lock.withLock { value = newValue } } }66}6768/// Reads Low Power Mode from ProcessInfo and, on macOS, the battery from IOKit power sources. Cheap enough to be read at each queue tick (every 2 s).69public final class SystemPowerSource: PowerSource {70    public init() {}71    public var state: PowerState {72        var s = PowerState(lowPowerMode: ProcessInfo.processInfo.isLowPowerModeEnabled)73        #if os(macOS)74        guard let blob = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(), let list = IOPSCopyPowerSourcesList(blob)?.takeRetainedValue() as? [CFTypeRef] else { return s }75        for ps in list {76            guard let d = IOPSGetPowerSourceDescription(blob, ps)?.takeUnretainedValue() as? [String: Any], (d[kIOPSTypeKey] as? String) == kIOPSInternalBatteryType else { continue }77            s.onBattery = (d[kIOPSPowerSourceStateKey] as? String) == kIOPSBatteryPowerValue78            if let cur = d[kIOPSCurrentCapacityKey] as? Double, let max = d[kIOPSMaxCapacityKey] as? Double, max > 0 { s.level = cur / max }79            else if let cur = d[kIOPSCurrentCapacityKey] as? Int, let max = d[kIOPSMaxCapacityKey] as? Int, max > 0 { s.level = Double(cur) / Double(max) }80        }81        #endif82        return s83    }84}85
Files main
Menu

Theme