Repository Public
1// SP Drive iOS2// File: Sync/TransferPolicy.swift3// Description: Sync engine 2.0 — when transfers may run. Pure decision logic (network path, Low Data Mode, Low Power Mode, battery,4// the user's Wi-Fi-only choice), retry delays with exponential backoff and jitter, and adaptive concurrency driven by5// measured throughput and error rate. Nothing here touches the network or the system: it is fed and it answers.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation1011/// What the device looks like right now, as far as transfers are concerned.12public struct TransferConditions: Sendable, Equatable {13 public var online: Bool14 /// Cellular or personal hotspot (`NWPath.isExpensive`).15 public var expensive: Bool16 /// Low Data Mode (`NWPath.isConstrained`).17 public var constrained: Bool18 public var lowPowerMode: Bool19 /// 0…1, nil when the device does not report it (simulator, Mac).20 public var batteryLevel: Double?21 public var charging: Bool2223 public init(online: Bool = true, expensive: Bool = false, constrained: Bool = false, lowPowerMode: Bool = false, batteryLevel: Double? = nil, charging: Bool = false) {24 self.online = online; self.expensive = expensive; self.constrained = constrained; self.lowPowerMode = lowPowerMode; self.batteryLevel = batteryLevel; self.charging = charging25 }2627 /// Wi-Fi, mains power, nothing restricted.28 public static let ideal = TransferConditions()29}3031/// The user's choices (Settings → Synchronisation).32public struct TransferPolicy: Sendable, Equatable, Codable {33 /// false = « Wi-Fi seulement »: nothing travels on an expensive path unless the user exempts a transfer explicitly.34 public var allowCellular: Bool35 /// Background work (offline pins, refreshes) may run in Low Data Mode. User-initiated transfers always may, one at a time.36 public var backgroundInLowDataMode: Bool37 /// Background work pauses in Low Power Mode.38 public var pauseBackgroundInLowPowerMode: Bool39 /// Below this battery level and not charging, background work waits. 0 disables the rule.40 public var batteryFloor: Double41 /// Upper bound of simultaneous transfers (the adaptive controller moves below it).42 public var maxConcurrency: Int43 /// Bandwidth cap in bytes per second for the whole queue, 0 = none. With a cap, transfers go one at a time, in paced segments.44 public var bandwidthLimit: Int644546 public init(allowCellular: Bool = true, backgroundInLowDataMode: Bool = false, pauseBackgroundInLowPowerMode: Bool = true, batteryFloor: Double = 0.2, maxConcurrency: Int = 6, bandwidthLimit: Int64 = 0) {47 self.allowCellular = allowCellular; self.backgroundInLowDataMode = backgroundInLowDataMode; self.pauseBackgroundInLowPowerMode = pauseBackgroundInLowPowerMode48 self.batteryFloor = batteryFloor; self.maxConcurrency = maxConcurrency; self.bandwidthLimit = max(0, bandwidthLimit)49 }5051 public static let `default` = TransferPolicy()5253 /// Why a transfer is not running although it is queued.54 public enum Hold: String, Sendable, Equatable, CaseIterable {55 case offline, waitingForWiFi, lowDataMode, lowPowerMode, lowBattery56 }5758 public struct Allowance: Sendable, Equatable {59 /// Simultaneous transfers the path can take (before the adaptive controller and the caller's own cap).60 public var limit: Int61 /// Why user-initiated transfers wait, if they do.62 public var userHold: Hold?63 /// Why background transfers wait, if they do.64 public var backgroundHold: Hold?6566 public func hold(userInitiated: Bool, exemptFromWiFiOnly: Bool = false) -> Hold? {67 let h = userInitiated ? userHold : backgroundHold68 if h == .waitingForWiFi, exemptFromWiFiOnly { return nil }69 return h70 }71 }7273 public func evaluate(_ c: TransferConditions) -> Allowance {74 guard c.online else { return Allowance(limit: 0, userHold: .offline, backgroundHold: .offline) }75 var limit = bandwidthLimit > 0 ? 1 : max(1, maxConcurrency)76 var user: Hold?, background: Hold?77 if c.expensive {78 limit = min(limit, 2)79 if !allowCellular { user = .waitingForWiFi; background = .waitingForWiFi }80 }81 if c.constrained {82 limit = 183 if background == nil, !backgroundInLowDataMode { background = .lowDataMode }84 }85 if c.lowPowerMode {86 limit = min(limit, 2)87 if background == nil, pauseBackgroundInLowPowerMode { background = .lowPowerMode }88 }89 if background == nil, batteryFloor > 0, !c.charging, let level = c.batteryLevel, level >= 0, level < batteryFloor { background = .lowBattery }90 return Allowance(limit: limit, userHold: user, backgroundHold: background)91 }92}9394extension TransferPolicy {95 /// With a cap, bytes travel in segments of about two seconds' worth (never less than 64 KiB, never more than a block).96 public func segment(max block: Int64) -> Int64 { bandwidthLimit > 0 ? min(block, max(64 * 1024, bandwidthLimit * 2)) : block }97 /// How long to wait after a segment so the average rate stays under the cap.98 public func pause(afterBytes bytes: Int64, took seconds: TimeInterval) -> TimeInterval {99 guard bandwidthLimit > 0 else { return 0 }100 return max(0, Double(bytes) / Double(bandwidthLimit) - max(0, seconds))101 }102}103104/// Delay before the next attempt of something that failed for a temporary reason: exponential, capped, with jitter so a fleet of105/// transfers (or of devices) does not come back at the same instant.106public enum Backoff {107 /// - Parameters:108 /// - attempt: 0 for the first retry.109 /// - unit: a number in 0…1 (random in production, fixed in tests).110 /// - Returns: between half of the exponential step and the whole step (« equal jitter »), never above `cap`.111 public static func delay(attempt: Int, base: TimeInterval = 0.5, cap: TimeInterval = 60, unit: Double = Double.random(in: 0...1)) -> TimeInterval {112 let step = min(cap, base * pow(2, Double(min(max(attempt, 0), 30))))113 return step / 2 + step / 2 * min(max(unit, 0), 1)114 }115}116117/// How many transfers run at once, from what is measured: more while adding one raises the total throughput, fewer when errors pile up.118/// Additive increase, multiplicative decrease, between 1 and 6.119public struct AdaptiveConcurrency: Sendable, Equatable {120 public static let bounds = 1...6121 public private(set) var limit: Int122 /// Outcomes since the limit last changed (true = success).123 private var outcomes: [Bool] = []124 /// Per-transfer throughput samples (bytes per second) since the limit last changed.125 private var samples: [Double] = []126 /// Total throughput (bytes per second) observed at each limit already tried.127 private var observed: [Int: Double] = [:]128 /// Successes to see before the limit may rise again (after a decrease, or once a plateau was found).129 private var cooldown = 0130131 public init(initial: Int = 3) { limit = min(max(initial, Self.bounds.lowerBound), Self.bounds.upperBound) }132133 static let window = 8134 static let samplesToJudge = 4135 /// Transfers smaller than this say nothing about throughput (latency dominates).136 static let informativeBytes: Int64 = 256 * 1024137138 /// A transfer step (a block, a download) succeeded.139 public mutating func recordSuccess(bytes: Int64, seconds: TimeInterval, active: Int) {140 push(true)141 if cooldown > 0 { cooldown -= 1 }142 guard bytes >= Self.informativeBytes, seconds > 0 else { return }143 samples.append(Double(bytes) / seconds)144 guard samples.count >= Self.samplesToJudge, !outcomes.suffix(Self.window).contains(false) else { return }145 let total = samples.reduce(0, +) / Double(samples.count) * Double(min(max(active, 1), limit))146 observed[limit] = total147 if let below = observed[limit - 1], total < below * 1.1 {148 // one more transfer at a time bought nothing: go back and stay there for a while149 change(to: limit - 1)150 cooldown = 32151 } else if cooldown == 0, limit < Self.bounds.upperBound {152 change(to: limit + 1)153 } else {154 samples.removeAll(keepingCapacity: true)155 }156 }157158 /// A transfer step failed for a reason that says something about the path (timeout, connection lost, 5xx, 429) — not « no network ».159 public mutating func recordFailure() {160 push(false)161 if outcomes.suffix(Self.window).filter({ !$0 }).count >= 3 {162 change(to: max(Self.bounds.lowerBound, limit / 2))163 observed = [:] // the path changed: what was measured before no longer holds164 cooldown = Self.window165 }166 }167168 private mutating func push(_ ok: Bool) {169 outcomes.append(ok)170 if outcomes.count > Self.window { outcomes.removeFirst(outcomes.count - Self.window) }171 }172173 private mutating func change(to new: Int) {174 limit = min(max(new, Self.bounds.lowerBound), Self.bounds.upperBound)175 outcomes.removeAll(keepingCapacity: true)176 samples.removeAll(keepingCapacity: true)177 }178}179180extension URLError.Code {181 /// The device has no usable network at all: waiting is the answer, the path's quality is not in question.182 var meansNoNetwork: Bool { [.notConnectedToInternet, .dataNotAllowed, .internationalRoamingOff, .cancelled].contains(self) }183}184