Cotton code
63 lines · 2.7 KB · SwiftRaw
import Foundation/// iOS's figure for the time left in the back, as the milliseconds the core's/// time box closes at — a little under it — or nil when the figure is no time/// box at all.////// RULE: no figure iOS gives ever traps. iOS answers `DBL_MAX` while the app is/// still in front (and may answer infinity or NaN): finite, so it passed an/// `isFinite` check, and `(left - 2) * 1_000` overflowed to infinity and the/// `Int` conversion trapped — the owner's phone crashed on every trip to the/// back on build 269 (13 Oct 2026, `SyncHold.begin`). A figure above what iOS/// ever grants in the back means the counting has not started: no box, and/// iOS's expiry handler is the cut.enum SyncHoldBudget {    /// Longer than iOS has ever granted an app in the back.    static let ceiling: TimeInterval = 180    static func milliseconds(left: TimeInterval) -> Int? {        guard left.isFinite, left <= ceiling else { return nil }        return Int((max(0, left - 2) * 1_000).rounded(.down))    }}#if os(iOS)    import UIKit    /// THE SECONDS iOS GIVES AN APP GOING BEHIND, held for the sync pass on the    /// wire, and how many are left — what `sync.background` closes the core's    /// time box at.    ///    /// Without the hold a pass running as the app left was frozen mid-read, and    /// on the next wake it was a straggler: every slice found it "still    /// finishing" and exchanged nothing (build 265, 13 Oct 2026). With it the    /// pass stops between pages inside the time, and the time running out cuts    /// it — the expiry handler says so, and the core cuts at the box's end on    /// its own as well, in case the handler does not get to run.    @MainActor    enum SyncHold {        private static var held: UIBackgroundTaskIdentifier = .invalid        /// Hold the time; `expired` is told when it runs out. Answers the        /// milliseconds left, a little under iOS's own figure, or nil when iOS        /// gives no figure.        static func begin(expired: @escaping @MainActor () -> Void) -> Int? {            end()            held = UIApplication.shared.beginBackgroundTask(withName: "cotton.sync") {                MainActor.assumeIsolated {                    expired()                    SyncHold.end()                }            }            guard held != .invalid else { return nil }            return SyncHoldBudget.milliseconds(left: UIApplication.shared.backgroundTimeRemaining)        }        /// The app is in front again, or the time is over.        static func end() {            guard held != .invalid else { return }            UIApplication.shared.endBackgroundTask(held)            held = .invalid        }    }#endif