Cotton code
173 lines · 7.6 KB · SwiftRaw
// Where one database's sync stands, as the engine says it (sync programme,// lane A — the architect's brief of 12 Oct 2026).//// The words are worked out in the core (`cotton_client::sync::line`), so a// Mac and a phone say the same thing, and nothing here composes a line of its// own with one exception: the page's "Not synced since 10:46 · mac-c not// reachable", whose time of day and Mac's name only the app knows — and for// another person's database, whose Mac it has no name for, "their Mac not// reachable".////   * Under a cap (the Databases sheet): `capLine` — "syncing · 62%",//     "copying · 400 MB to go", "offline", "update app", "update your Mac"//     — or nothing, and the//     people line stands. The cap turns while rows or bytes move and stands//     still when none can.//   * The database page's top: `pageLine` — the same thing as a sentence, in//     one slot that is empty when the database is current.//   * The device row reads the same value.//// Pure, decoded off the `databaseSync` frame and the status read.import Foundationpublic struct DatabaseSyncLine: Equatable, Sendable, Decodable {    /// Which of its lines a database is on (`sync::line::State`).    public enum State: String, Sendable, Decodable {        /// Level: the people line, the cap still.        case current        /// Too few changes to say are moving: the people line, the cap turns.        case moving        case syncing        case copying        case offline        case updateApp        /// This device is ahead of its serving Mac — the Mac's file is on an        /// older schema — and what it holds waits, whole, for the Mac's update.        case macBehind    }    public var state: State    /// The engine's line for under the cap; empty is the people line.    public var words: String    /// The engine's sentence for the page's top; empty when it has none.    public var page: String    /// How far through a catch-up or a copy, 0 to 99.    public var percent: Int?    /// Changes still to move in a catch-up whose whole is known.    public var toGo: Int?    /// Bytes of a file copy still to arrive.    public var bytesToGo: Int?    /// When a Mac last answered, while offline; `nil` when none ever has.    public var since: Date?    /// What is coming, a line a tool that still has rows to come ("Email ·    /// 41,000 of 58,900") and the rest as one — the device's own page lists    /// them.    public var coming: [String]    /// Level, as far as anyone knows — what a database is before a pass has    /// said anything about it.    public static let current = DatabaseSyncLine(state: .current)    public init(        state: State, words: String = "", page: String = "", percent: Int? = nil,        toGo: Int? = nil, bytesToGo: Int? = nil, since: Date? = nil, coming: [String] = []    ) {        self.state = state        self.words = words        self.page = page        self.percent = percent        self.toGo = toGo        self.bytesToGo = bytesToGo        self.since = since        self.coming = coming    }    /// The engine's standing off an event's payload (`sync`); `nil` from a    /// core that says none, which changes nothing.    public init?(_ value: JSONValue?) {        guard let value, let state = value["state"]?.string.flatMap(State.init(rawValue:)) else {            return nil        }        self.init(            state: state,            words: value["words"]?.string ?? "",            page: value["page"]?.string ?? "",            percent: value["percent"]?.int,            toGo: value["toGo"]?.int,            bytesToGo: value["bytesToGo"]?.int,            since: value["since"]?.double.map { Date(timeIntervalSince1970: $0 / 1000) },            coming: value["coming"]?.array?.compactMap(\.string) ?? []        )    }    public init(from decoder: Decoder) throws {        let container = try decoder.container(keyedBy: CodingKeys.self)        state = try container.decode(State.self, forKey: .state)        words = (try? container.decode(String.self, forKey: .words)) ?? ""        page = (try? container.decode(String.self, forKey: .page)) ?? ""        percent = try? container.decode(Int.self, forKey: .percent)        toGo = try? container.decode(Int.self, forKey: .toGo)        bytesToGo = try? container.decode(Int.self, forKey: .bytesToGo)        since = (try? container.decode(Double.self, forKey: .since)).map {            Date(timeIntervalSince1970: $0 / 1000)        }        coming = (try? container.decode([String].self, forKey: .coming)) ?? []    }    private enum CodingKeys: String, CodingKey {        case state, words, page, percent, toGo, bytesToGo, since, coming    }    /// What this device is called at the head of a sentence.    public static var thisDevice: String {        #if os(macOS)        return "This Mac"        #else        return "This phone"        #endif    }    /// The line under the cap, or `nil` for the people line.    public var capLine: String? { words.isEmpty ? nil : words }    /// Does the cap turn: while rows or bytes move. Offline and waiting for    /// an update it stands still — nothing can move.    public var turns: Bool { state == .moving || state == .syncing || state == .copying }    /// Is this a refusal no retry changes until something is updated ("update    /// app", "update your Mac"), drawn in red.    public var refuses: Bool { state == .updateApp || state == .macBehind }    /// Is there a share done to draw as the page's thin bar: a catch-up's or    /// a copy's, 0 to 1.    public var fraction: Double? {        guard state == .syncing || state == .copying, let percent else { return nil }        return Double(min(max(percent, 0), 100)) / 100    }    /// The page's top line, or `nil` when the slot is empty. `mac` is the    /// name of the Mac that serves this database, when the app knows it.    /// `theirs` is a database joined at another person's Mac    /// (`HeldDatabase.theirs`): this device holds no name for that Mac, so    /// the sentence says "their Mac" and never a name it does not have.    public func pageLine(        mac: String?, theirs: Bool = false, now: Date = Date(), timeZone: TimeZone = .current,        thisDevice: String = DatabaseSyncLine.thisDevice    ) -> String? {        if state == .macBehind {            // The twin of "Update the app": which Mac to update, when the app            // knows its name — never the Mac's own "schemaVersion must be N".            let update = theirs ? "update their Mac" : mac.map { "update your Mac on \($0)" } ?? "update your Mac"            return "\(thisDevice) is ahead of \(theirs ? "their" : "your") Mac \u{00B7} \(update)"        }        guard state == .offline else { return page.isEmpty ? nil : page }        let unreachable = theirs            ? "their Mac not reachable"            : mac.map { "\($0) not reachable" } ?? "no Mac reachable"        guard let since else { return "Not synced yet \u{00B7} \(unreachable)" }        return "Not synced since \(Self.timeOfDay(since, in: timeZone, now: now)) \u{00B7} \(unreachable)"    }    /// "10:46" — the hour and minute alone; a day old or more it carries the    /// day ("11 Oct 10:46"), or "since 10:46" would read as this morning.    static func timeOfDay(_ date: Date, in timeZone: TimeZone, now: Date) -> String {        var calendar = Calendar(identifier: .gregorian)        calendar.timeZone = timeZone        let formatter = DateFormatter()        formatter.locale = Locale(identifier: "en_GB")        formatter.timeZone = timeZone        formatter.dateFormat = calendar.isDate(date, inSameDayAs: now) ? "HH:mm" : "d MMM HH:mm"        return formatter.string(from: date)    }}