Cotton code
109 lines · 4.5 KB · SwiftRaw
// COTTON HEALTH'S ENGINE (13 Nov 2026): attached at launch by the app that// links HealthKit (`App/Cotton/CottonApp.swift`, `COTTON_HEALTH`). It does// two things and asks the person nothing:////   * It attaches the Read Apple Health door's reader (`DeviceReadings`)://     the door's tap is the one place the person is asked.//   * Once the person HAS answered (`status`, which never prompts), it keeps//     an observer on every type and asks HealthKit for hourly background//     delivery, so what the watch and phone record lands without opening//     the app. Registered at launch, before the first frame, as HealthKit//     needs to find them when it wakes the app; and again after the door's//     first read, the first time there is an answer to stand on.import CottonKitimport CottonUIimport Foundationimport HealthKit@MainActorpublic final class HealthEngine {    public static let shared = HealthEngine()    private var open: (@Sendable () async -> (any CottonCalling)?)?    private var reader: HealthReader?    private var observing = false    private let store = HKHealthStore()    /// Attach the door's reader and, where the person already answered, the    /// observers. `open` gives the core once it is open.    public func attach(_ open: @escaping @Sendable () async -> (any CottonCalling)?) {        self.open = open        DeviceReadings.reader = AppleHealthDoor(engine: self)        Task { await observe() }    }    /// The one reader over the open core.    func reader(_ core: any CottonCalling) -> HealthReader {        if let reader { return reader }        let made = HealthReader(core: core)        reader = made        return made    }    /// Observers and background delivery for every read type, once the    /// person has answered; nothing at all before that.    func observe() async {        guard !observing, let open, let core = await open() else { return }        let reader = reader(core)        guard let types = try? await reader.types(),              await SystemCapabilityAuthority().status(.appleHealth) == .authorized else { return }        observing = true        for type in types where type.anchored && type.statisticsFit {            guard let sampleType = type.sampleType else { continue }            store.execute(Self.observer(sampleType, reader: reader))            try? await store.enableBackgroundDelivery(for: sampleType, frequency: .hourly)        }    }    /// An observer that reads what changed and then tells HealthKit it is    /// done. Built `nonisolated`: HealthKit calls it off the main queue, and    /// a handler written inside this main-actor type would carry a    /// main-queue assertion into that call.    nonisolated static func observer(_ type: HKSampleType, reader: HealthReader) -> HKObserverQuery {        HKObserverQuery(sampleType: type, predicate: nil) { _, finished, error in            let done = ObserverDone(finished)            guard error == nil else { return done.call() }            Task {                _ = await reader.readAnswered()                done.call()            }        }    }}/// HealthKit's completion for one observer wake, called once the read is done.private final class ObserverDone: @unchecked Sendable {    let call: () -> Void    init(_ call: @escaping () -> Void) {        self.call = call    }}/// The Read Apple Health door: ask, read, say it.struct AppleHealthDoor: DeviceReading {    let engine: HealthEngine    func read(_ reads: DefinitionDeviceReads, core: any CottonCalling) async -> DeviceReadSaid {        let reader = await engine.reader(core)        let outcome = await reader.read()        await engine.observe()        return Self.said(outcome)    }    static func said(_ outcome: HealthReadOutcome) -> DeviceReadSaid {        switch outcome {        case .read(let changed) where changed == 0:            DeviceReadSaid(line: ShellLines.line("cards", "health.read.nothing"), failed: false)        case .read(let changed):            DeviceReadSaid(line: ShellLines.line("cards", "health.read.landed", ["n": "\(changed)"]), failed: false)        case .locked:            DeviceReadSaid(line: ShellLines.line("cards", "health.read.locked"), failed: true)        case .unavailable:            DeviceReadSaid(line: ShellLines.line("cards", "health.read.unavailable"), failed: true)        case .failed(let why):            DeviceReadSaid(line: ShellLines.line("cards", "health.read.failed", ["why": why]), failed: true)        }    }}