SPB Git

Repository Public License

SessionOrchestration.swift 20.4 KB 455 lines swift

1import Foundation2import NavigatorCore3import Persistence45// MARK: - Coalescing67/// Reduces a stream of `SessionChange`s to a shorter batch with the same effect on storage.8///9/// The guarantee is equivalence, not maximal compression: applying `drain()` gives the same stored state as10/// applying every recorded change in order. Rules (anything not listed is appended unchanged):11/// - `touchTab`, `setSessionState`, `selectTab`: replaces the previous change of the same kind when it is the12///   latest change recorded for that tab (or window).13/// - `closeTab` / `closeWindow`: a repeat is dropped (storage keeps the first closing date).14/// - `saveTab`: earlier touch / state / close changes of the tab made since its last full save are dropped15///   (the full row overwrites them). It replaces the previous `saveTab` in place only when that is the latest16///   change of the tab, both have the same window, space and group (so no ordering constraint with a window or17///   group saved in between can be broken) and no `reorderTabs` was recorded after it.18/// - `saveWindow`: same idea with `selectTab` / `closeWindow`; replaced in place when the space is the same.19/// - `saveGroup`: replaced in place when the space is the same.20/// - `reorderTabs`: replaces the previous reorder of the window when the new list contains every tab of the21///   old one and no `saveTab` was recorded in between (a full save carries its own order).22/// - `deleteTab` / `deleteWindow` / `deleteGroup`: pending partial changes of the entity are dropped; full23///   saves are kept, because other changes of the batch may depend on the row existing.24public struct SessionChangeCoalescer: Sendable {25    private enum Key: Hashable { case tab(TabID), window(WindowID), group(TabGroupID) }26    private enum Kind: Hashable { case save, touch, state, select, reorder, close, delete }2728    private struct Entry {29        var key: Key30        var kind: Kind31        var change: SessionChange?   // nil = dropped32    }3334    private var entries: [Entry] = []35    /// Indices of the live entries of each entity, ascending.36    private var indices: [Key: [Int]] = [:]37    private var lastReorderIndex = -138    private var lastTabSaveIndex = -139    /// Changes recorded since the last drain, before coalescing.40    public private(set) var recordedCount = 04142    public init() {}4344    public var isEmpty: Bool { indices.values.allSatisfy(\.isEmpty) }45    public var count: Int { indices.values.reduce(0) { $0 + $1.count } }4647    private mutating func append(_ key: Key, _ kind: Kind, _ change: SessionChange) {48        entries.append(Entry(key: key, kind: kind, change: change))49        indices[key, default: []].append(entries.count - 1)50        if kind == .reorder { lastReorderIndex = entries.count - 1 }51        if kind == .save, case .tab = key { lastTabSaveIndex = entries.count - 1 }52    }5354    private func latest(_ key: Key) -> (index: Int, entry: Entry)? {55        indices[key]?.last.map { ($0, entries[$0]) }56    }5758    /// Drops the entity's trailing entries of the given kinds (those after its last entry of another kind).59    private mutating func dropTrailing(_ key: Key, kinds: Set<Kind>) {60        guard var list = indices[key] else { return }61        while let last = list.last, kinds.contains(entries[last].kind) {62            entries[last].change = nil63            list.removeLast()64        }65        indices[key] = list66    }6768    /// Replaces the latest entry of `key` when it has `kind`, else appends.69    private mutating func replaceLatestOrAppend(_ key: Key, _ kind: Kind, _ change: SessionChange) {70        if let latest = latest(key), latest.entry.kind == kind {71            entries[latest.index].change = change72        } else {73            append(key, kind, change)74        }75    }7677    public mutating func record(_ change: SessionChange) {78        recordedCount += 179        switch change {80        case .touchTab(let id, _, _, _):81            replaceLatestOrAppend(.tab(id), .touch, change)82        case .setSessionState(let id, _):83            replaceLatestOrAppend(.tab(id), .state, change)84        case .selectTab(let window, _):85            replaceLatestOrAppend(.window(window), .select, change)86        case .closeTab(let id, _):87            if latest(.tab(id))?.entry.kind != .close { append(.tab(id), .close, change) }88        case .closeWindow(let id, _):89            if latest(.window(id))?.entry.kind != .close { append(.window(id), .close, change) }9091        case .saveTab(let tab):92            let key = Key.tab(tab.id)93            dropTrailing(key, kinds: [.touch, .state, .close])94            if let latest = latest(key), latest.entry.kind == .save, case .saveTab(let previous)? = latest.entry.change,95               previous.windowID == tab.windowID, previous.spaceID == tab.spaceID, previous.groupID == tab.groupID,96               lastReorderIndex < latest.index {97                entries[latest.index].change = change98            } else {99                append(key, .save, change)100            }101        case .saveWindow(let window):102            let key = Key.window(window.id)103            dropTrailing(key, kinds: [.select, .close])104            if let latest = latest(key), latest.entry.kind == .save, case .saveWindow(let previous)? = latest.entry.change,105               previous.spaceID == window.spaceID {106                entries[latest.index].change = change107            } else {108                append(key, .save, change)109            }110        case .saveGroup(let group):111            let key = Key.group(group.id)112            if let latest = latest(key), latest.entry.kind == .save, case .saveGroup(let previous)? = latest.entry.change,113               previous.spaceID == group.spaceID {114                entries[latest.index].change = change115            } else {116                append(key, .save, change)117            }118119        case .reorderTabs(let window, let ids):120            let key = Key.window(window)121            if let latest = latest(key), latest.entry.kind == .reorder, case .reorderTabs(_, let previous)? = latest.entry.change,122               Set(previous).isSubset(of: ids), lastTabSaveIndex < latest.index {123                entries[latest.index].change = nil124                indices[key]?.removeLast()125            }126            append(key, .reorder, change)127128        case .deleteTab(let id):129            dropTrailing(.tab(id), kinds: [.touch, .state, .close])130            if latest(.tab(id))?.entry.kind != .delete { append(.tab(id), .delete, change) }131        case .deleteWindow(let id):132            dropTrailing(.window(id), kinds: [.select, .close, .reorder])133            if latest(.window(id))?.entry.kind != .delete { append(.window(id), .delete, change) }134        case .deleteGroup(let id):135            if latest(.group(id))?.entry.kind != .delete { append(.group(id), .delete, change) }136        }137    }138139    /// The coalesced batch, in an order that is safe to apply. Empties the coalescer.140    public mutating func drain() -> [SessionChange] {141        let batch = entries.compactMap(\.change)142        self = SessionChangeCoalescer()143        return batch144    }145}146147// MARK: - Orchestrator148149public struct SessionFlushReport: Sendable, Equatable {150    /// Changes recorded since the previous flush.151    public var recorded: Int152    /// Changes handed to storage after coalescing.153    public var applied: Int154    /// Changes storage refused (description of the change's kind and of the error). Empty in normal operation.155    public var failures: [String]156157    public static let nothing = SessionFlushReport(recorded: 0, applied: 0, failures: [])158}159160/// Collects window and tab changes from the UI and writes them to `database.session` in debounced batches.161///162/// - A flush happens `debounce` after the last recorded change, and no later than `maximumDelay` after the163///   first unflushed one: a crash loses at most `maximumDelay` of changes.164/// - Changes that belong to a ghost window, space or tab are dropped at the door: nothing of a private window165///   reaches the queue, let alone the disk.166/// - If storage refuses the batch (it is atomic), the changes are retried one by one so that a single bad167///   change cannot block the others; refusals are reported and logged by the caller.168public actor SessionOrchestrator {169    public typealias Sleeper = @Sendable (Duration) async throws -> Void170171    private let database: NavigatorDatabase172    private let debounce: Duration173    private let maximumDelay: Duration174    private let sleep: Sleeper175    private let clock = ContinuousClock()176177    private var coalescer = SessionChangeCoalescer()178    private var ghostTabs = Set<TabID>()179    private var ghostGroups = Set<TabGroupID>()180    private var firstPendingAt: ContinuousClock.Instant?181    private var flushTask: Task<Void, Never>?182    private var generation = 0183    private var onFlush: (@Sendable (SessionFlushReport) -> Void)?184185    public init(database: NavigatorDatabase, debounce: Duration = .milliseconds(400),186                maximumDelay: Duration = .seconds(2),187                sleep: @escaping Sleeper = { try await Task.sleep(for: $0) }) {188        self.database = database189        self.debounce = debounce190        self.maximumDelay = max(maximumDelay, debounce)191        self.sleep = sleep192    }193194    /// Called after every automatic flush (diagnostics, tests).195    public func setFlushObserver(_ observer: (@Sendable (SessionFlushReport) -> Void)?) { onFlush = observer }196197    public var pendingCount: Int { coalescer.count }198199    // MARK: Recording200201    public func record(_ change: SessionChange) { record([change]) }202203    public func record(_ changes: [SessionChange]) {204        var accepted = false205        for change in changes where !isGhost(change) {206            coalescer.record(change)207            accepted = true208        }209        guard accepted else { return }210        if firstPendingAt == nil { firstPendingAt = clock.now }211        schedule()212    }213214    private func isGhost(_ change: SessionChange) -> Bool {215        let ghosts = database.ghosts216        switch change {217        case .saveWindow(let window):218            return ghosts.contains(window.id.raw) || ghosts.contains(window.spaceID.raw)219        case .saveTab(let tab):220            if ghosts.contains(tab.windowID.raw) || ghosts.contains(tab.spaceID.raw) {221                ghostTabs.insert(tab.id)222                return true223            }224            // A tab dragged out of a private window into a normal one becomes a normal tab.225            ghostTabs.remove(tab.id)226            return false227        case .saveGroup(let group):228            if ghosts.contains(group.spaceID.raw) { ghostGroups.insert(group.id); return true }229            ghostGroups.remove(group.id)230            return false231        case .touchTab(let id, _, _, _), .setSessionState(let id, _), .closeTab(let id, _):232            return ghostTabs.contains(id)233        case .deleteTab(let id):234            return ghostTabs.remove(id) != nil235        case .selectTab(let window, _), .reorderTabs(let window, _), .closeWindow(let window, _), .deleteWindow(let window):236            return ghosts.contains(window.raw)237        case .deleteGroup(let id):238            return ghostGroups.remove(id) != nil239        }240    }241242    /// Tells the orchestrator about tabs of a private window that it has not seen through `saveTab`.243    public func declareGhostTabs(_ ids: [TabID]) { ghostTabs.formUnion(ids) }244    public func forgetGhostTabs(_ ids: [TabID]) { ghostTabs.subtract(ids) }245246    // MARK: Flushing247248    private func schedule() {249        generation += 1250        let token = generation251        var delay = debounce252        if let firstPendingAt {253            let left = maximumDelay - (clock.now - firstPendingAt)254            delay = max(min(debounce, left), .zero)255        }256        flushTask?.cancel()257        flushTask = Task { [sleep] in258            do { try await sleep(delay) } catch { return }259            await self.timerFired(token)260        }261    }262263    private func timerFired(_ token: Int) async {264        guard token == generation, !coalescer.isEmpty else { return }265        let report = await flush()266        onFlush?(report)267    }268269    /// Writes everything pending now. Call when a window closes, when the app goes to the background and270    /// before `database.session.markCleanShutdown()`.271    @discardableResult272    public func flush() async -> SessionFlushReport {273        flushTask?.cancel()274        flushTask = nil275        generation += 1   // a timer that already left its sleep must not flush again276        firstPendingAt = nil277        let recorded = coalescer.recordedCount278        let batch = coalescer.drain()279        guard !batch.isEmpty else { return SessionFlushReport(recorded: recorded, applied: 0, failures: []) }280        do {281            try await database.session.apply(batch)282            return SessionFlushReport(recorded: recorded, applied: batch.count, failures: [])283        } catch {284            var applied = 0285            var failures: [String] = []286            for change in batch {287                do { try await database.session.apply([change]); applied += 1 } catch {288                    failures.append("\(Self.label(change)): \(error)")289                }290            }291            return SessionFlushReport(recorded: recorded, applied: applied, failures: failures)292        }293    }294295    /// Flushes and marks the session as cleanly shut down. The last call of a normal termination.296    public func shutdown() async throws {297        await flush()298        try await database.session.markCleanShutdown()299    }300301    /// Name of a change without its payload: URLs and titles never appear in a failure report.302    static func label(_ change: SessionChange) -> String {303        switch change {304        case .saveWindow: "saveWindow"305        case .saveTab: "saveTab"306        case .saveGroup: "saveGroup"307        case .touchTab: "touchTab"308        case .setSessionState: "setSessionState"309        case .selectTab: "selectTab"310        case .reorderTabs: "reorderTabs"311        case .closeTab: "closeTab"312        case .closeWindow: "closeWindow"313        case .deleteTab: "deleteTab"314        case .deleteWindow: "deleteWindow"315        case .deleteGroup: "deleteGroup"316        }317    }318}319320// MARK: - Restoration321322/// What the user chose to see at launch.323public enum LaunchRestorePolicy: String, Sendable, Codable, CaseIterable {324    /// Reopen the windows and tabs of the previous run.325    case restorePreviousSession326    /// Start with one new window; the previous windows stay available under "reopen closed window".327    case startFresh328}329330public struct RestoredWindow: Sendable, Equatable, Identifiable {331    /// The window with a valid `selectedTabID` and `split`.332    public var window: BrowserWindow333    /// Open tabs in display order, all `.dormant`.334    public var tabs: [Tab]335    /// Tabs the UI should load immediately (the selected tab and the panes of its split). Every other tab336    /// stays dormant until shown. Empty when the user must confirm the restoration first.337    public var tabsToLoad: [TabID]338    public var id: WindowID { window.id }339}340341/// The model the UI builds its first frame from.342public struct LaunchModel: Sendable, Equatable {343    public enum Mode: String, Sendable, Codable {344        /// Nothing stored: show onboarding / one window in the default space.345        case firstLaunch346        /// Previous run ended normally and its windows are restored.347        case restored348        /// Previous run crashed or was killed. The windows are provided but nothing loads until the user349        /// accepts "Restore previous session": a page that crashed the app must not be reloaded automatically.350        case crashRecovery351        /// The user asked for a fresh start (or there was nothing to restore).352        case fresh353    }354355    public var mode: Mode356    public var profiles: [Profile]357    public var spaces: [OrbitSpace]358    public var groups: [TabGroup]359    public var windows: [RestoredWindow]360    /// Windows of the previous run that are not being restored (fresh start): the UI closes them in storage so361    /// they appear under "reopen closed window".362    public var windowsToClose: [WindowID]363    /// Space for a new window when `windows` is empty: the space of the previous front window, else the first364    /// non-archived space.365    public var defaultSpaceID: SpaceID?366    public var requiresRestoreConfirmation: Bool { mode == .crashRecovery }367    public var tabCount: Int { windows.reduce(0) { $0 + $1.tabs.count } }368}369370public enum SessionRestorer {371    /// Turns what storage returned into the launch model. Pure.372    ///373    /// Repairs applied to every restored window: a selected tab that no longer exists becomes the most374    /// recently active tab; a split is validated against the existing tabs and the device's pane limit;375    /// windows without any tab are dropped (and listed in `windowsToClose`). Windows of an archived space are376    /// left untouched in storage and not restored: they come back when the space is unarchived.377    public static func launchModel(session: RestoredSession, launch: SessionLaunchInfo,378                                   policy: LaunchRestorePolicy = .restorePreviousSession,379                                   paneLimit: Int = SplitLayout.maximumPanes) -> LaunchModel {380        let liveSpaces = Set(session.spaces.map(\.id))381        let archivedSpaces = Set(session.spaces.filter(\.isArchived).map(\.id))382        var windows: [RestoredWindow] = []383        var toClose: [WindowID] = []384        for stored in session.windows where !archivedSpaces.contains(stored.spaceID) {385            let tabs = session.tabsByWindow[stored.id] ?? []386            guard !tabs.isEmpty, liveSpaces.contains(stored.spaceID) else { toClose.append(stored.id); continue }387            var window = stored388            let ids = Set(tabs.map(\.id))389            if window.selectedTabID.map({ !ids.contains($0) }) ?? true {390                window.selectedTabID = TabLayout.mostRecentlyUsed(tabs).first?.id391            }392            window.split = SplitEngine.restored(window.split, existingTabs: ids, limit: paneLimit)393            var toLoad: [TabID] = []394            if let split = window.split {395                toLoad = split.panes396                // The selected tab is the focused pane of a split window.397                window.selectedTabID = SplitEngine.focusedTab(of: split) ?? window.selectedTabID398            } else if let selected = window.selectedTabID {399                toLoad = [selected]400            }401            windows.append(RestoredWindow(window: window, tabs: tabs, tabsToLoad: toLoad))402        }403404        let frontSpace = windows.first?.window.spaceID405        let fallbackSpace = OrbitalLayout.listOrder(session.spaces).first?.id406        let mode: LaunchModel.Mode407        if launch.isFirstLaunch && windows.isEmpty {408            mode = .firstLaunch409        } else if windows.isEmpty || policy == .startFresh {410            mode = .fresh411        } else if launch.recoveredFromCrash {412            mode = .crashRecovery413        } else {414            mode = .restored415        }416        switch mode {417        case .firstLaunch, .fresh:418            toClose.append(contentsOf: windows.map(\.id))419            windows = []420        case .crashRecovery:421            windows = windows.map { var copy = $0; copy.tabsToLoad = []; return copy }422        case .restored:423            break424        }425        return LaunchModel(mode: mode, profiles: session.profiles, spaces: session.spaces, groups: session.groups,426                           windows: windows, windowsToClose: toClose, defaultSpaceID: frontSpace ?? fallbackSpace)427    }428429    /// The tabs to load once the user accepted the restoration after a crash.430    public static func confirmingRestore(_ model: LaunchModel) -> LaunchModel {431        guard model.mode == .crashRecovery else { return model }432        var copy = model433        copy.mode = .restored434        copy.windows = model.windows.map { restored in435            var window = restored436            window.tabsToLoad = restored.window.split?.panes ?? restored.window.selectedTabID.map { [$0] } ?? []437            return window438        }439        return copy440    }441442    /// Reads storage and builds the launch model: `beginSession()` then `restore()`.443    public static func launch(database: NavigatorDatabase, policy: LaunchRestorePolicy = .restorePreviousSession,444                              paneLimit: Int = SplitLayout.maximumPanes) async throws -> LaunchModel {445        let info = try await database.session.beginSession()446        let session = try await database.session.restore()447        let model = launchModel(session: session, launch: info, policy: policy, paneLimit: paneLimit)448        if !model.windowsToClose.isEmpty {449            let date = Date.now450            try await database.session.apply(model.windowsToClose.map { .closeWindow(id: $0, at: date) })451        }452        return model453    }454}455
Files main
Menu

Theme