SPB Git

Repository Public License

SessionStores.swift 23.6 KB 482 lines swift

1import Foundation2import NavigatorCore34/// A window the user closed, with the tabs it had, kept so it can be reopened.5public struct ClosedWindow: Sendable, Hashable {6    public var window: BrowserWindow7    public var tabs: [Tab]8}910enum SessionSQL {11    /// Display order inside a window: pinned tabs first, then the user's order.12    static let tabOrder = "is_pinned DESC, sort_order, created_at, id"1314    static func saveWindow(_ window: BrowserWindow, _ context: StoreContext, _ connection: SQLiteConnection) throws {15        if context.ghosts.contains(window.id.raw) {16            throw PersistenceError.ghostWriteRejected(entity: "window \(window.id)")17        }18        try context.requireSpace(window.spaceID, connection)19        try window.save(connection)20    }2122    /// `verified` caches owners already checked in this transaction (a session save touches few windows).23    static func saveTab(_ tab: Tab, _ context: StoreContext, _ connection: SQLiteConnection,24                        verified: inout Set<UUID>) throws {25        if !verified.contains(tab.windowID.raw) {26            try context.requireWindow(tab.windowID, connection)27            verified.insert(tab.windowID.raw)28        }29        if !verified.contains(tab.spaceID.raw) {30            try context.requireSpace(tab.spaceID, connection)31            verified.insert(tab.spaceID.raw)32        }33        try tab.save(connection)34    }3536    static func openTabs(window: WindowID, _ connection: SQLiteConnection) throws -> [Tab] {37        try connection.query("SELECT * FROM tabs WHERE window_id = ? AND closed_at IS NULL ORDER BY \(tabOrder)",38                             [window]).map(Tab.init(row:))39    }40}4142public struct WindowStore: Sendable {43    let context: StoreContext4445    public func save(_ window: BrowserWindow) async throws {46        try await context.transaction { try SessionSQL.saveWindow(window, context, $0) }47    }4849    public func window(_ id: WindowID) async throws -> BrowserWindow? {50        try await context.read {51            try $0.queryOne("SELECT * FROM windows WHERE id = ?", [id]).map(BrowserWindow.init(row:))52        }53    }5455    /// Open windows, optionally of one space, in `order`.56    public func openWindows(space: SpaceID? = nil) async throws -> [BrowserWindow] {57        try await context.read { connection in58            try connection.query("""59            SELECT * FROM windows WHERE closed_at IS NULL AND (?1 IS NULL OR space_id = ?1) ORDER BY sort_order, id60            """, [space]).map(BrowserWindow.init(row:))61        }62    }6364    /// Marks the window closed but keeps it and its tabs for "reopen closed window".65    public func close(_ id: WindowID, at date: Date = .now) async throws {66        try await context.transaction {67            _ = try $0.execute("UPDATE windows SET closed_at = ? WHERE id = ? AND closed_at IS NULL", [date, id])68        }69    }7071    /// Most recently closed windows first, each with the tabs that were open in it.72    public func recentlyClosed(limit: Int = 10) async throws -> [ClosedWindow] {73        try await context.read { connection in74            try connection.query("SELECT * FROM windows WHERE closed_at IS NOT NULL ORDER BY closed_at DESC LIMIT ?",75                                 [limit]).map { row in76                let window = try BrowserWindow(row: row)77                return ClosedWindow(window: window, tabs: try SessionSQL.openTabs(window: window.id, connection))78            }79        }80    }8182    /// Reopens a closed window and returns it with its tabs.83    public func reopen(_ id: WindowID) async throws -> ClosedWindow {84        try await context.transaction { connection in85            guard try connection.execute("UPDATE windows SET closed_at = NULL WHERE id = ?", [id]) == 1,86                  let row = try connection.queryOne("SELECT * FROM windows WHERE id = ?", [id]) else {87                throw PersistenceError.notFound(entity: "window", id: id.string)88            }89            return ClosedWindow(window: try BrowserWindow(row: row), tabs: try SessionSQL.openTabs(window: id, connection))90        }91    }9293    /// Permanently deletes the window and its tabs.94    public func delete(_ id: WindowID) async throws {95        try await context.transaction { _ = try $0.execute("DELETE FROM windows WHERE id = ?", [id]) }96    }97}9899public struct TabStore: Sendable {100    let context: StoreContext101102    public func save(_ tab: Tab) async throws { try await save([tab]) }103104    /// Inserts or updates several tabs in one transaction.105    public func save(_ tabs: [Tab]) async throws {106        try await context.transaction { connection in107            var verified = Set<UUID>()108            for tab in tabs { try SessionSQL.saveTab(tab, context, connection, verified: &verified) }109        }110    }111112    public func tab(_ id: TabID) async throws -> Tab? {113        try await context.read { try $0.queryOne("SELECT * FROM tabs WHERE id = ?", [id]).map(Tab.init(row:)) }114    }115116    /// Open tabs of a window: pinned first, then by `order`.117    public func tabs(window: WindowID) async throws -> [Tab] {118        try await context.read { try SessionSQL.openTabs(window: window, $0) }119    }120121    /// Open tabs of a space across its open windows.122    public func tabs(space: SpaceID) async throws -> [Tab] {123        try await context.read { connection in124            try connection.query("""125            SELECT t.* FROM tabs t JOIN windows w ON w.id = t.window_id126            WHERE t.space_id = ? AND t.closed_at IS NULL AND w.closed_at IS NULL127            ORDER BY w.sort_order, t.window_id, t.is_pinned DESC, t.sort_order, t.created_at, t.id128            """, [space]).map(Tab.init(row:))129        }130    }131132    public func pinnedTabs(space: SpaceID) async throws -> [Tab] {133        try await tabs(space: space).filter(\.isPinned)134    }135136    public func tabs(group: TabGroupID) async throws -> [Tab] {137        try await context.read { connection in138            try connection.query("SELECT * FROM tabs WHERE group_id = ? AND closed_at IS NULL ORDER BY sort_order, id",139                                 [group]).map(Tab.init(row:))140        }141    }142143    /// Direct children of a tab (tabs opened from it), for tree-style tab lists.144    public func children(of parent: TabID) async throws -> [Tab] {145        try await context.read { connection in146            try connection.query("SELECT * FROM tabs WHERE parent_id = ? AND closed_at IS NULL ORDER BY sort_order, id",147                                 [parent]).map(Tab.init(row:))148        }149    }150151    /// Rewrites `order` of the given tabs to match the sequence. Tabs not listed keep their value.152    public func reorder(window: WindowID, _ ids: [TabID]) async throws {153        try await context.transaction { connection in154            for (index, id) in ids.enumerated() {155                try connection.execute("UPDATE tabs SET sort_order = ? WHERE id = ? AND window_id = ?",156                                       [index, id, window])157            }158        }159    }160161    public func setPinned(_ id: TabID, _ pinned: Bool) async throws {162        try await context.transaction {163            _ = try $0.execute("UPDATE tabs SET is_pinned = ? WHERE id = ?", [pinned, id])164        }165    }166167    /// Updates only the lifecycle column, so a concurrent `touchTab` or title change is never overwritten (Blink).168    public func setLifecycle(_ id: TabID, _ lifecycle: TabLifecycle) async throws {169        try await context.transaction {170            _ = try $0.execute("UPDATE tabs SET lifecycle = ? WHERE id = ?", [lifecycle.rawValue, id])171        }172    }173174    public func setGroup(_ id: TabID, _ group: TabGroupID?) async throws {175        try await context.transaction {176            _ = try $0.execute("UPDATE tabs SET group_id = ? WHERE id = ?", [group, id])177        }178    }179180    /// Moves a tab to another window (same or different space) at the given order.181    public func move(_ id: TabID, to window: WindowID, order: Int) async throws {182        try await context.transaction { connection in183            try context.requireWindow(window, connection)184            let changed = try connection.execute("""185            UPDATE tabs SET window_id = ?1, sort_order = ?2,186                            space_id = (SELECT space_id FROM windows WHERE id = ?1) WHERE id = ?3187            """, [window, order, id])188            guard changed == 1 else { throw PersistenceError.notFound(entity: "tab", id: id.string) }189            // A group belongs to one space: drop the link when the tab leaves it.190            try connection.execute("""191            UPDATE tabs SET group_id = NULL192            WHERE id = ?1 AND group_id IS NOT NULL193              AND (SELECT space_id FROM tab_groups WHERE id = tabs.group_id) IS NOT tabs.space_id194            """, [id])195        }196    }197198    /// Marks the tab closed and keeps it for "reopen closed tab".199    public func close(_ id: TabID, at date: Date = .now) async throws {200        try await context.transaction {201            _ = try $0.execute("UPDATE tabs SET closed_at = ?, lifecycle = 'dormant' WHERE id = ? AND closed_at IS NULL",202                               [date, id])203        }204    }205206    /// Individually closed tabs, most recent first. Tabs of a closed *window* are reported by `WindowStore`.207    public func recentlyClosed(space: SpaceID? = nil, limit: Int = 25) async throws -> [Tab] {208        try await context.read { connection in209            try connection.query("""210            SELECT * FROM tabs WHERE closed_at IS NOT NULL AND (?1 IS NULL OR space_id = ?1)211            ORDER BY closed_at DESC LIMIT ?2212            """, [space, limit]).map(Tab.init(row:))213        }214    }215216    /// Reopens a closed tab, in its original window or — required when that window is itself closed — in217    /// `window`. The tab comes back `.dormant` with its session state, at its previous position.218    public func reopen(_ id: TabID, into window: WindowID? = nil) async throws -> Tab {219        try await context.transaction { connection in220            guard let row = try connection.queryOne("SELECT * FROM tabs WHERE id = ?", [id]) else {221                throw PersistenceError.notFound(entity: "tab", id: id.string)222            }223            var tab = try Tab(row: row)224            let target = window ?? tab.windowID225            guard let targetRow = try connection.queryOne("SELECT space_id, closed_at FROM windows WHERE id = ?",226                                                          [target]) else {227                throw PersistenceError.ownerNotPersisted(owner: "window", id: target.string)228            }229            guard try targetRow.get("closed_at", as: Date?.self) == nil else {230                throw PersistenceError.conflict("window \(target) is closed; reopen it or pass another window")231            }232            let targetSpace: SpaceID = try targetRow.get("space_id")233            if targetSpace != tab.spaceID { tab.groupID = nil }234            tab.windowID = target235            tab.spaceID = targetSpace236            tab.closedAt = nil237            tab.lifecycle = .dormant238            try tab.save(connection)239            return tab240        }241    }242243    /// Permanently deletes a tab.244    public func delete(_ id: TabID) async throws {245        try await context.transaction { _ = try $0.execute("DELETE FROM tabs WHERE id = ?", [id]) }246    }247}248249// MARK: - Session250251/// One incremental change of the window/tab state. The app coalesces changes (debounce) and hands a batch to252/// `SessionStore.apply`, which commits it in a single transaction.253public enum SessionChange: Sendable {254    case saveWindow(BrowserWindow)255    case saveTab(Tab)256    case saveGroup(TabGroup)257    /// Cheap update for the most frequent event (navigation committed, title changed, tab activated).258    case touchTab(id: TabID, url: URL?, title: String, lastActiveAt: Date)259    /// Replaces only the opaque WebKit state of a tab.260    case setSessionState(id: TabID, state: Data?)261    case selectTab(window: WindowID, tab: TabID?)262    case reorderTabs(window: WindowID, ids: [TabID])263    case closeTab(id: TabID, at: Date)264    case closeWindow(id: WindowID, at: Date)265    case deleteTab(TabID)266    case deleteWindow(WindowID)267    case deleteGroup(TabGroupID)268}269270/// Everything needed to rebuild the UI at launch.271public struct RestoredSession: Sendable {272    public var profiles: [Profile]273    public var spaces: [OrbitSpace]274    public var groups: [TabGroup]275    /// Open windows in `order`.276    public var windows: [BrowserWindow]277    /// Open tabs of open windows, in display order (pinned first), keyed by window.278    public var tabsByWindow: [WindowID: [Tab]]279    /// `false` when the previous run did not call `markCleanShutdown()` — i.e. it crashed or was killed.280    public var previousShutdownWasClean: Bool281282    public var tabCount: Int { tabsByWindow.values.reduce(0) { $0 + $1.count } }283284    public init(profiles: [Profile] = [], spaces: [OrbitSpace] = [], groups: [TabGroup] = [],285                windows: [BrowserWindow] = [], tabsByWindow: [WindowID: [Tab]] = [:],286                previousShutdownWasClean: Bool = true) {287        self.profiles = profiles; self.spaces = spaces; self.groups = groups; self.windows = windows288        self.tabsByWindow = tabsByWindow; self.previousShutdownWasClean = previousShutdownWasClean289    }290}291292public struct SessionLaunchInfo: Sendable, Equatable {293    /// No session was ever started on this database.294    public var isFirstLaunch: Bool295    public var previousShutdownWasClean: Bool296    /// The previous run ended without a clean shutdown: offer "restore previous session".297    public var recoveredFromCrash: Bool { !isFirstLaunch && !previousShutdownWasClean }298299    public init(isFirstLaunch: Bool, previousShutdownWasClean: Bool) {300        self.isFirstLaunch = isFirstLaunch; self.previousShutdownWasClean = previousShutdownWasClean301    }302}303304/// Crash-safe window and tab state.305///306/// Durability model: each `apply` is one committed WAL transaction. A commit survives an app crash or a force307/// quit. What a crash can lose is only what the caller had not flushed yet (its debounce window).308public struct SessionStore: Sendable {309    let context: StoreContext310311    static let cleanShutdownKey = "session.clean_shutdown"312313    /// Call once at launch, before restoring. Reports how the previous run ended and marks the new run as314    /// "in progress" (not clean) until `markCleanShutdown()` is called.315    public func beginSession() async throws -> SessionLaunchInfo {316        try await context.transaction { connection in317            let previous = try connection.scalar("SELECT value FROM app_state WHERE key = ?",318                                                 [Self.cleanShutdownKey], as: String.self)319            try connection.execute("""320            INSERT INTO app_state (key, value) VALUES (?, '0') ON CONFLICT(key) DO UPDATE SET value = '0'321            """, [Self.cleanShutdownKey])322            return SessionLaunchInfo(isFirstLaunch: previous == nil, previousShutdownWasClean: previous != "0")323        }324    }325326    /// Call when the app terminates normally, after the last `apply`. Also folds the WAL back into the database327    /// file so a clean quit leaves a single up-to-date file.328    public func markCleanShutdown() async throws {329        try await context.transaction { connection in330            try connection.execute("""331            INSERT INTO app_state (key, value) VALUES (?, '1') ON CONFLICT(key) DO UPDATE SET value = '1'332            """, [Self.cleanShutdownKey])333        }334        try await context.database.write { connection in335            // Best effort: a reader holding a snapshot makes the checkpoint partial, which is harmless.336            _ = try? connection.query("PRAGMA wal_checkpoint(TRUNCATE)")337        }338    }339340    /// Whether the flag currently says "clean" (true before the first `beginSession` too).341    public func isMarkedClean() async throws -> Bool {342        try await context.read { connection in343            try connection.scalar("SELECT value FROM app_state WHERE key = ?", [Self.cleanShutdownKey],344                                  as: String.self) != "0"345        }346    }347348    /// Applies a batch of changes atomically. Any ghost-owned or orphan item makes the whole batch fail.349    public func apply(_ changes: [SessionChange]) async throws {350        guard !changes.isEmpty else { return }351        try await context.transaction { connection in352            var verified = Set<UUID>()353            for change in changes {354                switch change {355                case .saveWindow(let window):356                    try SessionSQL.saveWindow(window, context, connection)357                    verified.insert(window.id.raw)358                    verified.insert(window.spaceID.raw)359                case .saveTab(let tab):360                    try SessionSQL.saveTab(tab, context, connection, verified: &verified)361                case .saveGroup(let group):362                    try context.requireSpace(group.spaceID, connection)363                    try group.save(connection)364                case .touchTab(let id, let url, let title, let lastActiveAt):365                    try connection.execute("UPDATE tabs SET url = ?, title = ?, last_active_at = ? WHERE id = ?",366                                           [url, title, lastActiveAt, id])367                case .setSessionState(let id, let state):368                    try connection.execute("UPDATE tabs SET session_state = ? WHERE id = ?", [state, id])369                case .selectTab(let window, let tab):370                    try connection.execute("UPDATE windows SET selected_tab_id = ? WHERE id = ?", [tab, window])371                case .reorderTabs(let window, let ids):372                    for (index, id) in ids.enumerated() {373                        try connection.execute("UPDATE tabs SET sort_order = ? WHERE id = ? AND window_id = ?",374                                               [index, id, window])375                    }376                case .closeTab(let id, let date):377                    try connection.execute("""378                    UPDATE tabs SET closed_at = ?, lifecycle = 'dormant' WHERE id = ? AND closed_at IS NULL379                    """, [date, id])380                case .closeWindow(let id, let date):381                    try connection.execute("UPDATE windows SET closed_at = ? WHERE id = ? AND closed_at IS NULL",382                                           [date, id])383                case .deleteTab(let id):384                    try connection.execute("DELETE FROM tabs WHERE id = ?", [id])385                case .deleteWindow(let id):386                    try connection.execute("DELETE FROM windows WHERE id = ?", [id])387                case .deleteGroup(let id):388                    try connection.execute("DELETE FROM tab_groups WHERE id = ?", [id])389                }390            }391        }392    }393394    /// Saves a full picture of the open windows and tabs: everything given is upserted, and open windows/tabs395    /// that are *not* in the picture are deleted. Recently closed tabs and windows are kept.396    public func replaceOpenState(windows: [BrowserWindow], tabs: [Tab], groups: [TabGroup] = []) async throws {397        try await context.transaction { connection in398            var verified = Set<UUID>()399            for group in groups {400                try context.requireSpace(group.spaceID, connection)401                try group.save(connection)402            }403            for window in windows {404                try SessionSQL.saveWindow(window, context, connection)405                verified.insert(window.id.raw)406                verified.insert(window.spaceID.raw)407            }408            for tab in tabs { try SessionSQL.saveTab(tab, context, connection, verified: &verified) }409410            try connection.executeScript("""411            CREATE TEMP TABLE IF NOT EXISTS session_keep (id TEXT PRIMARY KEY) WITHOUT ROWID;412            DELETE FROM session_keep;413            """)414            for window in windows { try connection.execute("INSERT OR IGNORE INTO session_keep VALUES (?)", [window.id]) }415            for tab in tabs { try connection.execute("INSERT OR IGNORE INTO session_keep VALUES (?)", [tab.id]) }416            try connection.executeScript("""417            DELETE FROM tabs WHERE closed_at IS NULL AND id NOT IN (SELECT id FROM session_keep)418                AND window_id IN (SELECT id FROM windows WHERE closed_at IS NULL);419            DELETE FROM windows WHERE closed_at IS NULL AND id NOT IN (SELECT id FROM session_keep);420            DELETE FROM session_keep;421            """)422        }423    }424425    /// Reads the whole session in one consistent snapshot. Tabs come back `.dormant`: no web view exists yet.426    ///427    /// - Parameter includeSessionState: pass `false` to skip the WebKit state blobs (a tab list that loads the428    ///   blob lazily with `TabStore.tab(_:)` when the tab is first shown).429    public func restore(includeSessionState: Bool = true) async throws -> RestoredSession {430        try await context.read { connection in431            let profiles = try connection.query("SELECT * FROM profiles ORDER BY created_at, id").map(Profile.init(row:))432            let spaces = try connection.query("SELECT * FROM spaces ORDER BY profile_id, sort_order, created_at, id")433                .map(OrbitSpace.init(row:))434            let groups = try connection.query("SELECT * FROM tab_groups ORDER BY space_id, sort_order, id")435                .map(TabGroup.init(row:))436            let windows = try connection.query("SELECT * FROM windows WHERE closed_at IS NULL ORDER BY sort_order, id")437                .map(BrowserWindow.init(row:))438            let stateColumn = includeSessionState ? "t.session_state" : "NULL"439            let rows = try connection.query("""440            SELECT t.id, t.window_id, t.space_id, t.parent_id, t.group_id, t.url, t.title, t.favicon_url,441                   t.is_pinned, t.is_muted, t.sort_order, t.lifecycle, \(stateColumn) AS session_state, t.zoom,442                   t.user_agent_mode, t.is_reader_active, t.created_at, t.last_active_at, t.closed_at443            FROM tabs t JOIN windows w ON w.id = t.window_id444            WHERE t.closed_at IS NULL AND w.closed_at IS NULL445            ORDER BY t.window_id, t.is_pinned DESC, t.sort_order, t.created_at, t.id446            """)447            var tabsByWindow: [WindowID: [Tab]] = [:]448            for row in rows {449                var tab = try Tab(row: row)450                tab.lifecycle = .dormant451                tabsByWindow[tab.windowID, default: []].append(tab)452            }453            let flag = try connection.scalar("SELECT value FROM app_state WHERE key = ?",454                                             [Self.cleanShutdownKey], as: String.self)455            return RestoredSession(profiles: profiles, spaces: spaces, groups: groups, windows: windows,456                                   tabsByWindow: tabsByWindow, previousShutdownWasClean: flag != "0")457        }458    }459460    /// Bounds the "recently closed" lists: keeps the newest `maxTabs` closed tabs and `maxWindows` closed461    /// windows and drops anything closed before `olderThan`. Returns the number of rows deleted.462    @discardableResult463    public func pruneClosed(maxTabs: Int = 50, maxWindows: Int = 10, olderThan cutoff: Date? = nil) async throws -> Int {464        try await context.transaction { connection in465            var deleted = 0466            deleted += try connection.execute("""467            DELETE FROM tabs WHERE closed_at IS NOT NULL AND id NOT IN468                (SELECT id FROM tabs WHERE closed_at IS NOT NULL ORDER BY closed_at DESC LIMIT ?)469            """, [maxTabs])470            deleted += try connection.execute("""471            DELETE FROM windows WHERE closed_at IS NOT NULL AND id NOT IN472                (SELECT id FROM windows WHERE closed_at IS NOT NULL ORDER BY closed_at DESC LIMIT ?)473            """, [maxWindows])474            if let cutoff {475                deleted += try connection.execute("DELETE FROM tabs WHERE closed_at < ?", [cutoff])476                deleted += try connection.execute("DELETE FROM windows WHERE closed_at < ?", [cutoff])477            }478            return deleted479        }480    }481}482
Files main
Menu

Theme