Cotton code
167 lines · 6.8 KB · SwiftRaw
// The session's last answers: a screen you come back to draws at once.//// The replica IS the cache (design P5) — every `read.*` answers off the local// file in milliseconds, and nothing here changes that. What this holds is the// last ANSWER each read gave, for the life of the session, so that a screen// pushed for the second time draws its content on its first frame and// re-reads behind it. Before this, `Hosted` built a fresh model on every push,// the read's `firstAnswerPending` started at `true` again, and the skeleton// showed for an answer that had been in memory a second ago. On the owner's// phone that read as "the app loads constantly" — over a database that never// left the device.//// Stale-while-revalidate over ONE source of truth. The entry is keyed by the// read's method and the canonical JSON of its request, so two screens asking// the same question share one answer; it remembers the screen FAMILIES the// read claimed, and the same `data` event that already sends a mounted screen// back to the core drops every entry those families cover (`SyncModel`'s// `announce` is the one caller). A cached answer for a screen that is NOT on// the stack therefore cannot be stale by more than one event, and a screen// that is on the stack re-reads anyway and stores the fresh answer.//// Small, and a session cache rather than a store: at most `capacity` entries// and `byteBudget` bytes of encoded answer, the least recently used going// first — a thread read at every window size and the whole photo library are// each one answer, and forty of those is not a memory the app pays for. The// database is the durable copy.import CottonKitimport Foundationimport SwiftUI/// A model that draws its last answer from the session cache and stores every/// later one there. `Hosted` hands the cache to any model that conforms, once,/// before the screen's first frame; `ScreenRead` conforms, so every scaffolded/// screen is seeded with no edit of its own.@MainActorpublic protocol AnswerSeeded: AnyObject {    /// Take the session cache: draw the last answer if there is one, and keep    /// the cache for the answers to come.    func attach(_ cache: AnswerCache)}@MainActor@Observablepublic final class AnswerCache {    /// One read, as a key: the method and its request in canonical bytes.    public struct Key: Hashable, Sendable {        public let method: String        public let request: String    }    private struct Entry {        var value: JSONValue        var families: Set<ScreenFamily>        /// The answer's size as encoded JSON — what the byte budget counts.        var bytes: Int        /// The tick of the last `seed` or `store` — what the eviction orders by.        var touched: Int    }    /// How many answers the session keeps: enough for every screen a person    /// walks through in a sitting.    public let capacity: Int    /// How much encoded answer the session keeps, in bytes. An answer larger    /// than the whole budget is not kept at all.    public let byteBudget: Int    private var entries: [Key: Entry] = [:]    private var tick = 0    public init(capacity: Int = 40, byteBudget: Int = 4 << 20) {        self.capacity = max(1, capacity)        self.byteBudget = max(1, byteBudget)    }    /// How many answers are held right now.    public var count: Int { entries.count }    /// How much encoded answer is held right now, in bytes.    public var bytes: Int { entries.values.reduce(0) { $0 + $1.bytes } }    /// The read's key: the method and the request encoded with SORTED keys, so    /// `["a": 1, "b": 2]` and `["b": 2, "a": 1]` are one question.    public static func key(_ method: String, _ request: some Encodable = EmptyRequest()) -> Key {        let encoder = JSONEncoder()        encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]        // A request that cannot be encoded cannot be sent either — the call        // would have thrown before any answer existed to cache — so an empty        // request is the honest key for it.        let bytes = (try? encoder.encode(request)) ?? Data()        return Key(method: method, request: String(decoding: bytes, as: UTF8.self))    }    /// The last answer this read gave, or `nil`.    public func seed(_ method: String, _ request: some Encodable = EmptyRequest()) -> JSONValue? {        let key = Self.key(method, request)        guard var entry = entries[key] else { return nil }        tick += 1        entry.touched = tick        entries[key] = entry        return entry.value    }    /// Keep this read's answer for the session. The families are UNIONED with    /// any the key already carries: two screens asking one question with    /// different claims both want the entry gone when either's tables move.    public func store(        _ method: String,        _ request: some Encodable = EmptyRequest(),        value: JSONValue,        families: Set<ScreenFamily>    ) {        let key = Self.key(method, request)        let size = Self.size(of: value)        guard size <= byteBudget else {            // Too big to keep at all: the screen reads it as it always did,            // and a stale copy under this key must not stand in.            entries.removeValue(forKey: key)            return        }        tick += 1        let claimed = families.union(entries[key]?.families ?? [])        entries[key] = Entry(value: value, families: claimed, bytes: size, touched: tick)        evictWhileOverBudget()    }    /// The answer's size as JSON bytes — the measure the budget is in.    static func size(of value: JSONValue) -> Int {        (try? JSONEncoder().encode(value))?.count ?? 0    }    /// A `data` event named these families: drop every answer that claimed one.    public func invalidate(families: [ScreenFamily]) {        guard !families.isEmpty else { return }        let moved = Set(families)        entries = entries.filter { $0.value.families.isDisjoint(with: moved) }    }    /// Forget everything — the database this session was reading is closed.    public func clear() {        entries = [:]    }    private func evictWhileOverBudget() {        while entries.count > capacity || bytes > byteBudget,            let oldest = entries.min(by: { $0.value.touched < $1.value.touched })        {            entries.removeValue(forKey: oldest.key)        }    }}// MARK: - In the environment/// The session cache, set once in `RootView` beside `cottonCore` and read by/// `Hosted`. Optional for `cottonCore`'s reason: a screen rendered outside the/// app has no session, and a model with no cache simply reads.private struct CottonAnswersKey: EnvironmentKey {    static let defaultValue: AnswerCache? = nil}extension EnvironmentValues {    public var cottonAnswers: AnswerCache? {        get { self[CottonAnswersKey.self] }        set { self[CottonAnswersKey.self] = newValue }    }}