Cotton code
354 lines · 18.0 KB · SwiftRaw
// A database switch is two frames: the old Home, then the new database's kept// Home — Me's head, its sync line, its Today rows and its fan in its own// order, all from the phone's own copy — and nothing between (295 A,// walker294 on a real-sized household of 13 databases: Today and the sync// line went for 100–180 ms at every switch, and the fan passed through the// bundle's cards in alphabetical order before it re-dealt into the kept one).//// THE CAUSES. The switch moved first and read after: `DatabaseScene.show`// aimed the calls and moved the shown id, and only then did the stack's// `onChange` turn Home (`turned`) and read it — so the first frame of the new// fan drew `HomeTiles.standard` (every built-in by name, Me in the middle)// and a Me page rebuilt with no Today and no line. The fix reads first// (`HomeModel.prepare`, awaited by `show`), turns Home in the same step as// the shown id (`turnToAsked` from `aimed`), draws only a database's own// order (`drawnTiles(for:)`), and keeps each database's page (`shell.today`,// its Today rows among its cards) and line where the rebuilt page reads them// in its first frame (the kept answer, `HomeSyncLines`).// Synthetic names and ids throughout.import CottonKitimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class SwitchPrepareTests: XCTestCase {    private var suite: String!    private var defaults: UserDefaults!    /// Ids of this test's own, so the run's kept Today and lines are its own.    private var own: HeldDatabase!    private var garden: HeldDatabase!    private var attic: HeldDatabase!    override func setUp() async throws {        suite = "SwitchPrepareTests-\(UUID().uuidString)"        defaults = UserDefaults(suiteName: suite)        let run = UUID().uuidString.prefix(8)        own = HeldDatabase(databaseId: "own-\(run)", name: "Personal", kind: .personal)        garden = HeldDatabase(databaseId: "garden-\(run)", name: "Garden", kind: .shared)        attic = HeldDatabase(databaseId: "attic-\(run)", name: "Attic", kind: .shared)    }    override func tearDown() async throws {        defaults.removePersistentDomain(forName: suite)    }    /// A window as `WindowSession` wires one: the scene's calls name the    /// shown database, Home reads through them, a switch's prepare is Home's,    /// and Home turns with the calls.    private func window(_ core: PerDatabaseCore) async -> (DatabaseScene, HomeModel, DatabasesModel) {        let databases = DatabasesModel(source: Held([own, garden, attic]), defaults: defaults)        await databases.refresh()        let scene = DatabaseScene()        let screens = DatabaseScopedCore(underlying: core, shown: scene.calls)        let home = HomeModel(core: screens, unscoped: core, toasts: ToastCenter(scheduler: ManualToastScheduler()))        home.askingDatabase = { [calls = scene.calls] in calls.id }        scene.prepare = { [home] id, calls in await home.prepare(shown: id, calls: calls) }        scene.aimed = { [home] _ in home.turnToAsked() }        await scene.seed(from: databases)        await home.load()        return (scene, home, databases)    }    /// RULE: show() reads the new database's Home before anything of the window moves — the shown id, the calls and the pin stay on the old database while the read is out, and a read already running for the old Home answers into the old Home — then turns in one step; the turned Home is that read, and the board's first ask after the turn is not a second read (295 A).    func testAShowReadsTheNewHomeBeforeAnythingMoves() async throws {        let core = PerDatabaseCore(own: own.databaseId)        core.home[nil] = Self.home(["notes", "todos"])        core.home[garden.databaseId] = Self.home(["mood", "goals", "calendar"])        let (scene, home, databases) = await window(core)        XCTAssertTrue(home.answers(nil))        core.hold(garden.databaseId)        let turning = Task { await scene.pick(garden.databaseId, in: databases) }        await core.waitForHeld()        XCTAssertEqual(scene.shownId, own.databaseId, "the shown id stays on the old database while the read is out")        XCTAssertNil(scene.calls.id, "and so do the calls")        XCTAssertEqual(scene.picks, 0)        core.home[nil] = Self.home(["todos", "notes"])        await home.load()        XCTAssertEqual(home.drawnTiles(for: nil)?.tools, ["todos", "notes"], "a read for the old Home answers into the old Home")        core.release()        await turning.value        XCTAssertEqual(scene.shownId, garden.databaseId)        XCTAssertEqual(scene.calls.id, garden.databaseId)        XCTAssertEqual(scene.picks, 1)        XCTAssertTrue(home.answers(garden.databaseId), "Home turned with the calls, on the read made before the turn")        XCTAssertEqual(home.drawnTiles(scene: scene, in: databases)?.tools, ["mood", "goals", "calendar"])        let reads = core.homeReads(garden.databaseId)        await home.loadUnlessPrepared()        XCTAssertEqual(core.homeReads(garden.databaseId), reads, "the board's first ask is the switch's read, not another")        await home.loadUnlessPrepared()        XCTAssertEqual(core.homeReads(garden.databaseId), reads + 1, "and only the first")    }    /// RULE: a refused read still turns — the window shows the new database and its page then says it could not read — and the newest of two taps wins: a switch still reading when another is asked, or when its cap is turned back to the database shown, turns nothing (295 A).    func testARefusalStillTurnsAndTheNewestTapWins() async throws {        let core = PerDatabaseCore(own: own.databaseId)        core.home[nil] = Self.home(["notes"])        core.home[attic.databaseId] = Self.home(["photos", "people"])        core.refuse.insert(garden.databaseId)        let (scene, home, databases) = await window(core)        await scene.show(garden.databaseId, in: databases)        XCTAssertEqual(scene.shownId, garden.databaseId, "refused, it still turns")        await home.loadUnlessPrepared()        XCTAssertNotNil(home.answer?.failed, "the core answered the read that failed")        XCTAssertTrue(home.bandUnreadable, "and the page says it could not read")        core.refuse.remove(garden.databaseId)        core.home[garden.databaseId] = Self.home(["mood"])        await scene.show(own.databaseId, in: databases)        core.hold(garden.databaseId)        let older = Task { await scene.show(garden.databaseId, in: databases) }        await core.waitForHeld()        let turnedNewer = await scene.show(attic.databaseId, in: databases)        XCTAssertTrue(turnedNewer)        core.release()        let turnedOlder = await older.value        XCTAssertFalse(turnedOlder, "the older tap turns nothing")        XCTAssertEqual(scene.shownId, attic.databaseId, "the newest tap wins")        XCTAssertEqual(scene.calls.id, attic.databaseId)        XCTAssertTrue(home.answers(attic.databaseId))        core.hold(garden.databaseId)        let back = Task { await DatabaseCapRow.choose(garden.databaseId, scene: scene, in: databases) }        await core.waitForHeld()        await DatabaseCapRow.choose(attic.databaseId, scene: scene, in: databases)        core.release()        await back.value        XCTAssertEqual(scene.shownId, attic.databaseId, "turned back to the cap shown: the switch still reading turns nothing")    }    /// GUARD: a switch produces exactly two distinct Home layouts; no frame of it shows the bundle's alphabetical order; Today's row count never drops to zero while the new database has rows.    /// RULE: a switch has two frames — the old Home, then the new database's kept Home: its fan in its own order, its Today rows and its sync line, all read from the phone's own copy before the switch's frame; nothing between, and never the bundle's cards by name (295 A, walker294).    func testASwitchIsTwoLayouts() async throws {        let core = PerDatabaseCore(own: own.databaseId)        core.home[nil] = Self.home(["notes", "todos", "mood"])        core.home[garden.databaseId] = Self.home(["goals", "calendar", "people"])        core.day[nil] = ["Water the ferns"]        core.day[garden.databaseId] = ["Sow the beans", "Turn the compost"]        core.line[own.databaseId] = "Up to date"        core.line[garden.databaseId] = "2 changes waiting to send"        let (scene, home, databases) = await window(core)        // The old database's page has read its own line.        await HomeSync.prepare(DatabaseScopedCore(underlying: core, database: nil), database: own.databaseId)        struct Layout: Equatable {            let shown: String?            let tiles: [String]?            let today: Int?            let line: String?        }        func layout() -> Layout {            let shown = scene.shownId            return Layout(                shown: shown, tiles: home.drawnTiles(scene: scene, in: databases)?.tools,                today: home.answer?.cards.filter { $0.kind == "day" }.count,                line: HomeSyncLines.last[shown ?? ""]?.words)        }        let before = layout()        XCTAssertEqual(before.today, 3, "Today reads across every database held")        core.hold(garden.databaseId)        let turning = Task { await scene.pick(garden.databaseId, in: databases) }        var seen = [before]        // Every yield is where a frame could fall: the layout is sampled at        // each, while the read is held and after it is let go.        await core.waitForHeld()        for step in 0..<400 {            if step == 40 { core.release() }            let sample = layout()            if sample != seen.last { seen.append(sample) }            await Task.yield()        }        await turning.value        let after = layout()        if after != seen.last { seen.append(after) }        XCTAssertEqual(seen.count, 2, "exactly two layouts: \(seen)")        XCTAssertEqual(seen.last?.shown, garden.databaseId)        XCTAssertEqual(seen.last?.tiles, ["goals", "calendar", "people"], "the new database's own order")        XCTAssertEqual(seen.last?.today, 3, "its Today rows in the turn's frame")        XCTAssertNotNil(seen.last?.line, "and its sync line")        for each in seen {            XCTAssertNotNil(each.tiles, "never a fan with no order")            XCTAssertGreaterThan(each.today ?? 0, 0, "Today never drops to zero while the database has rows")        }    }    /// RULE: Today's rows for a database a switch prepared are present, from its own read, in the first answer of its new page — never blank while the database has rows — and the read was asked for that database before the window turned (295 A, walker294).    func testTodayIsReadyForTheNewPage() async throws {        let core = PerDatabaseCore(own: own.databaseId)        core.home[garden.databaseId] = Self.home(["mood"])        core.day[garden.databaseId] = ["Sow the beans"]        let home = HomeModel(core: core, toasts: ToastCenter(scheduler: ManualToastScheduler()))        var aimed: String? = nil        home.askingDatabase = { aimed }        await home.prepare(shown: garden.databaseId, calls: garden.databaseId)        let asked = try XCTUnwrap(core.requests(CottonMethod.shellToday).first)        XCTAssertEqual(asked.text("database"), garden.databaseId, "asked for the database the switch turns to")        XCTAssertNil(home.answer, "nothing of the window moved")        aimed = garden.databaseId        home.turned()        let rows = home.answer?.cards.filter { $0.kind == "day" }.map { $0.deck.slots["title"]?.text }        XCTAssertEqual(rows, ["Sow the beans"], "the kept answer, drawn in the turn's frame")    }    // ── Fixtures ─────────────────────────────────────────────────────────    /// The arrangement a database's page answers, in `order`.    private static func home(_ order: [String]) -> String { TodayAnswerJSON.arrangement(order) }}/// A core that answers each database from its own copy, by the `database`/// its calls name (none, the personal one), and can hold one database's/// `shell.today` until released — a read that takes longer than a frame.private final class PerDatabaseCore: CottonCalling, @unchecked Sendable {    private let lock = NSLock()    private let ownId: String    /// Each database's arrangement block.    private var _home: [String?: String] = [:]    /// Each database's todos due today, by title: every page's Today reads    /// them across every database held, as the core does.    private var _day: [String?: [String]] = [:]    private var _line: [String: String] = [:]    private var _refuse: Set<String> = []    private var _calls: [(method: String, request: JSONValue)] = []    private var held: String?    private var waiting: CheckedContinuation<Void, Never>?    private var heard: CheckedContinuation<Void, Never>?    private var reached = false    init(own: String) { ownId = own }    var home: [String?: String] {        get { lock.withLock { _home } }        set { lock.withLock { _home = newValue } }    }    var day: [String?: [String]] {        get { lock.withLock { _day } }        set { lock.withLock { _day = newValue } }    }    var line: [String: String] {        get { lock.withLock { _line } }        set { lock.withLock { _line = newValue } }    }    var refuse: Set<String> {        get { lock.withLock { _refuse } }        set { lock.withLock { _refuse = newValue } }    }    func hold(_ database: String) {        lock.withLock {            held = database            reached = false        }    }    func release() {        let resume = lock.withLock { () -> CheckedContinuation<Void, Never>? in            held = nil            defer { waiting = nil }            return waiting        }        resume?.resume()    }    /// Answers once the held read has reached the core.    func waitForHeld() async {        await withCheckedContinuation { (done: CheckedContinuation<Void, Never>) in            let now = lock.withLock { () -> Bool in                if reached { return true }                heard = done                return false            }            if now { done.resume() }        }    }    func homeReads(_ database: String?) -> Int {        lock.withLock { _calls.filter { $0.method == CottonMethod.shellToday && $0.request.text("database") == database }.count }    }    func requests(_ method: String) -> [JSONValue] { lock.withLock { _calls.filter { $0.method == method }.map(\.request) } }    func callRaw(_ method: String, requestJSON: String) async throws -> String {        let request = (try? JSONDecoder().decode(JSONValue.self, from: Data(requestJSON.utf8))) ?? .object([:])        let database = request.text("database")        lock.withLock { _calls.append((method, request)) }        switch method {        case CottonMethod.shellToday:            let holds = lock.withLock { held != nil && held == database }            if holds {                await withCheckedContinuation { (done: CheckedContinuation<Void, Never>) in                    let hear = lock.withLock { () -> CheckedContinuation<Void, Never>? in                        waiting = done                        reached = true                        defer { heard = nil }                        return heard                    }                    hear?.resume()                }            }            if refuse.contains(database ?? "") {                let failed = TodayAnswerJSON.answer(                    unreadable: true, failed: ["why": "unreadable", "line": "Home could not be read.", "keeps_trying": false])                return #"{"ok":true,"data":\#(failed)}"#            }            guard let arrangement = home[database] else { return #"{"ok":false,"error":{"code":"none","message":"none"}}"# }            // Today's rows across every database held, as the core joins them.            let days = day            let titles = days.keys.sorted { ($0 ?? "") < ($1 ?? "") }.flatMap { days[$0] ?? [] }            let cards = titles.enumerated().map { index, title in                TodayAnswerJSON.card(id: "day/t\(index)", kind: "day", face: "today", table: "todo", record: "t\(index)",                                     slots: ["title": title])            }            return #"{"ok":true,"data":\#(TodayAnswerJSON.answer(arrangement: arrangement, cards: cards))}"#        case CottonMethod.shellHome:            // Home's one answer: its sync line is the database's own, or none.            let sync = line[database ?? ownId].map { #""line":"\#($0)","line_state":"up_to_date""# } ?? #""line":"","line_state":null"#            return #"""                {"ok":true,"data":{"gate":{"stage":"open","code":null,"refusal":"none","erase":false,"beat":0,"words":{},"progress":null,"ways_out":[]},                 "stand":"backed_up","backup":{"sent":0,"of":0,"line":""},                 "sync":{"state":"connected",\#(sync),"counter":0,"failures":0},                 "device":null,"acts":[],"notices":[]}}                """#        case CottonMethod.recordsList:            let copy = request["where"]?.text("database") ?? ownId            guard let state = line[copy] else { return #"{"ok":true,"data":{"records":[]}}"# }            return #"{"ok":true,"data":{"records":[{"id":"c1","table":"copy","data":{"role":"this_device","@slip_subtitle":"\#(state)"}}]}}"#        default:            return #"{"ok":false,"error":{"code":"unknown_method","message":"\#(method)"}}"#        }    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {}    func close() async {}}/// A held list, answered as given.private final class Held: DatabasesCalling, @unchecked Sendable {    private let held: [HeldDatabase]    init(_ held: [HeldDatabase]) { self.held = held }    func databases() async throws -> [HeldDatabase] { held }    func show(_ databaseId: String) async throws {}    func hide(_ databaseId: String) async throws {}    func create(name: String, toolkit: DatabaseToolkit) async throws -> HeldDatabase {        throw CottonCallError(code: "refused", message: "No.")    }}