Cotton code
251 lines · 11.1 KB · SwiftRaw
// The contract for notifications — sub-step 4j's half of `Boundary.swift`.//// A SEPARATE FILE for the reason `Boundary+4d.swift`'s header gives: several// lanes land at once, and a lane appending to the middle of somebody else's// file makes a merge conflict out of two independent additions. The rule// `Boundary.swift` states still binds every shape below: **where this file and// `crates/cotton-ffi/src/phone/{push,reminders}.rs`// disagree, the crate wins**, and `BoundaryContractTests` reads the method// table by path so the two cannot drift quietly.//// The three methods 4j adds://// | Method | Answers | Called by |// |---|---|---|// | `push.forget` | `{forgotten, reason?}` — never an error, on any path | sign-out, and before a leave |// | `reminders.desired` | `{reminders, count, horizonDays, timeZone, now}` — what SHOULD be scheduled | anything that shows what is coming — **nothing in this app, today** |// | `reminders.reconcile` | `{schedule, cancel, noop, timeZone, now}` — the same set diffed against what iOS holds | the scheduler, which APPLIES the two lists |//// **The diff is the crate's and this app never computes one.** Two// implementations of "which reminders change" would eventually disagree, and a// disagreement there is a person whose reminder fires twice or not at all// ([one-implementation-of-who-wins-the-same-schema-and-conflict-rule]). So// `held` goes down VERBATIM — foreign identifiers included, because// `is_cotton_identifier` lives inside `reconcile` and is the only place that// decision should exist — and the two lists come back to be applied as given.//// Decoding is generous exactly as the two files before it are: every field is// optional or defaulted, and nothing throws on a shape it does not recognise.import Foundationextension CottonMethod {    // ── The token ─────────────────────────────────────────────────────────    /// `DELETE /v1/devices/{deviceId}` — tell the server to forget this device.    ///    /// **Answers either way and never an error**, on every path including a    /// missing `deviceId` and an unreadable device key: a person handing back a    /// phone must never be trapped by a deregistration that could not reach the    /// server.    public static let pushForget = "push.forget"    // ── The local reminders ───────────────────────────────────────────────    // `reminders.desired` is the crate's fourth 4j method and this app does not    // ask it, so there is no constant for it — a name here with no caller is    // the thing 4b's review struck. It answers the desired set UNDIFFED, for a    // screen that shows what is coming; the scheduler asks the method below,    // which answers the same set already diffed against what iOS holds. A later    // lane that wants the plain list adds the constant with its caller.    /// The desired set, diffed against what iOS is already holding.    ///    /// The scheduler's method. It answers two lists and the scheduler applies    /// them — cancel first, then schedule, because iOS caps a bundle at 64    /// pending.    public static let remindersReconcile = "reminders.reconcile"}// MARK: - `push.forget`/// `push.forget`'s argument. The crate takes the quiet branch when it is absent.public struct PushForget: Encodable, Sendable, Equatable {    public var deviceId: String    public init(deviceId: String) { self.deviceId = deviceId }}/// `push.forget`'s answer — never an error, on any path.public struct PushForgotten: Decodable, Equatable, Sendable {    public var forgotten: Bool    /// `no_device_id`, `device_key_unreadable`, `unreachable`, or the server's    /// own code. Present only when `forgotten` is false.    public var reason: String?    public init(forgotten: Bool, reason: String? = nil) {        self.forgotten = forgotten        self.reason = reason    }    public init(from decoder: Decoder) throws {        let values = try decoder.container(keyedBy: CodingKeys.self)        forgotten = try values.decodeIfPresent(Bool.self, forKey: .forgotten) ?? false        reason = try values.decodeIfPresent(String.self, forKey: .reason)    }    private enum CodingKeys: String, CodingKey { case forgotten, reason }}// MARK: - `reminders.desired` / `reminders.reconcile`/// What both reminder methods take.////// `timeZone` is REQUIRED and an unknown one is a refusal, never a UTC/// fallback: the host runs `TZ=UTC` and a guess would put the morning nudge on/// the wrong morning. `now` is omitted — the crate defaults it from the/// injected clock, and there is no clock up here. `held` is/// `getPendingNotificationRequests`' answer VERBATIM, foreign identifiers/// included, and only `reminders.reconcile` reads it.////// **It encodes under `args`, and `push.forget` does not.** That is the/// crate's own split rather than an inconsistency this file could smooth: the/// two reminder methods read `request["args"]`, the way every `read.*` does,/// because they are queries over the replica. Writing it out here is what/// keeps a caller from having to know.public struct ReminderRequest: Encodable, Sendable {    public var timeZone: String    public var prefs: NotificationPrefs    /// Absent takes the engine's own fourteen days. Present is passed through,    /// and an impossible value is a refusal rather than a silent clamp.    public var horizonDays: Int?    public var held: [String]?    public init(        timeZone: String,        prefs: NotificationPrefs,        horizonDays: Int? = nil,        held: [String]? = nil    ) {        self.timeZone = timeZone        self.prefs = prefs        self.horizonDays = horizonDays        self.held = held    }    private enum Envelope: String, CodingKey { case args }    private enum Args: String, CodingKey { case timeZone, prefs, horizonDays, held }    public func encode(to encoder: Encoder) throws {        var envelope = encoder.container(keyedBy: Envelope.self)        var args = envelope.nestedContainer(keyedBy: Args.self, forKey: .args)        try args.encode(timeZone, forKey: .timeZone)        try args.encode(prefs, forKey: .prefs)        // Absent, not null: the crate reads `None | Some(Null)` as "the        // engine's own fourteen", so either spelling works — and sending only        // what the caller named keeps the wire honest about what was asked.        try args.encodeIfPresent(horizonDays, forKey: .horizonDays)        try args.encodeIfPresent(held, forKey: .held)    }}/// One notification the crate says should exist.////// The identifier is `cotton:<kind>:<recordId>:<stamp>`, minute-precision, and/// **the stamp IS the diffing mechanism**: moving a todo's time changes the/// NAME, so the old one and the new one naturally schedule-and-orphan with/// nothing read back from the OS. Nothing in this app parses or builds one.public struct DesiredReminder: Decodable, Equatable, Sendable {    public var identifier: String    /// `todo` | `event` | `birthday` | `alarm` | `mood` — the same five the tap    /// table reads back off a fired notification.    public var kind: String    /// The record a tap opens (a PERSON id for a birthday).    public var recordId: String    /// When it fires, ISO-8601.    public var at: String    public var title: String    public var body: String?    /// The held database this reminder's record lives in, set by the pass    /// for every database but the personal one (`ReminderDatabases`); nil —    /// the crate's row as it came — for the personal database. Never read    /// off the wire: the crate answers one database's rows at a time.    public var database: String?    public init(        identifier: String,        kind: String,        recordId: String,        at: String,        title: String,        body: String? = nil,        database: String? = nil    ) {        self.identifier = identifier        self.kind = kind        self.recordId = recordId        self.at = at        self.title = title        self.body = body        self.database = database    }    public init(from decoder: Decoder) throws {        let values = try decoder.container(keyedBy: CodingKeys.self)        identifier = try values.decodeIfPresent(String.self, forKey: .identifier) ?? ""        kind = try values.decodeIfPresent(String.self, forKey: .kind) ?? ""        recordId = try values.decodeIfPresent(String.self, forKey: .recordId) ?? ""        at = try values.decodeIfPresent(String.self, forKey: .at) ?? ""        title = try values.decodeIfPresent(String.self, forKey: .title) ?? ""        body = try values.decodeIfPresent(String.self, forKey: .body)    }    private enum CodingKeys: String, CodingKey {        case identifier, kind, recordId, at, title, body    }    /// The tap payload this notification carries — `{kind, id}`, the two fields    /// the second tap table reads. Deliberately two: the tap resolves the path    /// from the KIND, so a route move never strands a notification already    /// sitting in Notification Centre. A reminder from a database other than    /// the personal one adds `databaseId`, the stamp `NotificationTaps.link`    /// reads, so its tap opens the record in its own database.    public var userInfo: [String: String] {        var info = ["kind": kind, "id": recordId]        if let database { info["databaseId"] = database }        return info    }}/// `reminders.reconcile`'s answer — the plan, and the whole of it.////// `schedule` carries WHOLE ROWS because Swift builds a `UNNotificationRequest`/// out of each; `cancel` carries names because/// `removePendingNotificationRequests` takes names. **The scheduler applies/// both as given** — it does not filter, re-order, or add.public struct ReminderPlan: Decodable, Equatable, Sendable {    public var schedule: [DesiredReminder]    public var cancel: [String]    /// The common case, every tick. A caller that trusts this skips two    /// `UNUserNotificationCenter` calls.    public var noop: Bool    public var timeZone: String?    public var now: String?    public init(        schedule: [DesiredReminder] = [],        cancel: [String] = [],        noop: Bool = true,        timeZone: String? = nil,        now: String? = nil    ) {        self.schedule = schedule        self.cancel = cancel        self.noop = noop        self.timeZone = timeZone        self.now = now    }    public init(from decoder: Decoder) throws {        let values = try decoder.container(keyedBy: CodingKeys.self)        schedule = try values.decodeIfPresent([DesiredReminder].self, forKey: .schedule) ?? []        cancel = try values.decodeIfPresent([String].self, forKey: .cancel) ?? []        noop = try values.decodeIfPresent(Bool.self, forKey: .noop) ?? true        timeZone = try values.decodeIfPresent(String.self, forKey: .timeZone)        now = try values.decodeIfPresent(String.self, forKey: .now)    }    private enum CodingKeys: String, CodingKey {        case schedule, cancel, noop, timeZone, now    }}