Cotton code
373 lines · 16.2 KB · SwiftRaw
// The phone catching up in the background: what is asked of the core, and what// is asked of iOS.//// No phone and no scheduler here — the simulator has none either. The core is// a script of answers and iOS is a list of what was submitted, so the rules// are the ones a laptop can hold: a slice always carries its budget, the next// refresh is asked for before the slice runs, a phone still behind is owed the// long task, and nothing spins on a slice that moved no row.import CottonKitimport XCTest@testable import CottonUI/// A core that answers `sync.now` from a script, one answer per call, and/// records what each call carried. `sync.compact { budgetMs }` answers that/// it took `tookMs` (nothing owed, by default); one that `holds` stays/// unanswered, as a compaction running, until `sync.compact { stop: true }`/// stops it, and then answers it is still owed.private actor SlicedCore: CottonCalling {    private var answers: [String]    private let tookMs: Int?    private let holds: Bool    private(set) var requests: [String] = []    /// Every method asked, in order, and what each carried.    private(set) var calls: [String] = []    private var running: CheckedContinuation<Void, Never>?    init(_ answers: [String], tookMs: Int? = nil, holds: Bool = false) {        self.answers = answers        self.tookMs = tookMs        self.holds = holds    }    var waiting: Bool { running != nil }    func callRaw(_ method: String, requestJSON: String) async throws -> String {        // The reminder pass after a slice (4d0123f128, Days' alerts with Days closed) reads the notification switches        // first. Refused, and kept out of `calls`, so the pass stands aside: these tests are about the slice, and        // what they compare is what the slice asks.        if method == "device.preferences.read" {            return #"{"ok":false,"error":{"code":"not_here","message":"no preferences in this test"}}"#        }        calls.append("\(method) \(requestJSON)")        switch method {        case CottonMethod.syncNow:            requests.append(requestJSON)            guard !answers.isEmpty else {                return #"{"ok":false,"error":{"code":"sync_failed","message":"no more answers were scripted"}}"#            }            return answers.removeFirst()        case CottonMethod.syncCompact where requestJSON.contains("stop"):            let stopped = running != nil            running?.resume()            running = nil            return #"{"ok":true,"data":{"stopped":\#(stopped)}}"#        case CottonMethod.syncCompact:            if holds {                await withCheckedContinuation { running = $0 }                return #"{"ok":true,"data":{"owed":true,"needsMs":120000,"ran":false}}"#            }            guard let tookMs else { return #"{"ok":true,"data":{"owed":false,"needsMs":null}}"# }            return #"{"ok":true,"data":{"owed":false,"needsMs":96000,"ran":true,"tookMs":\#(tookMs)}}"#        default:            XCTFail("a catch-up asks nothing else: \(method)")            return #"{"ok":false,"error":{"code":"unknown_method","message":"no"}}"#        }    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {}    func close() async {}}/// How often a task was ended, and how.private final class Ended: @unchecked Sendable {    private let lock = NSLock()    private var said: [Bool] = []    func end(_ success: Bool) {        lock.lock()        said.append(success)        lock.unlock()    }    var all: [Bool] {        lock.lock()        defer { lock.unlock() }        return said    }}/// What iOS was asked for, in order.private final class Asked: CatchUpScheduling, @unchecked Sendable {    private let lock = NSLock()    private var submitted: [(CatchUpTask, Date?)] = []    var refuses = false    func submit(_ task: CatchUpTask, notBefore: Date?) throws {        if refuses { throw CocoaError(.featureUnsupported) }        lock.lock()        submitted.append((task, notBefore))        lock.unlock()    }    var tasks: [CatchUpTask] {        lock.lock()        defer { lock.unlock() }        return submitted.map(\.0)    }    var all: [(CatchUpTask, Date?)] {        lock.lock()        defer { lock.unlock() }        return submitted    }}@MainActorfinal class BackgroundCatchUpTests: XCTestCase {    /// `2026-10-11T12:00:00Z`.    private let now = Date(timeIntervalSince1970: 1_791_720_000)    private func ok(behind: Bool, pulled: Int = 0, pushed: Int = 0) -> String {        #"{"ok":true,"data":{"pushed":\#(pushed),"pulled":\#(pulled),"behind":\#(behind),"pending":0,"lastPullAt":null}}"#    }    private func catchUp(_ core: SlicedCore?, _ asked: Asked) -> BackgroundCatchUp {        BackgroundCatchUp(opener: { core }, scheduler: asked)    }    // ── A slice ──────────────────────────────────────────────────────────    /// RULE: A background sync on the phone always tells the core how long it has, so that it stops between pages instead of being frozen mid-request.    func testASliceAlwaysCarriesItsBudget() async {        let core = SlicedCore([ok(behind: false)])        let outcome = await catchUp(core, Asked()).slice()        XCTAssertEqual(outcome, .level)        let requests = await core.requests        XCTAssertEqual(requests, [#"{"budgetMs":25000}"#])    }    func testASliceReadsBehindAndWhetherAnythingMoved() async {        let core = SlicedCore([ok(behind: true, pulled: 500), ok(behind: true)])        let model = catchUp(core, Asked())        let first = await model.slice()        let second = await model.slice()        XCTAssertEqual(first, .behind(moved: true))        XCTAssertEqual(second, .behind(moved: false))    }    /// A phone with no Mac yet answers the number 0 for `behind`, not a    /// boolean. It is level, not a failure.    func testAPhoneWithNoMacYetIsLevel() async {        let core = SlicedCore([#"{"ok":true,"data":{"pushed":0,"pulled":0,"behind":0,"pending":0,"lastPullAt":null,"state":"no_server_yet"}}"#])        let outcome = await catchUp(core, Asked()).slice()        XCTAssertEqual(outcome, .level)    }    func testACoreThatCannotBeOpenedIsAFailedSliceAndNothingElse() async {        let outcome = await catchUp(nil, Asked()).slice()        guard case .failed = outcome else { return XCTFail("a locked phone has no core: \(outcome)") }    }    // ── What is asked of iOS ─────────────────────────────────────────────    /// RULE: When the phone app leaves the foreground it asks iOS for both catch-up tasks — the short periodic one no sooner than fifteen minutes on, and the long one that runs while charging.    func testLeavingTheFrontAsksForBothTasks() {        let asked = Asked()        catchUp(nil, asked).appWentAway(now: now)        let all = asked.all        XCTAssertEqual(all.map(\.0), [.refresh, .processing])        XCTAssertEqual(all[0].1, now.addingTimeInterval(15 * 60))        XCTAssertNil(all[1].1, "the long task runs whenever iOS finds the phone charging")    }    /// RULE: A refresh asks iOS for the next refresh before its slice runs, so a slice that is killed is never the last one; and a phone still behind after it is owed the long task.    func testARefreshAsksForTheNextOneFirstAndForTheLongTaskWhenStillBehind() async {        let asked = Asked()        let core = SlicedCore([ok(behind: true, pulled: 5000)])        let success = await catchUp(core, asked).runRefresh(now: now)        XCTAssertTrue(success)        XCTAssertEqual(asked.tasks, [.refresh, .processing])    }    /// RULE: An app's own background work (Post's round of This phone fetches) runs in the same wake as the slice, handed the core, on the short task and the long one.    @MainActor    func testAnAppsOwnWorkRunsInEachWakeWithTheCore() async {        let asked = Asked()        let catchUp = catchUp(SlicedCore([ok(behind: false), ok(behind: false)]), asked)        var ran = 0        catchUp.also { _ in ran += 1 }        _ = await catchUp.runRefresh(now: now)        XCTAssertEqual(ran, 1)        _ = await catchUp.runProcessing(expired: { false })        XCTAssertEqual(ran, 2)    }    /// RULE: With no core to open, an app's own background work does not run.    @MainActor    func testAnAppsOwnWorkWaitsForACore() async {        let catchUp = catchUp(nil, Asked())        var ran = false        catchUp.also { _ in ran = true }        _ = await catchUp.runRefresh(now: now)        XCTAssertFalse(ran)    }    func testARefreshThatLeavesThePhoneLevelAsksOnlyForTheNextRefresh() async {        let asked = Asked()        let success = await catchUp(SlicedCore([ok(behind: false, pulled: 12)]), asked).runRefresh(now: now)        XCTAssertTrue(success)        XCTAssertEqual(asked.tasks, [.refresh])    }    func testARefreshWhoseSliceFailedSaysSoToIOSAndStillHasItsNextOneAsked() async {        let asked = Asked()        let success = await catchUp(nil, asked).runRefresh(now: now)        XCTAssertFalse(success)        XCTAssertEqual(asked.tasks, [.refresh])    }    // ── The long task ────────────────────────────────────────────────────    /// RULE: The long catch-up task runs slice after slice until the phone is level, and each slice carries its own budget.    func testTheLongTaskSlicesUntilLevel() async {        let asked = Asked()        let core = SlicedCore([            ok(behind: true, pulled: 5000), ok(behind: true, pulled: 5000), ok(behind: false, pulled: 120),        ])        let success = await catchUp(core, asked).runProcessing(expired: { false })        XCTAssertTrue(success)        let requests = await core.requests        XCTAssertEqual(requests.count, 3)        XCTAssertEqual(Set(requests), [#"{"budgetMs":25000}"#])        XCTAssertEqual(asked.tasks, [], "a level phone is owed nothing more")    }    /// RULE: When iOS ends the long catch-up task while the phone is still behind, the task is asked for again and no further slice is started.    func testTheLongTaskStopsWhenIOSSaysTimeIsUpAndAsksToRunAgain() async {        let asked = Asked()        let core = SlicedCore([ok(behind: true, pulled: 5000), ok(behind: true, pulled: 5000)])        let success = await catchUp(core, asked).runProcessing(expired: { true })        XCTAssertTrue(success, "it moved rows: iOS is told the time was well spent")        let requests = await core.requests        XCTAssertEqual(requests.count, 1, "no slice is started once the time is up")        XCTAssertEqual(asked.tasks, [.processing])    }    /// RULE: A catch-up slice that is behind and moved nothing ends the long task rather than being asked again at once.    func testTheLongTaskNeverSpinsOnASliceThatMovedNothing() async {        let asked = Asked()        let core = SlicedCore([ok(behind: true), ok(behind: true), ok(behind: true)])        let success = await catchUp(core, asked).runProcessing(expired: { false })        XCTAssertFalse(success)        let requests = await core.requests        XCTAssertEqual(requests.count, 1)        XCTAssertEqual(asked.tasks, [.processing])    }    // ── The compaction ───────────────────────────────────────────────────    /// RULE: Once the long catch-up task's slices are level, it asks the core to compact the copy it may owe and waits for the answer (`sync.compact` with the most time the core takes: iOS says none), so the task never ends while the file is being rewritten.    func testTheLongTaskAsksForTheCompactionOnceLevelAndWaitsForIt() async {        let asked = Asked()        let core = SlicedCore([ok(behind: true, pulled: 5000), ok(behind: false)], tookMs: 61_000)        let success = await catchUp(core, asked).runProcessing(expired: { false })        XCTAssertTrue(success)        let calls = await core.calls        XCTAssertEqual(calls, [            #"sync.now {"budgetMs":25000}"#, #"sync.now {"budgetMs":25000}"#, #"sync.compact {"budgetMs":1800000}"#,        ])        XCTAssertEqual(asked.tasks, [], "compacted: nothing more is owed")    }    func testASliceThatMovedNothingStillLetsTheCopyCompactAndAsksForTheTaskOnce() async {        let asked = Asked()        let core = SlicedCore([ok(behind: true)])        let success = await catchUp(core, asked).runProcessing(expired: { false })        XCTAssertFalse(success)        let calls = await core.calls        XCTAssertEqual(calls.last, #"sync.compact {"budgetMs":1800000}"#)        XCTAssertEqual(asked.tasks, [.processing])    }    func testNoCompactionIsAskedOnceTheTimeIsUp() async {        let asked = Asked()        let core = SlicedCore([ok(behind: true, pulled: 5000)])        _ = await catchUp(core, asked).runProcessing(expired: { true })        let calls = await core.calls        XCTAssertFalse(calls.contains { $0.hasPrefix(CottonMethod.syncCompact) })    }    /// RULE: When iOS says the long task's time is up while it waits on the compaction, the compaction is stopped (`sync.compact { stop: true }`) before the task is ended, the task is ended exactly once, and a stopped compaction asks iOS for the task again.    func testAnExpiryWhileCompactingStopsItFirstEndsTheTaskOnceAndAsksAgain() async throws {        let asked = Asked()        let core = SlicedCore([ok(behind: false)], holds: true)        let model = catchUp(core, asked)        let ended = Ended()        let end = TaskEnd { ended.end($0) }        let run = Task { await model.processingTask(end) }        let deadline = Date().addingTimeInterval(5)        while await !core.waiting {            guard Date() < deadline else { return XCTFail("the compaction was never asked") }            try await Task.sleep(nanoseconds: 1_000_000)        }        XCTAssertTrue(model.compacting)        XCTAssertEqual(ended.all, [], "not ended while the file is being rewritten")        await model.expire(end)        await run.value        let calls = await core.calls        XCTAssertEqual(calls, [            #"sync.now {"budgetMs":25000}"#, #"sync.compact {"budgetMs":1800000}"#, #"sync.compact {"stop":true}"#,        ])        XCTAssertEqual(ended.all, [false], "ended once, as expired, after the stop")        XCTAssertFalse(model.compacting)        XCTAssertEqual(asked.tasks, [.processing], "stopped: the task is asked for again")    }    func testAnExpiryWithNoCompactionRunningEndsTheTaskAtOnceAndStopsNothing() async {        let core = SlicedCore([])        let ended = Ended()        let end = TaskEnd { ended.end($0) }        await catchUp(core, Asked()).expire(end)        end.finish(true)        let calls = await core.calls        XCTAssertEqual(calls, [])        XCTAssertEqual(ended.all, [false])        XCTAssertTrue(end.expired)    }    func testIOSRefusingATaskIsNotAFailureOfTheSlice() async {        let asked = Asked()        asked.refuses = true        let success = await catchUp(SlicedCore([ok(behind: true, pulled: 1)]), asked).runRefresh(now: now)        XCTAssertTrue(success, "Background App Refresh switched off stops nothing that is running")    }}/// RULE (launch-ios, 22 Nov 2026): an app whose plist runs nothing in the background (Words, Days) registers and asks for no catch-up task; Cotton's plist, with both identifiers and both modes, gets both.final class CatchUpPermittedTests: XCTestCase {    func testOnlyTasksThePlistPermitsAndHasTheModeFor() {        let ids = ["com.cottondb.catchup.refresh", "com.cottondb.catchup.processing"]        XCTAssertEqual(CatchUpTask.permitted(["BGTaskSchedulerPermittedIdentifiers": ids, "UIBackgroundModes": ["audio", "remote-notification", "fetch", "processing"]]), [.refresh, .processing])        XCTAssertEqual(CatchUpTask.permitted([:]), [], "Words and Days: no identifiers, no modes")        XCTAssertEqual(CatchUpTask.permitted(["UIBackgroundModes": ["audio"]]), [], "Story: Listen's audio alone")        XCTAssertEqual(CatchUpTask.permitted(["BGTaskSchedulerPermittedIdentifiers": ids, "UIBackgroundModes": ["fetch"]]), [.refresh])    }}