// 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.importCottonValuesimportFoundationimportUserNotifications/// What one pass did.publicstructReminderPassOutcome: Equatable, Sendable {/// The crate said nothing changes. The common case, every tick.publicvar noop: Boolpublicvar cancelled: Intpublicvar 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.publicvar refusal: String?publicinit( noop: Bool = true, cancelled: Int = 0, scheduled: Int = 0, refusal: String? = nil ) {self.noop = noopself.cancelled = cancelledself.scheduled = scheduledself.refusal = refusal }}/// The notification centre, behind a seam — so the pass is testable without one.publicprotocolReminderCentre: 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.publicstructSystemReminderCentre: ReminderCentre {publicinit() {}publicfunc heldIdentifiers() async -> [String] {await UNUserNotificationCenter.current().pendingNotificationRequests().map(\.identifier) }publicfunc cancel(_ identifiers: [String]) async {guard !identifiers.isEmpty else { return } UNUserNotificationCenter.current() .removePendingNotificationRequests(withIdentifiers: identifiers) }publicfunc schedule(_ reminders: [DesiredReminder]) async -> Int {var landed = 0for reminder in reminders {guardlet request = SystemReminderCentre.request(for: reminder) else { continue }do {tryawait 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.staticfunc request(for reminder: DesiredReminder) -> UNNotificationRequest? {guardlet at = CottonDate.instant(reminder.at) else { returnnil }let content = UNMutableNotificationContent() content.title = reminder.titleiflet body = reminder.body { content.body = body } content.sound = .default content.userInfo = reminder.userInfolet 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.publicstructReminderPass: Sendable {privatelet core: any CottonCallingprivatelet centre: any ReminderCentrepublicinit(core: any CottonCalling, centre: any ReminderCentre = SystemReminderCentre()) {self.core = coreself.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.publicfunc run( timeZone: String, prefs: NotificationPrefs, permission: NotificationPermission, others: [String]? = [] ) async -> ReminderPassOutcome {var forThisPass = prefsif 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 = falsefunc plan(_ caller: any CottonCalling, held: [String]) async -> ReminderPlan? {do {returntryawait caller.call(CottonMethod.remindersReconcile,ReminderRequest(timeZone: timeZone, prefs: forThisPass, held: held),as: ReminderPlan.self ) } catchlet refused asCottonCallError { refusal = refusal ?? refused.code } catch { refusal = refusal ?? "unreadable" }returnnil }// The personal database: the crate's identifiers as they are, and// every foreign one verbatim.iflet 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)guardlet 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 invar row = row row.identifier = ReminderDatabases.tag(row.identifier, database: database) row.database = databasereturn row } }// A database no longer held has no reminders left to want.iflet 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)returnReminderPassOutcome( 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.publicenumReminderDatabases {staticlet prefix = "db."staticlet separator: Character = "|"/// The name iOS holds `identifier` under for `database`.publicstaticfunc 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.publicstaticfunc untag(_ identifier: String) -> (database: String, identifier: String)? {guard identifier.hasPrefix(prefix), let bar = identifier.firstIndex(of: separator) else { returnnil }let database = String(identifier[identifier.index(identifier.startIndex, offsetBy: prefix.count)..<bar])guard !database.isEmpty else { returnnil }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.publicstaticfunc split(_ held: [String]) -> (personal: [String], byDatabase: [String: [String]]) {var personal: [String] = []var byDatabase: [String: [String]] = [:]for identifier in held {iflet tagged = untag(identifier) { byDatabase[tagged.database, default: []].append(tagged.identifier) } else { personal.append(identifier) } }return (personal, byDatabase) }}