SPB Git

Repository Public

AlertCenter.swift 11.4 KB 217 lines swift

1// SP Wallet iOS2// File: Core/System/AlertCenter.swift3// Description: The app's view of the server's alerts: a cheap foreground poll of the unread counters (the server has no APNs4//              path, only Web Push for browsers), the fetch of new rows when something changed, the unread count and highest5//              unread severity for the Home bell and the widgets, and the "notified at most once per device" bookkeeping.6//              Everything here comes from alert rows the server returned; the app never raises an alert of its own.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import Observation12import OSLog13import SPWalletCore1415/** The two reads the poller needs (AlertsAPI in the app, a scripted fake in tests). */16protocol AlertSource: Sendable {17    func unread() async throws -> AlertUnread18    func list(_ q: AlertListQuery) async throws -> AlertPage19}20extension AlertsAPI: AlertSource {}2122/** Where the highest alert id already handled on THIS device is kept. */23@MainActor protocol AlertSeenStore: AnyObject {24    var lastSeenId: Int64? { get set }25}2627@MainActor final class DefaultsAlertSeenStore: AlertSeenStore {28    private let defaults: UserDefaults?29    private let key: String30    private var memory: Int64?31    /** - Parameter defaults: nil keeps the value in memory only (UI tests). */32    init(defaults: UserDefaults?, key: String) { self.defaults = defaults; self.key = key }33    var lastSeenId: Int64? {34        get { defaults.map { $0.object(forKey: key) as? Int64 ?? ($0.object(forKey: key) as? NSNumber)?.int64Value } ?? memory }35        set { if let defaults { if let newValue { defaults.set(NSNumber(value: newValue), forKey: key) } else { defaults.removeObject(forKey: key) } } else { memory = newValue } }36    }37}3839/** What posts the local notifications and the app badge (NotificationService in the app, a recorder in tests). */40@MainActor protocol AlertNotifying: AnyObject {41    /** `rows` are NEW server alert rows, never seen by this device before. The implementation decides which kinds notify. */42    func notify(_ rows: [WalletAlert]) async43    func setBadge(_ unread: Int) async44}4546/** Result of one pass over the server's alerts. */47struct AlertPassResult: Equatable, Sendable {48    let counters: AlertUnread49    /** Unread rows as served (newest first, one page); nil when the pass did not need to fetch them. */50    let unreadRows: [WalletAlert]?51    /** Rows handed to the notifier during this pass. */52    let fresh: [WalletAlert]53}5455/**56 One pass: read the counters, and when the server has an id this device has not handled yet, fetch the unread rows and hand the57 new ones to the notifier — once. The watermark is advanced BEFORE notifying, with no suspension point between the comparison and58 the write: a row can be missed after a crash, it can never be notified twice.59 */60@MainActor final class AlertSync {61    private let source: AlertSource62    private let seen: AlertSeenStore63    private let notifier: AlertNotifying?64    /** Rows older than this are history, not news (the server's own dispatcher uses one hour too). */65    static let maxAge: TimeInterval = 36006667    init(source: AlertSource, seen: AlertSeenStore, notifier: AlertNotifying?) { self.source = source; self.seen = seen; self.notifier = notifier }6869    func pass(forceRows: Bool = false, now: Date = Date()) async throws -> AlertPassResult {70        let counters = try await source.unread()71        guard let before = seen.lastSeenId else {72            // first contact on this device: everything that exists is history; start from here without notifying anything73            seen.lastSeenId = counters.lastId74            let rows = counters.unread > 0 || forceRows ? try await source.list(AlertListQuery(limit: 50, unreadOnly: true)).items : nil75            await notifier?.setBadge(counters.unread)76            return AlertPassResult(counters: counters, unreadRows: rows, fresh: [])77        }78        if counters.lastId < before { seen.lastSeenId = counters.lastId } // the server's table was reset (throwaway stack): follow it79        guard counters.lastId > before || forceRows else {80            await notifier?.setBadge(counters.unread)81            return AlertPassResult(counters: counters, unreadRows: nil, fresh: [])82        }83        let page = try await source.list(AlertListQuery(limit: 50, unreadOnly: true))84        // re-read the watermark: another pass may have advanced it while this one was waiting for the server85        let floor = seen.lastSeenId ?? before86        let fresh = page.items.filter { $0.id > floor && !$0.isRead && now.timeIntervalSince($0.ts) <= Self.maxAge }87        seen.lastSeenId = max(floor, page.lastId, page.items.map(\.id).max() ?? 0)88        if !fresh.isEmpty { await notifier?.notify(fresh.sorted { $0.id < $1.id }) }89        await notifier?.setBadge(page.unread)90        return AlertPassResult(counters: page.counters, unreadRows: page.items, fresh: fresh)91    }9293    func forget() { seen.lastSeenId = nil }94    func setBadge(_ unread: Int) async { await notifier?.setBadge(unread) }95}9697@MainActor @Observable98final class AlertCenter {99    /** nil until the server answered once in this session: the bell then shows no number rather than a zero nobody measured. */100    private(set) var counters: AlertUnread?101    /** Highest severity among the unread rows the server returned; nil when there is none or it is not known. */102    private(set) var highestUnreadSeverity: AlertSeverity?103    /** Title of the newest unread critical alert (the catalogue's title: no amount, no address). */104    private(set) var criticalTitle: String?105    /** Changes whenever the server's counters changed: list screens reload on it. */106    private(set) var revision = 0107    private(set) var lastCheckedAt: Date?108109    @ObservationIgnored let sync: AlertSync110    @ObservationIgnored private let eligible: @MainActor () -> Bool111    @ObservationIgnored private let onChange: @MainActor () -> Void112    @ObservationIgnored private var loop: Task<Void, Never>?113    @ObservationIgnored private var passing = false114    @ObservationIgnored private let log = Logger(subsystem: "ai.spboucher.spwallet.ios", category: "alerts")115    static let interval: Duration = .seconds(60)116117    /**118     - Parameters:119       - eligible: polling only runs while this is true (signed in, not in offline consultation).120       - onChange: called when the counters or the critical title changed (the app republishes its widget snapshot).121     */122    init(source: AlertSource, seen: AlertSeenStore, notifier: AlertNotifying?, eligible: @escaping @MainActor () -> Bool, onChange: @escaping @MainActor () -> Void = {}) {123        sync = AlertSync(source: source, seen: seen, notifier: notifier)124        self.eligible = eligible; self.onChange = onChange125    }126127    /** The app's instance: AlertsAPI, UserDefaults (in memory for UI tests), local notifications. */128    convenience init(model: AppModel) {129        let env = model.env, cfg = env.configuration130        self.init(source: AlertsAPI(env.client),131                  seen: DefaultsAlertSeenStore(defaults: cfg.ephemeral ? nil : .standard, key: "alerts.lastSeenId." + (cfg.isProduction ? "prod" : "dev")),132                  notifier: NotificationService(preferences: env.preferences),133                  eligible: { [weak model] in guard let model else { return false }; return model.phase == .ready && !model.offlineBrowsing },134                  onChange: { [weak model] in model?.publishWidgetSnapshot() })135    }136137    // MARK: polling (foreground only)138139    /** Call when the scene becomes active. Polls now, then every 60 s while eligible; costs one tiny request per minute. */140    func start() {141        loop?.cancel()142        loop = Task { [weak self] in143            while !Task.isCancelled {144                guard let self else { return }145                if self.eligible() { await self.poll(); try? await Task.sleep(for: Self.interval) }146                else { try? await Task.sleep(for: .seconds(2)) } // local check only: waits for the sign-in without any request147            }148        }149    }150151    /** Call when the scene goes to the background. iOS suspends the process anyway; nothing here pretends otherwise. */152    func stop() { loop?.cancel(); loop = nil }153154    /** One pass now. Returns false when the server could not be read (the previous figures stay, they are not zeroed). */155    @discardableResult func poll(forceRows: Bool = false) async -> Bool {156        guard !passing else { return true }157        passing = true; defer { passing = false }158        do { apply(try await sync.pass(forceRows: forceRows || counters == nil)); return true }159        catch let e as APIError {160            if !e.isOffline, !e.isUnauthenticated { log.error("alert poll failed: \(e.code, privacy: .public)") }161            return false162        } catch { return false }163    }164165    private func apply(_ r: AlertPassResult) {166        lastCheckedAt = Date()167        let old = (counters, highestUnreadSeverity, criticalTitle)168        counters = r.counters169        if let rows = r.unreadRows { summarize(rows, counters: r.counters) }170        else if r.counters.unread == 0 { highestUnreadSeverity = nil; criticalTitle = nil }171        else if r.counters.critical == 0 { criticalTitle = nil; if highestUnreadSeverity == .critical { highestUnreadSeverity = nil } }172        if old.0 != counters { revision += 1 }173        if old.0 != counters || old.1 != highestUnreadSeverity || old.2 != criticalTitle { onChange() }174    }175176    private func summarize(_ rows: [WalletAlert], counters c: AlertUnread) {177        let unread = rows.filter { !$0.isRead }178        // the counters are authoritative for "is something critical unread"; the page gives the title and the other severities179        highestUnreadSeverity = c.critical > 0 ? .critical : unread.map(\.severity).max()180        criticalTitle = unread.first { $0.severity == .critical }.map { $0.text(locale: AlertPresentation.locale, detail: false).title }181    }182183    /** After the owner marked alerts read: the server's own counters after the change. */184    func applyCounters(_ c: AlertUnread, unreadRows: [WalletAlert]? = nil) {185        apply(AlertPassResult(counters: c, unreadRows: unreadRows, fresh: []))186        Task { await sync.setBadge(c.unread) }187        // without the rows, the severity summary of what is still unread must come from the server again188        if unreadRows == nil, c.unread > 0 { Task { await poll(forceRows: true) } }189    }190191    /** The background pass: same watermark and same figures as the foreground poll. */192    func backgroundAlertPass() async throws -> AlertPassResult {193        let r = try await sync.pass(forceRows: counters == nil)194        apply(r)195        return r196    }197198    /** Sign-out or session wipe: nothing of the wallet stays, including the watermark and the badge. */199    func reset() {200        stop()201        counters = nil; highestUnreadSeverity = nil; criticalTitle = nil; lastCheckedAt = nil; revision += 1202        sync.forget()203        Task { await sync.setBadge(0) }204    }205206    /** The server ended the session: figures are no longer live. They are dropped rather than shown as current. */207    func sessionEnded() { counters = nil; highestUnreadSeverity = nil; criticalTitle = nil }208209    // MARK: widget210211    /**212     The two alert fields of `WidgetSnapshot`. `unreadAlerts` is nil when the server has not been read (a widget then shows no213     count); `criticalAlert` is the catalogue title of the newest unread critical alert — never an amount or an address.214     */215    func widgetFields() -> (unreadAlerts: Int?, criticalAlert: String?) { (counters?.unread, criticalTitle) }216}217
Files main
Menu

Theme