SPB Git

Repository Public

BackgroundRefresh.swift 5.1 KB 93 lines swift

1// SP Wallet iOS2// File: Core/System/BackgroundRefresh.swift3// Description: The app-refresh background task (`ai.spboucher.spwallet.ios.refresh`): when a session token exists, ONE cheap pass —4//              the alert counters, the new alert rows (→ local notifications) and a portfolio read for the widget snapshot.5//6//              LIMITS, stated plainly. iOS decides if and when an app-refresh task runs: it depends on how often the app is7//              used, battery, Low Power Mode, network and the "Background App Refresh" switch; it may be hours, or never (an app8//              force-quit from the app switcher is not woken at all). `earliestBeginDate` is a lower bound, not a schedule.9//              The server has no APNs path, so nothing can wake the app for an alert. Therefore: a notification raised here is10//              true but may be LATE, and no time-critical alert may rely on it. The server session also ends after 30 minutes11//              idle / 12 hours: once it has ended, the pass stops and nothing is notified until the owner signs in again.12//13// Author: Simon-Pierre Boucher14// Contact: contact@spboucher.ai15import BackgroundTasks16import Foundation17import OSLog18import SPWalletCore1920enum BackgroundRefresh {21    static let identifier = "ai.spboucher.spwallet.ios.refresh"22    /** The system grants about 30 s; the pass gives up by itself before that. */23    static let budget: Duration = .seconds(25)24    static let earliest: TimeInterval = 30 * 602526    enum Outcome: Equatable, Sendable {27        /** No session token: nothing was requested from the server. */28        case signedOut29        case completed(newAlerts: Int)30        /** The server refused the session (401). Nothing is wiped; the pass just stops. */31        case sessionRefused32        case unreachable33        /** Out of time (own budget or the system's expiration). */34        case expired35    }3637    /**38     Ask iOS for a future run. Called when the app goes to the background and at the end of every run.39     A refusal (simulator, switch off in Settings) is not an error worth surfacing.40     */41    static func schedule() {42        let r = BGAppRefreshTaskRequest(identifier: identifier)43        r.earliestBeginDate = Date(timeIntervalSinceNow: earliest)44        do { try BGTaskScheduler.shared.submit(r) } catch { Logger(subsystem: "ai.spboucher.spwallet.ios", category: "background").info("refresh not scheduled") }45    }46    static func cancel() { BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: identifier) }4748    /**49     The body of `.backgroundTask(.appRefresh(BackgroundRefresh.identifier))`. SwiftUI cancels the surrounding task when the50     system's time expires; cancellation and the own budget both end the pass.51     - Parameters:52       - hasToken: whether a session token is stored (no request at all otherwise).53       - alerts: the alert pass (`AlertCenter.sync.pass`).54       - refreshPortfolio: provided by the app: reads the portfolio and republishes the widget snapshot.55     */56    @MainActor57    static func run(hasToken: @escaping @MainActor () async -> Bool,58                    alerts: @escaping @MainActor () async throws -> AlertPassResult,59                    refreshPortfolio: @escaping @MainActor () async -> Void,60                    budget: Duration = BackgroundRefresh.budget,61                    reschedule: @MainActor () -> Void = { BackgroundRefresh.schedule() }) async -> Outcome {62        guard await hasToken() else { return .signedOut } // signed out: no request, and no rescheduling either63        reschedule()64        let work = Task { @MainActor () -> Outcome in65            do {66                let r = try await alerts()67                if Task.isCancelled { return .expired }68                await refreshPortfolio()69                return Task.isCancelled ? .expired : .completed(newAlerts: r.fresh.count)70            } catch let e as APIError {71                // 401: the API client already dropped the token. Snapshots stay for offline consultation; no wipe here.72                return e.isUnauthenticated ? .sessionRefused : Task.isCancelled ? .expired : .unreachable73            } catch { return Task.isCancelled ? .expired : .unreachable }74        }75        let timer = Task { try? await Task.sleep(for: budget); work.cancel() }76        let outcome = await withTaskCancellationHandler { await work.value } onCancel: { work.cancel() }77        timer.cancel()78        return outcome79    }80}8182extension AlertCenter {83    /** The app's background pass, with the alert centre's own bookkeeping (same watermark as the foreground poll). */84    func backgroundPass(model: AppModel, refreshPortfolio: @escaping @MainActor () async -> Void) async -> BackgroundRefresh.Outcome {85        await BackgroundRefresh.run(hasToken: { [weak model] in await model?.env.client.hasToken ?? false },86                                    alerts: { [weak self] in87                                        guard let self else { throw CancellationError() }88                                        return try await self.backgroundAlertPass()89                                    },90                                    refreshPortfolio: refreshPortfolio)91    }92}93
Files main
Menu

Theme