Cotton code
176 lines · 9.0 KB · SwiftRaw
// THE CORE'S FEED (SHELL BRIEF, "What the shell does itself" 1–3): the library and the pass hand the core's phone-only// index (`albums.*`, crates/cotton-ffi/src/phone/albums_app.rs) what they read and saw, and the screens draw what the// core answers. Only facts go in: items (`albums.library.take`), what each picture showed (`albums.look.take`) and the// pass's state (`albums.pass.lines`). No act goes to the core from here (coordinator, 27 Nov: none until CORE 1b).//// Absence never removes a choice (rule A): `all_ids` is sent only when the read was complete with full access; items// leave otherwise only when PhotoKit's persistent changes name them deleted.#if os(iOS)import CottonKitimport CoreGraphicsimport Foundationimport osfinal class AlbumsFeed: Sendable {    let core: any CottonCalling    /// One call at a time, in the order given; the pass hands work over and never waits for the core.    private let queue: AsyncStream<@Sendable () async -> Void>.Continuation    /// Work handed over and not yet done. The pass waits on it (`caughtUp`), so what waits for the core stays a few    /// batches long: an unbounded queue held every look's prints and faces in memory while the core fell behind    /// (64,000 synthetic items on the simulator: the footprint rose in steps to 747 MB).    private let waiting = OSAllocatedUnfairLock(initialState: 0)    init(core: any CottonCalling) {        self.core = core        let (stream, continuation) = AsyncStream<@Sendable () async -> Void>.makeStream()        queue = continuation        Task.detached(priority: .utility) {            for await work in stream { await work() }        }    }    /// Hands `work` to the feed's queue and returns at once.    func later(_ work: @escaping @Sendable (AlbumsFeed) async -> Void) {        waiting.withLock { $0 += 1 }        queue.yield { [self] in            let started = ContinuousClock.now            await work(self)            let took = started.duration(to: .now)            busy.withLock { $0 += Double(took.components.seconds) + Double(took.components.attoseconds) / 1e18 }            waiting.withLock { $0 -= 1 }        }    }    /// Seconds the core has spent on the feed's work since launch (how fast it keeps up, for the pass's log line).    var busySeconds: Int { Int(busy.withLock { $0 }) }    private let busy = OSAllocatedUnfairLock(initialState: 0.0)    /// Work waiting for the core now.    var pending: Int { waiting.withLock { $0 } }    /// Returns once no more than `most` pieces of work wait for the core: the pass never runs further ahead of it.    func caughtUp(most: Int) async {        while pending > most { try? await Task.sleep(for: .milliseconds(50)) }    }    /// Items in batches of 1,000; `all` (every id in the library) only after a complete read with full access.    func take(_ assets: [LibraryAsset], sizes: [String: LibrarySize], all: [String]? = nil, removed: [String] = []) async {        var batches = stride(from: 0, to: assets.count, by: 1000).map { Array(assets[$0..<min($0 + 1000, assets.count)]) }        if batches.isEmpty { batches = [[]] }        for (n, batch) in batches.enumerated() {            var body: [String: Any] = ["items": batch.map { Self.item($0, sizes[$0.id]) }]            if n == 0, !removed.isEmpty { body["removed"] = removed }            if n == batches.count - 1, let all { body["all_ids"] = all }            await call("albums.library.take", body)        }    }    /// What one batch of the pass saw: the picture as grey at the size it came (never scaled up), with Vision's    /// findings; `null` when the phone gave no picture.    func looks(_ found: [(id: String, state: AlbumsItem.State, look: AlbumsLook?)], network: Bool = false) async {        let looks: [[String: Any]] = found.compactMap { one in            switch one.state {            case .looked, .small:                guard let look = one.look else { return nil }                var row: [String: Any] = ["id": one.id, "network": network, "platform": Self.platform(look)]                if let grey = look.grey {                    row["grey"] = ["width": grey.width, "height": grey.height, "pixels": grey.pixels.base64EncodedString()]                }                return row            case .onlyInCloud, .failed:                return ["id": one.id, "network": network, "grey": NSNull()]            default:                return nil            }        }        guard !looks.isEmpty else { return }        await call("albums.look.take", ["looks": looks])    }    enum PassState: String { case running, pausedBattery = "paused_battery", pausedClosed = "paused_closed" }    func lines(_ state: PassState, charging: Bool) async {        await call("albums.pass.lines", ["state": state.rawValue, "charging": charging])    }    /// People: every face with a vector and his names go to the core's GROUPING 1 (`albums.faces.group`); the groups    /// that come back replace the store's. Answers the groups shown, or nil when the core did not answer.    @discardableResult    func group(_ store: AlbumsStore) async -> Int? {        let names = store.names()        let faces: [[String: Any]] = store.faceInputs().map { ["key": $0.key, "photo": $0.photo, "vector": $0.vector.base64EncodedString()] }        let started = ContinuousClock.now        guard let out = await answer("albums.faces.group", ["faces": faces, "names": names]),              let groups = out["groups"] as? [[String: Any]] else { return nil }        let parsed = groups.map { g in            (faces: g["faces"] as? [String] ?? [], shown: g["shown"] as? Bool ?? false, person: g["person"] as? String)        }        store.setGroups(parsed)        let shown = parsed.filter(\.shown).count        Log.write("albums: \(faces.count) faces grouped in \(started.duration(to: .now)), \(groups.count) groups, \(shown) shown")        return shown    }    /// The core's answer, for the Dev measurements; nil on any error.    func answer(_ method: String, _ body: [String: Any] = [:]) async -> [String: Any]? {        guard let data = try? JSONSerialization.data(withJSONObject: body),              let raw = try? await core.callRaw(method, requestJSON: String(decoding: data, as: UTF8.self)),              let envelope = try? JSONSerialization.jsonObject(with: Data(raw.utf8)) as? [String: Any] else { return nil }        if let error = envelope["error"] {            // Once a run per method: a core without `albums.*` (or a refusal repeated each batch) is said, not spammed.            if Self.first(method) { Log.write("albums: \(method) refused: \(error)") }            return nil        }        return envelope["data"] as? [String: Any]    }    nonisolated(unsafe) private static var said = Set<String>()    private static let saying = NSLock()    private static func first(_ method: String) -> Bool {        saying.withLock { said.insert(method).inserted }    }    private func call(_ method: String, _ body: [String: Any]) async {        _ = await answer(method, body)    }    // MARK: The contract's shapes    static func item(_ a: LibraryAsset, _ size: LibrarySize?) -> [String: Any] {        var flags: [String] = []        if a.flags.contains(.screenshot) { flags.append("screenshot") }        if a.flags.contains(.screenRecording) { flags.append("screen_recording") }        if a.flags.contains(.live) { flags.append("live") }        if a.burst != nil { flags.append("burst") }        if a.flags.contains(.panorama) { flags.append("panorama") }        if a.flags.contains(.hdr) { flags.append("hdr") }        if a.flags.contains(.favourite) { flags.append("favourite") }        if a.flags.contains(.hidden) { flags.append("hidden") }        var row: [String: Any] = [            "id": a.id,            "kind": a.kind == .video ? "video" : "photo",            "taken_at_ms": Int64(((a.created ?? a.modified ?? .distantPast).timeIntervalSince1970 * 1000).rounded()),            "width": a.width, "height": a.height,            "duration_ms": Int64((a.duration * 1000).rounded()),            "flags": flags,        ]        // Bytes only when the phone said: never zero for unknown.        if let size, size.exact, size.bytes > 0 { row["bytes"] = size.bytes }        if let name = size?.filename, !name.isEmpty { row["path"] = name }        // Where it was taken, for trips and places (the core's rules/media/albums.rs): read by the core once its        // `albums.*` methods take it; until then serde leaves an unknown key alone.        if let lat = a.latitude, let lon = a.longitude { row["latitude"] = lat; row["longitude"] = lon }        return row    }    static func platform(_ look: AlbumsLook) -> [String: Any] {        var p: [String: Any] = ["utility": look.utility, "document": look.document, "faces": look.faces.count]        // Vision's print stays in this phone's own store (coordinator, 27 Nov): the core keeps only its own hash.        if let a = look.aesthetic { p["aesthetics"] = a }        if let best = look.faces.compactMap(\.quality).max() { p["face_quality"] = best }        return p    }}#endif