Repository Public
1// SP Notes iOS2// File: App/BackgroundSync.swift3// Description: Background synchronisation with BackgroundTasks: a short app refresh (pull what changed elsewhere) and a4// processing task that needs the network (push what is pending, upload files). The system decides if and when5// they run; nothing here assumes they do. A task that runs out of time is cancelled — the sync engine is6// resumable — and the next one is always requested again.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import BackgroundTasks11import Foundation12import SPNotesCore1314@MainActor15enum BackgroundSync {16 static let refreshIdentifier = "ai.spboucher.spnotes.ios.refresh"17 static let processingIdentifier = "ai.spboucher.spnotes.ios.sync"18 /// Earliest moment the system may wake the app for a refresh.19 static let refreshInterval: TimeInterval = 30 * 602021 private static var registered = false2223 /// Must be called before the end of launch. Both identifiers are declared in Info.plist.24 static func register() {25 guard !registered else { return }26 registered = true27 for identifier in [refreshIdentifier, processingIdentifier] {28 // The handler is delivered on the main queue, where the model lives.29 BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: .main) { task in30 MainActor.assumeIsolated { BackgroundRun(task: task).start() }31 }32 }33 }3435 /// Called when the app goes to the background. The processing task is only requested when something waits to be sent.36 static func scheduleAll() {37 guard let model = try? AppRuntime.model(), model.session == .signedIn else { return }38 submit(refreshRequest())39 if model.syncStatus.pending > 0 { submit(processingRequest()) }40 }4142 static func refreshRequest(now: Date = Date()) -> BGAppRefreshTaskRequest {43 let request = BGAppRefreshTaskRequest(identifier: refreshIdentifier)44 request.earliestBeginDate = now.addingTimeInterval(refreshInterval)45 return request46 }4748 static func processingRequest() -> BGProcessingTaskRequest {49 let request = BGProcessingTaskRequest(identifier: processingIdentifier)50 request.requiresNetworkConnectivity = true51 request.requiresExternalPower = false52 return request53 }5455 /// Submitting can block (it talks to a system daemon): done off the main thread. Refusals are expected (simulator,56 /// Background App Refresh turned off) and simply mean the sync happens at the next activation.57 private static func submit(_ request: BGTaskRequest) {58 nonisolated(unsafe) let request = request59 Task.detached(priority: .utility) { try? BGTaskScheduler.shared.submit(request) }60 }6162 /// What a finished background run asks for next.63 fileprivate static func reschedule(pending: Int) {64 guard let model = try? AppRuntime.model(), model.session == .signedIn else { return }65 submit(refreshRequest())66 if pending > 0 { submit(processingRequest()) }67 }68}6970/// One execution of a background task: syncs, reports the result once, and gives up cleanly when the time is over.71@MainActor72final class BackgroundRun {73 private let task: BGTask74 private var work: Task<Void, Never>?75 private var finished = false7677 init(task: BGTask) { self.task = task }7879 func start() {80 guard let model = try? AppRuntime.model() else {81 task.setTaskCompleted(success: false)82 return83 }84 // Called by the system on an arbitrary queue when the time is over.85 task.expirationHandler = { [weak self] in86 Task { @MainActor in self?.expire() }87 }88 work = Task {89 let outcome = await model.syncAndWait()90 let pending = (try? await model.store.counts().pending) ?? 091 self.finish(success: outcome == .completed && !Task.isCancelled, pending: pending)92 }93 }9495 private func expire() {96 work?.cancel()97 finish(success: false, pending: 1)98 }99100 private func finish(success: Bool, pending: Int) {101 guard !finished else { return }102 finished = true103 BackgroundSync.reschedule(pending: pending)104 task.setTaskCompleted(success: success)105 }106}107