Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/System/BackgroundWork.swift3// Description: Work done while the app is not in front. iOS / iPadOS: a BGAppRefreshTask (one sync of every mailbox with4// `syncNowAndWait()`, expiration handled, rescheduled) and a BGProcessingTask (body prefetch and attachment-cache maintenance, on power and5// an unmetered network). macOS: one coalesced, App Nap-friendly background activity. The system alone decides if and when any of this6// runs; with a push pipeline the app does not poll for new mail, and Low Power Mode / Low Data Mode suspend the optional work.7import Network8import SPMailCore9import SPMailSystem10import SwiftUI11#if os(iOS)12import BackgroundTasks13import UIKit14#else15import AppKit16#endif1718extension AppModel {19 /// Runs `work` for at most `seconds`; nil when the time ran out (the work is cancelled).20 static func withBudget<T: Sendable>(_ seconds: Double, _ work: @escaping @Sendable () async -> T) async -> T? {21 await withTaskGroup(of: T?.self) { group in22 group.addTask { await work() }23 group.addTask { try? await Task.sleep(for: .seconds(seconds)); return nil }24 let first = await group.next() ?? nil25 group.cancelAll()26 return first27 }28 }2930 /// One real sync of every mailbox (`syncNowAndWait`), all at once, within a time budget. True when every mailbox finished in time.31 func syncAll(budget: Double) async -> Bool {32 let all = Array(engines.values)33 guard !all.isEmpty else { return false }34 let done = await Self.withBudget(budget) {35 await withTaskGroup(of: Bool.self) { group in36 for e in all { group.addTask { (try? await e.syncNowAndWait()) != nil } }37 var ok = true38 for await r in group { ok = ok && r }39 return ok40 }41 }42 return done ?? false43 }44}4546/// Network conditions read once (the app's NetworkMonitor reports reachability and Low Data Mode; cellular / hotspot is asked here).47enum NetworkConditions {48 static func isExpensive() async -> Bool {49 await withCheckedContinuation { c in50 let monitor = NWPathMonitor()51 let once = OnceFlag()52 monitor.pathUpdateHandler = { path in53 guard once.take() else { return }54 monitor.cancel()55 c.resume(returning: path.isExpensive)56 }57 monitor.start(queue: DispatchQueue(label: "ai.spboucher.spmail.network.once"))58 }59 }60 private final class OnceFlag: @unchecked Sendable {61 private let lock = NSLock(); private var taken = false62 func take() -> Bool { lock.withLock { if taken { return false }; taken = true; return true } }63 }64}6566@MainActor67enum BackgroundWork {68 static let refreshId = AppConfig.refreshTaskId69 static let maintenanceId = "ai.spboucher.spmail.maintenance"7071 /// How often a refresh is asked for; nil = none. With a push pipeline the server announces new mail: a sparse refresh only keeps72 /// the cache and the widgets current.73 static func interval(_ app: AppModel) -> TimeInterval? {74 LocalNotificationPolicy.refreshInterval(pushPipelineActive: app.system.push.pipelineActive, lowPower: ProcessInfo.processInfo.isLowPowerModeEnabled, constrainedNetwork: app.monitor.isConstrained)75 }7677 /// The refresh itself: what the system-granted background time is spent on.78 static func refresh(_ app: AppModel) async -> Bool {79 guard await app.system.notifications.sessionReady() else { return false }80 let ok = await app.syncAll(budget: 24)81 await app.reloadMailboxes()82 await app.system.shared.writeSnapshot()83 return ok84 }8586 /// Optional work for when the device is on power and an unmetered network: bodies of the newest messages for offline reading, the87 /// attachment cache trimmed back to its budget, decrypted temporary files removed.88 static func maintenance(_ app: AppModel) async -> Bool {89 guard await app.system.notifications.sessionReady() else { return false }90 if !AppActivity.isActive { AppModel.purgeTemporaryFiles() }91 if let store = app.store { try? await store.setAttachmentCacheBudget(await store.attachmentCacheBudget) }92 let metered = await NetworkConditions.isExpensive()93 guard !ProcessInfo.processInfo.isLowPowerModeEnabled, !app.monitor.isConstrained, !metered else { return true }94 for engine in app.engines.values {95 if Task.isCancelled { return false }96 _ = await engine.prefetchNewest()97 }98 return !Task.isCancelled99 }100101 #if os(iOS)102 private struct TaskBox: @unchecked Sendable { let task: BGTask }103104 /// Registers the launch handlers. Must run before the application finishes launching.105 static func install(_ app: AppModel) {106 func register(_ id: String, _ work: @escaping @MainActor (AppModel) async -> Bool) {107 BGTaskScheduler.shared.register(forTaskWithIdentifier: id, using: nil) { task in108 let box = TaskBox(task: task)109 Task { @MainActor in110 schedule(app) // the next one is asked for first: an expired or failed run does not break the chain111 let job = Task { @MainActor in await work(app) }112 box.task.expirationHandler = { job.cancel() }113 let ok = await job.value114 box.task.setTaskCompleted(success: ok && !job.isCancelled)115 }116 }117 }118 register(refreshId) { await refresh($0) }119 register(maintenanceId) { await maintenance($0) }120 }121122 /// Asks the system for the next runs (when the app leaves the foreground, and after each run).123 static func schedule(_ app: AppModel) {124 guard app.phase == .ready || app.phase == .locked else { BGTaskScheduler.shared.cancelAllTaskRequests(); return }125 if let interval = interval(app) {126 let request = BGAppRefreshTaskRequest(identifier: refreshId)127 request.earliestBeginDate = Date().addingTimeInterval(interval)128 try? BGTaskScheduler.shared.submit(request)129 } else {130 BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: refreshId)131 }132 let processing = BGProcessingTaskRequest(identifier: maintenanceId)133 processing.requiresExternalPower = true134 processing.requiresNetworkConnectivity = true135 processing.earliestBeginDate = Date().addingTimeInterval(6 * 3600)136 try? BGTaskScheduler.shared.submit(processing)137 }138 #else139 private static var activity: NSBackgroundActivityScheduler?140 private static var lastMaintenance = Date.distantPast141142 /// One repeating background activity: the system coalesces it with other work and defers it under App Nap, on battery or thermal143 /// pressure. While the app runs, the live event stream already keeps the mailboxes current; this pass is the safety net.144 static func install(_ app: AppModel) { schedule(app) }145146 static func schedule(_ app: AppModel) {147 let wanted = interval(app)148 if let current = activity, wanted == current.interval { return }149 activity?.invalidate(); activity = nil150 guard let wanted else { return }151 let scheduler = NSBackgroundActivityScheduler(identifier: refreshId)152 scheduler.repeats = true153 scheduler.interval = wanted154 scheduler.tolerance = wanted / 2155 scheduler.qualityOfService = .utility156 scheduler.schedule { completion in157 let done = Finish(call: completion)158 Task { @MainActor in159 defer { done.call(.finished) }160 guard app.phase == .ready || app.phase == .locked else { return }161 _ = await refresh(app)162 if Date().timeIntervalSince(lastMaintenance) > 6 * 3600 { lastMaintenance = Date(); _ = await maintenance(app) }163 schedule(app)164 }165 }166 activity = scheduler167 }168 private struct Finish: @unchecked Sendable { let call: (NSBackgroundActivityScheduler.Result) -> Void }169 #endif170}171