Repository Public License
1// Persistence — the storage layer of ORIX Navigator on the system SQLite (see docs/PERSISTENCE.md).2import Foundation3import NavigatorCore45/// Runs file-system work (create directories, move a corrupt database aside, write an export) off the main6/// actor: a plain actor executes on the cooperative pool, never on the main thread.7actor FileWorker {8 static let shared = FileWorker()910 func run<T: Sendable>(_ body: @Sendable () throws -> T) throws -> T { try body() }11}1213/// What happened when a corrupt database was replaced.14public struct RecoveryReport: Sendable, Equatable {15 /// Why the original database was rejected.16 public var reason: String17 /// Directory next to the database that now holds the untouched original files.18 public var quarantineDirectory: URL19 /// The files moved there (database, `-wal`, `-shm` when present).20 public var movedFiles: [URL]21 public var date: Date22}2324/// The single entry point of the storage layer: opens the database, migrates it and vends the typed stores.25///26/// ```swift27/// let database = try await NavigatorDatabase(url: supportDirectory.appending(path: "Navigator.sqlite"))28/// let launch = try await database.session.beginSession()29/// let session = try await database.session.restore()30/// ```31///32/// Every store method is `async` and runs on the database's own serial queues; nothing here touches the33/// main actor.34public final class NavigatorDatabase: Sendable {35 public enum IntegrityCheckPolicy: Sendable, Equatable {36 /// Only the checks SQLite performs while reading.37 case never38 /// `PRAGMA quick_check` when the previous run did not shut down cleanly (default).39 case afterUncleanShutdown40 /// `PRAGMA quick_check` at every open.41 case always42 }4344 public struct Options: Sendable {45 public var connections: SQLiteDatabase.Configuration46 public var integrityCheck: IntegrityCheckPolicy4748 public init(connections: SQLiteDatabase.Configuration = .init(),49 integrityCheck: IntegrityCheckPolicy = .afterUncleanShutdown) {50 self.connections = connections; self.integrityCheck = integrityCheck51 }52 }5354 /// Facts about this open.55 public struct OpenInfo: Sendable, Equatable {56 /// Schema version found on disk (0 for a new database).57 public var previousSchemaVersion: Int58 public var schemaVersion: Int59 public var ranIntegrityCheck: Bool60 }6162 /// Low-level access for modules that need their own SQL. Prefer the stores.63 public let sqlite: SQLiteDatabase64 public let ghosts: GhostRegistry65 public let openInfo: OpenInfo66 private let context: StoreContext6768 private init(sqlite: SQLiteDatabase, openInfo: OpenInfo) {69 let ghosts = GhostRegistry()70 self.sqlite = sqlite71 self.ghosts = ghosts72 self.openInfo = openInfo73 self.context = StoreContext(database: sqlite, ghosts: ghosts)74 }7576 // MARK: Opening7778 /// Opens (creating and migrating as needed) the database at `url`.79 ///80 /// Throws `PersistenceError.databaseTooNew` for a database written by a newer build and81 /// `PersistenceError.corrupt` for a damaged file. In both cases the file is left exactly as it was.82 public convenience init(url: URL, options: Options = Options()) async throws {83 let (sqlite, info) = try await Self.open(.file(url), options: options)84 self.init(sqlite: sqlite, openInfo: info)85 }8687 /// A private in-memory database with the latest schema, for tests and previews.88 public static func inMemory() async throws -> NavigatorDatabase {89 let (sqlite, info) = try await open(.memory, options: Options())90 return NavigatorDatabase(sqlite: sqlite, openInfo: info)91 }9293 /// Opens the database and, if it is corrupt, moves the damaged files into a quarantine directory next to94 /// it, creates a fresh database and reports what was done. User data is never deleted: the caller tells95 /// the user and can offer the quarantined files for export or support.96 ///97 /// A database that is merely *too new* is not corruption and still throws.98 public static func openRecovering(url: URL, options: Options = Options()) async throws99 -> (database: NavigatorDatabase, recovery: RecoveryReport?) {100 do {101 return (try await NavigatorDatabase(url: url, options: options), nil)102 } catch PersistenceError.corrupt(_, let details) {103 let report = try await FileWorker.shared.run { try quarantine(url, reason: details) }104 return (try await NavigatorDatabase(url: url, options: options), report)105 }106 }107108 /// The files SQLite keeps for a database in WAL mode.109 public static func fileURLs(for url: URL) -> [URL] {110 [url, URL(fileURLWithPath: url.path + "-wal"), URL(fileURLWithPath: url.path + "-shm")]111 }112113 private static func open(_ location: SQLiteConnection.Location, options: Options) async throws114 -> (SQLiteDatabase, OpenInfo) {115 let path: String116 if case .file(let url) = location { path = url.path } else { path = ":memory:" }117 if case .file(let url) = location {118 try await FileWorker.shared.run {119 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(),120 withIntermediateDirectories: true)121 }122 }123 let sqlite: SQLiteDatabase124 do {125 sqlite = try await SQLiteDatabase(location: location, configuration: options.connections)126 } catch let error as SQLiteError where error.indicatesCorruption {127 throw PersistenceError.corrupt(path: path, details: error.message)128 }129 do {130 let policy = options.integrityCheck131 let info = try await sqlite.write { connection -> OpenInfo in132 let found = try Migrator.currentVersion(connection)133 guard found <= Schema.latestVersion else {134 throw PersistenceError.databaseTooNew(found: found, supported: Schema.latestVersion)135 }136 var shouldCheck = policy == .always137 if policy == .afterUncleanShutdown, found > 0 {138 let flag = try connection.scalar("SELECT value FROM app_state WHERE key = ?",139 [SessionStore.cleanShutdownKey], as: String.self)140 shouldCheck = flag == "0"141 }142 if shouldCheck {143 let problems = try integrityProblems(connection, full: false)144 guard problems.isEmpty else {145 throw PersistenceError.corrupt(path: path, details: problems.prefix(5).joined(separator: "; "))146 }147 }148 let outcome = try Migrator.migrate(connection)149 return OpenInfo(previousSchemaVersion: found, schemaVersion: outcome.toVersion,150 ranIntegrityCheck: shouldCheck)151 }152 if case .file(let url) = location {153 try await FileWorker.shared.run { applyFileProtection(to: url) }154 }155 return (sqlite, info)156 } catch {157 await sqlite.close()158 if let error = error as? SQLiteError, error.indicatesCorruption {159 throw PersistenceError.corrupt(path: path, details: error.message)160 }161 throw error162 }163 }164165 private static func integrityProblems(_ connection: SQLiteConnection, full: Bool) throws -> [String] {166 let rows = try connection.query(full ? "PRAGMA integrity_check" : "PRAGMA quick_check")167 let messages = rows.compactMap { row -> String? in168 if case .text(let text) = row[0] { return text }169 return nil170 }171 return messages == ["ok"] ? [] : messages172 }173174 private static func quarantine(_ url: URL, reason: String) throws -> RecoveryReport {175 let manager = FileManager.default176 let formatter = DateFormatter()177 formatter.locale = Locale(identifier: "en_US_POSIX")178 formatter.timeZone = TimeZone(identifier: "UTC")179 formatter.dateFormat = "yyyyMMdd-HHmmss"180 let now = Date.now181 let base = url.deletingLastPathComponent()182 var directory = base.appending(path: "\(url.lastPathComponent).corrupt-\(formatter.string(from: now))",183 directoryHint: .isDirectory)184 var attempt = 1185 while manager.fileExists(atPath: directory.path) {186 attempt += 1187 directory = base.appending(path: "\(url.lastPathComponent).corrupt-\(formatter.string(from: now))-\(attempt)",188 directoryHint: .isDirectory)189 }190 try manager.createDirectory(at: directory, withIntermediateDirectories: true)191 var moved: [URL] = []192 for file in fileURLs(for: url) where manager.fileExists(atPath: file.path) {193 let destination = directory.appending(path: file.lastPathComponent)194 try manager.moveItem(at: file, to: destination)195 moved.append(destination)196 }197 return RecoveryReport(reason: reason, quarantineDirectory: directory, movedFiles: moved, date: now)198 }199200 /// iOS: the database, WAL and shared-memory files stay encrypted until the first unlock after boot, and201 /// remain readable afterwards so background sync and downloads can write while the device is locked.202 /// The open flag covers files SQLite creates; this covers files that already existed.203 private static func applyFileProtection(to url: URL) {204 #if os(iOS)205 for file in fileURLs(for: url) where FileManager.default.fileExists(atPath: file.path) {206 try? FileManager.default.setAttributes(207 [.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], ofItemAtPath: file.path)208 }209 #endif210 }211212 // MARK: Maintenance213214 /// Runs `PRAGMA quick_check` (or the slower, exhaustive `integrity_check`). An empty result means healthy.215 public func checkIntegrity(full: Bool = false) async throws -> [String] {216 try await sqlite.write { try Self.integrityProblems($0, full: full) }217 }218219 public func schemaVersion() async throws -> Int {220 try await sqlite.read { try Migrator.currentVersion($0) }221 }222223 /// Closes every connection. Stores throw `PersistenceError.databaseClosed` afterwards.224 public func close() async { await sqlite.close() }225226 // MARK: Stores227228 public var profiles: ProfileStore { ProfileStore(context: context) }229 public var spaces: SpaceStore { SpaceStore(context: context) }230 public var windows: WindowStore { WindowStore(context: context) }231 public var tabs: TabStore { TabStore(context: context) }232 public var tabGroups: TabGroupStore { TabGroupStore(context: context) }233 public var session: SessionStore { SessionStore(context: context) }234 public var history: HistoryStore { HistoryStore(context: context) }235 public var bookmarks: BookmarkStore { BookmarkStore(context: context) }236 public var downloads: DownloadStore { DownloadStore(context: context) }237 public var permissions: PermissionStore { PermissionStore(context: context) }238 public var archives: ArchiveStore { ArchiveStore(context: context) }239 public var snapshots: SnapshotStore { SnapshotStore(context: context) }240 public var notes: NoteStore { NoteStore(context: context) }241 public var canvases: CanvasStore { CanvasStore(context: context) }242 public var agentRuns: AgentRunStore { AgentRunStore(context: context) }243 public var workflows: WorkflowStore { WorkflowStore(context: context) }244 public var sync: SyncStore { SyncStore(context: context) }245 public var settings: SettingsStore { SettingsStore(context: context) }246 public var lifecycle: DataLifecycle { DataLifecycle(context: context) }247}248