Cotton code
142 lines · 8.2 KB · SwiftRaw
// The serving Mac's off-Mac backup, as the board's one notice — driven through// `HomeModel.readBackup` over scripted `read.servingBackup` answers, shaped as// the core writes them (`methods/host_settings.rs`: the Mac's own failing// judgement per database, its reason and since when).import CottonKitimport XCTest@testable import CottonUI@MainActorfinal class BackupNoticeTests: XCTestCase {    private let mac = "mac-studio-0000"    private func database(_ id: String, _ state: String, reason: String? = nil, since: String? = nil) -> String {        let quoted = { (text: String?) in text.map { "\"\($0)\"" } ?? "null" }        return #"{"databaseId":"\#(id)","state":"\#(state)","lastError":\#(quoted(reason)),"since":\#(quoted(since))}"#    }    /// One answer as the core writes it: the Mac's worst-of line over its databases.    private func answer(        _ state: String, reason: String? = nil, since: String? = nil, databases: [String] = [],        by: String = "serving_mac", name: String? = "Studio Mac"    ) -> String {        let quoted = { (text: String?) in text.map { "\"\($0)\"" } ?? "null" }        let backup = #"{"state":"\#(state)","lastAt":null,"lastError":\#(quoted(reason)),"nextAt":null,"keptBytes":null,"since":\#(quoted(since)),"databases":[\#(databases.joined(separator: ","))]}"#        return #"{"deviceId":"\#(mac)","deviceName":\#(quoted(name)),"backup":\#(backup),"backupAnsweredBy":"\#(by)"}"#    }    private func model(_ first: String) -> (HomeModel, ScriptedCore) {        // Home answered: the board says no notice over a Home not read yet        // (6f747da52, 294 row 2), so the fact is asserted on an answered one.        let core = ScriptedCore([CottonMethod.readServingBackup: .ok(first), CottonMethod.shellToday: .ok(TodayAnswerJSON.answer())])        return (HomeModel(core: core, toasts: ToastCenter(scheduler: ManualToastScheduler())), core)    }    private var utc: Calendar {        var calendar = Calendar(identifier: .gregorian)        calendar.timeZone = TimeZone(identifier: "UTC")!        return calendar    }    /// RULE: a dead off-Mac backup once sat silent on the phone for two days —    /// a Mac whose backup failed, or fell behind past its own lag, is ONE notice    /// on the board naming the Mac with the Mac's own sentence, however many of    /// its databases fail; it clears when the Mac says it caught up, and    /// silence (no Mac answered) neither raises nor clears it.    func testAFailedOrBehindBackupIsOneNoticeUntilTheMacCatchesUp() async throws {        let refused = "the bucket refused the key"        let (home, core) = model(answer(            "failing", reason: refused, since: "2026-10-08T09:40:00.000Z",            databases: [database("db-personal", "failing", reason: refused, since: "2026-10-08T09:40:00.000Z")]))        // Failed: one notice, naming the Mac, in the Mac's words.        await home.load()        await home.readBackup()        let failed = try XCTUnwrap(home.backupNotice, "a failed backup says so")        XCTAssertEqual(failed.deviceId, mac)        let board = BoardHome(model: home, databaseName: nil, project: nil, now: Date())        XCTAssertTrue(BoardNotices.saysOwn(board, in: try BoardEntry.noticesForTests()), "the board's notices part draws it")        // Running and current: no notice.        await core.answer(CottonMethod.readServingBackup, .ok(answer("ok", databases: [database("db-personal", "ok")])))        await home.readBackup()        XCTAssertNil(home.backupNotice, "caught up clears it")        // Running but behind past the Mac's lag — the Mac's own judgement,        // which the core answers as failing with since when.        await core.answer(CottonMethod.readServingBackup, .ok(answer(            "failing", reason: "not caught up", since: "2026-10-09T22:00:00.000Z",            databases: [database("db-personal", "failing", reason: "not caught up", since: "2026-10-09T22:00:00.000Z")])))        await home.readBackup()        XCTAssertEqual(home.backupNotice?.reason, "not caught up")        XCTAssertEqual(home.backupNotice?.since, "2026-10-09T22:00:00.000Z")        // Two databases failing on one Mac: still ONE notice, since the earlier.        let two = answer("failing", reason: refused, databases: [            database("db-personal", "failing", reason: refused, since: "2026-10-09T08:00:00.000Z"),            database("db-studio", "failing", reason: "not caught up", since: "2026-10-08T07:00:00.000Z"),        ])        XCTAssertEqual(            BackupNotice.read(try JSONDecoder().decode(JSONValue.self, from: Data(two.utf8))),            .answered(BackupNotice(deviceId: mac, macName: "Studio Mac", since: "2026-10-08T07:00:00.000Z", reason: refused)))        await core.answer(CottonMethod.readServingBackup, .ok(two))        await home.readBackup()        XCTAssertEqual(home.backupNotice?.deviceId, mac)        // Silence: the phone could not reach the Mac, or the call failed —        // nothing new is said either way.        await core.answer(CottonMethod.readServingBackup, .ok(#"{"deviceId":null,"deviceName":null,"backup":null,"backupAnsweredBy":"no_serving_mac"}"#))        await home.readBackup()        XCTAssertEqual(home.backupNotice?.since, "2026-10-08T07:00:00.000Z", "no answer is not a recovery")        await core.answer(CottonMethod.readServingBackup, .refuse(code: "unreadable", message: "synthetic"))        await home.readBackup()        XCTAssertNotNil(home.backupNotice)        // Recovered: cleared.        await core.answer(CottonMethod.readServingBackup, .ok(answer("ok", databases: [            database("db-personal", "ok"), database("db-studio", "ok"),        ])))        await home.readBackup()        XCTAssertNil(home.backupNotice)        XCTAssertFalse(BoardNotices.saysOwn(board, in: try BoardEntry.noticesForTests()))    }    /// RULE: the notice says the owner's databases are not being backed up off    /// the Mac — so half a configuration (a bucket named, its settings not    /// adding up) raises it with what is missing, while silence, a first copy    /// still starting, and no bucket named at all (a Mac holding the only copy    /// by choice) raise none.    func testHalfASetupRaisesItAndSilenceStartingAndOffDoNot() async throws {        let (home, core) = model(#"{"deviceId":null,"deviceName":null,"backup":null,"backupAnsweredBy":"no_serving_mac"}"#)        await home.readBackup()        XCTAssertNil(home.backupNotice)        await core.answer(CottonMethod.readServingBackup, .ok(answer("running", by: "this_mac")))        await home.readBackup()        XCTAssertNil(home.backupNotice, "starting")        await core.answer(CottonMethod.readServingBackup, .ok(answer("never", by: "this_mac")))        await home.readBackup()        XCTAssertNil(home.backupNotice, "off")        let missing = "the backup is missing bucket, secret key"        await core.answer(CottonMethod.readServingBackup, .ok(answer("never", reason: missing, by: "this_mac")))        await home.readBackup()        let half = try XCTUnwrap(home.backupNotice)        XCTAssertEqual(half.kind, .halfSetUp)    }    /// RULE: Home raises the off-Mac backup only when the last copy that got through is more than a day old (or none ever did) — a Mac minutes behind is the stream catching up, and the card that said "not backed up since 1:48 am" thirty minutes later pushed the whole board down (11 Oct 2026).    func testABackupThatGotThroughWithinADayRaisesNothing() throws {        let now = Date(timeIntervalSince1970: 1_791_700_000)        func answer(lastAt: Date) -> JSONValue {            let stamp = ISO8601DateFormatter().string(from: lastAt)            let json = #"{"deviceId":"mac-1","deviceName":"Studio","backupAnsweredBy":"serving_mac","backup":{"state":"failing","lastAt":"\#(stamp)","lastError":"behind","since":"\#(stamp)","databases":[]}}"#            return try! JSONDecoder().decode(JSONValue.self, from: Data(json.utf8))        }        XCTAssertEqual(BackupNotice.read(answer(lastAt: now.addingTimeInterval(-30 * 60)), now: now), .answered(nil))        guard case .answered(let notice?) = BackupNotice.read(answer(lastAt: now.addingTimeInterval(-25 * 60 * 60)), now: now) else {            return XCTFail("a day-old backup is raised")        }        XCTAssertEqual(notice.deviceId, "mac-1")    }}