Cotton code
564 lines · 27.2 KB · SwiftRaw
// THE FIRST PASS, AND EVERY ONE AFTER (assets/design/albums/DECISIONS.md "The first pass, honest"; RESEARCH.md §1// "Background"): every photo is looked at once, on this phone, newest first, and what was found is kept// (`AlbumsStore`) after every 200: a checkpoint, so a pass stopped anywhere carries on where it stopped and never looks// twice. Four pictures at once (Apple: about five requests at a time).//// When it runs://   - while Albums is open, always;//   - after Start, on in the background as a continued task (iOS 26: the person started it with a tap; the phone//     shows its progress and the person can stop it; swiping Albums away ends it);//   - otherwise in the phone's processing time, only on the charger (`requiresExternalPower`), until the phone says//     stop.// The time left is measured from the last 500 looked at, never guessed. A photo with no picture on the phone (only in// iCloud, Optimise Storage) is counted and said, and looked at later on Wi-Fi at the same small size; never the// original.#if os(iOS)import BackgroundTasksimport CottonKitimport Foundationimport Networkimport Observationimport UIKit@MainActor@Observablefinal class AlbumsPass {    static let shared = AlbumsPass()    enum Pause: Equatable { case none, battery, away }    /// A task the scheduler hands over on its own queue, carried to the main actor that alone touches it after.    private struct HeldTask: @unchecked Sendable {        let task: BGTask        init(_ task: BGTask) { self.task = task }    }    private(set) var counts = AlbumsStore.Counts()    private(set) var running = false    private(set) var pause: Pause = .none    /// The library has been read at least once (the counts mean something).    private(set) var read = false    /// Changes every checkpoint: what the screens show follows it.    var revision = 0    var store: AlbumsStore { AlbumsStore.shared }    @ObservationIgnored private var stopAsked = false    @ObservationIgnored private var observer: UUID?    @ObservationIgnored private var continued: BGTask?    @ObservationIgnored private var retried = false    /// Faces on (the coordinator's word: on by default, grouping on this phone; one switch in You turns them off).    @ObservationIgnored var faces: Bool {        get { UserDefaults.standard.object(forKey: "albums.faces") as? Bool ?? true }        set { UserDefaults.standard.set(newValue, forKey: "albums.faces") }    }    nonisolated static let batch = 200    nonisolated static let atOnce = 4    var minutesLeft: Int? {        guard let rate = counts.perMinute, rate > 0 else { return nil }        return Int((Double(counts.waiting) / rate).rounded(.up))    }    var finished: Bool { read && counts.waiting == 0 && counts.photos > 0 }    // MARK: Reading the library    /// Brings the store to the library: the whole library the first time (or when the change token expired), only    /// what changed after that.    func readLibrary() async {        guard AlbumsLibrary.access.reads else { return }        let library = AlbumsLibrary.shared        let store = self.store        let (change, token) = await Task.detached(priority: .userInitiated) { (try? library.changes()) ?? (.wholePass, nil) }.value        let (fed, fedSizes, removed, complete, whole) = await Task.detached(priority: .userInitiated) {            () -> ([LibraryAsset], [String: LibrarySize], [String], Bool, Bool) in            switch change {            case .wholePass:                // Metadata first (fast), so the pass starts; each asset's size on disk is asked after (`fillSizes`).                let (assets, complete) = library.enumerate()                store.reconcile(assets, sizes: [:], complete: complete)                return (assets, [String: LibrarySize](), [String](), complete, true)            case .changed(let inserted, let removed, let updated):                let fresh = library.assets(inserted + updated)                let sizes = library.sizes(fresh)                store.apply(inserted: fresh, removed: removed, sizes: sizes)                return (fresh, sizes, removed, false, false)            }        }.value        if whole { lastReadComplete = complete }        // Handed to the core's queue before the token moves on; the pass never waits for the core.        let all = whole && complete ? fed.map(\.id) : nil        feed?.later { await $0.take(fed, sizes: fedSizes, all: all, removed: removed) }        if let token { library.saveToken(token) }        read = true        refresh()        fillSizes()        #if COTTON_DEV        if ProcessInfo.processInfo.arguments.contains("-albums-sizes"), !sizesMeasured {            sizesMeasured = true            Task.detached(priority: .utility) { await AlbumsLibrary.shared.measureSizes(count: 200) }        }        #endif        if observer == nil {            observer = library.observe { [weak self] _ in                Task { @MainActor in await self?.libraryChanged() }            }        }    }    @ObservationIgnored private var sizing = false    /// The core's feed (`AlbumsFeed`): set once the root has a core (`use`); until then the pass only keeps its own.    @ObservationIgnored private(set) var feed: AlbumsFeed?    func use(_ core: any CottonCalling) {        guard feed == nil else { return }        feed = AlbumsFeed(core: core)        // What was read before the core came: every item once, so the index starts whole.        if read { Task { await feedEverything() } }   // its own calls go through the queue    }    /// Every item the store holds, with what is known of its size; `all_ids` only when the last read was complete.    private func feedEverything() async {        guard let feed else { return }        let store = self.store        let complete = lastReadComplete        await Task.detached(priority: .utility) {            let items = store.items()            var sizes: [String: LibrarySize] = [:]            for item in items where item.exact { sizes[item.asset.id] = LibrarySize(bytes: item.bytes, exact: true, filename: item.filename) }            let all = complete ? items.map(\.asset.id) : nil            let fedSizes = sizes            feed.later { await $0.take(items.map(\.asset), sizes: fedSizes, all: all) }        }.value    }    @ObservationIgnored private var lastReadComplete = false    @ObservationIgnored private var sizesMeasured = false    /// The size on disk of every asset still "about", 500 at a time, behind the pass.    private func fillSizes() {        guard !sizing else { return }        sizing = true        let store = self.store        Task.detached(priority: .utility) {            while true {                let ids = store.unsized(500)                if ids.isEmpty { break }                let assets = AlbumsLibrary.shared.assets(ids)                var sizes = AlbumsLibrary.shared.sizes(assets)                // An asset gone from the library meanwhile keeps its row until the next read takes it out.                for id in ids where sizes[id] == nil { sizes[id] = LibrarySize(bytes: 0, exact: false, filename: "") }                store.setSizes(sizes)                let fedSizes = sizes                let feed = await AlbumsPass.shared.feed                feed?.later { await $0.take(assets, sizes: fedSizes) }                await feed?.caughtUp(most: 4)            }            await MainActor.run {                AlbumsPass.shared.sizing = false                AlbumsPass.shared.refresh()            }        }    }    private func libraryChanged() async {        await readLibrary()        if !running, UIApplication.shared.applicationState == .active { run() }        // A kept album gained a photo (kept too) or lost one (its copy stays, listed).        AlbumsKeeper.shared.members()        AlbumsKeeper.shared.resume()    }    func refresh() {        counts = store.counts()        revision += 1    }    // MARK: Running    /// Runs while Albums is open, until every photo has been looked at or something stops it.    func run() {        guard !running, AlbumsLibrary.access.reads else { return }        Task { await loop(reason: "open") }    }    /// Start: the pass begins now and carries on in the background as a continued task, with the phone's own    /// progress and Stop.    func start() {        run()        submitContinued()    }    func stop() { stopAsked = true }    /// The loop itself: batches of 200, four at a time, a checkpoint after each.    func loop(reason: String, progress: Progress? = nil) async {        guard !running else {            // Already running in this process: the background task only has to wait for it.            while running && !stopAsked { try? await Task.sleep(for: .seconds(1)) }            return        }        running = true        stopAsked = false        pause = .none        if !read { await readLibrary() }        if !retried {            retried = true            store.retryFailed()            refresh()        }        store.restartRate()        store.setMeta("pass.began", ISO8601DateFormatter().string(from: .now))        Log.write("albums: pass \(reason), \(counts.waiting) waiting")        let charging = Self.charging        feed?.later { await $0.lines(.running, charging: charging) }        let store = self.store        let faces = self.faces        var since = ContinuousClock.now        while !stopAsked {            let next = store.waiting(Self.batch)            if next.isEmpty { break }            let found = await Self.look(next, faces: faces)            store.record(found)            // The checkpoint is the store's; the core hears the same batch at once (SHELL BRIEF: after every look).            feed?.later { await $0.looks(found) }            refresh()            // Never more than a few batches ahead of the core (memory stays flat; the pace is the slower of the two).            await feed?.caughtUp(most: 4)            tick(&since)            Self.sampleMemory()            regroup(force: false)            sayFirstLook(force: false)            await coolDown()            if let progress {                progress.totalUnitCount = Int64(counts.photos)                progress.completedUnitCount = Int64(counts.photos - counts.waiting)            }        }        // Owed a closer look (only in iCloud, or looked at from a picture short of enough): once more on Wi-Fi with        // the network allowed, at the same size, never the original (DECISIONS: "then once with it on Wi-Fi").        if Self.asksICloud, counts.waiting == 0, Self.onWiFi, !stopAsked {            var after = Double.infinity            while !stopAsked, Self.onWiFi {                let owed = store.owed(Self.batch, after: after)                guard let oldest = owed.last else { break }                after = oldest.created?.timeIntervalSince1970 ?? 0                let found = await Self.look(owed, faces: faces, network: true)                // A second try that still gave nothing keeps what the first look had.                let better = found.filter { $0.look != nil || $0.state == .onlyInCloud }                store.record(better.filter { !($0.state == .onlyInCloud && $0.look == nil && store.state($0.id) == .small) })                feed?.later { await $0.looks(better, network: true) }                refresh()                if after == 0 { break }            }        }        tick(&since)        regroup(force: true)        sayFirstLook(force: true)        if counts.waiting == 0 {            if store.meta("pass.finished") == nil { store.setMeta("pass.finished", ISO8601DateFormatter().string(from: .now)) }            #if COTTON_DEV            if ProcessInfo.processInfo.arguments.contains("-albums-faces-mac") { Self.facesFromMac() }            if ProcessInfo.processInfo.arguments.contains("-albums-core"), finished, let feed { AlbumsMeasure.exportCore(feed) }            #endif        }        running = false        refresh()    }    /// Looks at a batch, `atOnce` at a time; each picture asked of the phone with the network off.    nonisolated static func look(_ assets: [LibraryAsset], faces: Bool, network: Bool = false) async -> [(id: String, state: AlbumsItem.State, look: AlbumsLook?)] {        let model = faces ? AlbumsFaces.model : nil        return await withTaskGroup(of: (String, AlbumsItem.State, AlbumsLook?).self) { group in            var out: [(id: String, state: AlbumsItem.State, look: AlbumsLook?)] = []            var iterator = assets.makeIterator()            func next() -> Bool {                guard let asset = iterator.next() else { return false }                group.addTask {                    let picture = await AlbumsLibrary.shared.localPicture(asset.id, side: AlbumsAnalysis.side, network: network)                    switch picture {                    case .picture(let image, let degraded), .small(let image, let degraded):                        var state = AlbumsItem.State.looked                        if case .small = picture { state = .small }                        var look = await AlbumsAnalysis.look(image, degraded: degraded, asset: asset, faces: faces, model: model)                        // Faces too small in the small picture but large enough in the original: once more, closer,                        // from what the phone holds (never the network). The time counts in the look's own.                        if faces, let side = AlbumsAnalysis.closerSide(look, asset: asset),                           case .picture(let near, _) = await AlbumsLibrary.shared.localPicture(asset.id, side: side),                           max(near.width, near.height) > look.side {                            let started = ContinuousClock.now                            let closer = await AlbumsAnalysis.closer(near, asset: asset, model: model)                            if closer.count >= look.faces.count { look.faces = closer }                            let took = started.duration(to: .now)                            look.millis += Double(took.components.seconds) * 1000 + Double(took.components.attoseconds) / 1e15                        }                        return (asset.id, state, look)                    case .onlyInCloud:                        return (asset.id, .onlyInCloud, nil)                    case .failed(let why):                        Log.write("albums: no picture for one asset (\(why))")                        return (asset.id, .failed, nil)                    }                }                return true            }            for _ in 0..<atOnce where next() {}            while let done = await group.next() {                out.append((id: done.0, state: done.1, look: done.2))                _ = next()            }            return out        }    }    // MARK: Time, heat, memory, people and what the phone reports (LOOK-ONLY, coordinator 27 Nov)    /// This build never asks iCloud for anything (LOOK-ONLY: "NO network fetch of originals in this build ... so it    /// cannot eat his data"): a photo with no adequate picture on the phone is counted, owed a closer look, and the pass    /// goes on. The Wi-Fi pass for what is owed comes in a later build by turning this on.    nonisolated static let asksICloud = false    /// Seconds the pass has run, all runs and launches together (time asleep or in the background never counts).    var seconds: Double { Double(store.meta("pass.seconds") ?? "") ?? 0 }    /// Photos a minute for the report: the whole look's average (looked over the time it ran) once a minute has run;    /// before that, the recent rate. A look whose time was not kept (a pass from before the time was counted) has only    /// the recent rate.    nonisolated static func perMinute(_ c: AlbumsStore.Counts, seconds: Double) -> Double? {        let looked = c.looked + c.small        if seconds >= 60, looked > 0 { return Double(looked) / seconds * 60 }        return c.perMinute    }    private func tick(_ since: inout ContinuousClock.Instant) {        let now = ContinuousClock.now        let d = since.duration(to: now)        store.setMeta("pass.seconds", String(seconds + Double(d.components.seconds) + Double(d.components.attoseconds) / 1e18))        since = now    }    /// What throttles the pass besides iOS itself: the phone's heat and Low Power Mode. Serious heat or Low Power    /// Mode: a 5-second rest after each batch of 200; critical heat: 30 seconds. iOS ends a background task under    /// memory pressure or heat on its own (the expiration handler stops at the next checkpoint).    private func coolDown() async {        let heat = ProcessInfo.processInfo.thermalState        let rest: Double = heat == .critical ? 30 : (heat == .serious || ProcessInfo.processInfo.isLowPowerModeEnabled) ? 5 : 0        guard rest > 0 else { return }        Self.throttled += 1        try? await Task.sleep(for: .seconds(rest))    }    /// Rests taken for heat or Low Power Mode.    nonisolated(unsafe) static private(set) var throttled = 0    /// The most memory Albums held at once (its footprint, as iOS counts it against the app), in MB; and memory    /// warnings iOS gave it.    nonisolated(unsafe) static private(set) var peakFootprintMB: Int = 0    nonisolated(unsafe) static private(set) var memoryWarnings = 0    private static let warningsWatched: NSObjectProtocol = NotificationCenter.default.addObserver(        forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: nil) { _ in AlbumsPass.memoryWarnings += 1 }    nonisolated static func footprintMB() -> Int? {        var info = task_vm_info_data_t()        var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<natural_t>.size)        let result = withUnsafeMutablePointer(to: &info) {            $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count) }        }        return result == KERN_SUCCESS ? Int(info.phys_footprint / 1_048_576) : nil    }    static func sampleMemory() {        _ = warningsWatched        if let mb = footprintMB(), mb > peakFootprintMB { peakFootprintMB = mb }    }    /// People: the core's GROUPING 1 over every face with a vector, in the core's queue (never on a screen's way).    /// During the pass only when the faces have grown by a quarter (at least 500) and five minutes have passed, since a    /// whole library's faces take seconds; always at the end of a run and after he names someone.    @ObservationIgnored private var grouped: (faces: Int, at: Date) = (0, .distantPast)    @ObservationIgnored private(set) var shownGroups = 0    func regroup(force: Bool) {        guard faces, let feed else { return }        let n = store.faceCount()        if !force {            guard n - grouped.faces >= max(500, grouped.faces / 4), Date.now.timeIntervalSince(grouped.at) >= 300 else { return }        } else if n == grouped.faces, grouped.at != .distantPast, !regroupAsked {            return        }        regroupAsked = false        grouped = (n, .now)        let store = self.store        feed.later { feed in            let shown = await feed.group(store)            await MainActor.run {                if let shown { AlbumsPass.shared.shownGroups = shown }                AlbumsPass.shared.revision += 1            }        }    }    @ObservationIgnored private var regroupAsked = false    /// He named or renamed a group: group again with his names as must-links.    func namesChanged() {        regroupAsked = true        regroup(force: true)    }    /// The counts the coordinator reads from his phone (the device's reported state, `albums`): counts and timings only.    /// Said every 2,000 photos looked and at the end of each run, because each change is a synced write.    @ObservationIgnored private var saidAt = -1    func sayFirstLook(force: Bool) {        guard let feed else { return }        let c = counts        let looked = c.looked + c.small        guard force || saidAt < 0 || looked - saidAt >= 2_000 else { return }        saidAt = looked        Log.write("albums: looked \(looked) of \(c.photos), \(Int(seconds)) s, \(Self.perMinute(c, seconds: seconds).map { Int($0.rounded()) } ?? 0) a minute, peak \(Self.peakFootprintMB) MB, \(Self.memoryWarnings) warnings, \(Self.throttled) rests, \(c.faces) faces, \(feed.pending) waiting for the core, core busy \(feed.busySeconds) s")        var albums: [String: Any] = [            "photos": c.photos, "videos": c.videos, "looked": looked, "small": c.small, "noLocalPicture": c.onlyInCloud,            "owed": c.small + c.onlyInCloud, "failed": c.failed, "seconds": Int(seconds), "faces": c.faces, "vectors": c.vectors,            "shownGroups": shownGroups, "warnings": Self.memoryWarnings,        ]        if let rate = Self.perMinute(c, seconds: seconds) { albums["perMinute"] = Int(rate.rounded()) }        if Self.peakFootprintMB > 0 { albums["peakFootprintMb"] = Self.peakFootprintMB }        nonisolated(unsafe) let said = albums  // numbers only, built here and never touched again        feed.later { _ = await $0.answer("diagnostics.say", ["albums": said]) }    }    // MARK: The background    nonisolated static let processing = "com.cottondb.albums.pass"    nonisolated static var continuedID: String { (Bundle.main.bundleIdentifier ?? "com.cottondb.albums") + ".pass.first" }    nonisolated private static var permitted: [String] {        Bundle.main.object(forInfoDictionaryKey: "BGTaskSchedulerPermittedIdentifiers") as? [String] ?? []    }    /// Before launch ends (`CottonAppDelegate`), and only in Albums: no other app's plist permits these.    nonisolated static func registerTasks() {        guard (Bundle.main.object(forInfoDictionaryKey: "BGTaskSchedulerPermittedIdentifiers") as? [String] ?? []).contains(processing) else { return }        BGTaskScheduler.shared.register(forTaskWithIdentifier: processing, using: nil) { task in            let held = HeldTask(task)            task.expirationHandler = { Task { @MainActor in AlbumsPass.shared.stop() } }            Task { @MainActor in                await AlbumsPass.shared.loop(reason: "processing")                held.task.setTaskCompleted(success: AlbumsPass.shared.counts.waiting == 0)                AlbumsPass.shared.scheduleProcessing()            }        }        BGTaskScheduler.shared.register(forTaskWithIdentifier: continuedID, using: nil) { task in            let held = HeldTask(task)            Task { @MainActor in await AlbumsPass.shared.runContinued(held.task) }        }    }    private func runContinued(_ task: BGTask) async {        continued = task        task.expirationHandler = { Task { @MainActor in            AlbumsPass.shared.stop()            AlbumsPass.shared.pause = .away        } }        let progress = (task as? BGContinuedProcessingTask)?.progress        progress?.totalUnitCount = Int64(max(1, counts.photos))        progress?.completedUnitCount = Int64(counts.photos - counts.waiting)        await loop(reason: "continued", progress: progress)        task.setTaskCompleted(success: counts.waiting == 0)        continued = nil    }    private func submitContinued() {        guard Self.permitted.contains(where: { $0.hasSuffix(".pass.*") }) else { return }        let request = BGContinuedProcessingTaskRequest(identifier: Self.continuedID, title: AlbumsWords.looking(counts.photos), subtitle: AlbumsWords.fillIn)        request.strategy = .queue        do { try BGTaskScheduler.shared.submit(request) } catch { Log.write("albums: continued task not taken (\(error.localizedDescription))") }    }    /// The rest, on the charger, when the phone has time.    func scheduleProcessing() {        guard counts.waiting > 0 || (Self.asksICloud && counts.small + counts.onlyInCloud > 0), Self.permitted.contains(Self.processing) else { return }        let request = BGProcessingTaskRequest(identifier: Self.processing)        request.requiresExternalPower = true        request.requiresNetworkConnectivity = false        do { try BGTaskScheduler.shared.submit(request) } catch { Log.write("albums: processing task not taken (\(error.localizedDescription))") }    }    /// Albums went to the background: unless the continued task carries it, the pass pauses, and says why.    #if COTTON_DEV    /// Dev `-albums-faces-mac` (the owner's sheet on a simulator): Documents/albums-faces-mac.json, {file: [face]}, from    /// the Mac harness's real Vision over the same synthetic library, replaces the simulator's own face rows once the    /// pass is done (a look made later would write its own again). See AlbumsStore.setFacesFromMac.    nonisolated static func facesFromMac() {        let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("albums-faces-mac.json")        guard let data = try? Data(contentsOf: url),              let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],              let files = root["files"] as? [String: [[String: Any]]] else {            Log.write("albums: -albums-faces-mac: no Documents/albums-faces-mac.json")            return        }        let took = AlbumsStore.shared.setFacesFromMac(files, looks: root["looks"] as? [String: [String: Any]] ?? [:],                                                      model: root["model"] as? String ?? "hyperface-50k-stylegan-pal8")        Log.write("albums: faces from the Mac for \(took) items")    }    #endif    /// Wi-Fi (or Ethernet), not a metered or Low Data path: where the pass may ask iCloud for what it is owed.    nonisolated(unsafe) private static var path: NWPath?    nonisolated private static let pathMonitor: NWPathMonitor = {        let monitor = NWPathMonitor()        monitor.pathUpdateHandler = { AlbumsPass.path = $0 }        monitor.start(queue: DispatchQueue(label: "albums.path"))        return monitor    }()    /// The network as the core's drain hears it (`media.network`): wifi, mobile, constrained or none.    nonisolated static var pathWord: String {        _ = pathMonitor        guard let path, path.status == .satisfied else { return "none" }        if path.isConstrained { return "constrained" }        return path.isExpensive ? "mobile" : "wifi"    }    /// Read from any thread: Keep's PhotoKit reads ask it as each piece arrives.    nonisolated static var onWiFi: Bool {        _ = pathMonitor        guard let path else { return false }        return path.status == .satisfied && !path.isExpensive && !path.isConstrained    }    static var charging: Bool {        UIDevice.current.isBatteryMonitoringEnabled = true        return [.charging, .full].contains(UIDevice.current.batteryState)    }    func wentAway() {        guard running, continued == nil else { scheduleProcessing(); return }        stop()        let charging = Self.charging        pause = charging ? .away : .battery        let feed = self.feed        feed?.later { await $0.lines(charging ? .pausedClosed : .pausedBattery, charging: charging) }        sayFirstLook(force: true)        scheduleProcessing()    }    func cameBack() {        pause = .none        Task {            await readLibrary()            run()        }    }    /// Faces turned off: every face and vector goes from this phone; the pass looks without them from now on.    func turnOffFaces() {        faces = false        store.forgetFaces()        refresh()    }}#endif