// Each database's definitions and verbs travel together. A catalogue cached // while Personal was visible must never hide a new database's starter tools. import CottonKit import Foundation import Observation @MainActor @Observable final class DatabaseTableCatalog { /// The composition root supplies an already scoped table environment and /// its one catalogue read. This model cannot issue arbitrary core calls. struct Source { let tables: AppTables let read: @Sendable (_ reload: Bool) async throws -> [TableDefinition] } private(set) var tables: AppTables private(set) var database: String? @ObservationIgnored private let makeSource: @MainActor (String?) -> Source @ObservationIgnored private var source: Source @ObservationIgnored private var generation = 0 init(makeSource: @escaping @MainActor (String?) -> Source) { self.makeSource = makeSource let source = makeSource(nil) self.source = source tables = source.tables } /// Turn to `database` now, without reading its definitions: the window /// calls this in the same step that aims its calls (`DatabaseScene`), so /// a screen drawn for the new database never reads through the last /// one's store — the board did, and kept the last database's tiles. func point(at database: String?) { guard database != self.database else { return } generation += 1 self.database = database // Each source stays bound to its database for its whole lifetime. // An in-flight read from the previous database can finish safely. source = makeSource(database) tables = source.tables } func refresh(database: String?, reload: Bool = false) async { point(at: database) generation += 1 let requested = generation let source = self.source do { let definitions = try await source.read(reload) guard !Task.isCancelled, requested == generation else { return } tables = AppTables(records: source.tables.records, definitions: TableDefinitions(definitions), linkTitles: tables.linkTitles) } catch { guard requested == generation else { return } Log.write("Could not refresh tool packages: \(error)") // The bundled set is all there is: drawn from, not waited on. tables = AppTables(records: tables.records, definitions: TableDefinitions(tables.definitions.all), linkTitles: tables.linkTitles) } } }