// Keeps the DEVICE's alarms in step with `cotton_alarms`. // // Before the rewrite the pass watched a QUERY CACHE, so the Alarms surface // never had to remember to "also tell the scheduler"; here it reads // `read.alarms` itself and reconciles when a `data` event names the table. That // is the same guarantee with one fewer moving part — and it removes the cache's // own ambiguity, since a read either answers or it fails, where an undefined // cache entry had to be told apart from an empty list by hand (an empty desired // set looks exactly like "the person deleted everything" and would cancel real // alarms). // // The pass also runs on foregrounding: that is when a permission changed in // Settings becomes visible to us, and permission decides both which BACKEND is // live and — since the ring bug — whether the pass may schedule AT ALL. // // Everything interesting is in `reconcileAlarms`, which is pure. This file is // the I/O shell: read the actual sets, run the diff, execute it, persist the // ledger. import CottonKit import CottonValues import Foundation /// Coalesce bursts: a screen that wrote three rows should reconcile once. private let alarmDebounce: Duration = .milliseconds(400) @MainActor @Observable public final class AlarmSyncModel { private let core: any CottonCalling private let device: any AlarmDevice private let authorizer: any AlarmAuthorizer private let preferences: any AlarmPreferences private let ledgerStore: AlarmLedgerStore private let calendar: Calendar private var running = false private var pending: Task? /// A request that arrived while a pass was in flight. The pass that is /// running read the desired set BEFORE that write landed, so dropping the /// request outright loses it for good — see `run(now:)`. private var missedRequest = false /// The gate as the last pass resolved it — what the screen's notice reads. /// `nil` until a pass has run: "we have not asked yet" and "nothing will /// ring" are different, and drawing the second before the first is a /// warning about a state nobody is in. public private(set) var gate: AlarmGate? /// The person set or switched on an alarm on this phone since the last /// pass (`Notification.Name.cottonRecordWrittenHere` naming the alarm /// table, not switched off): the one moment AlarmKit is asked for. private var alarmSetHere = false @ObservationIgnored private var setHereObserver: (any NSObjectProtocol)? /// Every alarm as the last pass read it — what the list's "next:" line /// counts down to (`AlarmListHead`). Empty until a pass has read them. private(set) var alarms: [Alarm] = [] public init( core: any CottonCalling, device: (any AlarmDevice)? = nil, authorizer: (any AlarmAuthorizer)? = nil, preferences: any AlarmPreferences = StoredAlarmPreferences(), ledgerStore: AlarmLedgerStore = AlarmLedgerStore(), calendar: Calendar = .current ) { self.core = core // The real device is built ONLY when one of the two was not supplied. // // `SystemAlarmDevice`'s default `centre` is `UNUserNotificationCenter // .current()`, and that call ABORTS the process in a unit-test host — // "bundleProxyForCurrentProcess is nil", because the host's main bundle // is Xcode's test agent and not an app. Building it eagerly and then // throwing it away meant a test that injected both doubles still // crashed on the line that made the one it never used. if let device, let authorizer { self.device = device self.authorizer = authorizer } else { let system = SystemAlarmDevice(calendar: calendar) self.device = device ?? system self.authorizer = authorizer ?? system } self.preferences = preferences self.ledgerStore = ledgerStore self.calendar = calendar setHereObserver = NotificationCenter.default.addObserver( forName: .cottonRecordWrittenHere, object: nil, queue: .main ) { [weak self] note in guard Self.setsAnAlarm(note.userInfo) else { return } MainActor.assumeIsolated { self?.alarmSetHere = true } } } /// Ask for a pass. Bursts coalesce; overlapping passes do not happen. /// /// Two concurrent diffs would read the same "actual" set and both schedule, /// so a pass already in flight does not start a second one — it REMEMBERS /// the request and runs it when the pass it collided with is done. See /// `run(now:)`: the pass in flight read its desired set before this write /// landed, so dropping the request loses it until the next foreground. public func reconcile(now: Date = Date()) { pending?.cancel() pending = Task { [weak self] in try? await Task.sleep(for: alarmDebounce) guard !Task.isCancelled else { return } await self?.run(now: now) } } /// The table this model watches. The rows are the person's alarms; a change /// to any of them can add, retime or silence something the OS is holding. private static let watchedTable = "cotton_alarms" /// The same table as a write names it (its definition's id). nonisolated private static let alarmDefinition = "alarm" /// An inbound fold, a write from another screen, a tool call on the Mac. /// /// The previous app's hook watched the whole query cache and reconciled /// on any `"updated"` / `"added"`, so an alarm that ARRIVED /// — by sync, from a tool, or from another device — reached the operating /// system at once. The first cut of this model reconciled only after a /// write made on the Alarms screen itself, which left every other path /// waiting for the next foreground. This is that guarantee, restored on the /// `data` event, which is the whole of invalidation on this app. /// /// It needs no `InvalidationMap` entry: the map decides which screen /// FAMILY a fold refreshes, and this is a model asking one question of the /// table list the event already carries. public func receive(_ event: ClientEvent) { guard case let .data(tables, _, _) = event else { return } guard tables.contains(AlarmSyncModel.watchedTable) else { return } reconcile() } /// Run one pass now, without the debounce. The foreground path and the /// tests use this. public func run(now: Date = Date()) async { // A pass already in flight read its desired set before whatever // prompted this call landed, so the request is REMEMBERED rather than // dropped: the previous hook could afford to drop one because its cache // subscription would fire again, and nothing re-fires here. if running { missedRequest = true return } running = true defer { running = false } // The list. A read that FAILS skips the pass rather than treating the // absence as an empty desired set: cancelling every alarm on the phone // because the file could not be opened is the worst thing this pass // could do. guard let answer = try? await core.callJSON(CottonMethod.readAlarms, EmptyRequest()) else { return } let alarms = answer.list("alarms").map { Alarm($0) } self.alarms = alarms // AlarmKit's permission is asked HERE, before the gate is read, so the // pass after the person sets an alarm on this phone schedules it on // the loud backend the moment they say yes (`askForAlarmKitIfDue`); // a launch's pass asks nothing. let setHere = alarmSetHere alarmSetHere = false await askForAlarmKitIfDue(authorizer, preferences: preferences, alarms: alarms, setHere: setHere) // THE GATE, asked every pass rather than cached, for the same reason // the backend is: the answer changes the moment somebody grants // permission in Settings or flips the Alarms switch, and a stale "yes" // is an alarm that does not ring behind a screen saying it will. let gate = await resolveAlarmGate(preferences: preferences, authorizer: authorizer) self.gate = gate let actualAlarmKitIds = await device.alarmKitIds() let actualNotificationKeys = await device.notificationKeys() let ledger = ledgerStore.read() var plan = reconcileAlarms( ReconcileInput( alarms: alarms, backend: gate.backend, actualAlarmKitIds: actualAlarmKitIds, actualNotificationKeys: actualNotificationKeys, ledger: ledger, canSchedule: gate.canSchedule, now: now, calendar: calendar ) ) for id in plan.cancelAlarmKit { _ = await device.cancelAlarmKit(id: id) } await device.cancelFallback(keys: plan.cancelNotifications) for planned in plan.scheduleAlarmKit { let ok = await device.scheduleAlarmKit(schedule(planned)) // A refused schedule must NOT be recorded as done, or the next pass // would see a matching signature and never retry. if !ok { plan.nextLedger[planned.id] = nil } } for planned in plan.scheduleNotifications { let ok = await device.scheduleFallback(schedule(planned), now: now) if !ok { plan.nextLedger[planned.id] = nil } } // A one-shot that rang is switched off, so the list stops showing a lit // switch for an alarm that is not coming and the header stops counting // down to it. The ledger entry is kept either way, so a failed write is // simply retried next pass rather than re-arming the alarm. for id in plan.firedOnce { await disable(id: id) } ledgerStore.write(plan.nextLedger) // Whatever arrived mid-pass gets the pass it asked for. `running` is // still true here, so this cannot recurse — it schedules through the // debounce like any other request. if missedRequest { missedRequest = false reconcile() } } /// An unnamed alarm still needs a word on the lock screen. private func schedule(_ planned: PlannedAlarm) -> AlarmSchedule { let label = planned.label.trimmingCharacters(in: .whitespacesAndNewlines) return AlarmSchedule( id: planned.id, title: label.isEmpty ? ShellLines.line("reminders", "alarms.untitled") : label, label: planned.label, stopLabel: "Stop", hour: planned.hour, minute: planned.minute, repeatDays: planned.repeatDays, sound: planned.sound ) } /// Switching a fired one-shot off is a WRITE to the person's own row, so it /// goes through the tool like any other. private func disable(id: String) async { let request = WriteRequest( tool: DayTool.updateAlarm, args: .object(["id": .string(id), "enabled": .bool(false)]) ) _ = try? await core.call(CottonMethod.write, request, as: WriteAnswer.self) } } /// The signature ledger — what each alarm was last scheduled AS. /// /// Device-local and deliberately so: `cotton_alarms` is SYNCED (the durable /// list is the same on every device the owner has) and only the SCHEDULING is /// local, because the alarm rings on the phone in the room. /// `@unchecked Sendable`: the only stored property is `UserDefaults`, which is /// documented thread-safe but is not marked `Sendable`. public struct AlarmLedgerStore: @unchecked Sendable { public static let key = "cotton.alarms.ledger" private let defaults: UserDefaults public init(defaults: UserDefaults = .standard) { self.defaults = defaults } /// A ledger that will not decode is read as EMPTY, which re-schedules /// everything — and both backends treat a re-schedule as an overwrite, so /// that is a repair rather than a duplicate. public func read() -> AlarmLedger { guard let data = defaults.data(forKey: Self.key), let ledger = try? JSONDecoder().decode(AlarmLedger.self, from: data) else { return [:] } return ledger } public func write(_ ledger: AlarmLedger) { guard let data = try? JSONEncoder().encode(ledger) else { return } defaults.set(data, forKey: Self.key) } } extension AlarmSyncModel { /// A write on this phone that made or switched on an alarm. nonisolated static func setsAnAlarm(_ info: [AnyHashable: Any]?) -> Bool { guard info?["table"] as? String == alarmDefinition else { return false } let enabled = (info?["data"] as? [String: RecordValue])?["enabled"] return enabled != .bool(false) && enabled != .number(0) } } extension Notification.Name { /// The person created or changed a row on this phone (`CoreRecords`), with /// its table and written columns: what `AlarmSyncModel` reads to know an /// alarm was set here. public static let cottonRecordWrittenHere = Notification.Name("com.cottondb.recordWrittenHere") }