SPB Git

Repository Public License

BlinkPolicy.swift 9.5 KB 203 lines swift

1import Foundation2import NavigatorCore34/// Memory pressure as reported by the system (dispatch memory-pressure source on macOS, memory warnings on iOS).5public enum MemoryPressure: Int, Sendable, Codable, Comparable, CaseIterable {6    case normal, warning, critical7    public static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue }8}910/// How many web views may stay alive.11public struct BlinkBudget: Sendable, Equatable, Codable {12    /// Live web views allowed under normal memory pressure (at least 1).13    public var maximumLiveWebViews: Int14    /// A tab used more recently than this is not suspended for being over budget under normal pressure15    /// (the user is probably switching back and forth). Ignored under memory pressure.16    public var graceInterval: TimeInterval17    /// When set, an unprotected, unpinned tab idle for longer is suspended even if the budget is not exceeded.18    public var idleLimit: TimeInterval?1920    public init(maximumLiveWebViews: Int, graceInterval: TimeInterval = 30, idleLimit: TimeInterval? = nil) {21        self.maximumLiveWebViews = max(maximumLiveWebViews, 1)22        self.graceInterval = max(graceInterval, 0)23        self.idleLimit = idleLimit.map { max($0, 60) }24    }2526    /// Default budget for a device. Product heuristics (documented in docs/ORBIT.md), not measurements:27    /// roughly one live web view per 1.3 GB of physical memory on a Mac, per 1 GB on iOS/iPadOS where the28    /// system kills apps much earlier, within fixed bounds.29    ///30    /// | Physical memory | Mac | iPad | iPhone |31    /// |---|---|---|---|32    /// | 4 GB | 4 | 3 | 3 |33    /// | 8 GB | 6 | 4 | 4 |34    /// | 16 GB | 12 | 8 | 6 |35    /// | 32 GB | 24 | 8 | 6 |36    /// | 64 GB and more | 40 | 8 | 6 |37    public static func automatic(physicalMemoryBytes: UInt64, platform: SplitPlatform) -> BlinkBudget {38        let gigabytes = Double(physicalMemoryBytes) / 1_073_741_82439        let live: Int40        switch platform {41        case .mac: live = min(max(Int((gigabytes / 1.3).rounded(.down)), 4), 40)42        case .pad: live = min(max(Int((gigabytes * 0.6).rounded(.down)), 3), 8)43        case .phone: live = min(max(Int((gigabytes * 0.5).rounded(.down)), 3), 6)44        }45        return BlinkBudget(maximumLiveWebViews: live)46    }4748    public static func automaticForThisDevice(platform: SplitPlatform = SplitCapacity.currentPlatform) -> BlinkBudget {49        automatic(physicalMemoryBytes: ProcessInfo.processInfo.physicalMemory, platform: platform)50    }5152    /// Live web views allowed at a pressure level: the full budget, half of it (at least 1) under `warning`,53    /// none beyond the protected tabs under `critical`.54    public func limit(under pressure: MemoryPressure) -> Int {55        switch pressure {56        case .normal: maximumLiveWebViews57        case .warning: max(maximumLiveWebViews / 2, 1)58        case .critical: 059        }60    }61}6263/// What the policy needs to know about a tab. The UI layer builds it from the model and the web engine state.64public struct BlinkTabState: Sendable, Equatable, Identifiable {65    public var id: TabID66    public var lifecycle: TabLifecycle67    public var lastActiveAt: Date68    /// Shown right now: selected tab of a visible window, or any pane of its split.69    public var isVisible: Bool70    public var isPlayingAudio: Bool71    /// Camera, microphone or screen capture in use.72    public var isCapturingMedia: Bool73    /// The page reported form input that was not submitted (see docs/ORBIT.md for what the page script detects).74    public var hasUnsubmittedInput: Bool75    public var isPinned: Bool76    /// The user asked that this tab (or its site) never be suspended.77    public var isExcludedByUser: Bool7879    public init(id: TabID, lifecycle: TabLifecycle, lastActiveAt: Date, isVisible: Bool = false,80                isPlayingAudio: Bool = false, isCapturingMedia: Bool = false, hasUnsubmittedInput: Bool = false,81                isPinned: Bool = false, isExcludedByUser: Bool = false) {82        self.id = id; self.lifecycle = lifecycle; self.lastActiveAt = lastActiveAt; self.isVisible = isVisible83        self.isPlayingAudio = isPlayingAudio; self.isCapturingMedia = isCapturingMedia84        self.hasUnsubmittedInput = hasUnsubmittedInput; self.isPinned = isPinned; self.isExcludedByUser = isExcludedByUser85    }8687    /// Why this tab may never be suspended, most important reason first; `nil` when it may.88    public var protection: BlinkProtection? {89        if isVisible { return .visible }90        if isCapturingMedia { return .capturingMedia }91        if isPlayingAudio { return .playingAudio }92        if hasUnsubmittedInput { return .unsubmittedInput }93        if isExcludedByUser { return .excludedByUser }94        return nil95    }96}9798public enum BlinkProtection: String, Sendable, Codable, CaseIterable {99    case visible, capturingMedia, playingAudio, unsubmittedInput, excludedByUser100}101102public enum BlinkReason: String, Sendable, Codable, CaseIterable {103    /// Resume: the tab is on screen and has no web view.104    case becameVisible105    /// Suspend: more live web views than the budget allows.106    case overBudget107    /// Suspend: idle for longer than `BlinkBudget.idleLimit`.108    case idle109    case memoryPressureWarning110    case memoryPressureCritical111}112113public struct BlinkDecision: Sendable, Equatable {114    public enum Action: String, Sendable, Codable { case suspend, resume }115    public var tabID: TabID116    public var action: Action117    public var reason: BlinkReason118}119120public struct BlinkPlan: Sendable, Equatable {121    /// Resumes first, then suspensions from the best candidate to the worst.122    public var decisions: [BlinkDecision]123    /// Live web views once the decisions are applied.124    public var liveCountAfter: Int125    /// The limit that was enforced.126    public var limit: Int127    /// Live web views that remain above the limit because they are all protected.128    public var overLimitBy: Int129    /// Protected tabs and why (shown in the tab's context menu: "kept awake because…").130    public var protected: [TabID: BlinkProtection]131132    public var suspensions: [TabID] { decisions.filter { $0.action == .suspend }.map(\.tabID) }133    public var resumptions: [TabID] { decisions.filter { $0.action == .resume }.map(\.tabID) }134}135136/// Blink: decides which tabs keep a web view. Pure and deterministic; the UI layer performs the releases.137///138/// Rules, in order:139/// 1. A visible tab without a web view is resumed.140/// 2. Protected tabs (`BlinkTabState.protection`) are never suspended, whatever the pressure. They still count141///    against the limit.142/// 3. With `idleLimit`, an unprotected, unpinned tab idle for longer is suspended.143/// 4. While live web views exceed the limit for the pressure level, unprotected live tabs are suspended:144///    unpinned before pinned, least recently active first (id as the final tie-break). Under normal pressure,145///    tabs inside the grace interval are skipped; under memory pressure nothing unprotected is spared.146public enum BlinkPolicy {147    public static func evaluate(tabs: [BlinkTabState], budget: BlinkBudget, pressure: MemoryPressure = .normal,148                                now: Date) -> BlinkPlan {149        var decisions: [BlinkDecision] = []150        var protected: [TabID: BlinkProtection] = [:]151        var live = Set<TabID>()152153        for tab in tabs {154            if let protection = tab.protection { protected[tab.id] = protection }155            if tab.lifecycle == .live { live.insert(tab.id) }156        }157        for tab in tabs.sorted(by: { $0.id < $1.id }) where tab.isVisible && tab.lifecycle != .live {158            decisions.append(BlinkDecision(tabID: tab.id, action: .resume, reason: .becameVisible))159            live.insert(tab.id)160        }161162        let candidates = tabs.filter { $0.lifecycle == .live && $0.protection == nil }.sorted { lhs, rhs in163            if lhs.isPinned != rhs.isPinned { return !lhs.isPinned }164            return (lhs.lastActiveAt, lhs.id) < (rhs.lastActiveAt, rhs.id)165        }166        var suspended = Set<TabID>()167168        if let idleLimit = budget.idleLimit {169            for tab in candidates where !tab.isPinned && now.timeIntervalSince(tab.lastActiveAt) > idleLimit {170                decisions.append(BlinkDecision(tabID: tab.id, action: .suspend, reason: .idle))171                suspended.insert(tab.id)172                live.remove(tab.id)173            }174        }175176        let limit = budget.limit(under: pressure)177        let reason: BlinkReason178        switch pressure {179        case .normal: reason = .overBudget180        case .warning: reason = .memoryPressureWarning181        case .critical: reason = .memoryPressureCritical182        }183        for tab in candidates where live.count > limit && !suspended.contains(tab.id) {184            if pressure == .normal, now.timeIntervalSince(tab.lastActiveAt) < budget.graceInterval { continue }185            decisions.append(BlinkDecision(tabID: tab.id, action: .suspend, reason: reason))186            suspended.insert(tab.id)187            live.remove(tab.id)188        }189        return BlinkPlan(decisions: decisions, liveCountAfter: live.count, limit: limit,190                         overLimitBy: max(live.count - limit, 0), protected: protected)191    }192193    /// Lifecycle a tab has once a decision was carried out. `nil` when the decision does not apply to the194    /// current state (already suspended, already live): the bookkeeping must not record a transition.195    public static func transition(from lifecycle: TabLifecycle, applying action: BlinkDecision.Action) -> TabLifecycle? {196        switch (lifecycle, action) {197        case (.live, .suspend): .suspended198        case (.suspended, .resume), (.dormant, .resume): .live199        default: nil200        }201    }202}203
Files main
Menu

Theme