Cotton code
291 lines · 12.9 KB · SwiftRaw
// The ONE thing that touches `UNUserNotificationCenter`, and the pass that// drives it.//// **Rust owns the diff and this file never computes one.** The pass reads what// iOS is holding, hands it down VERBATIM as `held`, and applies the two lists// `reminders.reconcile` answers: `cancel` by name, `schedule` as whole rows.// Foreign identifiers go down untouched, because `is_cotton_identifier` lives// inside the crate's `reconcile` and that is the only place the decision should// exist — filtering here would be the one rule of this diff that is not set// arithmetic living in the half that cannot be tested on Linux.//// Three rules the port must keep, each of which fails quietly when broken:////   * **Permission is the real master switch, and a revoked permission is a//     WIPE.** Not granted means the desired set is EMPTY, which cancels//     everything already standing. A pass that short-circuited on "no//     permission, nothing to do" would leave stale reminders scheduled for//     ever. It is expressed by sending `enabled: false` for the pass rather//     than by a second emptiness rule here — `enabled` is the permission AND//     the preference, which keeps the emptiness decision in the engine that//     owns it.//   * **Cancel BEFORE schedule**, because iOS caps a bundle at 64 pending and//     the other order can lose the newest reminder to the ceiling. The crate//     also keeps its own desired set under `PENDING_BUDGET` (48), so the//     ceiling is something this pass stays under rather than something it//     discovers — see `cotton-core/src/rules/reminders.rs`.//   * **An absolute date, never a repeating trigger.** Recurrence is//     pre-expanded by the engine, one row per occurrence; a repeating trigger//     here would fire a series the reconcile cannot see.//// What does NOT port, with its reason: the pass used to read a query CACHE by// key prefix. There is no cache in this app — the pass asks the replica through// the crate, which is strictly simpler and is the same answer.import CottonValuesimport Foundationimport UserNotifications/// What one pass did.public struct ReminderPassOutcome: Equatable, Sendable {    /// The crate said nothing changes. The common case, every tick.    public var noop: Bool    public var cancelled: Int    public var scheduled: Int    /// The crate's refusal code, when the pass could not be decided at all.    /// `bad_request` (a zone this phone named and the engine cannot resolve),    /// `unreadable` (the file), `unknown_method` (a build without the crate    /// half). Never shown to anybody: a reminder pass has no screen.    public var refusal: String?    public init(        noop: Bool = true,        cancelled: Int = 0,        scheduled: Int = 0,        refusal: String? = nil    ) {        self.noop = noop        self.cancelled = cancelled        self.scheduled = scheduled        self.refusal = refusal    }}/// The notification centre, behind a seam — so the pass is testable without one.public protocol ReminderCentre: Sendable {    /// Every identifier the OS is currently holding — ours and everyone else's.    func heldIdentifiers() async -> [String]    /// Take these off the queue, by name.    func cancel(_ identifiers: [String]) async    /// Put these on it. Answers how many landed: an individual failure is    /// swallowed, because one reminder the OS would not take must not stop the    /// other thirteen.    func schedule(_ reminders: [DesiredReminder]) async -> Int}/// The real centre.////// It holds no centre of its own and reaches `UNUserNotificationCenter.current()`/// at each call, rather than storing it: the class is not `Sendable`, this type/// has to be (the pass crosses to whichever thread asked for it), and a stored/// reference would have to be vouched for by hand. There is exactly one/// notification centre per process, so "the current one" is not a lookup that/// can answer differently.public struct SystemReminderCentre: ReminderCentre {    public init() {}    public func heldIdentifiers() async -> [String] {        await UNUserNotificationCenter.current().pendingNotificationRequests().map(\.identifier)    }    public func cancel(_ identifiers: [String]) async {        guard !identifiers.isEmpty else { return }        UNUserNotificationCenter.current()            .removePendingNotificationRequests(withIdentifiers: identifiers)    }    public func schedule(_ reminders: [DesiredReminder]) async -> Int {        var landed = 0        for reminder in reminders {            guard let request = SystemReminderCentre.request(for: reminder) else { continue }            do {                try await UNUserNotificationCenter.current().add(request)                landed += 1            } catch {                // Swallowed per reminder, on purpose: the pass keeps going.            }        }        return landed    }    /// One `UNNotificationRequest`, out of one desired row.    ///    /// `userInfo` is `{kind, id}` and nothing else — the tap resolves the path    /// from the kind, so a route move never strands a notification already    /// sitting in Notification Centre.    ///    /// The trigger is a NON-REPEATING calendar trigger over the instant's own    /// components, which is what the previous build's date trigger compiled    /// to.    /// A row whose `at` will not parse is skipped rather than scheduled at an    /// invented instant: iOS accepts a malformed date and then never fires it,    /// which is a reminder that is silently dead rather than absent.    static func request(for reminder: DesiredReminder) -> UNNotificationRequest? {        guard let at = CottonDate.instant(reminder.at) else { return nil }        let content = UNMutableNotificationContent()        content.title = reminder.title        if let body = reminder.body { content.body = body }        content.sound = .default        content.userInfo = reminder.userInfo        let parts = Calendar.current.dateComponents(            [.year, .month, .day, .hour, .minute, .second],            from: at        )        return UNNotificationRequest(            identifier: reminder.identifier,            content: content,            trigger: UNCalendarNotificationTrigger(dateMatching: parts, repeats: false)        )    }}/// One reconcile pass.public struct ReminderPass: Sendable {    private let core: any CottonCalling    private let centre: any ReminderCentre    public init(core: any CottonCalling, centre: any ReminderCentre = SystemReminderCentre()) {        self.core = core        self.centre = centre    }    /// Read what iOS holds, ask the crate for each held database's plan,    /// apply them.    ///    /// - Parameters:    ///   - timeZone: the IANA zone every local-hour decision is made in.    ///     REQUIRED and never guessed — the host runs `TZ=UTC` and a guess would    ///     put the morning nudge on the wrong morning.    ///   - prefs: the person's switches, as this device holds them.    ///   - permission: what the OS says right now.    ///   - others: the held databases other than the personal one, each    ///     reconciled against its own reminders only (`ReminderDatabases`);    ///     nil while the held list is not known, when no database's    ///     reminders are judged gone. With none, the pass is the one    ///     personal call it always was.    public func run(        timeZone: String,        prefs: NotificationPrefs,        permission: NotificationPermission,        others: [String]? = []    ) async -> ReminderPassOutcome {        var forThisPass = prefs        if permission != .granted {            // The master switch, and it is a WIPE rather than a skip. See the            // file header.            forThisPass.enabled = false        }        // ONE queue for the whole app, split by database: each database's        // pass sees only its own reminders, so the crate's "cancel every        // Cotton identifier I do not want" never reaches another database's.        let queue = ReminderDatabases.split(await centre.heldIdentifiers())        var cancel: [String] = []        var schedule: [DesiredReminder] = []        var refusal: String?        var changed = false        func plan(_ caller: any CottonCalling, held: [String]) async -> ReminderPlan? {            do {                return try await caller.call(                    CottonMethod.remindersReconcile,                    ReminderRequest(timeZone: timeZone, prefs: forThisPass, held: held),                    as: ReminderPlan.self                )            } catch let refused as CottonCallError {                refusal = refusal ?? refused.code            } catch {                refusal = refusal ?? "unreadable"            }            return nil        }        // The personal database: the crate's identifiers as they are, and        // every foreign one verbatim.        if let personal = await plan(core, held: queue.personal), !personal.noop {            changed = true            cancel += personal.cancel            schedule += personal.schedule        }        var seen: Set<String> = []        for database in others ?? [] where !database.isEmpty && seen.insert(database).inserted {            let scoped = DatabaseScopedCore(underlying: core, database: database)            guard let own = await plan(scoped, held: queue.byDatabase[database] ?? []), !own.noop else { continue }            changed = true            cancel += own.cancel.map { ReminderDatabases.tag($0, database: database) }            schedule += own.schedule.map { row in                var row = row                row.identifier = ReminderDatabases.tag(row.identifier, database: database)                row.database = database                return row            }        }        // A database no longer held has no reminders left to want.        if let others {            for (database, identifiers) in queue.byDatabase.sorted(by: { $0.key < $1.key })            where !others.contains(database) {                changed = true                cancel += identifiers.map { ReminderDatabases.tag($0, database: database) }            }        }        guard changed else {            return refusal.map { ReminderPassOutcome(refusal: $0) } ?? ReminderPassOutcome(noop: true)        }        // CANCEL BEFORE SCHEDULE, across every database. See the file header.        await centre.cancel(cancel)        let scheduled = await centre.schedule(schedule)        return ReminderPassOutcome(            noop: false,            cancelled: cancel.count,            scheduled: scheduled,            refusal: refusal        )    }}/// Which held database a scheduled reminder is for (several databases on one/// device, P10).////// The crate names a reminder `cotton:<kind>:<recordId>:<stamp>` and answers/// one database at a time, so one record id in two databases is one name, and/// a pass that saw another database's names would cancel them as unwanted./// A reminder for any database but the personal one is therefore held by iOS/// under its database: `db.<databaseId>|` before the crate's own name. The/// crate never sees the tag — each database's pass is handed its own names/// with the tag taken off, and its plan has the tag put back — and to the/// crate's `is_cotton_identifier` a tagged name is not one of its own, so/// the personal pass leaves it alone. The personal database's names are the/// crate's own, unchanged: with one database nothing here changes a byte.public enum ReminderDatabases {    static let prefix = "db."    static let separator: Character = "|"    /// The name iOS holds `identifier` under for `database`.    public static func tag(_ identifier: String, database: String) -> String {        "\(prefix)\(database)\(separator)\(identifier)"    }    /// The database and the crate's own name of a tagged identifier; nil for    /// anything else.    public static func untag(_ identifier: String) -> (database: String, identifier: String)? {        guard identifier.hasPrefix(prefix), let bar = identifier.firstIndex(of: separator) else { return nil }        let database = String(identifier[identifier.index(identifier.startIndex, offsetBy: prefix.count)..<bar])        guard !database.isEmpty else { return nil }        return (database, String(identifier[identifier.index(after: bar)...]))    }    /// What iOS holds, split: every untagged identifier (the personal    /// database's and every foreign one) verbatim, and each database's own    /// names with the tag taken off.    public static func split(_ held: [String]) -> (personal: [String], byDatabase: [String: [String]]) {        var personal: [String] = []        var byDatabase: [String: [String]] = [:]        for identifier in held {            if let tagged = untag(identifier) {                byDatabase[tagged.database, default: []].append(tagged.identifier)            } else {                personal.append(identifier)            }        }        return (personal, byDatabase)    }}