SPB Git

Repository Public License

SessionTests.swift 14.1 KB 254 lines swift

1import Foundation2import NavigatorCore3import Testing4@testable import Persistence56@Suite struct SessionTests {7    @Test func incrementalChangesAreRestored() async throws {8        let fixture = try await Fixture.make()9        let session = fixture.database.session10        let window = BrowserWindow(spaceID: fixture.space.id, order: 0)11        let group = TabGroup(spaceID: fixture.space.id, name: "Docs")12        var tabs = (0..<4).map { fixture.tab(in: window, "https://example.com/\($0)", title: "Tab \($0)", order: $0) }13        tabs[2].isPinned = true14        tabs[3].groupID = group.id15        tabs[1].lifecycle = .live16        tabs[1].sessionState = Data(repeating: 7, count: 4_096)1718        try await session.apply([.saveWindow(window), .saveGroup(group)] + tabs.map(SessionChange.saveTab))19        try await session.apply([20            .touchTab(id: tabs[0].id, url: url("https://example.com/navigated"), title: "Navigated", lastActiveAt: day(3)),21            .setSessionState(id: tabs[0].id, state: Data([1, 2, 3])),22            .selectTab(window: window.id, tab: tabs[0].id),23            .reorderTabs(window: window.id, ids: [tabs[3].id, tabs[1].id, tabs[0].id]),24        ])2526        let restored = try await session.restore()27        #expect(restored.profiles == [fixture.profile])28        #expect(restored.spaces == [fixture.space])29        #expect(restored.groups == [group])30        #expect(restored.windows.map(\.id) == [window.id])31        #expect(restored.windows[0].selectedTabID == tabs[0].id)32        let restoredTabs = try #require(restored.tabsByWindow[window.id])33        // Pinned first, then the new order.34        #expect(restoredTabs.map(\.id) == [tabs[2].id, tabs[3].id, tabs[1].id, tabs[0].id])35        // Nothing is alive after a restore, whatever was stored.36        #expect(restoredTabs.allSatisfy { $0.lifecycle == .dormant })37        let navigated = try #require(restoredTabs.last)38        #expect(navigated.url == url("https://example.com/navigated"))39        #expect(navigated.title == "Navigated")40        #expect(navigated.lastActiveAt == day(3))41        #expect(navigated.sessionState == Data([1, 2, 3]))42        #expect(restoredTabs[2].sessionState == Data(repeating: 7, count: 4_096))43        #expect(restoredTabs[1].groupID == group.id)44        #expect(restored.tabCount == 4)4546        let light = try await session.restore(includeSessionState: false)47        #expect(light.tabsByWindow[window.id]?.allSatisfy { $0.sessionState == nil } == true)48        // The blob is still stored; only this read skipped it.49        #expect(try await fixture.database.tabs.tab(tabs[1].id)?.sessionState?.count == 4_096)50    }5152    @Test func aBatchIsAtomic() async throws {53        let fixture = try await Fixture.make()54        let window = BrowserWindow(spaceID: fixture.space.id)55        let good = fixture.tab(in: window)56        let orphan = Tab(windowID: WindowID(), spaceID: fixture.space.id, createdAt: day(), lastActiveAt: day())57        await #expect(throws: PersistenceError.self) {58            try await fixture.database.session.apply([.saveWindow(window), .saveTab(good), .saveTab(orphan)])59        }60        let restored = try await fixture.database.session.restore()61        #expect(restored.windows.isEmpty)62        #expect(restored.tabCount == 0)63    }6465    @Test func reopenClosedTabsAndWindows() async throws {66        let fixture = try await Fixture.make()67        let database = fixture.database68        let window = try await fixture.window()69        let tabs = (0..<3).map { fixture.tab(in: window, "https://example.com/\($0)", title: "Tab \($0)", order: $0) }70        var stateful = tabs71        stateful[1].sessionState = Data("back-forward list".utf8)72        try await database.tabs.save(stateful)7374        try await database.session.apply([.closeTab(id: tabs[1].id, at: second(10))])75        try await database.tabs.close(tabs[0].id, at: second(20))76        #expect(try await database.tabs.tabs(window: window.id).map(\.id) == [tabs[2].id])77        // Most recently closed first.78        #expect(try await database.tabs.recentlyClosed().map(\.id) == [tabs[0].id, tabs[1].id])79        #expect(try await database.session.restore().tabCount == 1)8081        let reopened = try await database.tabs.reopen(tabs[1].id)82        #expect(reopened.closedAt == nil)83        #expect(reopened.order == 1)84        #expect(reopened.sessionState == Data("back-forward list".utf8))85        #expect(try await database.tabs.tabs(window: window.id).map(\.id) == [tabs[1].id, tabs[2].id])86        #expect(try await database.tabs.recentlyClosed().map(\.id) == [tabs[0].id])8788        // Closing a window keeps it and its open tabs together.89        try await database.windows.close(window.id, at: second(30))90        #expect(try await database.session.restore().windows.isEmpty)91        #expect(try await database.session.restore().tabCount == 0)92        let closed = try await database.windows.recentlyClosed()93        #expect(closed.map(\.window.id) == [window.id])94        #expect(closed[0].tabs.map(\.id) == [tabs[1].id, tabs[2].id])9596        // A closed tab of a closed window needs a destination…97        await #expect(throws: PersistenceError.self) { _ = try await database.tabs.reopen(tabs[0].id) }98        let other = try await fixture.window(order: 1)99        let rehomed = try await database.tabs.reopen(tabs[0].id, into: other.id)100        #expect(rehomed.windowID == other.id)101        #expect(try await database.tabs.tabs(window: other.id).map(\.id) == [tabs[0].id])102103        // …and the window itself comes back with its tabs.104        let back = try await database.windows.reopen(window.id)105        #expect(back.window.closedAt == nil)106        #expect(back.tabs.map(\.id) == [tabs[1].id, tabs[2].id])107        #expect(try await database.session.restore().tabCount == 3)108        await #expect(throws: PersistenceError.notFound(entity: "window", id: "00000000-0000-0000-0000-000000000000")) {109            _ = try await database.windows.reopen(WindowID(UUID(uuidString: "00000000-0000-0000-0000-000000000000")!))110        }111    }112113    @Test func closedListsAreBounded() async throws {114        let fixture = try await Fixture.make()115        let database = fixture.database116        let window = try await fixture.window()117        let tabs = (0..<30).map { fixture.tab(in: window, "https://example.com/\($0)", order: $0) }118        try await database.tabs.save(tabs)119        try await database.session.apply(tabs.prefix(20).enumerated().map { .closeTab(id: $0.element.id, at: second(Double($0.offset))) })120        #expect(try await database.session.pruneClosed(maxTabs: 5, maxWindows: 10) == 15)121        // The five most recently closed remain.122        #expect(try await database.tabs.recentlyClosed().map(\.id) == tabs[15..<20].reversed().map(\.id))123        #expect(try await database.session.pruneClosed(maxTabs: 5, maxWindows: 10, olderThan: second(18)) == 3)124        #expect(try await database.tabs.recentlyClosed().count == 2)125        #expect(try await database.tabs.tabs(window: window.id).count == 10)126    }127128    @Test func replaceOpenStateDropsWhatIsGoneButKeepsClosedItems() async throws {129        let fixture = try await Fixture.make()130        let database = fixture.database131        let first = try await fixture.window(order: 0)132        let second = try await fixture.window(order: 1)133        let kept = fixture.tab(in: first, "https://kept.example/")134        let dropped = fixture.tab(in: first, "https://dropped.example/", order: 1)135        let closedEarlier = fixture.tab(in: first, "https://closed.example/", order: 2)136        let inSecond = fixture.tab(in: second, "https://second.example/")137        try await database.tabs.save([kept, dropped, closedEarlier, inSecond])138        try await database.tabs.close(closedEarlier.id, at: day(1))139140        var updated = kept141        updated.title = "Updated"142        let fresh = fixture.tab(in: first, "https://fresh.example/", order: 1)143        try await database.session.replaceOpenState(windows: [first], tabs: [updated, fresh])144145        let restored = try await database.session.restore()146        #expect(restored.windows.map(\.id) == [first.id])147        #expect(restored.tabsByWindow[first.id]?.map(\.id) == [kept.id, fresh.id])148        #expect(restored.tabsByWindow[first.id]?.first?.title == "Updated")149        #expect(try await database.tabs.tab(dropped.id) == nil)150        #expect(try await database.tabs.tab(inSecond.id) == nil)151        #expect(try await database.tabs.recentlyClosed().map(\.id) == [closedEarlier.id])152    }153154    @Test func cleanShutdownFlagTellsACrashFromAQuit() async throws {155        let scratch = try ScratchDirectory()156157        // First launch ever.158        var database = try await NavigatorDatabase(url: scratch.databaseURL)159        let fixture = try await Fixture.make(in: database)160        var launch = try await database.session.beginSession()161        #expect(launch == SessionLaunchInfo(isFirstLaunch: true, previousShutdownWasClean: true))162        #expect(!launch.recoveredFromCrash)163        #expect(try await database.session.isMarkedClean() == false)164        let window = try await fixture.window()165        try await database.tabs.save(fixture.tab(in: window, "https://example.com/before-quit"))166        // Normal quit.167        try await database.session.markCleanShutdown()168        await database.close()169        // A clean shutdown folds the WAL back: no leftover WAL content.170        let wal = NavigatorDatabase.fileURLs(for: scratch.databaseURL)[1]171        let walSize = (try? FileManager.default.attributesOfItem(atPath: wal.path)[.size] as? Int) ?? 0172        #expect(walSize == 0)173174        // Second launch: previous run was clean.175        database = try await NavigatorDatabase(url: scratch.databaseURL)176        #expect(try await database.session.restore().previousShutdownWasClean == true)177        launch = try await database.session.beginSession()178        #expect(launch == SessionLaunchInfo(isFirstLaunch: false, previousShutdownWasClean: true))179        try await database.session.apply([.saveTab(fixture.tab(in: window, "https://example.com/before-crash", order: 1))])180        // Crash: the process disappears. Nothing is closed, checkpointed or flagged; the connections of the181        // "dead" process are simply never used again while a new process opens the same files.182        let crashed = database183184        // Third launch: a crash is detected and the committed tabs are all there.185        database = try await NavigatorDatabase(url: scratch.databaseURL)186        #expect(database.openInfo.ranIntegrityCheck)187        let restored = try await database.session.restore()188        #expect(restored.previousShutdownWasClean == false)189        #expect(restored.tabsByWindow[window.id]?.compactMap(\.url?.lastPathComponent) == ["before-quit", "before-crash"])190        launch = try await database.session.beginSession()191        #expect(launch == SessionLaunchInfo(isFirstLaunch: false, previousShutdownWasClean: false))192        #expect(launch.recoveredFromCrash)193        try await database.session.markCleanShutdown()194        await database.close()195        await crashed.close()196197        database = try await NavigatorDatabase(url: scratch.databaseURL)198        #expect(try await database.session.beginSession().recoveredFromCrash == false)199        await database.close()200    }201202    /// Measures saving and restoring 100 tabs in 5 windows on a file database. Reports numbers, asserts none.203    @Test func restorationBenchmark() async throws {204        let scratch = try ScratchDirectory()205        var database = try await NavigatorDatabase(url: scratch.databaseURL)206        let fixture = try await Fixture.make(in: database)207        let windows = (0..<5).map { BrowserWindow(spaceID: fixture.space.id, order: $0) }208        // 16 KiB of opaque state per tab: the order of magnitude of a WebKit interaction state with history.209        let state = Data((0..<16_384).map { UInt8(truncatingIfNeeded: $0 &* 31) })210        var changes: [SessionChange] = windows.map(SessionChange.saveWindow)211        for (windowIndex, window) in windows.enumerated() {212            for index in 0..<20 {213                var tab = fixture.tab(in: window, "https://site\(windowIndex).example.com/path/\(index)?q=benchmark",214                                      title: "Window \(windowIndex) — tab \(index)", order: index, pinned: index < 2)215                tab.sessionState = state216                changes.append(.saveTab(tab))217            }218        }219        let clock = ContinuousClock()220        let saveTime = try await clock.measure { try await database.session.apply(changes) }221        try await database.session.markCleanShutdown()222        await database.close()223224        // Cold: a new set of connections, as at launch (the OS file cache is warm; this is not a cold boot).225        var session: RestoredSession?226        let openTime = try await clock.measure { database = try await NavigatorDatabase(url: scratch.databaseURL) }227        let coldRestore = try await clock.measure { session = try await database.session.restore() }228        let restored = try #require(session)229        #expect(restored.windows.count == 5)230        #expect(restored.tabCount == 100)231        #expect(restored.tabsByWindow.values.allSatisfy { $0.count == 20 && $0.prefix(2).allSatisfy(\.isPinned) })232        #expect(restored.tabsByWindow.values.allSatisfy { $0.allSatisfy { $0.sessionState == state } })233234        var warm: [Double] = []235        for _ in 0..<20 {236            warm.append(milliseconds(try await clock.measure { _ = try await database.session.restore() }))237        }238        var light: [Double] = []239        for _ in 0..<20 {240            light.append(milliseconds(try await clock.measure { _ = try await database.session.restore(includeSessionState: false) }))241        }242        warm.sort(); light.sort()243        print("""244        [benchmark] session of 100 tabs in 5 windows (16 KiB state per tab, file database, WAL):245        [benchmark]   save (one transaction, 105 changes): \(format(milliseconds(saveTime))) ms246        [benchmark]   open database at launch:             \(format(milliseconds(openTime))) ms247        [benchmark]   restore, first after open:           \(format(milliseconds(coldRestore))) ms248        [benchmark]   restore, median of 20:               \(format(warm[10])) ms249        [benchmark]   restore without state blobs, median: \(format(light[10])) ms250        """)251        await database.close()252    }253}254
Files main
Menu

Theme