diff --git a/apple/TablePro/Core/Compare/CompareSyncProfileStorage.swift b/apple/TablePro/Core/Compare/CompareSyncProfileStorage.swift index a110caca49..b0f80ddb00 100644 --- a/apple/TablePro/Core/Compare/CompareSyncProfileStorage.swift +++ b/apple/TablePro/Core/Compare/CompareSyncProfileStorage.swift @@ -2,14 +2,6 @@ // CompareSyncProfileStorage.swift // TablePro // -// Named comparison setups, keyed by source scope, target scope, and mode. -// -// The key used to be the pair of connection ids alone, which cannot tell two -// databases on one server apart. A profile saved under the old key is read back -// and adopted onto whatever database each connection currently points at, which -// is the same place it was saved from, so nothing is silently retargeted and -// nothing is thrown away. -// import Foundation import os @@ -26,8 +18,7 @@ internal struct CompareSyncProfile: Codable, Hashable, Identifiable { internal var selectedObjects: [String] internal var tableScopes: [String: DataTableScope] - /// The compared-column exclusions a profile saved before they became per table. Read so a - /// saved comparison keeps leaving out the columns it left out, never written back. + // Column exclusions saved before they became per table, so an old comparison keeps leaving them out. internal var legacyExcludedColumns: Set internal init( @@ -87,9 +78,7 @@ internal struct CompareSyncProfile: Codable, Hashable, Identifiable { dataOptions = try container.decodeIfPresent(DataCompareOptions.self, forKey: .dataOptions) ?? .default selectedObjects = try container.decodeIfPresent([String].self, forKey: .selectedObjects) ?? [] tableScopes = try container.decodeIfPresent([String: DataTableScope].self, forKey: .tableScopes) ?? [:] - /// Kept on the profile once it has been read, because saving or deleting any comparison - /// rewrites the whole stored array, and a profile still waiting to be loaded would lose the - /// columns it was told to leave out. + // Carried once read: every save rewrites the whole array, and a profile not yet loaded would lose them. if let carried = try container.decodeIfPresent(Set.self, forKey: .legacyExcludedColumns) { legacyExcludedColumns = carried return @@ -132,8 +121,10 @@ internal final class CompareSyncProfileStorage { internal static let shared = CompareSyncProfileStorage() private static let logger = Logger(subsystem: "com.TablePro", category: "CompareSyncProfileStorage") - private static let defaultsKey = "compareSyncProfiles" - private static let lastSetupKey = "compareSyncLastSetup" + private static let profilesKey = JSONDefaultsKey<[CompareSyncProfile]>("compareSyncProfiles") + // The same entry as written when a profile was keyed by the connection pair alone. + private static let legacyProfilesKey = JSONDefaultsKey<[LegacyProfile]>("compareSyncProfiles") + private static let lastSetupKey = JSONDefaultsKey("compareSyncLastSetup") private let defaults: UserDefaults @@ -143,37 +134,22 @@ internal final class CompareSyncProfileStorage { // MARK: - Last setup - /// The pair, the mode and the options the window last held, so reopening it lands on the same - /// comparison rather than on two empty pickers. It carries no included objects: what to change - /// is a decision about one comparison's results, and re-arming it against a report that has not - /// run yet would put a stale choice behind an Apply button. + // Holds no included objects: re-arming them before the report runs would put a stale choice behind Apply. internal func lastSetup() -> CompareSyncProfile? { - guard let data = defaults.data(forKey: Self.lastSetupKey) else { return nil } - do { - return try JSONDecoder().decode(CompareSyncProfile.self, from: data) - } catch { - Self.logger.error("Failed to decode last setup: \(error.publicLogShape, privacy: .public)") - return nil - } + defaults.read(Self.lastSetupKey).value } internal func rememberSetup(_ profile: CompareSyncProfile) { - do { - defaults.set(try JSONEncoder().encode(profile), forKey: Self.lastSetupKey) - } catch { - Self.logger.error("Failed to persist last setup: \(error.publicLogShape, privacy: .public)") - } + try? defaults.write(profile, to: Self.lastSetupKey) } // MARK: - Saved comparisons internal func allProfiles() -> [CompareSyncProfile] { - guard let data = defaults.data(forKey: Self.defaultsKey) else { return [] } - do { - return try JSONDecoder().decode([CompareSyncProfile].self, from: data) - } catch { - Self.logger.error("Failed to decode profiles: \(error.publicLogShape, privacy: .public)") - return migrateLegacyProfiles(from: data) + switch defaults.read(Self.profilesKey) { + case .missing: return [] + case .value(let profiles): return profiles + case .unreadable: return migrateLegacyProfiles() } } @@ -192,21 +168,15 @@ internal final class CompareSyncProfileStorage { } private func persist(_ profiles: [CompareSyncProfile]) { - do { - defaults.set(try JSONEncoder().encode(profiles), forKey: Self.defaultsKey) - } catch { - Self.logger.error("Failed to persist profiles: \(error.publicLogShape, privacy: .public)") - } + try? defaults.write(profiles, to: Self.profilesKey) } - /// A profile written before an endpoint carried a database is adopted onto whichever database - /// its connections currently point at, which is where it was saved from. Discarding them - /// instead would lose setups the user had already named. - private func migrateLegacyProfiles(from data: Data) -> [CompareSyncProfile] { - guard let legacy = try? JSONDecoder().decode([LegacyProfile].self, from: data) else { return [] } + // Adopted onto the database each connection points at now, which is where it was saved from. + private func migrateLegacyProfiles() -> [CompareSyncProfile] { + guard let legacy = defaults.read(Self.legacyProfilesKey).value else { return [] } let connections = ConnectionStorage.shared.loadConnections() let databaseByConnection = Dictionary( - connections.map { ($0.id, $0.database ?? "") }, uniquingKeysWith: { first, _ in first } + connections.map { ($0.id, $0.database) }, uniquingKeysWith: { first, _ in first } ) let migrated = legacy.map { entry in CompareSyncProfile( @@ -244,8 +214,7 @@ internal final class CompareSyncProfileStorage { let structureOptions: StructureCompareOptions let dataOptions: DataCompareOptions let selectedTables: [String] - /// The compared-column exclusions this shape stored inside its options, read here because - /// `DataCompareOptions` no longer carries them and the migration is the last chance to. + // Stored inside the options, which no longer carry it, so the migration is the last chance to read it. let excludedColumns: Set private enum CodingKeys: String, CodingKey { diff --git a/apple/TablePro/Core/ConnectionLibrary/RecentConnectionsStore.swift b/apple/TablePro/Core/ConnectionLibrary/RecentConnectionsStore.swift index 673be4d9c7..96a5309f04 100644 --- a/apple/TablePro/Core/ConnectionLibrary/RecentConnectionsStore.swift +++ b/apple/TablePro/Core/ConnectionLibrary/RecentConnectionsStore.swift @@ -5,15 +5,12 @@ import Combine import Foundation -import os import TableProConnectionLibrary @MainActor internal final class RecentConnectionsStore: ObservableObject { internal static let shared = RecentConnectionsStore() - nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "RecentConnectionsStore") - private let defaults: UserDefaults private let appEvents: AppEvents @Published internal private(set) var ledger: RecentConnectionsLedger @@ -24,7 +21,7 @@ internal final class RecentConnectionsStore: ObservableObject { ) { self.defaults = defaults self.appEvents = appEvents - self.ledger = Self.load(from: defaults) + self.ledger = defaults.read(PreferenceKeys.recentConnections).value ?? RecentConnectionsLedger() } internal var lastConnected: [UUID: Date] { @@ -58,24 +55,7 @@ internal final class RecentConnectionsStore: ObservableObject { private func commit(_ updated: RecentConnectionsLedger) { guard updated != ledger else { return } ledger = updated - do { - let data = try JSONEncoder().encode(updated) - defaults.set(data, forKey: PreferenceKeys.recentConnections.name) - } catch { - Self.logger.error("Failed to save recent connections: \(error.publicLogShape, privacy: .public)") - } + try? defaults.write(updated, to: PreferenceKeys.recentConnections) appEvents.connectionListStateChanged.send(()) } - - private static func load(from defaults: UserDefaults) -> RecentConnectionsLedger { - guard let data = defaults.data(forKey: PreferenceKeys.recentConnections.name) else { - return RecentConnectionsLedger() - } - do { - return try JSONDecoder().decode(RecentConnectionsLedger.self, from: data) - } catch { - logger.error("Discarding unreadable recent connections: \(error.publicLogShape, privacy: .public)") - return RecentConnectionsLedger() - } - } } diff --git a/apple/TablePro/Core/MCP/Outside/MCPServerStore.swift b/apple/TablePro/Core/MCP/Outside/MCPServerStore.swift index 61f1b53dc1..cc1534bc6f 100644 --- a/apple/TablePro/Core/MCP/Outside/MCPServerStore.swift +++ b/apple/TablePro/Core/MCP/Outside/MCPServerStore.swift @@ -5,38 +5,21 @@ import Combine import Foundation -import os import TableProMCP -/// The outside MCP servers this Mac knows about, and their bearer tokens. -/// -/// The configuration is device-local JSON in UserDefaults; the token is in the Keychain, keyed by -/// the server's id, so removing a server removes its credential and nothing else has to remember to. -/// Nothing here syncs: a server reachable from this Mac is not necessarily reachable from another, -/// and a token that travelled would be a credential the user did not choose to copy. +// Device-local and never synced: a server this Mac reaches may not be reachable from another. @MainActor internal final class MCPServerStore: ObservableObject { internal static let shared = MCPServerStore() - nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "MCPServerStore") - - private static let defaultsKey = "com.TablePro.mcp.outsideServers" + private static let serversKey = JSONDefaultsKey<[MCPServerConfiguration]>("com.TablePro.mcp.outsideServers") @Published internal private(set) var servers: [MCPServerConfiguration] = [] private let defaults: UserDefaults private let keychain: any KeychainStoring - /// Both come from `AppStorageEnvironment` rather than from `.standard` and the real Keychain. - /// A store that names those directly reads the developer's own data under test isolation, which - /// is the one thing the sandbox exists to prevent. - /// The defaults come from `AppStorageEnvironment` rather than from `.standard`, so a store that - /// names them directly cannot read the developer's own data under test isolation. - /// - /// The Keychain is `MCPServerTokenKeychain` in production and the sandbox's own file store under - /// test. `AppStorageEnvironment.keychain` is `KeychainHelper`, which marks every item - /// synchronizable once the user turns on connection password sync, and a token for a server - /// this Mac can reach is not a credential they chose to copy to another one. + // Not `AppStorageEnvironment.keychain` in production: it syncs items once password sync is on. internal init( defaults: UserDefaults = AppStorageEnvironment.shared.defaults, keychain: (any KeychainStoring)? = nil @@ -44,7 +27,7 @@ internal final class MCPServerStore: ObservableObject { self.defaults = defaults let environment = AppStorageEnvironment.shared self.keychain = keychain ?? (environment.isIsolated ? environment.keychain : MCPServerTokenKeychain()) - servers = Self.decode(defaults.data(forKey: Self.defaultsKey)) + servers = defaults.read(Self.serversKey).value ?? [] } // MARK: - Reads @@ -53,15 +36,12 @@ internal final class MCPServerStore: ObservableObject { servers.first { $0.id == id } } - /// The servers a session on this connection may reach. A nil connection reaches none: a session - /// with no connection cannot pass the allowlist, and defaulting to "all" there would make a - /// half-built session the most privileged one in the app. + // A nil connection reaches none, so a half-built session is never the most privileged one. internal func servers(allowedFor connectionId: UUID?) -> [MCPServerConfiguration] { guard let connectionId else { return [] } return servers.filter { $0.allowedConnectionIds.contains(connectionId) } } - /// Whether one tool name, already namespaced, belongs to a server this connection may reach. internal func allowsTool(named toolName: String, connectionId: UUID?) -> Bool { guard let server = server(owningTool: toolName) else { return false } return server.allows(connectionId: connectionId) @@ -96,8 +76,6 @@ internal final class MCPServerStore: ObservableObject { return nil } - /// Removes the server and its credential together. A token left behind would be a live secret - /// for a server the user believes they deleted. internal func remove(id: UUID) { servers.removeAll { $0.id == id } keychain.delete(forKey: Self.tokenKey(id)) @@ -116,9 +94,7 @@ internal final class MCPServerStore: ObservableObject { persist() } - /// Called when a connection is deleted, so its id does not sit in an allowlist forever. A new - /// connection cannot inherit it (ids are fresh UUIDs), but a stale entry makes the settings pane - /// lie about how far a server reaches. + // A stale id would make the settings pane overstate how far a server reaches. internal func forgetConnection(_ connectionId: UUID) { var next = servers var changed = false @@ -131,9 +107,7 @@ internal final class MCPServerStore: ObservableObject { persist() } - /// Nil for a locked or cancelled Keychain as well as a missing token. The call that needs it - /// fails with the server unreachable, which is the honest report: a token TablePro cannot read is - /// a token it does not have. + // Nil for a locked or cancelled Keychain too: the call then fails with the server unreachable. internal func token(for serverId: UUID) -> String? { guard case .found(let token) = keychain.readStringResult(forKey: Self.tokenKey(serverId)) else { return nil @@ -148,20 +122,6 @@ internal final class MCPServerStore: ObservableObject { } private func persist() { - do { - defaults.set(try JSONEncoder().encode(servers), forKey: Self.defaultsKey) - } catch { - Self.logger.error("Failed to persist outside MCP servers: \(error.localizedDescription)") - } - } - - private static func decode(_ data: Data?) -> [MCPServerConfiguration] { - guard let data else { return [] } - do { - return try JSONDecoder().decode([MCPServerConfiguration].self, from: data) - } catch { - Self.logger.error("Failed to load outside MCP servers: \(error.localizedDescription)") - return [] - } + try? defaults.write(servers, to: Self.serversKey) } } diff --git a/apple/TablePro/Core/Services/TeamLibrary/TeamLibraryState.swift b/apple/TablePro/Core/Services/TeamLibrary/TeamLibraryState.swift index e779eaafa3..4d15bce003 100644 --- a/apple/TablePro/Core/Services/TeamLibrary/TeamLibraryState.swift +++ b/apple/TablePro/Core/Services/TeamLibrary/TeamLibraryState.swift @@ -151,28 +151,26 @@ internal struct TeamLibraryStateStore { func loadAll() -> [TeamLibraryTeamState] { let files = (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? [] return files.filter { $0.pathExtension == "json" }.compactMap { file in - guard let data = try? Data(contentsOf: file) else { return nil } - do { - return try JSONDecoder().decode(TeamLibraryTeamState.self, from: data) - } catch { - Self.logger.error("Dropping an unreadable team library file: \(error.publicLogShape, privacy: .public)") - try? FileManager.default.removeItem(at: file) + let store = JSONFileStore(url: file) + switch store.read() { + case .value(let state): + return state + case .unreadable(let error) where error is DecodingError: + try? store.remove() + return nil + // A file that could not be read at all is kept for the next launch. + case .missing, .unreadable: return nil } } } func save(_ state: TeamLibraryTeamState) { - do { - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - try JSONEncoder().encode(state).write(to: file(for: state.teamID), options: .atomic) - } catch { - Self.logger.error("Could not store the team library: \(error.publicLogShape, privacy: .public)") - } + try? teamFile(state.teamID).write(state) } func remove(teamID: String) { - try? FileManager.default.removeItem(at: file(for: teamID)) + try? teamFile(teamID).remove() } func removeAll() { @@ -182,9 +180,9 @@ internal struct TeamLibraryStateStore { // What the last /v1 pull cached, keyed by client ID like a /v2 snapshot, so the first one matches it item by item. func loadLegacy(now: Date) -> TeamLibraryLegacyLibrary? { - guard let data = try? Data(contentsOf: legacyFile) else { return nil } + guard let cache = legacyCache.read().value else { return nil } do { - return try JSONDecoder().decode(TeamLibraryLegacyCache.self, from: data).library(at: now) + return try cache.library(at: now) } catch { Self.logger.error("The /v1 team library cache is unreadable: \(error.publicLogShape, privacy: .public)") return nil @@ -192,13 +190,17 @@ internal struct TeamLibraryStateStore { } func removeLegacy() { - try? FileManager.default.removeItem(at: legacyFile) + try? legacyCache.remove() defaults.removeObject(forKey: Self.legacyPullKey) } - private func file(for teamID: String) -> URL { + private var legacyCache: JSONFileStore { + JSONFileStore(url: legacyFile) + } + + private func teamFile(_ teamID: String) -> JSONFileStore { let name = String(teamID.unicodeScalars.filter { CharacterSet.alphanumerics.contains($0) || $0 == "_" }) - return directory.appendingPathComponent("\(name).json") + return JSONFileStore(url: directory.appendingPathComponent("\(name).json")) } } diff --git a/apple/TablePro/Core/Storage/AIChatStorage.swift b/apple/TablePro/Core/Storage/AIChatStorage.swift index 0e09c5245d..2ea773eb52 100644 --- a/apple/TablePro/Core/Storage/AIChatStorage.swift +++ b/apple/TablePro/Core/Storage/AIChatStorage.swift @@ -13,19 +13,6 @@ actor AIChatStorage { private let directory: URL - private static let encoder: JSONEncoder = { - let encoder = JSONEncoder() - encoder.dateEncodingStrategy = .iso8601 - encoder.outputFormatting = [.prettyPrinted, .sortedKeys] - return encoder - }() - - private static let decoder: JSONDecoder = { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 - return decoder - }() - private init() { let dir = AppStorageEnvironment.shared.applicationSupportRoot .appendingPathComponent("TablePro", isDirectory: true) @@ -60,18 +47,16 @@ actor AIChatStorage { } nonisolated private static func write(_ conversation: AIConversation, into directory: URL) { - let fileURL = directory.appendingPathComponent("\(conversation.id.uuidString).json") - + let store = file(for: conversation.id, in: directory) do { - var data = try Self.encoder.encode(conversation) - + var data = try store.coding.encode(conversation) if data.count > Self.maxFileSize { let originalSize = data.count let originalCount = conversation.messages.count var trimmed = conversation - trimmed.messages = Array(trimmed.messages.suffix(Self.turnsKeptWhenTrimmed)) + trimmed.messages = Array(conversation.messages.suffix(Self.turnsKeptWhenTrimmed)) let dropped = originalCount - trimmed.messages.count - data = try Self.encoder.encode(trimmed) + data = try store.coding.encode(trimmed) Self.logger.warning( """ Trimmed conversation \(conversation.id, privacy: .public): \ @@ -80,13 +65,20 @@ actor AIChatStorage { """ ) } - - try data.write(to: fileURL, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) + try store.write(encoded: data) } catch { Self.logger.error("Failed to save conversation \(conversation.id): \(error.localizedDescription)") } } + nonisolated private static func file(for id: UUID, in directory: URL) -> JSONFileStore { + JSONFileStore( + url: directory.appendingPathComponent("\(id.uuidString).json"), + coding: .prettyISO8601, + writingOptions: [.atomic, .completeFileProtectionUntilFirstUserAuthentication] + ) + } + // A conversation stored before conversations carried a connection id is shown everywhere, not lost. static func isShown(conversationOf owner: UUID?, on connectionId: UUID?) -> Bool { connectionId == nil || owner == nil || owner == connectionId @@ -109,34 +101,20 @@ actor AIChatStorage { let summaries: [AIConversation] = files .filter { $0.pathExtension == "json" } .compactMap { fileURL in - do { - let data = try Data(contentsOf: fileURL) - let header = try Self.decoder.decode(ConversationHeader.self, from: data) - guard Self.isShown(conversationOf: header.connectionId, on: connectionId) else { return nil } - return header.summary - } catch { - Self.logger.error("Failed to load conversation from \(fileURL.lastPathComponent): \(error.localizedDescription)") - return nil - } + let header = JSONFileStore(url: fileURL, coding: .prettyISO8601).read().value + guard let header, Self.isShown(conversationOf: header.connectionId, on: connectionId) else { return nil } + return header.summary } return summaries.sorted { $0.updatedAt > $1.updatedAt } } func load(id: UUID) -> AIConversation? { - let fileURL = directory.appendingPathComponent("\(id.uuidString).json") - guard let data = try? Data(contentsOf: fileURL) else { return nil } - return try? Self.decoder.decode(AIConversation.self, from: data) + Self.file(for: id, in: directory).read().value } func delete(_ id: UUID) { - let fileURL = directory.appendingPathComponent("\(id.uuidString).json") - - do { - try FileManager.default.removeItem(at: fileURL) - } catch { - Self.logger.error("Failed to delete conversation \(id): \(error.localizedDescription)") - } + try? Self.file(for: id, in: directory).remove() } func deleteAll() { diff --git a/apple/TablePro/Core/Storage/AgentSessionStore.swift b/apple/TablePro/Core/Storage/AgentSessionStore.swift index 51479cb344..3e05080645 100644 --- a/apple/TablePro/Core/Storage/AgentSessionStore.swift +++ b/apple/TablePro/Core/Storage/AgentSessionStore.swift @@ -4,65 +4,26 @@ // import Foundation -import os -/// Where agent sessions live between launches, on this Mac only. -/// -/// Device-local on purpose. A transcript carries query results, schema and whatever the user typed -/// about their data, and none of that is declared in the CloudKit production schema, so writing it -/// there is both a product decision nobody has made and a record type the server would reject. -/// -/// Not an actor. Restore has to finish before the first window exists, or a window that opens while -/// the load is suspended finds no sessions, mints one, and is then joined by the stored one: two -/// sessions on one conversation, both persisted, both in the rail. Reading one small file -/// synchronously closes that by construction. Measured on the record shape it reads: 0.08ms for ten -/// sessions and 0.6ms for two hundred, against a launch budget in the hundreds of milliseconds. +// Device-local: CloudKit has no record type for a transcript. Not an actor, so restore lands before a first window mints a second session. internal struct AgentSessionStore: Sendable { - private static let logger = Logger(subsystem: "com.TablePro", category: "AgentSessionStore") - - private let fileURL: URL - - private static let encoder: JSONEncoder = { - let encoder = JSONEncoder() - encoder.dateEncodingStrategy = .iso8601 - encoder.outputFormatting = [.prettyPrinted, .sortedKeys] - return encoder - }() - - private static let decoder: JSONDecoder = { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 - return decoder - }() + private let file: JSONFileStore<[AgentSessionRecord]> internal init(directory: URL? = nil) { let root = directory ?? AppStorageEnvironment.shared.applicationSupportRoot .appendingPathComponent("TablePro", isDirectory: true) - fileURL = root.appendingPathComponent("AgentSessions.json") - do { - try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) - } catch { - Self.logger.error("Could not create the agent session directory: \(error.localizedDescription)") - } + file = JSONFileStore( + url: root.appendingPathComponent("AgentSessions.json"), + coding: .prettyISO8601, + writingOptions: [.atomic, .completeFileProtectionUntilFirstUserAuthentication] + ) } internal func load() -> [AgentSessionRecord] { - guard FileManager.default.fileExists(atPath: fileURL.path) else { return [] } - do { - let data = try Data(contentsOf: fileURL) - return try Self.decoder.decode([AgentSessionRecord].self, from: data) - } catch { - Self.logger.error("Could not read agent sessions: \(error.localizedDescription)") - return [] - } + file.read().value ?? [] } internal func save(_ records: [AgentSessionRecord]) { - do { - let data = try Self.encoder.encode(records) - try data.write(to: fileURL, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) - } catch { - Self.logger.error("Could not write agent sessions: \(error.localizedDescription)") - } + try? file.write(records) } } diff --git a/apple/TablePro/Core/Storage/ConnectionApprovalStore.swift b/apple/TablePro/Core/Storage/ConnectionApprovalStore.swift index cc4147e58a..bf295297f9 100644 --- a/apple/TablePro/Core/Storage/ConnectionApprovalStore.swift +++ b/apple/TablePro/Core/Storage/ConnectionApprovalStore.swift @@ -109,24 +109,21 @@ internal final class ConnectionApprovalStore { return true } + private var approvalsKey: JSONDefaultsKey { + JSONDefaultsKey(kind.storageKey) + } + private func approvals() -> Approvals { - guard let data = defaults.data(forKey: kind.storageKey), - let decoded = try? JSONDecoder().decode(Approvals.self, from: data) - else { return [:] } - return decoded + defaults.read(approvalsKey).value ?? [:] } private func save(_ approvals: Approvals) { let kept = approvals.filter { !$0.value.isEmpty } guard !kept.isEmpty else { - defaults.removeObject(forKey: kind.storageKey) - return - } - guard let data = try? JSONEncoder().encode(kept) else { - Self.logger.error("Could not encode \(self.kind.logName, privacy: .public)") + defaults.removeValue(for: approvalsKey) return } - defaults.set(data, forKey: kind.storageKey) + try? defaults.write(kept, to: approvalsKey) } } diff --git a/apple/TablePro/Core/Storage/CustomSlashCommandStorage.swift b/apple/TablePro/Core/Storage/CustomSlashCommandStorage.swift index 9a20765697..4ebe066671 100644 --- a/apple/TablePro/Core/Storage/CustomSlashCommandStorage.swift +++ b/apple/TablePro/Core/Storage/CustomSlashCommandStorage.swift @@ -5,7 +5,6 @@ import Combine import Foundation -import os import TableProSyncTransport enum CustomSlashCommandError: LocalizedError, Equatable { @@ -28,8 +27,7 @@ final class CustomSlashCommandStorage: ObservableObject { nonisolated static let syncCategory = "customSlashCommands" - nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "CustomSlashCommandStorage") - private static let defaultsKey = "ai.customSlashCommands.v1" + private static let defaultsKey = JSONDefaultsKey<[CustomSlashCommand]>("ai.customSlashCommands.v1") private let defaults: UserDefaults private let syncTracker: SyncChangeTracker @@ -41,7 +39,6 @@ final class CustomSlashCommandStorage: ObservableObject { self.commands = Self.load(from: defaults) } - /// Replaces all commands from a remote sync without re-marking them dirty. func applyRemote(_ commands: [CustomSlashCommand]) { self.commands = commands persist(markDirty: false) @@ -97,23 +94,16 @@ final class CustomSlashCommandStorage: ObservableObject { private func persist(markDirty: Bool = true) { do { - let data = try JSONEncoder().encode(commands) - defaults.set(data, forKey: Self.defaultsKey) - if markDirty { - syncTracker.markDirty(.settings, id: Self.syncCategory) - } + try defaults.write(commands, to: Self.defaultsKey) } catch { - Self.logger.warning("Failed to persist custom slash commands: \(error.publicLogShape, privacy: .public)") + return + } + if markDirty { + syncTracker.markDirty(.settings, id: Self.syncCategory) } } private static func load(from defaults: UserDefaults) -> [CustomSlashCommand] { - guard let data = defaults.data(forKey: Self.defaultsKey) else { return [] } - do { - return try JSONDecoder().decode([CustomSlashCommand].self, from: data) - } catch { - Self.logger.warning("Failed to load custom slash commands: \(error.publicLogShape, privacy: .public)") - return [] - } + defaults.read(Self.defaultsKey).value ?? [] } } diff --git a/apple/TablePro/Core/Storage/DatabaseTreeFilterStorage.swift b/apple/TablePro/Core/Storage/DatabaseTreeFilterStorage.swift index 1b3e80acfd..beba8dda43 100644 --- a/apple/TablePro/Core/Storage/DatabaseTreeFilterStorage.swift +++ b/apple/TablePro/Core/Storage/DatabaseTreeFilterStorage.swift @@ -10,43 +10,35 @@ final class DatabaseTreeFilterStorage { self.defaults = defaults } - private func databasesKey(connectionId: UUID) -> String { - "com.TablePro.treeDatabaseFilter.\(connectionId.uuidString).selected" + private func databasesKey(connectionId: UUID) -> JSONDefaultsKey<[String]> { + JSONDefaultsKey("com.TablePro.treeDatabaseFilter.\(connectionId.uuidString).selected") } - /// Keyed per database inside one value, because a schema name means something only inside the - /// database that holds it. An engine with no database name keys its schemas under "". - private func schemasKey(connectionId: UUID) -> String { - "com.TablePro.treeSchemaFilter.\(connectionId.uuidString).selected" + // Keyed per database, since a schema name means something only inside its database. No database name keys as "". + private func schemasKey(connectionId: UUID) -> JSONDefaultsKey<[String: [String]]> { + JSONDefaultsKey("com.TablePro.treeSchemaFilter.\(connectionId.uuidString).selected", coding: .sortedKeys) } func selectedDatabases(connectionId: UUID) -> Set { - guard let data = defaults.data(forKey: databasesKey(connectionId: connectionId)), - let names = try? JSONDecoder().decode([String].self, from: data) - else { return [] } - return Set(names) + Set(defaults.read(databasesKey(connectionId: connectionId)).value ?? []) } func setSelectedDatabases(_ databases: Set, connectionId: UUID) { let key = databasesKey(connectionId: connectionId) guard !databases.isEmpty else { - defaults.removeObject(forKey: key) + defaults.removeValue(for: key) return } - guard let data = try? JSONEncoder().encode(databases.sorted()) else { return } - defaults.set(data, forKey: key) + try? defaults.write(databases.sorted(), to: key) } - /// The raw selection, empty for no filter. A reader that decides what to read wants - /// `SidebarSchemaFilter`, which sets aside names the sidebar would not show. + // The raw selection, empty for no filter. A reader deciding what to load wants `SidebarSchemaFilter`. func selectedSchemas(connectionId: UUID, database: String) -> Set { allSelectedSchemas(connectionId: connectionId)[database] ?? [] } func allSelectedSchemas(connectionId: UUID) -> [String: Set] { - guard let data = defaults.data(forKey: schemasKey(connectionId: connectionId)), - let stored = try? JSONDecoder().decode([String: [String]].self, from: data) - else { return [:] } + let stored = defaults.read(schemasKey(connectionId: connectionId)).value ?? [:] return stored.reduce(into: [:]) { result, entry in guard !entry.value.isEmpty else { return } result[entry.key] = Set(entry.value) @@ -66,18 +58,15 @@ final class DatabaseTreeFilterStorage { result[entry.key] = entry.value.sorted() } guard !stored.isEmpty else { - defaults.removeObject(forKey: key) + defaults.removeValue(for: key) return } - let encoder = JSONEncoder() - encoder.outputFormatting = .sortedKeys - guard let data = try? encoder.encode(stored) else { return } - defaults.set(data, forKey: key) + try? defaults.write(stored, to: key) } func removeFilter(for connectionId: UUID) { - defaults.removeObject(forKey: databasesKey(connectionId: connectionId)) - defaults.removeObject(forKey: schemasKey(connectionId: connectionId)) + defaults.removeValue(for: databasesKey(connectionId: connectionId)) + defaults.removeValue(for: schemasKey(connectionId: connectionId)) } func removeFilters(for connectionIds: Set) { diff --git a/apple/TablePro/Core/Storage/ERDiagramPositionStorage.swift b/apple/TablePro/Core/Storage/ERDiagramPositionStorage.swift index e51cc682b3..364cdf0258 100644 --- a/apple/TablePro/Core/Storage/ERDiagramPositionStorage.swift +++ b/apple/TablePro/Core/Storage/ERDiagramPositionStorage.swift @@ -1,7 +1,5 @@ import Foundation -/// Persists user-arranged table node positions for ER diagrams. -/// Keyed by connection + schema so positions survive across sessions. @MainActor final class ERDiagramPositionStorage { static let shared = ERDiagramPositionStorage() @@ -9,25 +7,22 @@ final class ERDiagramPositionStorage { private init() {} - private func key(connectionId: UUID, schemaKey: String) -> String { - "com.TablePro.erDiagram.positions.\(connectionId.uuidString).\(schemaKey)" + private func key(connectionId: UUID, schemaKey: String) -> JSONDefaultsKey<[String: CodablePoint]> { + JSONDefaultsKey("com.TablePro.erDiagram.positions.\(connectionId.uuidString).\(schemaKey)") } func load(connectionId: UUID, schemaKey: String) -> [String: CGPoint] { - guard let data = defaults.data(forKey: key(connectionId: connectionId, schemaKey: schemaKey)), - let stored = try? JSONDecoder().decode([String: CodablePoint].self, from: data) - else { return [:] } + let stored = defaults.read(key(connectionId: connectionId, schemaKey: schemaKey)).value ?? [:] return stored.mapValues { CGPoint(x: $0.x, y: $0.y) } } func save(_ positions: [String: CGPoint], connectionId: UUID, schemaKey: String) { let stored = positions.mapValues { CodablePoint(x: $0.x, y: $0.y) } - guard let data = try? JSONEncoder().encode(stored) else { return } - defaults.set(data, forKey: key(connectionId: connectionId, schemaKey: schemaKey)) + try? defaults.write(stored, to: key(connectionId: connectionId, schemaKey: schemaKey)) } func clear(connectionId: UUID, schemaKey: String) { - defaults.removeObject(forKey: key(connectionId: connectionId, schemaKey: schemaKey)) + defaults.removeValue(for: key(connectionId: connectionId, schemaKey: schemaKey)) } } diff --git a/apple/TablePro/Core/Storage/ExportProfileStorage.swift b/apple/TablePro/Core/Storage/ExportProfileStorage.swift index a557c05ac2..b754e14e83 100644 --- a/apple/TablePro/Core/Storage/ExportProfileStorage.swift +++ b/apple/TablePro/Core/Storage/ExportProfileStorage.swift @@ -4,14 +4,9 @@ // import Foundation -import os import TableProPluginKit -/// One saved export: the format, and which objects it covered with how each was narrowed. -/// -/// The format's own options already persist globally through `SettablePlugin`, and the last format -/// through `TransferDialogStorage`. What neither carries is the selection, which is the part a user -/// rebuilds by hand every time: forty tables ticked, three of them filtered, two limited. +// Format options and the last format persist elsewhere; this keeps the selection a user would rebuild by hand. struct ExportProfile: Codable, Identifiable, Equatable { struct Entry: Codable, Equatable { let container: String @@ -34,8 +29,7 @@ struct ExportProfile: Codable, Identifiable, Equatable { self.rowScope = rowScope } - /// Matches the row it was saved from. Keyed by kind as well as name, because a routine and - /// a table can share one. + // Keyed by kind as well as name, because a routine and a table can share one. var key: String { "\(container).\(kind).\(name)" } } @@ -56,16 +50,11 @@ struct ExportProfile: Codable, Identifiable, Equatable { } } -/// Saved export profiles, one file per connection. -/// -/// Device-local: a profile names tables on one server, and syncing it would offer a selection whose -/// objects the other Mac's connection may not have. +// Device-local: a profile names tables on one server, which the other Mac's connection may not have. @MainActor final class ExportProfileStorage { static let shared = ExportProfileStorage() - private static let logger = Logger(subsystem: "com.TablePro", category: "ExportProfileStorage") - private let directory: URL private var cache: [UUID: [ExportProfile]] = [:] @@ -85,8 +74,7 @@ final class ExportProfileStorage { return loaded } - /// Saving under a name that already exists replaces it, so re-saving a profile the user is - /// working on does not leave two rows with the same label in the picker. + // Saving under a name that already exists replaces it, so the picker never shows one label twice. func save(_ profile: ExportProfile, for connectionId: UUID) { var profiles = profiles(for: connectionId) if let index = profiles.firstIndex(where: { $0.name == profile.name }) { @@ -128,9 +116,7 @@ final class ExportProfileStorage { return ExportProfile(name: name, formatId: formatId, entries: entries) } - /// Applies a profile over the tree the dialog is showing. An object the profile names that the - /// database no longer has is dropped rather than resurrected, and one the profile does not name - /// is deselected, so applying a profile twice gives the same selection both times. + // A gone object stays gone and an unnamed one is deselected, so applying a profile twice gives the same selection. nonisolated static func apply(_ profile: ExportProfile, to databases: [ExportDatabaseItem]) -> [ExportDatabaseItem] { let entries = profile.entriesByKey return databases.map { database in @@ -157,8 +143,7 @@ final class ExportProfileStorage { } } - /// How many of a profile's objects the current tree still holds, so the picker can say when a - /// profile has gone stale instead of silently selecting fewer rows than it names. + // Lets the picker say a profile has gone stale instead of silently selecting fewer rows than it names. nonisolated static func matchCount(_ profile: ExportProfile, in databases: [ExportDatabaseItem]) -> Int { let present = Set(databases.flatMap { database in database.objects.map { object in @@ -176,35 +161,21 @@ final class ExportProfileStorage { // MARK: - Persistence - private func fileURL(for connectionId: UUID) -> URL { - directory.appendingPathComponent("\(connectionId.uuidString).json") + private func file(for connectionId: UUID) -> JSONFileStore<[ExportProfile]> { + JSONFileStore(url: directory.appendingPathComponent("\(connectionId.uuidString).json")) } private func load(_ connectionId: UUID) -> [ExportProfile] { - let url = fileURL(for: connectionId) - guard let data = try? Data(contentsOf: url) else { return [] } - do { - return try JSONDecoder().decode([ExportProfile].self, from: data) - } catch { - Self.logger.warning("Failed to read export profiles: \(error.localizedDescription)") - return [] - } + file(for: connectionId).read().value ?? [] } private func persist(_ profiles: [ExportProfile], for connectionId: UUID) { cache[connectionId] = profiles - let url = fileURL(for: connectionId) - do { - try FileManager.default.createDirectory( - at: directory, withIntermediateDirectories: true) - guard !profiles.isEmpty else { - try? FileManager.default.removeItem(at: url) - return - } - let data = try JSONEncoder().encode(profiles) - try data.write(to: url, options: .atomic) - } catch { - Self.logger.warning("Failed to write export profiles: \(error.localizedDescription)") + let store = file(for: connectionId) + guard !profiles.isEmpty else { + try? store.remove() + return } + try? store.write(profiles) } } diff --git a/apple/TablePro/Core/Storage/ExternalConnectionTrustStore.swift b/apple/TablePro/Core/Storage/ExternalConnectionTrustStore.swift index ae671d9f0d..f5d6e5cc99 100644 --- a/apple/TablePro/Core/Storage/ExternalConnectionTrustStore.swift +++ b/apple/TablePro/Core/Storage/ExternalConnectionTrustStore.swift @@ -24,7 +24,9 @@ internal final class ExternalConnectionTrustStore: ExternalConnectionTrustChecki internal static let shared = ExternalConnectionTrustStore() nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "ExternalConnectionTrustStore") - private static let storageKey = "com.TablePro.externalConnectionTrust.entries" + private static let storageKey = JSONDefaultsKey<[TrustedExternalConnection]>( + "com.TablePro.externalConnectionTrust.entries" + ) private let defaults: UserDefaults @@ -53,22 +55,18 @@ internal final class ExternalConnectionTrustStore: ExternalConnectionTrustChecki } internal func revokeAll() { - defaults.removeObject(forKey: Self.storageKey) + defaults.removeValue(for: Self.storageKey) } internal func entries() -> [TrustedExternalConnection] { - guard let data = defaults.data(forKey: Self.storageKey), - let decoded = try? JSONDecoder().decode([TrustedExternalConnection].self, from: data) - else { return [] } - return decoded.filter { $0.key.isLoopbackHost } + (defaults.read(Self.storageKey).value ?? []).filter { $0.key.isLoopbackHost } } private func save(_ entries: [TrustedExternalConnection]) { guard !entries.isEmpty else { - defaults.removeObject(forKey: Self.storageKey) + defaults.removeValue(for: Self.storageKey) return } - guard let data = try? JSONEncoder().encode(entries) else { return } - defaults.set(data, forKey: Self.storageKey) + try? defaults.write(entries, to: Self.storageKey) } } diff --git a/apple/TablePro/Core/Storage/FavoriteDatabasesStorage.swift b/apple/TablePro/Core/Storage/FavoriteDatabasesStorage.swift index 422335c8a3..47b52a1738 100644 --- a/apple/TablePro/Core/Storage/FavoriteDatabasesStorage.swift +++ b/apple/TablePro/Core/Storage/FavoriteDatabasesStorage.swift @@ -4,22 +4,18 @@ // import Foundation -import os import TableProSyncTransport extension Notification.Name { internal static let favoriteDatabasesDidChange = Notification.Name("FavoriteDatabasesDidChange") } -/// Every entry lives under one key rather than one key per connection, so a sync push can resolve a -/// dirty id back to its entry without knowing which connections exist, and so deleting a connection -/// leaves nothing behind to forget. `FavoriteTablesStorage` is the same shape. +// One key for every connection, so a sync push resolves a dirty id without knowing the connections. `FavoriteTablesStorage` is the same shape. @MainActor internal final class FavoriteDatabasesStorage { internal static let shared = FavoriteDatabasesStorage() - private static let logger = Logger(subsystem: "com.TablePro", category: "FavoriteDatabasesStorage") - private static let storageKey = "com.TablePro.favoriteDatabases" + private static let storageKey = JSONDefaultsKey>("com.TablePro.favoriteDatabases") private let defaults: UserDefaults private let syncTracker: SyncChangeTracker @@ -35,13 +31,7 @@ internal final class FavoriteDatabasesStorage { internal func loadFavorites() -> Set { if let cache { return cache } - guard let data = defaults.data(forKey: Self.storageKey), - let decoded = try? JSONDecoder().decode(Set.self, from: data) - else { - cache = [] - return [] - } - let valid = decoded.filter { !$0.database.isEmpty } + let valid = (defaults.read(Self.storageKey).value ?? []).filter { !$0.database.isEmpty } cache = valid return valid } @@ -105,9 +95,7 @@ internal final class FavoriteDatabasesStorage { } } - /// The composite id never includes the environment. A record keyed on a mutable payload is - /// orphaned the moment that payload changes, so re-tagging a database would leave the old - /// record behind and push a second one beside it. + // No environment in the id: re-tagging a database would orphan the old record and push a second one. nonisolated internal static func syncId(for entry: FavoriteDatabaseEntry) -> String { (entry.connectionId.uuidString + "|" + entry.database).sha256 } @@ -158,13 +146,9 @@ internal final class FavoriteDatabasesStorage { private func persist(_ favorites: Set) { cache = favorites guard !favorites.isEmpty else { - defaults.removeObject(forKey: Self.storageKey) + defaults.removeValue(for: Self.storageKey) return } - do { - defaults.set(try JSONEncoder().encode(favorites), forKey: Self.storageKey) - } catch { - Self.logger.error("Failed to encode favorite databases: \(error.publicLogShape, privacy: .public)") - } + try? defaults.write(favorites, to: Self.storageKey) } } diff --git a/apple/TablePro/Core/Storage/HighlightRuleStorage.swift b/apple/TablePro/Core/Storage/HighlightRuleStorage.swift index 21ef256822..be3cfb9fe6 100644 --- a/apple/TablePro/Core/Storage/HighlightRuleStorage.swift +++ b/apple/TablePro/Core/Storage/HighlightRuleStorage.swift @@ -20,12 +20,6 @@ final class HighlightRuleStorage: ObservableObject, TableScopedSettingsStore { private let storageDirectory: URL private var cache: [UUID: [String: [HighlightRule]]] = [:] - private let encoder: JSONEncoder = { - let encoder = JSONEncoder() - encoder.outputFormatting = [.sortedKeys] - return encoder - }() - private let decoder = JSONDecoder() init(storageDirectory: URL? = nil) { self.storageDirectory = storageDirectory ?? Self.resolvedStorageDirectory() @@ -98,7 +92,7 @@ final class HighlightRuleStorage: ObservableObject, TableScopedSettingsStore { guard !connectionIds.isEmpty else { return } for connectionId in connectionIds { cache[connectionId] = [:] - removeFile(at: fileURL(for: connectionId)) + try? file(for: connectionId).remove() removeFile(at: unreadableFileURL(for: connectionId)) } revision &+= 1 @@ -107,9 +101,9 @@ final class HighlightRuleStorage: ObservableObject, TableScopedSettingsStore { private func commit(_ entries: [String: [HighlightRule]], for connectionId: UUID) { cache[connectionId] = entries if entries.isEmpty { - removeFile(at: fileURL(for: connectionId)) + try? file(for: connectionId).remove() } else { - write(entries, for: connectionId) + try? file(for: connectionId).write(StoredRules(entries)) } revision &+= 1 } @@ -117,40 +111,18 @@ final class HighlightRuleStorage: ObservableObject, TableScopedSettingsStore { private func loadEntries(for connectionId: UUID) -> [String: [HighlightRule]] { if let cached = cache[connectionId] { return cached } - let url = fileURL(for: connectionId) - guard FileManager.default.fileExists(atPath: url.path) else { - cache[connectionId] = [:] - return [:] - } - - do { - let data = try Data(contentsOf: url) - let decoded = try decoder.decode([String: [LossyHighlightRule]].self, from: data) - let entries = decoded.compactMapValues { lossy -> [HighlightRule]? in - let rules = lossy.compactMap(\.rule) - return rules.isEmpty ? nil : rules - } - cache[connectionId] = entries - return entries - } catch { - Self.logger.error( - "Unreadable highlight rules for \(connectionId, privacy: .public): \(error.publicLogShape, privacy: .public)" - ) + let entries: [String: [HighlightRule]] + switch file(for: connectionId).read() { + case .missing: + entries = [:] + case .value(let stored): + entries = stored.entries + case .unreadable: preserveUnreadableFile(for: connectionId) - cache[connectionId] = [:] - return [:] - } - } - - private func write(_ entries: [String: [HighlightRule]], for connectionId: UUID) { - do { - let data = try encoder.encode(entries) - try data.write(to: fileURL(for: connectionId), options: .atomic) - } catch { - Self.logger.error( - "Failed to write highlight rules for \(connectionId, privacy: .public): \(error.publicLogShape, privacy: .public)" - ) + entries = [:] } + cache[connectionId] = entries + return entries } private func preserveUnreadableFile(for connectionId: UUID) { @@ -181,6 +153,10 @@ final class HighlightRuleStorage: ObservableObject, TableScopedSettingsStore { storageDirectory.appendingPathComponent("\(connectionId.uuidString).json") } + private func file(for connectionId: UUID) -> JSONFileStore { + JSONFileStore(url: fileURL(for: connectionId), coding: .sortedKeys) + } + private static func resolvedStorageDirectory() -> URL { AppStorageEnvironment.shared.applicationSupportRoot .appendingPathComponent("TablePro", isDirectory: true) @@ -188,6 +164,28 @@ final class HighlightRuleStorage: ObservableObject, TableScopedSettingsStore { } } +// Rules decode one by one, so one this build cannot read does not cost the rest, and a table left with none drops out. +private struct StoredRules: Codable { + let entries: [String: [HighlightRule]] + + init(_ entries: [String: [HighlightRule]]) { + self.entries = entries + } + + init(from decoder: Decoder) throws { + let decoded = try decoder.singleValueContainer().decode([String: [LossyHighlightRule]].self) + entries = decoded.compactMapValues { lossy -> [HighlightRule]? in + let rules = lossy.compactMap(\.rule) + return rules.isEmpty ? nil : rules + } + } + + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(entries) + } +} + private struct LossyHighlightRule: Decodable { let rule: HighlightRule? diff --git a/apple/TablePro/Core/Storage/HistoryPanelPreferencesStorage.swift b/apple/TablePro/Core/Storage/HistoryPanelPreferencesStorage.swift index f07377d7ab..83625123e5 100644 --- a/apple/TablePro/Core/Storage/HistoryPanelPreferencesStorage.swift +++ b/apple/TablePro/Core/Storage/HistoryPanelPreferencesStorage.swift @@ -1,5 +1,4 @@ import Foundation -import os struct HistoryPanelPreferences: Codable, Equatable, Sendable { var isVisible: Bool @@ -50,34 +49,19 @@ struct HistoryPanelPreferences: Codable, Equatable, Sendable { } enum HistoryPanelPreferencesStorage { - private static let logger = Logger(subsystem: "com.TablePro", category: "HistoryPanelPreferencesStorage") - - private static func key(for connectionId: UUID) -> String { - "HistoryPanel.\(connectionId.uuidString)" + private static func key(for connectionId: UUID) -> JSONDefaultsKey { + JSONDefaultsKey("HistoryPanel.\(connectionId.uuidString)") } static func load(for connectionId: UUID) -> HistoryPanelPreferences { - guard let data = AppStorageEnvironment.shared.defaults.data(forKey: key(for: connectionId)) else { - return .default - } - do { - return try JSONDecoder().decode(HistoryPanelPreferences.self, from: data) - } catch { - logger.error("Failed to decode history panel preferences: \(error.publicLogShape, privacy: .public)") - return .default - } + AppStorageEnvironment.shared.defaults.read(key(for: connectionId)).value ?? .default } static func save(_ preferences: HistoryPanelPreferences, for connectionId: UUID) { - do { - let data = try JSONEncoder().encode(preferences) - AppStorageEnvironment.shared.defaults.set(data, forKey: key(for: connectionId)) - } catch { - logger.error("Failed to encode history panel preferences: \(error.publicLogShape, privacy: .public)") - } + try? AppStorageEnvironment.shared.defaults.write(preferences, to: key(for: connectionId)) } static func remove(for connectionId: UUID) { - AppStorageEnvironment.shared.defaults.removeObject(forKey: key(for: connectionId)) + AppStorageEnvironment.shared.defaults.removeValue(for: key(for: connectionId)) } } diff --git a/apple/TablePro/Core/Storage/ImportColumnMappingStore.swift b/apple/TablePro/Core/Storage/ImportColumnMappingStore.swift index 744b0d19be..c5d0b388a3 100644 --- a/apple/TablePro/Core/Storage/ImportColumnMappingStore.swift +++ b/apple/TablePro/Core/Storage/ImportColumnMappingStore.swift @@ -5,8 +5,7 @@ import Foundation -/// Keyed by the table rather than the file, because the same export is downloaded again under new -/// names. Device-local, so it needs no CloudKit record type. +// Keyed by table, not file, since the same export comes back under new names. Device-local: no CloudKit record type. @MainActor internal final class ImportColumnMappingStore: TableScopedSettingsStore { static let shared = ImportColumnMappingStore() @@ -20,21 +19,21 @@ internal final class ImportColumnMappingStore: TableScopedSettingsStore { } func overrides(for scope: TableScope) -> [String: ImportMappingOverride] { - guard let data = store.dataValue(forKey: PreferenceKeys.importColumnMapping(scope).name), - let overrides = try? JSONDecoder().decode([String: ImportMappingOverride].self, from: data) else { - return [:] - } - return overrides + store.read(PreferenceKeys.importColumnMapping(scope)).value ?? [:] } func remember(_ overrides: [String: ImportMappingOverride], forFields fields: [String], in scope: TableScope) { let merged = ImportColumnMatcher.merging(overrides, forFields: fields, into: self.overrides(for: scope)) - let key = PreferenceKeys.importColumnMapping(scope).name - guard !merged.isEmpty, let data = try? JSONEncoder().encode(merged) else { - store.setDataValue(nil, forKey: key) + let key = PreferenceKeys.importColumnMapping(scope) + guard !merged.isEmpty else { + store.removeValue(for: key) return } - store.setDataValue(data, forKey: key) + do { + try store.write(merged, to: key) + } catch { + store.removeValue(for: key) + } } func renameTable(from oldScope: TableScope, to newScope: TableScope) { @@ -60,7 +59,7 @@ internal final class ImportColumnMappingStore: TableScopedSettingsStore { } func dropTable(_ scope: TableScope) { - store.setDataValue(nil, forKey: PreferenceKeys.importColumnMapping(scope).name) + store.removeValue(for: PreferenceKeys.importColumnMapping(scope)) } func dropContainer(connectionId: UUID, database: String, schema: String?) { diff --git a/apple/TablePro/Core/Storage/InspectorFieldHeightStore.swift b/apple/TablePro/Core/Storage/InspectorFieldHeightStore.swift index aef607926e..32864f177f 100644 --- a/apple/TablePro/Core/Storage/InspectorFieldHeightStore.swift +++ b/apple/TablePro/Core/Storage/InspectorFieldHeightStore.swift @@ -5,7 +5,6 @@ import Combine import Foundation -import os // Device-local. Keyed by column name alone, so a size holds on every row and in every result showing that column. @MainActor @@ -13,8 +12,7 @@ internal final class InspectorFieldHeightStore: ObservableObject { static let shared = InspectorFieldHeightStore() static let capacity = 200 - nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "InspectorFieldHeightStore") - private static let key = PreferenceKeys.rowInspectorFieldHeights.name + private static let key = PreferenceKeys.rowInspectorFieldHeights @Published private(set) var heights: [String: Double] = [:] // Least recently set first, so the oldest is dropped past `capacity`. @@ -48,7 +46,7 @@ internal final class InspectorFieldHeightStore: ObservableObject { func reload() { var loaded: [String: Double] = [:] var loadedOrder: [String] = [] - for entry in store.dataValue(forKey: Self.key).flatMap(Self.decode) ?? [] { + for entry in store.read(Self.key).value ?? [] { if loaded.updateValue(entry.height, forKey: entry.column) != nil { loadedOrder.removeAll { $0 == entry.column } } @@ -60,23 +58,10 @@ internal final class InspectorFieldHeightStore: ObservableObject { private func persist() { let entries = order.compactMap { column in heights[column].map { Entry(column: column, height: $0) } } - do { - store.setDataValue(try JSONEncoder().encode(entries), forKey: Self.key) - } catch { - Self.logger.error("Could not save field heights: \(error.publicLogShape, privacy: .public)") - } - } - - private static func decode(_ data: Data) -> [Entry]? { - do { - return try JSONDecoder().decode([Entry].self, from: data) - } catch { - logger.error("Discarding unreadable field heights: \(error.publicLogShape, privacy: .public)") - return nil - } + try? store.write(entries, to: Self.key) } - private struct Entry: Codable { + struct Entry: Codable { let column: String let height: Double } diff --git a/apple/TablePro/Core/Storage/LastOpenConnectionsStorage.swift b/apple/TablePro/Core/Storage/LastOpenConnectionsStorage.swift index 27b2499100..1809555f1c 100644 --- a/apple/TablePro/Core/Storage/LastOpenConnectionsStorage.swift +++ b/apple/TablePro/Core/Storage/LastOpenConnectionsStorage.swift @@ -2,24 +2,18 @@ // LastOpenConnectionsStorage.swift // TablePro // -// Records which connections had open windows at last quit so the -// "Reopen Last Session" startup behavior can recover after a crash, -// where AppKit's window-restoration archive is never written. -// import Foundation -import os +// Reopen Last Session reads this after a crash too, when AppKit never wrote its window-restoration archive. @MainActor final class LastOpenConnectionsStorage { static let shared = LastOpenConnectionsStorage() - nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "LastOpenConnections") - // The legacy file keeps the [UUID] format older builds read, holding only connections that // reconnect, so an older build never dials one the user canceled. - private let legacyURL: URL - private let sessionURL: URL + private let legacyFile: JSONFileStore<[UUID]> + private let sessionFile: JSONFileStore private var isSealed = false private convenience init() { @@ -29,8 +23,8 @@ final class LastOpenConnectionsStorage { init(directory: URL) { try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - legacyURL = directory.appendingPathComponent("LastOpenConnections.json") - sessionURL = directory.appendingPathComponent("LastSession.json") + legacyFile = JSONFileStore(url: directory.appendingPathComponent("LastOpenConnections.json")) + sessionFile = JSONFileStore(url: directory.appendingPathComponent("LastSession.json")) } // A missing legacy list means an older build removed it, so this never leaves the session alone: @@ -43,31 +37,31 @@ final class LastOpenConnectionsStorage { return } let reconnecting = session.reconnectingIds - let hasLegacy = FileManager.default.fileExists(atPath: legacyURL.path) + let hasLegacy = legacyFile.exists if !hasLegacy { - write(reconnecting, to: legacyURL) + try? legacyFile.write(reconnecting) } - write(session, to: sessionURL) + try? sessionFile.write(session) if hasLegacy { - write(reconnecting, to: legacyURL) + try? legacyFile.write(reconnecting) } } // An older build rewrites only the legacy file, so when the two disagree the newer one is current. func load() -> LastSession { - guard let legacy = read([UUID].self, from: legacyURL) else { return .empty } + guard let legacy = legacyFile.read().value else { return .empty } let legacySession = LastSession( connections: legacy.map { LastSession.Connection(id: $0, reconnects: true) }, shownConnectionId: nil ) - guard let session = read(LastSession.self, from: sessionURL) else { return legacySession } + guard let session = sessionFile.read().value else { return legacySession } guard session.reconnectingIds != legacy else { return session } - return modificationDate(of: legacyURL) > modificationDate(of: sessionURL) ? legacySession : session + return modificationDate(of: legacyFile.url) > modificationDate(of: sessionFile.url) ? legacySession : session } func clear() { - remove(legacyURL) - remove(sessionURL) + try? legacyFile.remove() + try? sessionFile.remove() } // The quit save is the last word: AppKit closes the windows after it, and no coordinator may @@ -76,32 +70,8 @@ final class LastOpenConnectionsStorage { isSealed = true } - private func write(_ value: some Encodable, to url: URL) { - do { - let data = try JSONEncoder().encode(value) - try data.write(to: url, options: .atomic) - } catch { - Self.logger.error("Failed to save last open connections: \(error.publicLogShape, privacy: .public)") - } - } - - private func read(_ type: Value.Type, from url: URL) -> Value? { - guard FileManager.default.fileExists(atPath: url.path) else { return nil } - do { - return try JSONDecoder().decode(type, from: Data(contentsOf: url)) - } catch { - Self.logger.error("Failed to load last open connections: \(error.publicLogShape, privacy: .public)") - return nil - } - } - private func modificationDate(of url: URL) -> Date { let attributes = try? FileManager.default.attributesOfItem(atPath: url.path) return attributes?[.modificationDate] as? Date ?? .distantPast } - - private func remove(_ url: URL) { - guard FileManager.default.fileExists(atPath: url.path) else { return } - try? FileManager.default.removeItem(at: url) - } } diff --git a/apple/TablePro/Core/Storage/LoadableExtensionApprovalStore.swift b/apple/TablePro/Core/Storage/LoadableExtensionApprovalStore.swift index 46ea4b7824..30142c8ca2 100644 --- a/apple/TablePro/Core/Storage/LoadableExtensionApprovalStore.swift +++ b/apple/TablePro/Core/Storage/LoadableExtensionApprovalStore.swift @@ -13,21 +13,15 @@ internal protocol LoadableExtensionApproving { func approve(_ extensions: [LoadableExtension], for connectionId: UUID) } -/// The SQLite extensions a person has agreed to load on this Mac, per connection. -/// -/// An extension is native code that runs inside TablePro, and a connection's list travels through -/// iCloud, exports, `tablepro://` links, linked folders and the team library. So the list alone -/// never authorizes a load: an entry loads only once it was added in the connection form on this -/// Mac or confirmed in the prompt a connect shows. Approval is keyed to the connection as well as -/// the file, so trusting a library for one connection does not quietly approve it for another one -/// that arrives later naming the same path. It is never synced, which is what makes a list that -/// arrived from elsewhere ask first. +// Never synced and keyed per connection: a list that arrived from iCloud, an export, a link or the team library asks before it loads. @MainActor internal final class LoadableExtensionApprovalStore: LoadableExtensionApproving { internal static let shared = LoadableExtensionApprovalStore() nonisolated private static let logger = Logger(subsystem: "com.TablePro", category: "LoadableExtensionApprovalStore") - private static let storageKey = "com.TablePro.loadableExtensionApprovals" + private static let storageKey = JSONDefaultsKey<[String: Set]>( + "com.TablePro.loadableExtensionApprovals" + ) private let defaults: UserDefaults @@ -68,22 +62,15 @@ internal final class LoadableExtensionApprovalStore: LoadableExtensionApproving } private func approvals() -> [String: Set] { - guard let data = defaults.data(forKey: Self.storageKey), - let decoded = try? JSONDecoder().decode([String: Set].self, from: data) - else { return [:] } - return decoded + defaults.read(Self.storageKey).value ?? [:] } private func save(_ approvals: [String: Set]) { let kept = approvals.filter { !$0.value.isEmpty } guard !kept.isEmpty else { - defaults.removeObject(forKey: Self.storageKey) + defaults.removeValue(for: Self.storageKey) return } - guard let data = try? JSONEncoder().encode(kept) else { - Self.logger.error("Could not encode SQLite extension approvals") - return - } - defaults.set(data, forKey: Self.storageKey) + try? defaults.write(kept, to: Self.storageKey) } } diff --git a/apple/TablePro/Core/Storage/MCPApprovalStore.swift b/apple/TablePro/Core/Storage/MCPApprovalStore.swift index 4b4c7c4e8d..517ecc480f 100644 --- a/apple/TablePro/Core/Storage/MCPApprovalStore.swift +++ b/apple/TablePro/Core/Storage/MCPApprovalStore.swift @@ -26,17 +26,13 @@ protocol MCPApprovalStoring: Sendable { func record(_ denial: MCPConnectionDenial) async } -/// Durable, revocable MCP connection grants, device-local. -/// -/// A grant is a security decision the user made, so it outlives the session that earned it: the -/// server is torn down and rebuilt whenever the port changes, and the app is relaunched far more -/// often than that. It is never synced, for the same reason MCP tokens are not. +// Device-local and never synced, like MCP tokens. A grant outlives the session because the server is rebuilt on every port change. actor MCPApprovalStore: MCPApprovalStoring { static let shared = MCPApprovalStore() private static let logger = Logger(subsystem: "com.TablePro", category: "MCPApprovalStore") - private static let grantsKey = "com.TablePro.mcp.connectionGrants" - private static let denialsKey = "com.TablePro.mcp.connectionDenials" + private static let grantsKey = JSONDefaultsKey<[MCPConnectionGrant]>("com.TablePro.mcp.connectionGrants") + private static let denialsKey = JSONDefaultsKey<[MCPConnectionDenial]>("com.TablePro.mcp.connectionDenials") private let defaults: UserDefaults @@ -45,61 +41,53 @@ actor MCPApprovalStore: MCPApprovalStoring { } func grants() -> [MCPConnectionGrant] { - decode([MCPConnectionGrant].self, forKey: Self.grantsKey) + load(Self.grantsKey) } func record(_ grant: MCPConnectionGrant) { var updated = grants().filter { $0.id != grant.id } updated.append(grant) - encode(updated, forKey: Self.grantsKey) + save(updated, to: Self.grantsKey) Self.logger.info("Remembered an MCP connection grant for \(grant.subject, privacy: .public)") } func revoke(subject: String, connectionId: UUID) { - encode( + save( grants().filter { !($0.subject == subject && $0.connectionId == connectionId) }, - forKey: Self.grantsKey + to: Self.grantsKey ) } func revokeAll(subject: String) { - encode(grants().filter { $0.subject != subject }, forKey: Self.grantsKey) + save(grants().filter { $0.subject != subject }, to: Self.grantsKey) } func revokeEverything() { - defaults.removeObject(forKey: Self.grantsKey) + defaults.removeValue(for: Self.grantsKey) } func denial(subject: String, connectionId: UUID, now: Date) -> Date? { - let surviving = decode([MCPConnectionDenial].self, forKey: Self.denialsKey) - .filter { $0.expiresAt > now } - encode(surviving, forKey: Self.denialsKey) + let surviving = load(Self.denialsKey).filter { $0.expiresAt > now } + save(surviving, to: Self.denialsKey) return surviving.first { $0.subject == subject && $0.connectionId == connectionId }?.expiresAt } func record(_ denial: MCPConnectionDenial) { - var updated = decode([MCPConnectionDenial].self, forKey: Self.denialsKey) + var updated = load(Self.denialsKey) .filter { !($0.subject == denial.subject && $0.connectionId == denial.connectionId) } updated.append(denial) - encode(updated, forKey: Self.denialsKey) + save(updated, to: Self.denialsKey) } - private func decode(_ type: [T].Type, forKey key: String) -> [T] { - guard let data = defaults.data(forKey: key), - let decoded = try? JSONDecoder().decode(type, from: data) - else { return [] } - return decoded + private func load(_ key: JSONDefaultsKey<[Element]>) -> [Element] { + defaults.read(key).value ?? [] } - private func encode(_ value: some Encodable & Collection, forKey key: String) { - guard !value.isEmpty else { - defaults.removeObject(forKey: key) + private func save(_ elements: [Element], to key: JSONDefaultsKey<[Element]>) { + guard !elements.isEmpty else { + defaults.removeValue(for: key) return } - guard let data = try? JSONEncoder().encode(value) else { - Self.logger.error("Failed to encode MCP approvals for \(key, privacy: .public)") - return - } - defaults.set(data, forKey: key) + try? defaults.write(elements, to: key) } } diff --git a/apple/TablePro/Core/Storage/Preferences/CodableListPreferenceStore.swift b/apple/TablePro/Core/Storage/Preferences/CodableListPreferenceStore.swift index cca54d2e14..acb02729c0 100644 --- a/apple/TablePro/Core/Storage/Preferences/CodableListPreferenceStore.swift +++ b/apple/TablePro/Core/Storage/Preferences/CodableListPreferenceStore.swift @@ -4,38 +4,22 @@ // import Foundation -import os final class CodableListPreferenceStore: @unchecked Sendable { - private static var logger: Logger { - Logger(subsystem: "com.TablePro", category: "CodableListPreferenceStore") - } - - private let key: DefaultsKey<[Element]> + private let key: JSONDefaultsKey<[Element]> private let store: KeyValueStore - init(key: DefaultsKey<[Element]>, store: KeyValueStore) { + init(key: JSONDefaultsKey<[Element]>, store: KeyValueStore) { self.key = key self.store = store } func load() -> [Element] { - guard let data = store.dataValue(forKey: key.name) else { return [] } - do { - return try JSONDecoder().decode([Element].self, from: data) - } catch { - Self.logger.error("Failed to decode \(self.key.name, privacy: .public): \(error.publicLogShape, privacy: .public)") - return [] - } + store.read(key).value ?? [] } func save(_ elements: [Element]) { - do { - let data = try JSONEncoder().encode(elements) - store.setDataValue(data, forKey: key.name) - } catch { - Self.logger.error("Failed to encode \(self.key.name, privacy: .public): \(error.publicLogShape, privacy: .public)") - } + try? store.write(elements, to: key) } func add(_ element: Element) { diff --git a/apple/TablePro/Core/Storage/Preferences/JSONDefaultsKey.swift b/apple/TablePro/Core/Storage/Preferences/JSONDefaultsKey.swift new file mode 100644 index 0000000000..15ace949cd --- /dev/null +++ b/apple/TablePro/Core/Storage/Preferences/JSONDefaultsKey.swift @@ -0,0 +1,42 @@ +// +// JSONDefaultsKey.swift +// TablePro +// + +import Foundation + +// A defaults entry holding one JSON-encoded value. Plain property list values keep `DefaultsKey`. +internal struct JSONDefaultsKey: Sendable { + internal let name: String + internal let coding: StoreCoding + + internal init(_ name: String, coding: StoreCoding = .plain) { + self.name = name + self.coding = coding + } +} + +internal extension KeyValueStore { + func read(_ key: JSONDefaultsKey) -> StoreRead { + guard let data = dataValue(forKey: key.name) else { return .missing } + do { + return .value(try key.coding.decode(Value.self, from: data)) + } catch { + StoreLog.unreadable(key.name, error) + return .unreadable(error) + } + } + + func write(_ value: Value, to key: JSONDefaultsKey) throws { + do { + setDataValue(try key.coding.encode(value), forKey: key.name) + } catch { + StoreLog.unwritable(key.name, error) + throw error + } + } + + func removeValue(for key: JSONDefaultsKey) { + setDataValue(nil, forKey: key.name) + } +} diff --git a/apple/TablePro/Core/Storage/Preferences/JSONFileStore.swift b/apple/TablePro/Core/Storage/Preferences/JSONFileStore.swift new file mode 100644 index 0000000000..98a1f1138a --- /dev/null +++ b/apple/TablePro/Core/Storage/Preferences/JSONFileStore.swift @@ -0,0 +1,78 @@ +// +// JSONFileStore.swift +// TablePro +// + +import Foundation + +// One JSON-encoded value in one file. Files with an integrity tag use `IntegrityStampedFileStore`. +internal struct JSONFileStore: Sendable { + internal let url: URL + internal let coding: StoreCoding + internal let writingOptions: Data.WritingOptions + + internal init(url: URL, coding: StoreCoding = .plain, writingOptions: Data.WritingOptions = .atomic) { + self.url = url + self.coding = coding + self.writingOptions = writingOptions + } + + private var name: String { url.lastPathComponent } + + internal var exists: Bool { + FileManager.default.fileExists(atPath: url.path) + } + + internal func read() -> StoreRead where Value: Decodable { + let data: Data + do { + data = try Data(contentsOf: url) + } catch CocoaError.fileReadNoSuchFile { + return .missing + } catch { + StoreLog.unreadable(name, error) + return .unreadable(error) + } + do { + return .value(try coding.decode(Value.self, from: data)) + } catch { + StoreLog.unreadable(name, error) + return .unreadable(error) + } + } + + internal func write(_ value: Value) throws where Value: Encodable { + let data: Data + do { + data = try coding.encode(value) + } catch { + StoreLog.unwritable(name, error) + throw error + } + try write(encoded: data) + } + + // For a caller that already encoded the value with `coding`, such as one checking its size first. + internal func write(encoded data: Data) throws { + do { + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), withIntermediateDirectories: true + ) + try data.write(to: url, options: writingOptions) + } catch { + StoreLog.unwritable(name, error) + throw error + } + } + + internal func remove() throws { + do { + try FileManager.default.removeItem(at: url) + } catch CocoaError.fileNoSuchFile { + return + } catch { + StoreLog.unwritable(name, error) + throw error + } + } +} diff --git a/apple/TablePro/Core/Storage/Preferences/PreferenceKeys.swift b/apple/TablePro/Core/Storage/Preferences/PreferenceKeys.swift index d8e62759b0..730bec286d 100644 --- a/apple/TablePro/Core/Storage/Preferences/PreferenceKeys.swift +++ b/apple/TablePro/Core/Storage/Preferences/PreferenceKeys.swift @@ -1,30 +1,30 @@ import Foundation +import TableProConnectionLibrary enum PreferenceKeys { - static let linkedFolders = DefaultsKey<[LinkedFolder]>("com.TablePro.linkedFolders") - static let linkedSQLFolders = DefaultsKey<[LinkedSQLFolder]>("com.TablePro.linkedSQLFolders") + static let linkedFolders = JSONDefaultsKey<[LinkedFolder]>("com.TablePro.linkedFolders") + static let linkedSQLFolders = JSONDefaultsKey<[LinkedSQLFolder]>("com.TablePro.linkedSQLFolders") static let selectedSettingsPane = DefaultsKey("com.TablePro.settings.selectedPane") - static let rowInspectorFieldHeights = DefaultsKey("com.TablePro.rightSidebar.fieldHeights") + static let rowInspectorFieldHeights = JSONDefaultsKey<[InspectorFieldHeightStore.Entry]>("com.TablePro.rightSidebar.fieldHeights") // Text or Map, as the field's picker last left it. Device-local, like the heights beside it. static let rowInspectorGeometryFieldMode = DefaultsKey("com.TablePro.rightSidebar.geometryFieldMode") - static let workspaceRailOrder = DefaultsKey<[WorkspaceID]>("com.TablePro.workspaceRail.order") + static let workspaceRailOrder = JSONDefaultsKey<[WorkspaceID]>("com.TablePro.workspaceRail.order") static let queryPlanRawFontSize = DefaultsKey("com.TablePro.queryPlan.rawFontSize") static let queryPlanBarMetric = DefaultsKey("com.TablePro.queryPlan.barMetric") static let lastBackupDirectory = DefaultsKey("com.TablePro.backup.lastDirectory") - /// The newest build this Mac has run, for the Welcome window's What's New link. Device-local: it - /// records what has been shown here, not a preference, so it must not sync to another Mac. + // Device-local: what What's New has shown on this Mac, so it never syncs. static let lastSeenAppBuild = DefaultsKey("com.TablePro.welcome.lastSeenAppBuild") - /// What a build before `lastSeenAppBuild` recorded instead, read once to carry it over. + // What a build before `lastSeenAppBuild` recorded instead, read once to carry it over. static let lastSeenAppVersion = DefaultsKey("com.TablePro.welcome.lastSeenAppVersion") - /// Device-local: the sign-in window shows once per Mac, whatever another Mac has seen. + // Device-local: the sign-in window shows once per Mac, whatever another Mac has seen. static let signInPromptShown = DefaultsKey("com.TablePro.account.signInPromptShown") static let connectionListSortMode = DefaultsKey("com.TablePro.connectionList.sortMode") static let connectionListFavoritesOrder = DefaultsKey<[String]>("com.TablePro.connectionList.favoritesOrder") static let connectionListShowsRecent = DefaultsKey("com.TablePro.connectionList.showsRecent") - static let recentConnections = DefaultsKey("com.TablePro.connectionList.recentConnections") - /// Device-local, and in the standard domain so a configuration profile can pin it. + static let recentConnections = JSONDefaultsKey("com.TablePro.connectionList.recentConnections") + // Device-local, and in the standard domain so a configuration profile can pin it. static let receivesBetaUpdates = DefaultsKey("com.TablePro.updates.receivesBetaUpdates") - /// Set by Relaunch to Update and cleared by the next launch, which reopens the last session once. + // Set by Relaunch to Update and cleared by the next launch, which reopens the last session once. static let reopenSessionAfterRelaunch = DefaultsKey("com.TablePro.updates.reopenSessionAfterRelaunch") // Device-local: the highest plugin manifest serial accepted here, so an older signed manifest is refused. static let pluginRegistrySerial = DefaultsKey("com.TablePro.plugins.registrySerial") @@ -57,27 +57,27 @@ enum PreferenceKeys { static let tableFoldersPrefix = "com.TablePro.tableFolders." static let rowGenerationPrefix = "com.TablePro.rowGeneration." - static func columnDisplayFormats(_ scope: TableScope) -> DefaultsKey<[String: ValueDisplayFormat]> { - DefaultsKey(columnDisplayFormatsPrefix + scope.storageComponent) + static func columnDisplayFormats(_ scope: TableScope) -> JSONDefaultsKey<[String: String]> { + JSONDefaultsKey(columnDisplayFormatsPrefix + scope.storageComponent) } - static func recentTables(connectionId: UUID) -> DefaultsKey<[RecentTableEntry]> { - DefaultsKey("com.TablePro.recentTables." + connectionId.uuidString) + static func recentTables(connectionId: UUID) -> JSONDefaultsKey<[RecentTableEntry]> { + JSONDefaultsKey("com.TablePro.recentTables." + connectionId.uuidString) } static func foreignKeyLabelColumn(_ scope: TableScope) -> DefaultsKey { DefaultsKey(foreignKeyLabelColumnPrefix + scope.storageComponent) } - static func importColumnMapping(_ scope: TableScope) -> DefaultsKey<[String: ImportMappingOverride]> { - DefaultsKey(importColumnMappingPrefix + scope.storageComponent) + static func importColumnMapping(_ scope: TableScope) -> JSONDefaultsKey<[String: ImportMappingOverride]> { + JSONDefaultsKey(importColumnMappingPrefix + scope.storageComponent) } - static func rowGeneration(_ scope: TableScope) -> DefaultsKey { - DefaultsKey(rowGenerationPrefix + scope.storageComponent) + static func rowGeneration(_ scope: TableScope) -> JSONDefaultsKey { + JSONDefaultsKey(rowGenerationPrefix + scope.storageComponent) } - static func tableFolders(connectionId: UUID) -> DefaultsKey { - DefaultsKey(tableFoldersPrefix + connectionId.uuidString) + static func tableFolders(connectionId: UUID) -> JSONDefaultsKey { + JSONDefaultsKey(tableFoldersPrefix + connectionId.uuidString) } } diff --git a/apple/TablePro/Core/Storage/Preferences/StoreRead.swift b/apple/TablePro/Core/Storage/Preferences/StoreRead.swift new file mode 100644 index 0000000000..1cf0634946 --- /dev/null +++ b/apple/TablePro/Core/Storage/Preferences/StoreRead.swift @@ -0,0 +1,89 @@ +// +// StoreRead.swift +// TablePro +// + +import Foundation +import os + +// What a stored value read back as. Missing and unreadable differ: a store must not write over data it could not read. +internal enum StoreRead { + case missing + case value(Value) + case unreadable(any Error) + + internal var value: Value? { + if case .value(let value) = self { return value } + return nil + } + + internal var isUnreadable: Bool { + if case .unreadable = self { return true } + return false + } + + internal func map(_ transform: (Value) -> Mapped) -> StoreRead { + switch self { + case .missing: return .missing + case .value(let value): return .value(transform(value)) + case .unreadable(let error): return .unreadable(error) + } + } +} + +// The JSON shape a store writes. Changing it for an existing store breaks the previous stable's read. +internal struct StoreCoding: @unchecked Sendable { + internal let encoder: JSONEncoder + internal let decoder: JSONDecoder + + internal static let plain = StoreCoding(encoder: JSONEncoder(), decoder: JSONDecoder()) + + internal static let sortedKeys: StoreCoding = { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return StoreCoding(encoder: encoder, decoder: JSONDecoder()) + }() + + internal static let prettyISO8601: StoreCoding = { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + return StoreCoding(encoder: encoder, decoder: decoder) + }() + + internal func encode(_ value: some Encodable) throws -> Data { + try encoder.encode(value) + } + + internal func decode(_ type: Value.Type, from data: Data) throws -> Value { + try decoder.decode(type, from: data) + } +} + +internal enum StoreLog { + static let logger = Logger(subsystem: "com.TablePro", category: "Store") + + static func unreadable(_ name: String, _ error: any Error) { + logger.error( + "Unreadable \(publicPart(of: name), privacy: .public) (\(name, privacy: .private)): \(error.publicLogShape, privacy: .public)" + ) + } + + static func unwritable(_ name: String, _ error: any Error) { + logger.error( + "Could not save \(publicPart(of: name), privacy: .public) (\(name, privacy: .private)): \(error.publicLogShape, privacy: .public)" + ) + } + + // A key or file name continues past a connection id with database, schema and table names, which are user data. + static func publicPart(of name: String) -> String { + let components = name.split(separator: ".", omittingEmptySubsequences: false) + let scoped = components.firstIndex { component in + UUID(uuidString: String(component).removingPercentEncoding ?? String(component)) != nil + } + guard let scoped else { return name } + return (components[.. String { - "QueryInsights.\(connectionId.uuidString)" + private static func key(for connectionId: UUID) -> JSONDefaultsKey { + JSONDefaultsKey("QueryInsights.\(connectionId.uuidString)") } static func load(for connectionId: UUID) -> QueryInsightsPreferences { - guard let data = AppStorageEnvironment.shared.defaults.data(forKey: key(for: connectionId)) else { - return .default - } - do { - return try JSONDecoder().decode(QueryInsightsPreferences.self, from: data) - } catch { - logger.error("Failed to decode query insights preferences: \(error.publicLogShape, privacy: .public)") - return .default - } + AppStorageEnvironment.shared.defaults.read(key(for: connectionId)).value ?? .default } static func save(_ preferences: QueryInsightsPreferences, for connectionId: UUID) { - do { - let data = try JSONEncoder().encode(preferences) - AppStorageEnvironment.shared.defaults.set(data, forKey: key(for: connectionId)) - } catch { - logger.error("Failed to encode query insights preferences: \(error.publicLogShape, privacy: .public)") - } + try? AppStorageEnvironment.shared.defaults.write(preferences, to: key(for: connectionId)) } static func remove(for connectionId: UUID) { - AppStorageEnvironment.shared.defaults.removeObject(forKey: key(for: connectionId)) + AppStorageEnvironment.shared.defaults.removeValue(for: key(for: connectionId)) } } diff --git a/apple/TablePro/Core/Storage/RecentTablesStore.swift b/apple/TablePro/Core/Storage/RecentTablesStore.swift index c62a48d945..62b053cb5e 100644 --- a/apple/TablePro/Core/Storage/RecentTablesStore.swift +++ b/apple/TablePro/Core/Storage/RecentTablesStore.swift @@ -7,11 +7,7 @@ struct RecentTableEntry: Codable, Equatable, Identifiable { let name: String let isView: Bool - /// The kind the object was opened as, as a `TableInfo.TableType` raw value. - /// - /// Nil for an entry written before the kind was recorded, and for an open whose caller knew - /// only whether the object was a view. Kept as a string rather than the enum so an entry - /// naming a kind this build has dropped decodes to nil instead of failing the whole file. + // A raw value, not the enum, so a kind this build has dropped reads as nil instead of failing the whole list. let objectType: String? let openedAt: Date @@ -27,9 +23,7 @@ struct RecentTableEntry: Codable, Equatable, Identifiable { var isUnqualified: Bool { schema?.isEmpty ?? true } - /// An entry recorded before the schema was known names the same table as a qualified one, but - /// opens that name in whichever schema is browsed when it is clicked. Only a qualified entry - /// replaces an unqualified one: the reverse would trade a known schema for a guess. + // Only a qualified entry replaces an unqualified one: the reverse would trade a known schema for a guess. func supersedes(_ other: RecentTableEntry) -> Bool { !isUnqualified && other.isUnqualified && other.scopeKey == scopeKey && other.name == name } @@ -38,10 +32,7 @@ struct RecentTableEntry: Codable, Equatable, Identifiable { TableInfo(name: name, type: resolvedType, rowCount: nil, schema: schema) } - /// `isView` alone cannot say what an object is, only that it is not a table: a MariaDB sequence - /// recorded through it came back as a view, so the Recent row offered Drop View and issued - /// `DROP VIEW`, which fails with ERROR 4092 on the sequence the tree row drops correctly. - /// An entry that predates the kind still resolves the way it always did. + // `isView` alone turned a MariaDB sequence into a view, so its Recent row issued a failing `DROP VIEW`. private var resolvedType: TableInfo.TableType { if let objectType, let type = TableInfo.TableType(rawValue: objectType) { return type } return isView ? .view : .table @@ -68,23 +59,25 @@ final class RecentTablesStore { } func entries(connectionId: UUID) -> [RecentTableEntry] { - if let data = defaults.data(forKey: PreferenceKeys.recentTables(connectionId: connectionId).name) { - return (try? JSONDecoder().decode([RecentTableEntry].self, from: data)) ?? [] + switch defaults.read(PreferenceKeys.recentTables(connectionId: connectionId)) { + case .missing: return migrateLegacy(connectionId: connectionId) + case .value(let entries): return entries + case .unreadable: return [] } - return migrateLegacy(connectionId: connectionId) } private func migrateLegacy(connectionId: UUID) -> [RecentTableEntry] { - let legacyKey = legacyKeyPrefix + connectionId.uuidString - guard let data = defaults.data(forKey: legacyKey), - let entries = try? JSONDecoder().decode([RecentTableEntry].self, from: data) else { - return [] - } + let key = legacyKey(for: connectionId) + guard let entries = defaults.read(key).value else { return [] } persist(entries, connectionId: connectionId) - defaults.removeObject(forKey: legacyKey) + defaults.removeValue(for: key) return entries } + private func legacyKey(for connectionId: UUID) -> JSONDefaultsKey<[RecentTableEntry]> { + JSONDefaultsKey(legacyKeyPrefix + connectionId.uuidString) + } + @discardableResult func record( connectionId: UUID, @@ -119,9 +112,7 @@ final class RecentTablesStore { return updated } - /// Drops the entries inside one schema, for a schema that no longer exists. Dropping the whole - /// database's entries would take the sibling schemas with it, and leaving them is what made a - /// Recent row open a tab whose query failed with "relation does not exist". + // For a schema that no longer exists, whose entries otherwise open tabs failing with "relation does not exist". @discardableResult func clear(connectionId: UUID, database: String?, schema: String) -> [RecentTableEntry] { let updated = entries(connectionId: connectionId).filter { @@ -131,9 +122,7 @@ final class RecentTablesStore { return updated } - /// A renamed table keeps its position rather than being dropped and re-added, which would look - /// like the user had just opened it. Any stale entry already sitting on the new name is removed - /// first: two entries with one id map to a single cached node and the outline draws neither. + // A stale entry on the new name goes first: two entries with one id share a node and the outline draws neither. func rename(connectionId: UUID, entry: RecentTableEntry, to newName: String) -> [RecentTableEntry] { mutate(connectionId: connectionId) { entries in guard let index = entries.firstIndex(where: { $0.id == entry.id }) else { return false } @@ -182,8 +171,6 @@ final class RecentTablesStore { } } - /// The entry takes the schema where it stands, keeping its position and the time it was opened, - /// rather than being recorded again as if the user had just opened it. func resolveSchema( connectionId: UUID, database: String?, @@ -203,9 +190,7 @@ final class RecentTablesStore { } } - /// Reads, mutates and persists in one place, so a rename lands on disk whether or not the - /// Recent section is on screen. The live list is empty while Show Recent Tables is off, and - /// renaming only that left a dead entry to reappear under the old name when it came back on. + // Persists whether or not Recent is on screen, so a rename made while it is off leaves no dead entry. private func mutate( connectionId: UUID, _ body: (inout [RecentTableEntry]) -> Bool @@ -224,8 +209,8 @@ final class RecentTablesStore { } func removeEntries(for connectionId: UUID) { - defaults.removeObject(forKey: PreferenceKeys.recentTables(connectionId: connectionId).name) - defaults.removeObject(forKey: legacyKeyPrefix + connectionId.uuidString) + defaults.removeValue(for: PreferenceKeys.recentTables(connectionId: connectionId)) + defaults.removeValue(for: legacyKey(for: connectionId)) } static func merged(_ entry: RecentTableEntry, into existing: [RecentTableEntry]) -> [RecentTableEntry] { @@ -241,7 +226,6 @@ final class RecentTablesStore { } private func persist(_ entries: [RecentTableEntry], connectionId: UUID) { - guard let data = try? JSONEncoder().encode(entries) else { return } - defaults.set(data, forKey: PreferenceKeys.recentTables(connectionId: connectionId).name) + try? defaults.write(entries, to: PreferenceKeys.recentTables(connectionId: connectionId)) } } diff --git a/apple/TablePro/Core/Storage/RecentlyClosedTabStore.swift b/apple/TablePro/Core/Storage/RecentlyClosedTabStore.swift index 1e1af6db52..a41e21e021 100644 --- a/apple/TablePro/Core/Storage/RecentlyClosedTabStore.swift +++ b/apple/TablePro/Core/Storage/RecentlyClosedTabStore.swift @@ -39,10 +39,7 @@ internal extension RecentlyClosedTabEntry { private static let previewLength = 48 } -/// Durable history of recently closed tabs, deliberately independent of `TabDiskActor`. -/// `TabDiskActor` answers "what is open right now" and is recomputed from the surviving -/// windows on every save, so a closed tab necessarily falls out of it. This store is the -/// append-and-prune log that lets a closed tab come back. +// Independent of `TabDiskActor`, which is recomputed from the surviving windows on every save and so drops a closed tab. @MainActor internal final class RecentlyClosedTabStore: ObservableObject { internal static let shared = RecentlyClosedTabStore() @@ -55,11 +52,13 @@ internal final class RecentlyClosedTabStore: ObservableObject { @Published internal private(set) var entries: [RecentlyClosedTabEntry] = [] private let directory: URL + private let stateFile: JSONFileStore internal init(directory: URL = RecentlyClosedTabStore.defaultDirectory()) { self.directory = directory + stateFile = JSONFileStore(url: directory.appendingPathComponent("entries.json")) createDirectories() - entries = Self.decodeEntries(at: Self.stateFileURL(in: directory)) + entries = stateFile.read().value?.entries ?? [] prune() persist() } @@ -80,12 +79,7 @@ internal final class RecentlyClosedTabStore: ObservableObject { entries.first } - /// The entry with any overflow text folded back into the tab, so the caller holds everything - /// needed to rebuild the tab without touching disk again. - /// - /// Reading removes nothing. Opening the tab can still fail or wait on a connect, and an entry - /// taken out before the tab is on screen is a closed tab lost for good; `discard(id:)` is the - /// caller's to call once it is shown. + // Removes nothing: opening the tab can still fail or wait on a connect, so the caller discards it once shown. internal func restorableEntry(id: UUID) -> RecentlyClosedTabEntry? { guard var entry = entries.first(where: { $0.id == id }) else { return nil } if let overflow = overflowText(for: entry) { @@ -168,9 +162,7 @@ internal final class RecentlyClosedTabStore: ObservableObject { // MARK: - Overflow Files - /// A query above `maxPersistableQuerySize` is blanked by `toPersistedTab()` to keep the - /// tab-state JSON small. A recovery entry cannot afford that, so the full text goes to a - /// sidecar file instead of being silently truncated. + // `toPersistedTab()` blanks a query above `maxPersistableQuerySize`, so the full text goes to a sidecar file. private func writeOverflow(_ query: String, fileName: String) -> Bool { do { try query.write(to: overflowDirectory.appendingPathComponent(fileName), atomically: true, encoding: .utf8) @@ -206,24 +198,7 @@ internal final class RecentlyClosedTabStore: ObservableObject { } private func persist() { - do { - let data = try JSONEncoder().encode(entries) - try data.write(to: Self.stateFileURL(in: directory), options: .atomic) - } catch { - Self.logger.fault("Failed to persist recently closed tabs: \(error.publicLogShape, privacy: .public)") - } - } - - /// One unreadable entry must not cost the user the rest of the history, so entries decode - /// leniently, matching `TabDiskState`. - private static func decodeEntries(at url: URL) -> [RecentlyClosedTabEntry] { - guard let data = try? Data(contentsOf: url) else { return [] } - do { - return try JSONDecoder().decode([LossyEntry].self, from: data).compactMap(\.value) - } catch { - logger.error("Failed to load recently closed tabs: \(error.publicLogShape, privacy: .public)") - return [] - } + try? stateFile.write(StoredEntries(entries)) } nonisolated internal static func defaultDirectory() -> URL { @@ -232,9 +207,23 @@ internal final class RecentlyClosedTabStore: ObservableObject { .appendingPathComponent("TablePro", isDirectory: true) .appendingPathComponent("RecentlyClosedTabs", isDirectory: true) } +} + +// Entries decode one by one, matching `TabDiskState`, so one unreadable entry does not cost the rest of the history. +private struct StoredEntries: Codable { + let entries: [RecentlyClosedTabEntry] + + init(_ entries: [RecentlyClosedTabEntry]) { + self.entries = entries + } + + init(from decoder: Decoder) throws { + entries = try decoder.singleValueContainer().decode([LossyEntry].self).compactMap(\.value) + } - private static func stateFileURL(in directory: URL) -> URL { - directory.appendingPathComponent("entries.json") + func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(entries) } } diff --git a/apple/TablePro/Core/Storage/RowGenerationSettingsStore.swift b/apple/TablePro/Core/Storage/RowGenerationSettingsStore.swift index 2314b58a66..927e8c928c 100644 --- a/apple/TablePro/Core/Storage/RowGenerationSettingsStore.swift +++ b/apple/TablePro/Core/Storage/RowGenerationSettingsStore.swift @@ -19,12 +19,11 @@ internal final class RowGenerationSettingsStore: TableScopedSettingsStore { } func settings(for scope: TableScope) -> RowGenerationSettings? { - guard let data = store.dataValue(forKey: PreferenceKeys.rowGeneration(scope).name) else { return nil } - return try? JSONDecoder().decode(RowGenerationSettings.self, from: data) + store.read(PreferenceKeys.rowGeneration(scope)).value } func save(_ settings: RowGenerationSettings, for scope: TableScope) { - store.setDataValue(try? JSONEncoder().encode(settings), forKey: PreferenceKeys.rowGeneration(scope).name) + try? store.write(settings, to: PreferenceKeys.rowGeneration(scope)) } func renameTable(from oldScope: TableScope, to newScope: TableScope) { @@ -50,7 +49,7 @@ internal final class RowGenerationSettingsStore: TableScopedSettingsStore { } func dropTable(_ scope: TableScope) { - store.setDataValue(nil, forKey: PreferenceKeys.rowGeneration(scope).name) + store.removeValue(for: PreferenceKeys.rowGeneration(scope)) } func dropContainer(connectionId: UUID, database: String, schema: String?) { diff --git a/apple/TablePro/Core/Storage/SandboxKeychainStore.swift b/apple/TablePro/Core/Storage/SandboxKeychainStore.swift index a5126ab0b9..46756f31de 100644 --- a/apple/TablePro/Core/Storage/SandboxKeychainStore.swift +++ b/apple/TablePro/Core/Storage/SandboxKeychainStore.swift @@ -4,23 +4,14 @@ // import Foundation -import os -/// The keychain a sandboxed run gets instead of the login keychain. Backed by a plain file inside -/// the sandbox, so a UI test's credentials never reach the real keychain and never survive the run. -/// -/// A namespaced service string on the real keychain was the alternative and is worse: the items -/// would still be written to the user's login keychain, and reading them on a headless machine -/// needs the keychain unlocked, which is a documented CI failure mode. Nothing here is secret, -/// because nothing in a sandbox outlives the test that made it. +// A plain file in the sandbox, so a UI test's credentials never reach the login keychain, which a headless run cannot unlock. internal final class SandboxKeychainStore: KeychainStoring { - private let fileURL: URL + private let file: JSONFileStore<[String: String]> private let lock = NSLock() - private static let logger = Logger(subsystem: "com.TablePro", category: "SandboxKeychainStore") - internal init(fileURL: URL) { - self.fileURL = fileURL + file = JSONFileStore(url: fileURL) } @discardableResult @@ -48,20 +39,10 @@ internal final class SandboxKeychainStore: KeychainStoring { } private func load() -> [String: String] { - guard let data = try? Data(contentsOf: fileURL), - let items = try? JSONDecoder().decode([String: String].self, from: data) - else { return [:] } - return items + file.read().value ?? [:] } private func persist(_ items: [String: String]) -> Bool { - do { - let data = try JSONEncoder().encode(items) - try data.write(to: fileURL, options: .atomic) - return true - } catch { - Self.logger.error("Sandbox keychain write failed: \(error.publicLogShape, privacy: .public)") - return false - } + (try? file.write(items)) != nil } } diff --git a/apple/TablePro/Core/Storage/ServerDashboardTileStorage.swift b/apple/TablePro/Core/Storage/ServerDashboardTileStorage.swift index 5880cd99a4..ef02a8c21f 100644 --- a/apple/TablePro/Core/Storage/ServerDashboardTileStorage.swift +++ b/apple/TablePro/Core/Storage/ServerDashboardTileStorage.swift @@ -4,11 +4,8 @@ // import Foundation -import os struct ServerDashboardTileStorage: Sendable { - private static let logger = Logger(subsystem: "com.TablePro", category: "ServerDashboardTileStorage") - private let defaults: @Sendable () -> UserDefaults init(defaults: @escaping @Sendable () -> UserDefaults = { AppStorageEnvironment.shared.defaults }) { @@ -19,14 +16,12 @@ struct ServerDashboardTileStorage: Sendable { "ServerDashboardTiles.\(connectionId.uuidString)" } + private static func entry(for connectionId: UUID) -> JSONDefaultsKey { + JSONDefaultsKey(key(for: connectionId)) + } + func load(for connectionId: UUID) -> ServerDashboardTileLayout { - guard let data = defaults().data(forKey: Self.key(for: connectionId)) else { return .empty } - do { - return try JSONDecoder().decode(ServerDashboardTileLayout.self, from: data) - } catch { - Self.logger.error("Failed to decode dashboard tiles: \(error.publicLogShape, privacy: .public)") - return .empty - } + defaults().read(Self.entry(for: connectionId)).value ?? .empty } func save(_ layout: ServerDashboardTileLayout, for connectionId: UUID) { @@ -34,14 +29,10 @@ struct ServerDashboardTileStorage: Sendable { remove(for: connectionId) return } - do { - defaults().set(try JSONEncoder().encode(layout), forKey: Self.key(for: connectionId)) - } catch { - Self.logger.error("Failed to encode dashboard tiles: \(error.publicLogShape, privacy: .public)") - } + try? defaults().write(layout, to: Self.entry(for: connectionId)) } func remove(for connectionId: UUID) { - defaults().removeObject(forKey: Self.key(for: connectionId)) + defaults().removeValue(for: Self.entry(for: connectionId)) } } diff --git a/apple/TablePro/Core/Storage/TableFolderStorage.swift b/apple/TablePro/Core/Storage/TableFolderStorage.swift index 72b50a51fa..2a6dbfc8a1 100644 --- a/apple/TablePro/Core/Storage/TableFolderStorage.swift +++ b/apple/TablePro/Core/Storage/TableFolderStorage.swift @@ -11,12 +11,7 @@ extension Notification.Name { static let tableFoldersDidChange = Notification.Name("TableFoldersDidChange") } -/// The folders tables and views are filed into, one document per connection. -/// -/// A folder only records which objects belong to it, so nothing here ever reaches the database: -/// deleting a folder puts its objects back in their sections. Every edit goes through `commit`, -/// which persists before it marks anything for sync, because a sync mark can start a push that -/// reads this store. +// A folder only records which objects it holds, so nothing here ever reaches the database. @MainActor internal final class TableFolderStorage: TableScopedSettingsStore { static let shared = TableFolderStorage() @@ -24,15 +19,14 @@ internal final class TableFolderStorage: TableScopedSettingsStore { private static let logger = Logger(subsystem: "com.TablePro", category: "TableFolderStorage") - private struct Document: Codable, Equatable { + struct Document: Codable, Equatable { var folders: [TableFolder] = [] var items: [TableFolderItem] = [] var isEmpty: Bool { folders.isEmpty && items.isEmpty } } - /// The sync marks one edit leaves. Deletions are marked first, so an id an edit both removed and - /// wrote back ends up waiting to be saved rather than deleted. + // Deletions are marked first, so an id an edit both removed and wrote back ends up saved, not deleted. private struct SyncMarks { var dirtyFolders: [String] = [] var deletedFolders: [String] = [] @@ -48,8 +42,7 @@ internal final class TableFolderStorage: TableScopedSettingsStore { private let syncTracker: SyncChangeTracker private let notificationCenter: NotificationCenter private var documents: [UUID: Document] = [:] - /// Connections whose stored folders did not decode. They read as empty and are never written, - /// so a damaged or newer document is left for a fix rather than replaced by the next edit. + // Read as empty and never written, so a damaged or newer document is not replaced by the next edit. private var unreadableConnectionIds: Set = [] init( @@ -93,8 +86,7 @@ internal final class TableFolderStorage: TableScopedSettingsStore { storedConnectionIds().flatMap { document(for: $0).items } } - /// "New Folder", then "New Folder 2" and up, the way Finder numbers an untitled folder. Compared - /// without regard to case, because two folders a Move to menu cannot tell apart are no help. + // Ignores case, because two folders a Move to menu cannot tell apart are no help. func availableFolderName(in scope: DatabaseScope) -> String { let taken = Set(layout(in: scope).folders.map { $0.name.lowercased() }) let base = String(localized: "New Folder") @@ -139,7 +131,6 @@ internal final class TableFolderStorage: TableScopedSettingsStore { commit(document, for: connectionId, marks: SyncMarks(dirtyFolders: [id.uuidString])) } - /// The folder goes and its objects return to their sections. func deleteFolder(id: UUID, connectionId: UUID) { var document = document(for: connectionId) guard !document.folders.extract(where: { $0.id == id }).isEmpty else { return } @@ -150,7 +141,6 @@ internal final class TableFolderStorage: TableScopedSettingsStore { )) } - /// Files each object into the folder, taking it out of whichever folder held it before. func fileObjects(_ names: [String], in scope: DatabaseScope, into folderId: UUID) { var document = document(for: scope.connectionId) guard document.folders.contains(where: { $0.id == folderId && $0.scope == scope }) else { return } @@ -194,9 +184,7 @@ internal final class TableFolderStorage: TableScopedSettingsStore { // MARK: - Undo - /// The folders and placements an edit is about to touch, as they are now. Restoring it writes - /// back only these entries, so anything else that changed in between, a rename from another - /// window or a pull from another Mac, is left alone. + // Only these entries are restored, so a rename from another window or a pull from another Mac in between survives. func capture(folderIds: Set, itemKeys: Set, connectionId: UUID) -> TableFolderRevision { let document = document(for: connectionId) var folders: [UUID: TableFolder?] = [:] @@ -214,12 +202,7 @@ internal final class TableFolderStorage: TableScopedSettingsStore { return TableFolderRevision(connectionId: connectionId, folders: folders, items: items) } - /// Puts the captured entries back and returns what they were just before, which is the redo. - /// - /// A folder that still exists gets its name back and stays where it is now: a schema renamed - /// since the edit has moved the folder and its objects together, and putting the old scope back - /// would strand the folder away from them. Taking a folder away takes every object still filed - /// in it too, so nothing is left pointing at a folder that is gone. + // Returns the redo. A live folder keeps its scope, since a schema rename since the edit moved its objects with it. @discardableResult func restore(_ revision: TableFolderRevision) -> TableFolderRevision { let current = capture( @@ -270,11 +253,7 @@ internal final class TableFolderStorage: TableScopedSettingsStore { // MARK: - Remote changes - /// Applies what another Mac pushed, marking nothing: a mark here would push the change straight - /// back at the device that made it. An item may arrive before its folder does, and it waits in - /// the store until the folder lands, because the sidebar only places items whose folder exists. - /// A connection kept Local only here takes no folder change from anywhere else, the way the - /// connection itself does not. + // Marks nothing: a mark would push the change straight back to the Mac that made it. func applyRemote(folders: [TableFolder], items: [TableFolderItem], excluding keptLocal: Set = []) { let foldersByConnection = Dictionary(grouping: folders) { $0.scope.connectionId } let itemsByConnection = Dictionary(grouping: items) { $0.scope.connectionId } @@ -295,8 +274,7 @@ internal final class TableFolderStorage: TableScopedSettingsStore { commitRemote(touched) } - /// A folder deleted elsewhere takes its placements with it here too. The other Mac tombstoned - /// them as well, so waiting for those deletions would only leave the objects hidden in between. + // Placements go with their folder; waiting for their own tombstones would hide the objects meanwhile. func removeRemote(folderIds: Set, itemSyncIds: Set, excluding keptLocal: Set = []) { guard !folderIds.isEmpty || !itemSyncIds.isEmpty else { return } var touched: [UUID: Document] = [:] @@ -340,8 +318,7 @@ internal final class TableFolderStorage: TableScopedSettingsStore { )) } - /// A placement arriving in the renamed container replaces one the container already held for - /// the same object, so no two placements ever share a key or a CloudKit record. + // An arriving placement replaces one already there, so no two placements share a key or a CloudKit record. func renameContainer( connectionId: UUID, fromDatabase: String, @@ -382,7 +359,7 @@ internal final class TableFolderStorage: TableScopedSettingsStore { unfileObjects([scope.table], in: Self.folderScope(of: scope)) } - /// The folders of a dropped database or schema go with it, because the objects they held did. + // The folders go too, because the objects they held did. func dropContainer(connectionId: UUID, database: String, schema: String?) { var document = document(for: connectionId) let doomedFolders = document.folders.extract { $0.scope.isInside(database: database, schema: schema) } @@ -401,7 +378,7 @@ internal final class TableFolderStorage: TableScopedSettingsStore { guard !document.isEmpty else { continue } documents[connectionId] = Document() unreadableConnectionIds.remove(connectionId) - store.setDataValue(nil, forKey: Self.key(for: connectionId)) + store.removeValue(for: Self.key(for: connectionId)) let folderIds = document.folders.map(\.id.uuidString) let itemIds = document.items.map(\.syncId) if leavesTombstones { @@ -416,15 +393,14 @@ internal final class TableFolderStorage: TableScopedSettingsStore { postChange(for: purged) } - /// `CatalogEditAdoption` builds every `TableScope` from a resolved `DatabaseScope`, so the - /// database is always present there. The fallback only keeps a hand-built scope from crashing. + // `CatalogEditAdoption` always sets the database; the fallback only covers a hand-built scope. private static func folderScope(of scope: TableScope) -> DatabaseScope { DatabaseScope(connectionId: scope.connectionId, database: scope.database ?? "", schema: scope.schema) } // MARK: - Persistence - /// Persists, then marks, then notifies, and does none of it when the write did not land. + // Persists before marking, because a sync mark can start a push that reads this store. @discardableResult private func commit(_ document: Document, for connectionId: UUID, marks: SyncMarks) -> Bool { guard persist(document, for: connectionId) else { return false } @@ -438,27 +414,15 @@ internal final class TableFolderStorage: TableScopedSettingsStore { private func document(for connectionId: UUID) -> Document { if let cached = documents[connectionId] { return cached } - guard let loaded = loadDocument(for: connectionId) else { + let stored = store.read(Self.key(for: connectionId)) + if stored.isUnreadable { unreadableConnectionIds.insert(connectionId) - documents[connectionId] = Document() - return Document() } + let loaded = stored.value ?? Document() documents[connectionId] = loaded return loaded } - private func loadDocument(for connectionId: UUID) -> Document? { - guard let data = store.dataValue(forKey: Self.key(for: connectionId)) else { return Document() } - do { - return try JSONDecoder().decode(Document.self, from: data) - } catch { - Self.logger.error( - "Failed to decode table folders for \(connectionId, privacy: .public): \(error.publicLogShape, privacy: .public) \(error.localizedDescription, privacy: .private)" - ) - return nil - } - } - private func persist(_ document: Document, for connectionId: UUID) -> Bool { guard !unreadableConnectionIds.contains(connectionId) else { Self.logger.error("Left unreadable table folders for \(connectionId, privacy: .public) unchanged") @@ -466,19 +430,16 @@ internal final class TableFolderStorage: TableScopedSettingsStore { } guard !document.isEmpty else { documents[connectionId] = document - store.setDataValue(nil, forKey: Self.key(for: connectionId)) + store.removeValue(for: Self.key(for: connectionId)) return true } do { - store.setDataValue(try JSONEncoder().encode(document), forKey: Self.key(for: connectionId)) - documents[connectionId] = document - return true + try store.write(document, to: Self.key(for: connectionId)) } catch { - Self.logger.error( - "Failed to encode table folders for \(connectionId, privacy: .public): \(error.publicLogShape, privacy: .public) \(error.localizedDescription, privacy: .private)" - ) return false } + documents[connectionId] = document + return true } private func storedConnectionIds() -> [UUID] { @@ -488,8 +449,8 @@ internal final class TableFolderStorage: TableScopedSettingsStore { return Array(Set(stored).union(documents.keys)) } - private static func key(for connectionId: UUID) -> String { - PreferenceKeys.tableFolders(connectionId: connectionId).name + private static func key(for connectionId: UUID) -> JSONDefaultsKey { + PreferenceKeys.tableFolders(connectionId: connectionId) } private func postChange(for connectionIds: Set) { @@ -511,8 +472,7 @@ internal final class TableFolderStorage: TableScopedSettingsStore { } } -/// Some folders and placements of one connection as they stood at a moment. A nil value means the -/// entry did not exist then. +// A nil value means the entry did not exist when captured. internal struct TableFolderRevision: Equatable { internal let connectionId: UUID internal let folders: [UUID: TableFolder?] @@ -520,7 +480,6 @@ internal struct TableFolderRevision: Equatable { } private extension Array { - /// Removes the elements that match and returns them, in one pass over the array. mutating func extract(where shouldExtract: (Element) -> Bool) -> [Element] { var extracted: [Element] = [] removeAll { element in diff --git a/apple/TablePro/Core/Storage/TableHealthHistoryStorage.swift b/apple/TablePro/Core/Storage/TableHealthHistoryStorage.swift index 7a70a5d8e6..5137775d95 100644 --- a/apple/TablePro/Core/Storage/TableHealthHistoryStorage.swift +++ b/apple/TablePro/Core/Storage/TableHealthHistoryStorage.swift @@ -226,25 +226,17 @@ final class TableHealthHistoryStorage: TableHealthHistoryStoring, TableScopedSet return loaded.document } + // The file store reports a file that will not open and one that will not decode alike; only the second is set aside. private func read(_ connectionId: UUID) throws -> Loaded { - let url = fileURL(for: connectionId) - guard FileManager.default.fileExists(atPath: url.path) else { return Loaded() } - let data: Data - do { - data = try Data(contentsOf: url) - } catch { - Self.logger.error( - "Failed to read Table Health history for \(connectionId, privacy: .public): \(error.publicLogShape, privacy: .public)" - ) - throw TableHealthHistoryStorageError.readFailed(error.localizedDescription) - } - do { - return Loaded(document: try JSONDecoder().decode(Document.self, from: data)) - } catch { - Self.logger.error( - "Unreadable Table Health history for \(connectionId, privacy: .public): \(error.publicLogShape, privacy: .public)" - ) + switch file(for: connectionId).read() { + case .missing: + return Loaded() + case .value(let document): + return Loaded(document: document) + case .unreadable(is DecodingError): return Loaded(isUnreadable: true) + case .unreadable(let error): + throw TableHealthHistoryStorageError.readFailed(error.localizedDescription) } } @@ -272,20 +264,14 @@ final class TableHealthHistoryStorage: TableHealthHistoryStoring, TableScopedSet } private func save(_ document: Document, for connectionId: UUID) throws { - let url = fileURL(for: connectionId) + let store = file(for: connectionId) do { - guard !document.databases.isEmpty else { - if FileManager.default.fileExists(atPath: url.path) { - try FileManager.default.removeItem(at: url) - } - return + if document.databases.isEmpty { + try store.remove() + } else { + try store.write(document) } - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - try JSONEncoder().encode(document).write(to: url, options: .atomic) } catch { - Self.logger.error( - "Failed to save Table Health history for \(connectionId, privacy: .public): \(error.publicLogShape, privacy: .public)" - ) throw TableHealthHistoryStorageError.saveFailed(error.localizedDescription) } } @@ -306,6 +292,10 @@ final class TableHealthHistoryStorage: TableHealthHistoryStoring, TableScopedSet directory.appendingPathComponent("\(connectionId.uuidString).json") } + private func file(for connectionId: UUID) -> JSONFileStore { + JSONFileStore(url: fileURL(for: connectionId)) + } + private func corruptFileURL(for connectionId: UUID, number: Int) -> URL { directory.appendingPathComponent("\(connectionId.uuidString).corrupt-\(number).json") } diff --git a/apple/TablePro/Core/Storage/ValueDisplayFormatStorage.swift b/apple/TablePro/Core/Storage/ValueDisplayFormatStorage.swift index 9921cf8941..707e28319c 100644 --- a/apple/TablePro/Core/Storage/ValueDisplayFormatStorage.swift +++ b/apple/TablePro/Core/Storage/ValueDisplayFormatStorage.swift @@ -35,7 +35,7 @@ internal final class ValueDisplayFormatStorage: TableScopedSettingsStore { let key = Self.key(for: scope) let addedKey = Self.addedKey(for: scope) var first: [String: String] = [:] - var added = (Self.names(store.dataValue(forKey: addedKey)) ?? [:]) + var added = (store.read(addedKey).value ?? [:]) .filter { ValueDisplayFormat(rawValue: $0.value) == nil && formats[$0.key] == nil } for (column, format) in formats { if Self.namesReadBy083.contains(format.rawValue) { @@ -44,34 +44,34 @@ internal final class ValueDisplayFormatStorage: TableScopedSettingsStore { added[column] = format.rawValue } } - write(first, forKey: key) - write(added, forKey: addedKey) + write(first, to: key) + write(added, to: addedKey) removeLegacy(for: scope) sweepSchemas() } func load(for scope: TableScope) -> [String: ValueDisplayFormat]? { - let first = Self.names(store.dataValue(forKey: Self.key(for: scope))) - let added = Self.names(store.dataValue(forKey: Self.addedKey(for: scope))) + let first = store.read(Self.key(for: scope)).value + let added = store.read(Self.addedKey(for: scope)).value guard first != nil || added != nil else { return migrateLegacy(for: scope) } let names = (added ?? [:]).merging(first ?? [:]) { _, firstName in firstName } return names.compactMapValues(ValueDisplayFormat.init(rawValue:)) } func clear(for scope: TableScope) { - store.setDataValue(nil, forKey: Self.key(for: scope)) - store.setDataValue(nil, forKey: Self.addedKey(for: scope)) + store.removeValue(for: Self.key(for: scope)) + store.removeValue(for: Self.addedKey(for: scope)) removeLegacy(for: scope) sweepSchemas() } func renameTable(from oldScope: TableScope, to newScope: TableScope) { - let oldKey = Self.key(for: oldScope) + let oldKey = Self.key(for: oldScope).name if store.dataValue(forKey: oldKey) == nil { migrateLegacy(for: oldScope) } - store.moveValue(fromKey: oldKey, toKey: Self.key(for: newScope)) - store.moveValue(fromKey: Self.addedKey(for: oldScope), toKey: Self.addedKey(for: newScope)) + store.moveValue(fromKey: oldKey, toKey: Self.key(for: newScope).name) + store.moveValue(fromKey: Self.addedKey(for: oldScope).name, toKey: Self.addedKey(for: newScope).name) } func renameContainer( @@ -118,7 +118,7 @@ internal final class ValueDisplayFormatStorage: TableScopedSettingsStore { var avro: Set = [] var protobuf: Set = [] for key in store.keys(withPrefix: Self.keyPrefix) where key.hasSuffix(Self.addedSuffix) { - for name in (Self.names(store.dataValue(forKey: key)) ?? [:]).values { + for name in (store.read(JSONDefaultsKey<[String: String]>(key)).value ?? [:]).values { switch ValueDisplayFormat(rawValue: name) { case .avro(let schemaID)?: avro.insert(schemaID) case .protobufSchema(let schemaID, _)?: protobuf.insert(schemaID) @@ -133,26 +133,26 @@ internal final class ValueDisplayFormatStorage: TableScopedSettingsStore { @discardableResult private func migrateLegacy(for scope: TableScope) -> [String: ValueDisplayFormat]? { let legacyKey = Self.legacyKey(for: scope) - guard let names = Self.names(store.dataValue(forKey: legacyKey)), !names.isEmpty else { return nil } - write(names, forKey: Self.key(for: scope)) - store.setDataValue(nil, forKey: legacyKey) + guard let names = store.read(legacyKey).value, !names.isEmpty else { return nil } + write(names, to: Self.key(for: scope)) + store.removeValue(for: legacyKey) return names.compactMapValues(ValueDisplayFormat.init(rawValue:)) } - private func write(_ names: [String: String], forKey key: String) { - guard !names.isEmpty, let data = try? JSONEncoder().encode(names) else { - store.setDataValue(nil, forKey: key) + private func write(_ names: [String: String], to key: JSONDefaultsKey<[String: String]>) { + guard !names.isEmpty else { + store.removeValue(for: key) return } - store.setDataValue(data, forKey: key) + do { + try store.write(names, to: key) + } catch { + store.removeValue(for: key) + } } private func removeLegacy(for scope: TableScope) { - store.setDataValue(nil, forKey: Self.legacyKey(for: scope)) - } - - private static func names(_ data: Data?) -> [String: String]? { - data.flatMap { try? JSONDecoder().decode([String: String].self, from: $0) } + store.removeValue(for: Self.legacyKey(for: scope)) } private static let keyPrefix = PreferenceKeys.columnDisplayFormatsPrefix @@ -160,16 +160,16 @@ internal final class ValueDisplayFormatStorage: TableScopedSettingsStore { // A table key is four dot-joined, percent-encoded parts, so a fifth part never names another table. private static let addedSuffix = ".added" - private static func key(for scope: TableScope) -> String { - PreferenceKeys.columnDisplayFormats(scope).name + private static func key(for scope: TableScope) -> JSONDefaultsKey<[String: String]> { + PreferenceKeys.columnDisplayFormats(scope) } - private static func addedKey(for scope: TableScope) -> String { - key(for: scope) + addedSuffix + private static func addedKey(for scope: TableScope) -> JSONDefaultsKey<[String: String]> { + JSONDefaultsKey(key(for: scope).name + addedSuffix) } - private static func legacyKey(for scope: TableScope) -> String { - legacyKeyPrefix(for: scope.connectionId) + scope.table + private static func legacyKey(for scope: TableScope) -> JSONDefaultsKey<[String: String]> { + JSONDefaultsKey(legacyKeyPrefix(for: scope.connectionId) + scope.table) } private static func legacyKeyPrefix(for connectionId: UUID) -> String { diff --git a/apple/TablePro/Core/Storage/WorkspaceRailOrderStore.swift b/apple/TablePro/Core/Storage/WorkspaceRailOrderStore.swift index 9b354bf9c4..4c7a6d7729 100644 --- a/apple/TablePro/Core/Storage/WorkspaceRailOrderStore.swift +++ b/apple/TablePro/Core/Storage/WorkspaceRailOrderStore.swift @@ -15,7 +15,7 @@ internal final class WorkspaceRailOrderStore { internal init(defaults: UserDefaults = AppStorageEnvironment.shared.defaults) { self.defaults = defaults - self.cachedOrder = Self.decode(from: defaults) + self.cachedOrder = defaults.read(PreferenceKeys.workspaceRailOrder).value ?? [] } internal var order: [WorkspaceID] { @@ -33,25 +33,13 @@ internal final class WorkspaceRailOrderStore { setOrder(WorkspaceRailOrdering.merged(visibleOrder: visibleOrder, into: cachedOrder)) } - /// Deleting a connection takes its arrangement with it. Nothing else ever removed an entry, so - /// the ids of deleted connections, and of databases that no longer exist, stayed in defaults for - /// good and every drag added more. `ConnectionLocalState.purge` is where the app already sheds a - /// deleted connection's local state, and it is the one caller. + // The one place entries leave, called from `ConnectionLocalState.purge`, so deleted connections stop piling up. internal func removeEntries(for connectionIds: Set) { guard !connectionIds.isEmpty else { return } setOrder(cachedOrder.filter { !connectionIds.contains($0.connectionId) }) } private func persist() { - guard let data = try? JSONEncoder().encode(cachedOrder) else { return } - defaults.set(data, forKey: PreferenceKeys.workspaceRailOrder.name) - } - - private static func decode(from defaults: UserDefaults) -> [WorkspaceID] { - guard let data = defaults.data(forKey: PreferenceKeys.workspaceRailOrder.name), - let ids = try? JSONDecoder().decode([WorkspaceID].self, from: data) else { - return [] - } - return ids + try? defaults.write(cachedOrder, to: PreferenceKeys.workspaceRailOrder) } } diff --git a/apple/TablePro/Models/UI/FilterPreset.swift b/apple/TablePro/Models/UI/FilterPreset.swift index bee49e5be9..c78f90207e 100644 --- a/apple/TablePro/Models/UI/FilterPreset.swift +++ b/apple/TablePro/Models/UI/FilterPreset.swift @@ -1,6 +1,5 @@ import Foundation -/// Represents a saved filter preset with a name and filters struct FilterPreset: Identifiable, Codable, Equatable { let id: UUID var name: String @@ -15,19 +14,16 @@ struct FilterPreset: Identifiable, Codable, Equatable { } } -/// Storage manager for filter presets @MainActor final class FilterPresetStorage { static let shared = FilterPresetStorage() - private let presetsKey = "com.TablePro.filter.presets" + private static let presetsKey = JSONDefaultsKey<[FilterPreset]>("com.TablePro.filter.presets") private let defaults = AppStorageEnvironment.shared.defaults - /// Cached presets to avoid repeated UserDefaults read + JSON decode private var cachedPresets: [FilterPreset]? private init() {} - /// Save a new preset func savePreset(_ preset: FilterPreset) { var presets = loadAllPresets() @@ -55,12 +51,10 @@ struct FilterPreset: Identifiable, Codable, Equatable { return candidate } - /// Load all saved presets (cached after first read) func loadAllPresets() -> [FilterPreset] { if let cached = cachedPresets { return cached } - guard let data = defaults.data(forKey: presetsKey), - let presets = try? JSONDecoder().decode([FilterPreset].self, from: data) else { + guard let presets = defaults.read(Self.presetsKey).value else { cachedPresets = [] return [] } @@ -69,20 +63,17 @@ struct FilterPreset: Identifiable, Codable, Equatable { return sorted } - /// Delete a preset func deletePreset(_ preset: FilterPreset) { var presets = loadAllPresets() presets.removeAll { $0.id == preset.id } saveAllPresets(presets) } - /// Delete all presets func deleteAllPresets() { - defaults.removeObject(forKey: presetsKey) + defaults.removeValue(for: Self.presetsKey) cachedPresets = nil } - /// Rename a preset func renamePreset(_ preset: FilterPreset, to newName: String) { var updatedPreset = preset updatedPreset.name = newName @@ -92,8 +83,11 @@ struct FilterPreset: Identifiable, Codable, Equatable { // MARK: - Private private func saveAllPresets(_ presets: [FilterPreset]) { - guard let data = try? JSONEncoder().encode(presets) else { return } - defaults.set(data, forKey: presetsKey) + do { + try defaults.write(presets, to: Self.presetsKey) + } catch { + return + } cachedPresets = presets.sorted { $0.createdAt > $1.createdAt } } } diff --git a/apple/TablePro/ViewModels/FavoritesExpansionState.swift b/apple/TablePro/ViewModels/FavoritesExpansionState.swift index 784a14b29b..57de10673c 100644 --- a/apple/TablePro/ViewModels/FavoritesExpansionState.swift +++ b/apple/TablePro/ViewModels/FavoritesExpansionState.swift @@ -14,10 +14,11 @@ internal final class FavoritesExpansionState: ObservableObject { @Published private(set) var linkedNodesByConnection: [UUID: Set] = [:] @Published private(set) var collapsedDatabaseEnvironmentsByConnection: [UUID: Set] = [:] - private let foldersKey = "com.TablePro.favoritesExpandedFolders" - private let linkedKey = "com.TablePro.favoritesExpandedLinkedNodes" - private let collapsedDatabaseEnvironmentsKey = - "com.TablePro.favoritesCollapsedDatabaseEnvironments" + private static let foldersKey = JSONDefaultsKey<[UUID: Set]>("com.TablePro.favoritesExpandedFolders") + private static let linkedKey = JSONDefaultsKey<[UUID: Set]>("com.TablePro.favoritesExpandedLinkedNodes") + // Raw values, so one environment this build does not know drops only itself. + private static let collapsedDatabaseEnvironmentsKey = + JSONDefaultsKey<[UUID: Set]>("com.TablePro.favoritesCollapsedDatabaseEnvironments") private let defaults: UserDefaults @@ -94,50 +95,44 @@ internal final class FavoritesExpansionState: ObservableObject { } private func load() { - if let data = defaults.data(forKey: foldersKey), - let decoded = try? JSONDecoder().decode([UUID: Set].self, from: data) { + if let decoded = defaults.read(Self.foldersKey).value { foldersByConnection = decoded } - if let data = defaults.data(forKey: linkedKey), - let decoded = try? JSONDecoder().decode([UUID: Set].self, from: data) { + if let decoded = defaults.read(Self.linkedKey).value { linkedNodesByConnection = decoded } - collapsedDatabaseEnvironmentsByConnection = Self.decodeCollapsedEnvironments( - defaults.data(forKey: collapsedDatabaseEnvironmentsKey) - ) + collapsedDatabaseEnvironmentsByConnection = defaults.read(Self.collapsedDatabaseEnvironmentsKey) + .value.map(Self.knownEnvironments) ?? [:] } - /// Decoded per raw value rather than whole. `Set` fails the entire - /// payload on one case this build does not know, which would silently discard the collapsed - /// state of every group of every connection, permanently, from the next write onward. internal static func decodeCollapsedEnvironments( _ data: Data? ) -> [UUID: Set] { guard let data, - let raw = try? JSONDecoder().decode([UUID: Set].self, from: data) + let raw = try? collapsedDatabaseEnvironmentsKey.coding.decode([UUID: Set].self, from: data) else { return [:] } - return raw.compactMapValues { values in + return knownEnvironments(raw) + } + + nonisolated private static func knownEnvironments( + _ raw: [UUID: Set] + ) -> [UUID: Set] { + raw.compactMapValues { values in let environments = Set(values.compactMap(FavoriteDatabaseEnvironment.init(rawValue:))) return environments.isEmpty ? nil : environments } } private func persistFolders() { - if let data = try? JSONEncoder().encode(foldersByConnection) { - defaults.set(data, forKey: foldersKey) - } + try? defaults.write(foldersByConnection, to: Self.foldersKey) } private func persistLinkedNodes() { - if let data = try? JSONEncoder().encode(linkedNodesByConnection) { - defaults.set(data, forKey: linkedKey) - } + try? defaults.write(linkedNodesByConnection, to: Self.linkedKey) } private func persistCollapsedDatabaseEnvironments() { let raw = collapsedDatabaseEnvironmentsByConnection.mapValues { Set($0.map(\.rawValue)) } - if let data = try? JSONEncoder().encode(raw) { - defaults.set(data, forKey: collapsedDatabaseEnvironmentsKey) - } + try? defaults.write(raw, to: Self.collapsedDatabaseEnvironmentsKey) } } diff --git a/apple/TablePro/Views/Backup/RestoreDatabaseFlow.swift b/apple/TablePro/Views/Backup/RestoreDatabaseFlow.swift index 72a73d503f..12da075f97 100644 --- a/apple/TablePro/Views/Backup/RestoreDatabaseFlow.swift +++ b/apple/TablePro/Views/Backup/RestoreDatabaseFlow.swift @@ -84,10 +84,7 @@ struct RestoreDatabaseFlow: View { .background(Color(nsColor: .windowBackgroundColor)) } - /// An engine that reaches one database is not asked which one. - /// - /// SQLite reports an empty database list, so the picker rendered its empty state with a - /// permanently dimmed Restore button and no way forward but Cancel. DuckDB is the same shape. + // SQLite and DuckDB report no database list, which would leave the picker with no way forward. @MainActor private func resolveTarget() async { guard phase == .resolvingTarget else { return } @@ -103,12 +100,10 @@ struct RestoreDatabaseFlow: View { VStack(spacing: 0) { sourceBanner Divider() - DatabaseSwitcherSheet( - isPresented: $isPresented, - mode: .restore, + RestoreTargetPicker( + connection: connection, currentDatabase: initialDatabase, - databaseType: connection.type, - connectionId: connection.id, + onCancel: { isPresented = false }, onSelect: { database in Task { await startRestore(database: database) } } @@ -138,8 +133,7 @@ struct RestoreDatabaseFlow: View { private var serviceState: NativeDumpState { service.state } - /// Which of an engine's formats this file is. DuckDB writes either one `.duckdb` file or a - /// folder of Parquet, and only the file system says which one the user picked. + // DuckDB writes either one `.duckdb` file or a folder of Parquet; only the file system says which. private var formatId: String? { let formats = NativeDumpRegistry.formats(for: connection.type) guard formats.count > 1 else { return formats.first?.id } @@ -171,8 +165,7 @@ struct RestoreDatabaseFlow: View { } } - /// A restore replays a dump into a database that already has contents, and the tools it drives - /// do not ask. Picking a database in the list used to be the last step before the first write. + // The dump tools overwrite without asking, so the confirmation is the last step before a write. private func startRestore(database: String) async { guard let message = RestoreConfirmationText.message(for: connection.type, formatId: formatId) else { phase = .failed( @@ -207,3 +200,63 @@ struct RestoreDatabaseFlow: View { } } } + +private struct RestoreTargetPicker: View { + let currentDatabase: String + let databaseType: DatabaseType + let connectionId: UUID + let onCancel: () -> Void + let onSelect: (String) -> Void + @StateObject private var viewModel: DatabaseSwitcherViewModel + + init( + connection: DatabaseConnection, + currentDatabase: String, + onCancel: @escaping () -> Void, + onSelect: @escaping (String) -> Void + ) { + self.currentDatabase = currentDatabase + self.databaseType = connection.type + self.connectionId = connection.id + self.onCancel = onCancel + self.onSelect = onSelect + self._viewModel = StateObject( + wrappedValue: DatabaseSwitcherViewModel( + connectionId: connection.id, + currentDatabase: currentDatabase, + databaseType: connection.type, + switchTarget: .database, + sidebarState: SharedSidebarState.forConnection(connection.id) + )) + } + + var body: some View { + NavigationStack { + DatabaseSwitcherList( + viewModel: viewModel, + currentDatabase: currentDatabase, + activeDatabase: currentDatabase, + databaseType: databaseType, + connectionId: connectionId, + commands: nil, + onCommit: onSelect, + dismiss: onCancel + ) + .navigationTitle(String(localized: "Restore Database")) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button(String(localized: "Cancel"), action: onCancel) + } + ToolbarItem(placement: .confirmationAction) { + Button(String(localized: "Restore")) { + if let database = viewModel.primarySelection { + onSelect(database) + } + } + .disabled(viewModel.primarySelection == nil) + } + } + } + .frame(width: 480, height: 460) + } +} diff --git a/apple/TablePro/Views/DatabaseSwitcher/DatabaseSwitcherList.swift b/apple/TablePro/Views/DatabaseSwitcher/DatabaseSwitcherList.swift new file mode 100644 index 0000000000..e2ff42296d --- /dev/null +++ b/apple/TablePro/Views/DatabaseSwitcher/DatabaseSwitcherList.swift @@ -0,0 +1,427 @@ +// +// DatabaseSwitcherList.swift +// TablePro +// + +import AppKit +import SwiftUI +import TableProPluginKit + +// The searchable container list the toolbar chooser and the restore picker share. +struct DatabaseSwitcherList: View { + // What the chooser offers beyond picking a row. Nil leaves only picking, favorites and Copy Name. + struct ContainerCommands { + let isReadOnly: Bool + let schemaEditEligibility: SchemaEditEligibility.Context + let onRequestCreate: () -> Void + let onRequestDrop: ([DatabaseContainerRef]) -> Void + let onRequestExport: ([DatabaseContainerRef]) -> Void + let onRequestEdit: (DatabaseContainerRef) -> Void + } + + @ObservedObject var viewModel: DatabaseSwitcherViewModel + let currentDatabase: String? + // The database the rows belong to; in schema mode the rows are schemas inside it. + let activeDatabase: String + let databaseType: DatabaseType + let connectionId: UUID + let commands: ContainerCommands? + let onCommit: (String) -> Void + // The host owns the surface: an AppKit popover or panel, or a flow's sheet. + let dismiss: () -> Void + + @State private var supportsCreateDatabase = false + @State private var favoriteDatabases: Set = [] + + private var switchTarget: ContainerSwitchTarget { viewModel.switchTarget } + + private var supportsDropDatabase: Bool { + PluginManager.shared.supportsDropDatabase(for: databaseType) + } + private var supportsDropSchema: Bool { + PluginManager.shared.supportsDropSchema(for: databaseType) + } + private var showsCreateRow: Bool { + guard let commands, !commands.isReadOnly else { return false } + switch switchTarget { + case .database: return supportsCreateDatabase + case .schema: return SchemaEditEligibility.canCreate(context: commands.schemaEditEligibility) + } + } + private var containerName: String { + switch switchTarget { + case .database: PluginManager.shared.containerEntityName(for: databaseType) + case .schema: PluginManager.shared.schemaEntityName(for: databaseType) + } + } + private var containerNamePlural: String { + containerName + "s" + } + + var body: some View { + VStack(spacing: 0) { + searchField + + Divider() + + content + + if showsCreateRow { + Divider() + createButton + } + } + .background(refreshShortcut) + .task { await viewModel.fetchDatabases() } + .task { await refreshCreateSupport() } + .onAppear { reloadFavorites() } + .onReceive(NotificationCenter.default.publisher(for: .favoriteDatabasesDidChange)) { _ in + reloadFavorites() + } + } + + private var refreshShortcut: some View { + Button("") { + Task { await viewModel.refreshDatabases() } + } + .keyboardShortcut("r", modifiers: .command) + .hidden() + } + + private var searchField: some View { + NativeSearchField( + text: $viewModel.searchText, + placeholder: String(format: String(localized: "Search %@"), containerNamePlural.lowercased()), + onMoveUp: { viewModel.moveUp() }, + onMoveDown: { viewModel.moveDown() }, + onSubmit: { commitSelection() }, + focusOnAppear: true + ) + .padding(.horizontal, 8) + .padding(.vertical, 6) + } + + @ViewBuilder + private var content: some View { + if viewModel.isLoading { + loadingView + } else if let error = viewModel.errorMessage { + errorView(error) + } else if switchTarget == .database, + PluginManager.shared.connectionMode(for: databaseType) == .fileBased { + sqliteState + } else if viewModel.filteredDatabases.isEmpty { + emptyState + } else { + list + } + } + + // The search field keeps focus for the whole flow, so the list only presents its selection. + private var list: some View { + FieldDrivenList( + sections: listSections, + selection: $viewModel.selectedDatabases, + allowsMultipleSelection: commands != nil, + onPrimaryAction: { name in + viewModel.selectedDatabase = name + commitSelection() + }, + menuItems: { contextMenuItems(for: $0) }, + row: { row(for: $0) } + ) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + + // Unlike the sidebar tree, a switcher lists every container the server returned (#2832). + private var listSections: [FieldDrivenListSection] { + let sections = viewModel.visibleSections + return [ + FieldDrivenListSection(id: "containers", items: sections.user), + FieldDrivenListSection(id: "system", title: String(localized: "System"), items: sections.system) + ] + } + + private func row(for database: DatabaseMetadata) -> some View { + let isCurrent = database.name == currentDatabase + return HStack(spacing: 8) { + Image(systemName: "checkmark") + .font(.body.weight(.semibold)) + .selectionAwareTint(Color.accentColor) + .opacity(isCurrent ? 1 : 0) + .frame(width: 14) + .accessibilityLabel( + Text(String(format: String(localized: "Current %@"), containerName.lowercased())) + ) + .accessibilityHidden(!isCurrent) + + Image(systemName: database.icon) + .font(.body) + .selectionAwareTint(database.isSystemDatabase ? Color.secondary : Color.accentColor) + .frame(width: 16) + .accessibilityHidden(true) + + Text(database.name) + .font(.body) + .lineLimit(1) + .truncationMode(.middle) + + Spacer(minLength: 0) + + favoriteIndicator(for: database) + } + .padding(.horizontal, 8) + .contentShape(Rectangle()) + } + + // A glyph, not a button: the hosting cell returns nil from hitTest, so the toggle lives in the menu. + @ViewBuilder + private func favoriteIndicator(for database: DatabaseMetadata) -> some View { + let isFavorite = switchTarget == .database && favoriteDatabases.contains(database.name) + Image(systemName: "star.fill") + .font(.caption) + .selectionAwareTint(Color.yellow) + .opacity(isFavorite ? 1 : 0) + .accessibilityLabel(Text(String(localized: "Favorite"))) + .accessibilityHidden(!isFavorite) + } + + private func contextMenuItems(for selection: Set) -> [FieldDrivenMenuItem] { + let targets = containerRefs(for: selection) + var items: [FieldDrivenMenuItem] = favoriteItems(for: targets) + + if !targets.isEmpty { + let copyTitle = targets.count == 1 + ? String(localized: "Copy Name") + : String(format: String(localized: "Copy %lld Names"), targets.count) + items.append(FieldDrivenMenuItem(title: copyTitle) { + ClipboardService.shared.writeText(targets.map(\.name).joined(separator: ",")) + }) + } + guard let commands else { return items } + + // The same reachability check the sidebar's Export item makes. + if !targets.isEmpty, ExportPreselection.canPreselect( + containers: targets, + activeDatabase: activeDatabase, + canReachOtherDatabases: databaseType.supportsConnectionPooling + ) { + items.append(FieldDrivenMenuItem(title: String(localized: "Export…")) { + dismiss() + commands.onRequestExport(targets) + }) + } + + if let editable = SchemaEditEligibility.editable(targets, context: commands.schemaEditEligibility) { + items.append(.separator) + items.append( + FieldDrivenMenuItem( + title: String(format: String(localized: "Edit %@\u{2026}"), containerName) + ) { + dismiss() + commands.onRequestEdit(editable) + } + ) + } + + let droppable = ContainerDropEligibility.droppable( + targets, context: dropEligibilityContext(isReadOnly: commands.isReadOnly) + ) + if !droppable.isEmpty { + items.append(.separator) + items.append(FieldDrivenMenuItem(title: dropMenuTitle(for: droppable)) { + dismiss() + commands.onRequestDrop(droppable) + }) + } + return items + } + + // Schema names in the database favorites store would be favorites that name nothing. + private func reloadFavorites() { + guard switchTarget == .database else { return } + favoriteDatabases = Set( + FavoriteDatabasesStorage.shared.favorites(for: connectionId).map(\.database) + ) + } + + private func favoriteItems(for targets: [DatabaseContainerRef]) -> [FieldDrivenMenuItem] { + guard switchTarget == .database else { return [] } + let databases = targets.filter { $0.kind == .database }.compactMap(\.database) + guard !databases.isEmpty else { return [] } + + let stored = FavoriteDatabasesStorage.shared.favorites(for: connectionId) + let environments = Dictionary( + stored.map { ($0.database, $0.environment) }, + uniquingKeysWith: { first, _ in first } + ) + let state = FavoriteDatabaseSelectionState(environments: databases.map { environments[$0] }) + + var items: [FieldDrivenMenuItem] = [ + FieldDrivenMenuItem( + title: FavoriteDatabaseMenu.submenuTitle(for: state), + submenu: FavoriteDatabaseMenu.environmentItems(for: state).map { item in + FieldDrivenMenuItem(title: item.title, isOn: item.isOn) { + for database in databases { + FavoriteDatabasesStorage.shared.setFavorite( + database: database, + environment: item.environment, + connectionId: connectionId + ) + } + } + } + ) + ] + if state.hasFavorite { + items.append(FieldDrivenMenuItem(title: FavoriteDatabaseMenu.removeTitle) { + for database in databases { + FavoriteDatabasesStorage.shared.removeFavorite( + database: database, + connectionId: connectionId + ) + } + }) + } + items.append(.separator) + return items + } + + // A schema row needs a schema ref, or Drop reaches dropDatabase and Export cannot resolve it. + private func containerRefs(for selection: Set) -> [DatabaseContainerRef] { + viewModel.filteredDatabases + .filter { selection.contains($0.name) } + .map { item in + switch switchTarget { + case .database: + return .database(item.name, isSystem: item.isSystemDatabase) + case .schema: + return .schema( + database: activeDatabase, schema: item.name, isSystem: item.isSystemDatabase + ) + } + } + } + + private func dropMenuTitle(for targets: [DatabaseContainerRef]) -> String { + DatabaseDropRequest( + targets: targets, + entityName: containerName, + entityNamePlural: containerNamePlural + ).menuTitle + } + + private func dropEligibilityContext(isReadOnly: Bool) -> ContainerDropEligibility.Context { + ContainerDropEligibility.Context( + activeDatabase: activeDatabase, + activeSchema: switchTarget == .schema ? currentDatabase : nil, + supportsDropDatabase: supportsDropDatabase, + supportsDropSchema: supportsDropSchema, + isReadOnly: isReadOnly + ) + } + + private var loadingView: some View { + VStack(spacing: 10) { + ProgressView().controlSize(.small) + Text(String(format: String(localized: "Loading %@…"), containerNamePlural.lowercased())) + .font(.callout) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + + private func errorView(_ message: String) -> some View { + VStack(spacing: 10) { + Image(systemName: "exclamationmark.triangle") + .font(.title3) + .foregroundStyle(.orange) + Text(String(format: String(localized: "Failed to load %@"), containerNamePlural.lowercased())) + .font(.callout.weight(.medium)) + RevealedTextView(message) + .font(.caption) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .padding(.horizontal, 12) + Button(String(localized: "Retry")) { + Task { await viewModel.fetchDatabases() } + } + .controlSize(.small) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding(.vertical, 12) + } + + private var sqliteState: some View { + VStack(spacing: 10) { + Image(systemName: "doc") + .font(.title3) + .foregroundStyle(.secondary) + Text(String(localized: "SQLite is file-based")) + .font(.callout.weight(.medium)) + Text(String(localized: "Open a different file from the Welcome window.")) + .font(.caption) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .padding(.horizontal, 12) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding(.vertical, 12) + } + + private var emptyState: some View { + VStack(spacing: 10) { + Image(systemName: "magnifyingglass") + .font(.title3) + .foregroundStyle(.secondary) + if viewModel.searchText.isEmpty { + Text(String(format: String(localized: "No %@"), containerNamePlural.lowercased())) + .font(.callout.weight(.medium)) + } else { + Text(String( + format: String(localized: "No %1$@ match “%2$@”"), + containerNamePlural.lowercased(), + viewModel.searchText + )) + .font(.callout) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .padding(.vertical, 12) + } + + private var createButton: some View { + HStack { + Button { + dismiss() + commands?.onRequestCreate() + } label: { + Label(String(format: String(localized: "New %@…"), containerName), systemImage: "plus") + } + .buttonStyle(.borderless) + .help(String(format: String(localized: "New %@ (⌘N)"), containerName)) + .keyboardShortcut("n", modifiers: .command) + + Spacer() + } + .padding(.horizontal, 12) + .padding(.vertical, 8) + } + + private func commitSelection() { + guard let name = viewModel.primarySelection else { return } + onCommit(name) + } + + private func refreshCreateSupport() async { + guard commands != nil else { return } + do { + let spec = try await viewModel.loadCreateDatabaseForm() + supportsCreateDatabase = spec != nil + } catch { + supportsCreateDatabase = false + } + } +} diff --git a/apple/TablePro/Views/DatabaseSwitcher/DatabaseSwitcherPopover.swift b/apple/TablePro/Views/DatabaseSwitcher/DatabaseSwitcherPopover.swift index fde38cc1f1..3d0bd0462d 100644 --- a/apple/TablePro/Views/DatabaseSwitcher/DatabaseSwitcherPopover.swift +++ b/apple/TablePro/Views/DatabaseSwitcher/DatabaseSwitcherPopover.swift @@ -5,8 +5,7 @@ import TableProPluginKit struct DatabaseSwitcherPopoverHost: View { @ObservedObject private var databaseManager = DatabaseManager.shared weak var coordinator: MainContentCoordinator? - /// Which container dimension this presentation switches. An engine can have both, so the caller - /// names the one it opened rather than the popover guessing from the engine's primary target. + // An engine can switch both dimensions, so the caller names the one it opened. var target: ContainerSwitchTarget? let dismiss: () -> Void @@ -28,26 +27,28 @@ struct DatabaseSwitcherPopoverHost: View { switchTarget: switchTarget, databaseType: connection.type, connectionId: connection.id, - isReadOnly: coordinator.safeModeLevel.blocksAllWrites, + commands: DatabaseSwitcherList.ContainerCommands( + isReadOnly: coordinator.safeModeLevel.blocksAllWrites, + schemaEditEligibility: coordinator.schemaEditContext, + onRequestCreate: { [weak coordinator] in + switch switchTarget { + case .database: coordinator?.activeSheet = .createDatabase + case .schema: coordinator?.createSchema(database: nil) + } + }, + onRequestDrop: { [weak coordinator] containers in + coordinator?.requestContainerDrop(containers) + }, + onRequestExport: { [weak coordinator] containers in + coordinator?.openExportDialog(containers: containers) + }, + onRequestEdit: { [weak coordinator] container in + coordinator?.editSchema(container) + } + ), onSelect: { [weak coordinator] container in Task { await coordinator?.switchContainer(to: container, target: switchTarget) } }, - onRequestCreate: { [weak coordinator] in - switch switchTarget { - case .database: coordinator?.activeSheet = .createDatabase - case .schema: coordinator?.createSchema(database: nil) - } - }, - onRequestDrop: { [weak coordinator] containers in - coordinator?.requestContainerDrop(containers) - }, - onRequestExport: { [weak coordinator] containers in - coordinator?.openExportDialog(containers: containers) - }, - onRequestEdit: { [weak coordinator] container in - coordinator?.editSchema(container) - }, - schemaEditEligibility: coordinator.schemaEditContext, dismiss: dismiss ) } else { @@ -58,84 +59,34 @@ struct DatabaseSwitcherPopoverHost: View { struct DatabaseSwitcherPopover: View { let currentDatabase: String? - /// The database the rows belong to, which is the same thing as `currentDatabase` only when the - /// popover is switching databases. In schema mode the rows are schemas inside this database. let activeDatabase: String - let switchTarget: ContainerSwitchTarget let databaseType: DatabaseType let connectionId: UUID - let isReadOnly: Bool + let commands: DatabaseSwitcherList.ContainerCommands let onSelect: (String) -> Void - let onRequestCreate: () -> Void - let onRequestDrop: ([DatabaseContainerRef]) -> Void - let onRequestExport: ([DatabaseContainerRef]) -> Void - let onRequestEdit: (DatabaseContainerRef) -> Void - let schemaEditEligibility: SchemaEditEligibility.Context - - /// An explicit closure rather than `@Environment(\.dismiss)`: the presenter owns the surface, - /// and this content is hosted in an AppKit popover or panel that SwiftUI cannot dismiss. + // AppKit hosts this content in a popover or panel that SwiftUI's dismiss cannot close. let dismiss: () -> Void @StateObject private var viewModel: DatabaseSwitcherViewModel - @State private var supportsCreateDatabase = false - @State private var favoriteDatabases: Set = [] - /// One declaration, read by this view's own frame and by whoever presents it, so the - /// surface and its host can never disagree about how big it is. + // Read by this view's frame and by the presenter, so the two never disagree on size. static let contentSize = NSSize(width: 320, height: 360) - private var supportsDropDatabase: Bool { - PluginManager.shared.supportsDropDatabase(for: databaseType) - } - private var supportsDropSchema: Bool { - PluginManager.shared.supportsDropSchema(for: databaseType) - } - /// The row creates whatever the list is showing, asked per target. It used to be - /// database-only, which left the schema list with no way to make one at all on the sidebar - /// shapes that draw no schema row. - private var showsCreateRow: Bool { - guard !isReadOnly else { return false } - switch switchTarget { - case .database: return supportsCreateDatabase - case .schema: return SchemaEditEligibility.canCreate(context: schemaEditEligibility) - } - } - private var containerName: String { - switch switchTarget { - case .database: PluginManager.shared.containerEntityName(for: databaseType) - case .schema: PluginManager.shared.schemaEntityName(for: databaseType) - } - } - private var containerNamePlural: String { - containerName + "s" - } - init( currentDatabase: String?, activeDatabase: String, switchTarget: ContainerSwitchTarget, databaseType: DatabaseType, connectionId: UUID, - isReadOnly: Bool, + commands: DatabaseSwitcherList.ContainerCommands, onSelect: @escaping (String) -> Void, - onRequestCreate: @escaping () -> Void, - onRequestDrop: @escaping ([DatabaseContainerRef]) -> Void, - onRequestExport: @escaping ([DatabaseContainerRef]) -> Void, - onRequestEdit: @escaping (DatabaseContainerRef) -> Void, - schemaEditEligibility: SchemaEditEligibility.Context, dismiss: @escaping () -> Void ) { self.currentDatabase = currentDatabase self.activeDatabase = activeDatabase - self.switchTarget = switchTarget self.databaseType = databaseType self.connectionId = connectionId - self.isReadOnly = isReadOnly + self.commands = commands self.onSelect = onSelect - self.onRequestCreate = onRequestCreate - self.onRequestDrop = onRequestDrop - self.onRequestExport = onRequestExport - self.onRequestEdit = onRequestEdit - self.schemaEditEligibility = schemaEditEligibility self.dismiss = dismiss self._viewModel = StateObject( wrappedValue: DatabaseSwitcherViewModel( @@ -149,377 +100,21 @@ struct DatabaseSwitcherPopover: View { } var body: some View { - VStack(spacing: 0) { - searchField - - Divider() - - content - - if showsCreateRow { - Divider() - createButton - } - } - .frame(width: Self.contentSize.width, height: Self.contentSize.height) - .background(refreshShortcut) - .task { await viewModel.fetchDatabases() } - .task { await refreshCreateSupport() } - .onAppear { reloadFavorites() } - .onReceive(NotificationCenter.default.publisher(for: .favoriteDatabasesDidChange)) { _ in - reloadFavorites() - } - } - - private var refreshShortcut: some View { - Button("") { - Task { await viewModel.refreshDatabases() } - } - .keyboardShortcut("r", modifiers: .command) - .hidden() - } - - private var searchField: some View { - NativeSearchField( - text: $viewModel.searchText, - placeholder: String(format: String(localized: "Search %@"), containerNamePlural.lowercased()), - onMoveUp: { viewModel.moveUp() }, - onMoveDown: { viewModel.moveDown() }, - onSubmit: { commitSelection() }, - focusOnAppear: true - ) - .padding(.horizontal, 8) - .padding(.vertical, 6) - } - - @ViewBuilder - private var content: some View { - if viewModel.isLoading { - loadingView - } else if let error = viewModel.errorMessage { - errorView(error) - } else if switchTarget == .database, - PluginManager.shared.connectionMode(for: databaseType) == .fileBased { - sqliteState - } else if viewModel.filteredDatabases.isEmpty { - emptyState - } else { - list - } - } - - /// The search field keeps focus for the whole flow, so the list is a presentation of that - /// field's selection rather than a second focusable control. See `FieldDrivenList`. - private var list: some View { - FieldDrivenList( - sections: listSections, - selection: $viewModel.selectedDatabases, - allowsMultipleSelection: true, - onPrimaryAction: { name in - viewModel.selectedDatabase = name - commitSelection() - }, - menuItems: { contextMenuItems(for: $0) }, - row: { row(for: $0) } - ) - .frame(maxWidth: .infinity, maxHeight: .infinity) - } - - /// System containers trail in a section of their own. A switcher is where a container is reached - /// by name, so it lists every one the server returned, unlike the sidebar tree (#2832). - private var listSections: [FieldDrivenListSection] { - let sections = viewModel.visibleSections - return [ - FieldDrivenListSection(id: "containers", items: sections.user), - FieldDrivenListSection(id: "system", title: String(localized: "System"), items: sections.system) - ] - } - - private func row(for database: DatabaseMetadata) -> some View { - let isCurrent = database.name == currentDatabase - return HStack(spacing: 8) { - Image(systemName: "checkmark") - .font(.body.weight(.semibold)) - .selectionAwareTint(Color.accentColor) - .opacity(isCurrent ? 1 : 0) - .frame(width: 14) - .accessibilityLabel( - Text(String(format: String(localized: "Current %@"), containerName.lowercased())) - ) - .accessibilityHidden(!isCurrent) - - Image(systemName: database.icon) - .font(.body) - .selectionAwareTint(database.isSystemDatabase ? Color.secondary : Color.accentColor) - .frame(width: 16) - .accessibilityHidden(true) - - Text(database.name) - .font(.body) - .lineLimit(1) - .truncationMode(.middle) - - Spacer(minLength: 0) - - favoriteIndicator(for: database) - } - .padding(.horizontal, 8) - .contentShape(Rectangle()) - } - - /// A status glyph, not a control. `FieldDrivenCellHostingView` returns nil from `hitTest`, so a - /// button in this row could never be clicked; the right-click menu is where the toggle lives. - @ViewBuilder - private func favoriteIndicator(for database: DatabaseMetadata) -> some View { - let isFavorite = switchTarget == .database && favoriteDatabases.contains(database.name) - Image(systemName: "star.fill") - .font(.caption) - .selectionAwareTint(Color.yellow) - .opacity(isFavorite ? 1 : 0) - .accessibilityLabel(Text(String(localized: "Favorite"))) - .accessibilityHidden(!isFavorite) - } - - private func contextMenuItems(for selection: Set) -> [FieldDrivenMenuItem] { - let targets = containerRefs(for: selection) - let droppable = ContainerDropEligibility.droppable(targets, context: dropEligibilityContext) - var items: [FieldDrivenMenuItem] = favoriteItems(for: targets) - - if !targets.isEmpty { - let copyTitle = targets.count == 1 - ? String(localized: "Copy Name") - : String(format: String(localized: "Copy %lld Names"), targets.count) - items.append(FieldDrivenMenuItem(title: copyTitle) { - ClipboardService.shared.writeText(targets.map(\.name).joined(separator: ",")) - }) - /// The sidebar's menu has always asked whether the dialog can reach these containers - /// before offering Export. This list offered it unconditionally, so the two menus for - /// the same command could disagree. - if ExportPreselection.canPreselect( - containers: targets, - activeDatabase: activeDatabase, - canReachOtherDatabases: databaseType.supportsConnectionPooling - ) { - items.append(FieldDrivenMenuItem(title: String(localized: "Export…")) { - dismiss() - onRequestExport(targets) - }) - } - } - - if let editable = SchemaEditEligibility.editable(targets, context: schemaEditEligibility) { - items.append(.separator) - items.append( - FieldDrivenMenuItem( - title: String(format: String(localized: "Edit %@\u{2026}"), containerName) - ) { - dismiss() - onRequestEdit(editable) + DatabaseSwitcherList( + viewModel: viewModel, + currentDatabase: currentDatabase, + activeDatabase: activeDatabase, + databaseType: databaseType, + connectionId: connectionId, + commands: commands, + onCommit: { name in + if name != currentDatabase { + onSelect(name) } - ) - } - - if !droppable.isEmpty { - items.append(.separator) - items.append(FieldDrivenMenuItem(title: dropMenuTitle(for: droppable)) { dismiss() - onRequestDrop(droppable) - }) - } - return items - } - - /// Only in database mode. In schema mode these rows are schemas, and a schema name written into - /// the database favorites store is a favorite that names nothing. - private func reloadFavorites() { - guard switchTarget == .database else { return } - favoriteDatabases = Set( - FavoriteDatabasesStorage.shared.favorites(for: connectionId).map(\.database) - ) - } - - private func favoriteItems(for targets: [DatabaseContainerRef]) -> [FieldDrivenMenuItem] { - guard switchTarget == .database else { return [] } - let databases = targets.filter { $0.kind == .database }.compactMap(\.database) - guard !databases.isEmpty else { return [] } - - let stored = FavoriteDatabasesStorage.shared.favorites(for: connectionId) - let environments = Dictionary( - stored.map { ($0.database, $0.environment) }, - uniquingKeysWith: { first, _ in first } - ) - let state = FavoriteDatabaseSelectionState(environments: databases.map { environments[$0] }) - - var items: [FieldDrivenMenuItem] = [ - FieldDrivenMenuItem( - title: FavoriteDatabaseMenu.submenuTitle(for: state), - submenu: FavoriteDatabaseMenu.environmentItems(for: state).map { item in - FieldDrivenMenuItem(title: item.title, isOn: item.isOn) { - for database in databases { - FavoriteDatabasesStorage.shared.setFavorite( - database: database, - environment: item.environment, - connectionId: connectionId - ) - } - } - } - ) - ] - if state.hasFavorite { - items.append(FieldDrivenMenuItem(title: FavoriteDatabaseMenu.removeTitle) { - for database in databases { - FavoriteDatabasesStorage.shared.removeFavorite( - database: database, - connectionId: connectionId - ) - } - }) - } - items.append(.separator) - return items - } - - /// A row's ref has to carry the kind the row actually is. Building a `.database` ref out of a - /// schema name sends Drop to `dropDatabase` and gives Export a container it cannot resolve. - private func containerRefs(for selection: Set) -> [DatabaseContainerRef] { - viewModel.filteredDatabases - .filter { selection.contains($0.name) } - .map { item in - switch switchTarget { - case .database: - return .database(item.name, isSystem: item.isSystemDatabase) - case .schema: - return .schema( - database: activeDatabase, schema: item.name, isSystem: item.isSystemDatabase - ) - } - } - } - - private func dropMenuTitle(for targets: [DatabaseContainerRef]) -> String { - DatabaseDropRequest( - targets: targets, - entityName: containerName, - entityNamePlural: containerNamePlural - ).menuTitle - } - - private var dropEligibilityContext: ContainerDropEligibility.Context { - ContainerDropEligibility.Context( - activeDatabase: activeDatabase, - activeSchema: switchTarget == .schema ? currentDatabase : nil, - supportsDropDatabase: supportsDropDatabase, - supportsDropSchema: supportsDropSchema, - isReadOnly: isReadOnly + }, + dismiss: dismiss ) - } - - private var loadingView: some View { - VStack(spacing: 10) { - ProgressView().controlSize(.small) - Text(String(format: String(localized: "Loading %@…"), containerNamePlural.lowercased())) - .font(.callout) - .foregroundStyle(.secondary) - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - } - - private func errorView(_ message: String) -> some View { - VStack(spacing: 10) { - Image(systemName: "exclamationmark.triangle") - .font(.title3) - .foregroundStyle(.orange) - Text(String(format: String(localized: "Failed to load %@"), containerNamePlural.lowercased())) - .font(.callout.weight(.medium)) - RevealedTextView(message) - .font(.caption) - .foregroundStyle(.secondary) - .multilineTextAlignment(.center) - .padding(.horizontal, 12) - Button(String(localized: "Retry")) { - Task { await viewModel.fetchDatabases() } - } - .controlSize(.small) - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .padding(.vertical, 12) - } - - private var sqliteState: some View { - VStack(spacing: 10) { - Image(systemName: "doc") - .font(.title3) - .foregroundStyle(.secondary) - Text(String(localized: "SQLite is file-based")) - .font(.callout.weight(.medium)) - Text(String(localized: "Open a different file from the Welcome window.")) - .font(.caption) - .foregroundStyle(.secondary) - .multilineTextAlignment(.center) - .padding(.horizontal, 12) - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .padding(.vertical, 12) - } - - private var emptyState: some View { - VStack(spacing: 10) { - Image(systemName: "magnifyingglass") - .font(.title3) - .foregroundStyle(.secondary) - if viewModel.searchText.isEmpty { - Text(String(format: String(localized: "No %@"), containerNamePlural.lowercased())) - .font(.callout.weight(.medium)) - } else { - Text(String( - format: String(localized: "No %1$@ match “%2$@”"), - containerNamePlural.lowercased(), - viewModel.searchText - )) - .font(.callout) - .foregroundStyle(.secondary) - .multilineTextAlignment(.center) - } - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .padding(.vertical, 12) - } - - private var createButton: some View { - HStack { - Button { - dismiss() - onRequestCreate() - } label: { - Label(String(format: String(localized: "New %@…"), containerName), systemImage: "plus") - } - .buttonStyle(.borderless) - .help(String(format: String(localized: "New %@ (⌘N)"), containerName)) - .keyboardShortcut("n", modifiers: .command) - - Spacer() - } - .padding(.horizontal, 12) - .padding(.vertical, 8) - } - - private func commitSelection() { - guard let name = viewModel.primarySelection else { return } - if name == currentDatabase { - dismiss() - return - } - onSelect(name) - dismiss() - } - - private func refreshCreateSupport() async { - do { - let spec = try await viewModel.loadCreateDatabaseForm() - supportsCreateDatabase = spec != nil - } catch { - supportsCreateDatabase = false - } + .frame(width: Self.contentSize.width, height: Self.contentSize.height) } } diff --git a/apple/TablePro/Views/DatabaseSwitcher/DatabaseSwitcherSheet.swift b/apple/TablePro/Views/DatabaseSwitcher/DatabaseSwitcherSheet.swift deleted file mode 100644 index 61d8d74e79..0000000000 --- a/apple/TablePro/Views/DatabaseSwitcher/DatabaseSwitcherSheet.swift +++ /dev/null @@ -1,260 +0,0 @@ -import AppKit -import SwiftUI -import TableProPluginKit - -/// Database picker presented as a modal sheet for backup and restore flows. -/// Quick database switching from the toolbar uses `DatabaseSwitcherPopover`. -struct DatabaseSwitcherSheet: View { - enum Mode { - case backup - case restore - } - - @Binding var isPresented: Bool - @Environment(\.dismiss) private var dismiss - - let mode: Mode - let currentDatabase: String? - let databaseType: DatabaseType - let connectionId: UUID - let onSelect: (String) -> Void - - @StateObject private var viewModel: DatabaseSwitcherViewModel - - private enum FocusField { case list } - - @FocusState private var focus: FocusField? - - init( - isPresented: Binding, - mode: Mode, - currentDatabase: String?, - databaseType: DatabaseType, - connectionId: UUID, - onSelect: @escaping (String) -> Void - ) { - self._isPresented = isPresented - self.mode = mode - self.currentDatabase = currentDatabase - self.databaseType = databaseType - self.connectionId = connectionId - self.onSelect = onSelect - self._viewModel = StateObject( - wrappedValue: DatabaseSwitcherViewModel( - connectionId: connectionId, - currentDatabase: currentDatabase, - databaseType: databaseType, - sidebarState: SharedSidebarState.forConnection(connectionId) - )) - } - - var body: some View { - NavigationStack { - VStack(spacing: 0) { - searchField - Divider() - content - } - .navigationTitle(navigationTitle) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button(String(localized: "Cancel")) { - dismiss() - } - } - ToolbarItem(placement: .confirmationAction) { - Button(primaryButtonLabel) { - commitSelection() - } - .disabled(primaryButtonDisabled) - } - } - } - .frame(width: 480, height: 460) - .onExitCommand { dismiss() } - .task { await viewModel.fetchDatabases() } - } - - private var navigationTitle: String { - switch mode { - case .backup: return String(localized: "Backup Database") - case .restore: return String(localized: "Restore Database") - } - } - - private var primaryButtonLabel: String { - switch mode { - case .backup: return String(localized: "Choose Destination…") - case .restore: return String(localized: "Restore") - } - } - - private var primaryButtonDisabled: Bool { - viewModel.selectedDatabase == nil - } - - private var searchField: some View { - NativeSearchField( - text: $viewModel.searchText, - placeholder: String(localized: "Search databases"), - onMoveUp: { viewModel.moveUp() }, - onMoveDown: { viewModel.moveDown() }, - focusOnAppear: true - ) - .padding(.horizontal, 12) - .padding(.vertical, 8) - } - - @ViewBuilder - private var content: some View { - if viewModel.isLoading { - loadingView - } else if let error = viewModel.errorMessage { - errorView(error) - } else if viewModel.filteredDatabases.isEmpty { - emptyState - } else { - list - } - } - - private var list: some View { - ScrollViewReader { proxy in - let sections = viewModel.visibleSections - List(selection: $viewModel.selectedDatabase) { - ForEach(sections.user) { db in - row(for: db) - } - if !sections.system.isEmpty { - Section(String(localized: "System")) { - ForEach(sections.system) { db in - row(for: db) - } - } - } - } - .listStyle(.inset) - .focused($focus, equals: .list) - .onChange(of: viewModel.selectedDatabase) { newValue in - guard let item = newValue else { return } - withMotion(.easeInOut(duration: 0.15)) { - proxy.scrollTo(item, anchor: .center) - } - } - .modifier(ReturnKeyCommit(action: commitSelection)) - } - } - - private func row(for database: DatabaseMetadata) -> some View { - let isCurrent = database.name == currentDatabase - return HStack(spacing: 8) { - Image(systemName: "checkmark") - .font(.body.weight(.semibold)) - .selectionAwareTint(Color.accentColor) - .opacity(isCurrent ? 1 : 0) - .frame(width: 14) - .accessibilityLabel(Text("Current database")) - .accessibilityHidden(!isCurrent) - - Image(systemName: database.icon) - .font(.body) - .selectionAwareTint(database.isSystemDatabase ? Color.secondary : Color.accentColor) - .frame(width: 16) - .accessibilityHidden(true) - - Text(database.name) - .font(.body) - .lineLimit(1) - .truncationMode(.middle) - - Spacer(minLength: 0) - } - .padding(.vertical, 2) - .contentShape(Rectangle()) - .listRowSeparator(.hidden) - .id(database.name) - .tag(database.name) - } - - private var loadingView: some View { - VStack(spacing: 10) { - ProgressView().controlSize(.small) - Text(String(localized: "Loading databases…")) - .font(.callout) - .foregroundStyle(.secondary) - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - } - - private func errorView(_ message: String) -> some View { - VStack(spacing: 10) { - Image(systemName: "exclamationmark.triangle") - .font(.title3) - .foregroundStyle(.orange) - Text(String(localized: "Failed to load databases")) - .font(.callout.weight(.medium)) - RevealedTextView(message) - .font(.caption) - .foregroundStyle(.secondary) - .multilineTextAlignment(.center) - .padding(.horizontal, 16) - Button(String(localized: "Retry")) { - Task { await viewModel.fetchDatabases() } - } - .controlSize(.small) - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - } - - private var emptyState: some View { - VStack(spacing: 10) { - Image(systemName: "magnifyingglass") - .font(.title3) - .foregroundStyle(.secondary) - if viewModel.searchText.isEmpty { - Text(String(localized: "No databases")) - .font(.callout.weight(.medium)) - } else { - Text(String(format: String(localized: "No databases match “%@”"), viewModel.searchText)) - .font(.callout) - .foregroundStyle(.secondary) - .multilineTextAlignment(.center) - .padding(.horizontal, 16) - } - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - } - - private func commitSelection() { - guard let database = viewModel.selectedDatabase else { return } - onSelect(database) - } -} - -#Preview("Backup") { - DatabaseSwitcherSheet( - isPresented: .constant(true), - mode: .backup, - currentDatabase: "production", - databaseType: .postgresql, - connectionId: UUID() - ) { _ in } -} - -/// `onKeyPress` is macOS 14. On 13 the sheet's default button still commits, so Return keeps -/// working; what the handler adds is committing while focus sits in the list. -private struct ReturnKeyCommit: ViewModifier { - let action: () -> Void - - @ViewBuilder - func body(content: Content) -> some View { - if #available(macOS 14.0, *) { - content.onKeyPress(.return) { - action() - return .handled - } - } else { - content - } - } -} diff --git a/apple/TableProTests/Core/Storage/CodableListPreferenceStoreTests.swift b/apple/TableProTests/Core/Storage/CodableListPreferenceStoreTests.swift index 1a4bf52310..98f6bc2530 100644 --- a/apple/TableProTests/Core/Storage/CodableListPreferenceStoreTests.swift +++ b/apple/TableProTests/Core/Storage/CodableListPreferenceStoreTests.swift @@ -16,7 +16,7 @@ struct CodableListPreferenceStoreTests { private let pool = EphemeralDefaultsPool() private func makeStore() throws -> CodableListPreferenceStore { - CodableListPreferenceStore(key: DefaultsKey<[Item]>("com.TablePro.test.items"), store: try pool.make().defaults) + CodableListPreferenceStore(key: JSONDefaultsKey<[Item]>("com.TablePro.test.items"), store: try pool.make().defaults) } @Test("Loading an unset key returns an empty list") diff --git a/apple/TableProTests/Core/Storage/JSONStoreTests.swift b/apple/TableProTests/Core/Storage/JSONStoreTests.swift new file mode 100644 index 0000000000..99538a15ea --- /dev/null +++ b/apple/TableProTests/Core/Storage/JSONStoreTests.swift @@ -0,0 +1,153 @@ +// +// JSONStoreTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import Testing + +private struct Sample: Codable, Equatable { + var name: String + var count: Int + var savedAt: Date +} + +private let sample = Sample(name: "orders", count: 3, savedAt: Date(timeIntervalSince1970: 1_700_000_000)) + +struct JSONDefaultsKeyTests { + @Test + func missingKeyReadsAsMissing() throws { + let scratch = try EphemeralDefaults() + let read = scratch.defaults.read(JSONDefaultsKey("com.TablePro.test.sample")) + guard case .missing = read else { + Issue.record("expected missing, got \(read)") + return + } + } + + @Test + func writtenValueReadsBackWithTheBytesAPlainEncoderWrites() throws { + let scratch = try EphemeralDefaults() + let key = JSONDefaultsKey("com.TablePro.test.sample") + + try scratch.defaults.write(sample, to: key) + + #expect(scratch.defaults.read(key).value == sample) + let stored = try #require(scratch.defaults.data(forKey: key.name)) + let storedObject = try JSONSerialization.jsonObject(with: stored) as? NSDictionary + let plainObject = try JSONSerialization.jsonObject(with: JSONEncoder().encode(sample)) as? NSDictionary + #expect(storedObject == plainObject) + } + + @Test + func undecodableValueReadsAsUnreadableAndStaysStored() throws { + let scratch = try EphemeralDefaults() + let key = JSONDefaultsKey("com.TablePro.test.sample") + let damaged = Data("not json".utf8) + scratch.defaults.set(damaged, forKey: key.name) + + #expect(scratch.defaults.read(key).isUnreadable) + #expect(scratch.defaults.data(forKey: key.name) == damaged) + } + + @Test + func removeClearsTheKey() throws { + let scratch = try EphemeralDefaults() + let key = JSONDefaultsKey("com.TablePro.test.sample") + try scratch.defaults.write(sample, to: key) + + scratch.defaults.removeValue(for: key) + + #expect(scratch.defaults.object(forKey: key.name) == nil) + } + + @Test + func sortedKeysCodingWritesKeysInOrder() throws { + let scratch = try EphemeralDefaults() + let key = JSONDefaultsKey<[String: Int]>("com.TablePro.test.sorted", coding: .sortedKeys) + + try scratch.defaults.write(["b": 2, "a": 1, "c": 3], to: key) + + let stored = try #require(scratch.defaults.data(forKey: key.name)) + #expect(String(decoding: stored, as: UTF8.self) == #"{"a":1,"b":2,"c":3}"#) + } +} + +struct JSONFileStoreTests { + private func makeDirectory() throws -> URL { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("JSONFileStoreTests-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + return directory + } + + @Test + func missingFileReadsAsMissing() throws { + let directory = try makeDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let store = JSONFileStore(url: directory.appendingPathComponent("absent.json")) + + guard case .missing = store.read() else { + Issue.record("expected missing") + return + } + #expect(!store.exists) + } + + @Test + func writeCreatesTheFolderAndReadsBack() throws { + let directory = try makeDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("nested/sample.json") + let store = JSONFileStore(url: url, coding: .prettyISO8601) + + try store.write(sample) + + #expect(store.read().value == sample) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + #expect(try Data(contentsOf: url) == (try encoder.encode(sample))) + } + + @Test + func undecodableFileReadsAsUnreadableAndIsKept() throws { + let directory = try makeDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let url = directory.appendingPathComponent("damaged.json") + let damaged = Data("{\"name\":".utf8) + try damaged.write(to: url) + let store = JSONFileStore(url: url) + + #expect(store.read().isUnreadable) + #expect(try Data(contentsOf: url) == damaged) + } + + @Test + func removingAMissingFileSucceeds() throws { + let directory = try makeDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let store = JSONFileStore(url: directory.appendingPathComponent("absent.json")) + + try store.remove() + + #expect(!store.exists) + } +} + +struct StoreLogTests { + @Test + func publicPartStopsAtTheConnectionId() { + let scope = TableScope(connectionId: UUID(), database: "shop", schema: "public", table: "orders") + let name = PreferenceKeys.columnDisplayFormats(scope).name + + #expect(StoreLog.publicPart(of: name) == "com.TablePro.columns.displayFormat.*") + } + + @Test + func publicPartKeepsANameWithNoConnectionId() { + #expect(StoreLog.publicPart(of: "com.TablePro.favoriteDatabases") == "com.TablePro.favoriteDatabases") + #expect(StoreLog.publicPart(of: "AgentSessions.json") == "AgentSessions.json") + } +} diff --git a/apple/changelog.d/4303.changed.md b/apple/changelog.d/4303.changed.md new file mode 100644 index 0000000000..af327ef861 --- /dev/null +++ b/apple/changelog.d/4303.changed.md @@ -0,0 +1 @@ +Restore Dump's database picker shows favorite databases and their menu, like the toolbar switcher.