Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/main/browser/browser-client-host-command-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ export function selectCommandPage(
}
}
if (command.pageHostGeneration < page.generation) {
const previous = page.records.get(command.commandSequence)
if (
command.command.type === 'switchProfile' &&
previous?.result?.status === 'completed' &&
previous.event.pageHostGeneration === command.pageHostGeneration &&
previous.event.commandId === command.commandId &&
commandsMatch(previous.event, command)
) {
return { page, commit: () => {} }
}
throw new Error('browser_host_page_generation_stale')
}
if (command.pageHostGeneration === page.generation) {
Expand Down Expand Up @@ -88,6 +98,12 @@ function commandsMatch(
if (first.command.type !== second.command.type) {
return false
}
if (first.command.type === 'switchProfile' && second.command.type === 'switchProfile') {
return (
first.command.nextPageHostGeneration === second.command.nextPageHostGeneration &&
JSON.stringify(first.command.profile) === JSON.stringify(second.command.profile)
)
}
if (first.command.type === 'navigate' && second.command.type === 'navigate') {
return first.command.url === second.command.url
}
Expand Down Expand Up @@ -121,6 +137,13 @@ export function assertNewPageCommand(
page: PageState,
command: BrowserClientHostCommandEvent
): void {
const active = [...page.records.values()].filter((record) => record.status !== 'settled')
if (
active.some((record) => record.event.command.type === 'switchProfile') ||
(command.command.type === 'switchProfile' && active.length > 0)
) {
throw new Error('browser_host_profile_switch_pending')
}
if (page.nextSequence === 1 && command.command.type === 'navigate') {
throw new Error('browser_host_command_create_required')
}
Expand Down Expand Up @@ -169,6 +192,9 @@ export function recordBrowserClientPageCommandResult(
command: BrowserClientHostCommandEvent['command'],
result: BrowserClientHostCommandResult
): void {
if (command.type === 'switchProfile' && result.status === 'completed') {
page.generation = command.nextPageHostGeneration
}
if (isBrowserClientPageBootstrapCommand(command)) {
page.created = result.status === 'completed'
page.createFailed = !page.created
Expand Down
3 changes: 3 additions & 0 deletions src/main/browser/browser-client-host-command-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,9 @@ export function createPageState(browserPageId: string, generation: number): Page
function snapshotPageCommand(
command: BrowserClientHostCommandEvent['command']
): BrowserClientHostCommandEvent['command'] {
if (command.type === 'switchProfile') {
return Object.freeze({ ...command, profile: Object.freeze({ ...command.profile }) })
}
if (command.type === 'reclaimPage') {
return Object.freeze({
...command,
Expand Down
16 changes: 16 additions & 0 deletions src/main/browser/browser-client-page-automation-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,22 @@ describe('BrowserClientPageAutomationRuntime', () => {
expect(fixture.unregisterGuest).toHaveBeenCalledWith('page-a')
})

it('retires an old automation session without stripping the guest needed by rollback', async () => {
const fixture = createFixture()
await fixture.runtime.execute(input(), new AbortController().signal)
await fixture.runtime.retire({
browserPageId: 'page-a',
pageHostGeneration: 9,
registration,
keepGuestBinding: true
})
expect(fixture.onTabClosed).toHaveBeenCalledWith(42)
expect(fixture.unregisterGuest).not.toHaveBeenCalled()
await expect(fixture.runtime.execute(input(), new AbortController().signal)).resolves.toEqual({
clicked: true
})
})

it('rejects aborts and registration failures before RPC dispatch', async () => {
const fixture = createFixture()
const controller = new AbortController()
Expand Down
5 changes: 3 additions & 2 deletions src/main/browser/browser-client-page-automation-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type AutomationPageInput = {
type AutomationPageRetirement = Pick<
AutomationPageInput,
'browserPageId' | 'pageHostGeneration' | 'registration'
>
> & { keepGuestBinding?: boolean }

type AutomationRuntimeDependencies = {
browserManager: Pick<
Expand Down Expand Up @@ -68,8 +68,9 @@ export class BrowserClientPageAutomationRuntime {
await bridge.onTabClosed(current.webContentsId)
}
if (
!input.keepGuestBinding &&
this.dependencies.browserManager.getGuestWebContentsId(input.browserPageId) ===
current.webContentsId
current.webContentsId
) {
this.dependencies.browserManager.unregisterGuest(input.browserPageId)
}
Expand Down
21 changes: 21 additions & 0 deletions src/main/browser/browser-client-page-availability.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { BrowserClientPageCommandExecutorDependencies } from './browser-client-page-command-executor-dependencies'
import type { BrowserRoutePageGuestIdentity } from './browser-route-page-authority'
import type { BrowserClientRetainedPage } from './browser-client-page-retained-state'

Expand All @@ -22,3 +23,23 @@ export function markBrowserClientPageUnavailable(
onUnavailable(registration.browserPageId, page.generation)
return true
}

export function publishBrowserClientRetainedPage(
dependencies: BrowserClientPageCommandExecutorDependencies,
pages: Map<string, BrowserClientRetainedPage>,
page: BrowserClientRetainedPage
): void {
const previous = pages.get(page.inventory.browserPageId)
previous?.releaseAvailabilityWatch?.()
if (previous) {
previous.releaseAvailabilityWatch = undefined
}
page.releaseAvailabilityWatch = dependencies.routeWebContents.watchPageAvailability?.(
page.inventory.browserPageId,
(registration) =>
markBrowserClientPageUnavailable(pages, registration, (browserPageId, generation) =>
dependencies.onPageUnavailable?.(browserPageId, generation)
)
)
pages.set(page.inventory.browserPageId, page)
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export type BrowserClientPageCommandExecutorDependencies = BrowserClientPageAuth
signal: AbortSignal
): Promise<unknown>
retireAutomation(input: {
keepGuestBinding?: boolean
browserPageId: string
pageHostGeneration: number
registration: BrowserClientRetainedPage['registration']
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { BrowserRoutePreparePageInput } from './browser-route-session-state'
import type { BrowserClientHostCommandEvent } from '../../shared/browser-client-host-protocol'
import { vi } from 'vitest'
import { BrowserClientPageCommandExecutor } from './browser-client-page-command-executor'
Expand Down Expand Up @@ -89,7 +90,7 @@ export function createHarness(options: { maxPages?: number } = {}) {
}),
selectRenderer: vi.fn(() => renderer),
routeSessions: {
preparePage: vi.fn(async () => {
preparePage: vi.fn(async (_input: BrowserRoutePreparePageInput) => {
order.push('prepare-page')
return routeSession
})
Expand Down
106 changes: 52 additions & 54 deletions src/main/browser/browser-client-page-command-executor.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import { closeBrowserClientExecutorPages } from './browser-client-page-executor-close'
import {
switchBrowserClientPageProfile,
retireSwitchedBrowserClientPage
} from './browser-client-page-profile-switch'
import {
BROWSER_CLIENT_HOST_PAGE_INVENTORY_MAX_PAGES,
type BrowserClientHostedPageInventory,
Expand All @@ -20,7 +25,7 @@ import { BrowserClientPageNavigationFence } from './browser-client-page-navigati
import { executeBrowserClientPageReconciliationCommand } from './browser-client-page-reconciliation'
import {
findBrowserClientPageByWebContentsId,
forgetBrowserClientRetainedPage,
retireBrowserClientRetainedPage,
type BrowserClientRetainedPage
} from './browser-client-page-retained-state'
import {
Expand All @@ -32,7 +37,7 @@ import {
executeBrowserClientPageAutomationCommand,
navigateBrowserClientPageCommand
} from './browser-client-page-command-execution'
import { markBrowserClientPageUnavailable } from './browser-client-page-availability'
import { publishBrowserClientRetainedPage } from './browser-client-page-availability'
import type {
BrowserClientPageAuthorityIdentity,
BrowserClientPageCommandExecutorDependencies
Expand All @@ -43,6 +48,7 @@ export class BrowserClientPageCommandExecutor {
private readonly pages = new Map<string, BrowserClientRetainedPage>()
private readonly creatingPages = new Map<string, BrowserClientHostedPageInventory>()
private readonly failedPages = new Map<string, BrowserClientHostedPageInventory>()
private readonly retiredProfileCleanups = new Map<Promise<void>, BrowserClientRetainedPage>()
private readonly navigationFence = new BrowserClientPageNavigationFence()
private closePromise: Promise<void> | null = null
private authorityConnectionIdentity: string
Expand Down Expand Up @@ -83,6 +89,28 @@ export class BrowserClientPageCommandExecutor {
signal: AbortSignal
): Promise<unknown> {
switch (event.command.type) {
case 'switchProfile':
return switchBrowserClientPageProfile({
event,
signal,
retainedCleanups: this.retiredProfileCleanups,
pages: this.pages,
dependencies: {
...this.dependencies,
authorityConnectionIdentity: this.authorityConnectionIdentity,
legacyAuthorityConnectionIdentity: this.legacyAuthorityConnectionIdentity
},
assertAvailable: () =>
this.navigationFence.assertAvailable(this.closed || this.authorityTransitioning),
commit: (page) => publishBrowserClientRetainedPage(this.dependencies, this.pages, page),
cleanup: (page) => this.cleanupPage(page, undefined, false),
retirePrevious: (page) =>
retireSwitchedBrowserClientPage(
page,
(old) => this.cleanupPage(old),
this.retiredProfileCleanups
)
})
case 'createPage':
return this.createPage(event, signal)
case 'navigate':
Expand Down Expand Up @@ -188,24 +216,14 @@ export class BrowserClientPageCommandExecutor {
this.authorityTransitioning = false
}

async retirePage(browserPageId: string, pageHostGeneration: number): Promise<boolean> {
const page = this.pages.get(browserPageId)
if (!page || page.generation !== pageHostGeneration) {
return false
}
page.retiring ??= this.cleanupPage(page)
try {
await page.retiring
} catch (error) {
forgetBrowserClientRetainedPage(this.pages, browserPageId, page)
this.failedPages.set(
browserPageId,
Object.freeze({ ...page.inventory, state: 'outcomeUnknown' })
)
throw error
}
forgetBrowserClientRetainedPage(this.pages, browserPageId, page)
return true
retirePage(browserPageId: string, pageHostGeneration: number): Promise<boolean> {
return retireBrowserClientRetainedPage(
this.pages,
this.failedPages,
browserPageId,
pageHostGeneration,
(page) => this.cleanupPage(page)
)
}

private async createPage(
Expand Down Expand Up @@ -252,17 +270,7 @@ export class BrowserClientPageCommandExecutor {
signal,
() => this.navigationFence.assertAvailable(this.closed || this.authorityTransitioning),
(page) => {
page.releaseAvailabilityWatch = this.dependencies.routeWebContents.watchPageAvailability?.(
event.browserPageId,
(registration) =>
markBrowserClientPageUnavailable(
this.pages,
registration,
(browserPageId, generation) =>
this.dependencies.onPageUnavailable?.(browserPageId, generation)
)
)
this.pages.set(event.browserPageId, page)
publishBrowserClientRetainedPage(this.dependencies, this.pages, page)
}
)
}
Expand All @@ -274,7 +282,8 @@ export class BrowserClientPageCommandExecutor {

private async cleanupPage(
page: BrowserClientRetainedPage,
previousRendererPage?: BrowserClientPageRendererIdentity
previousRendererPage?: BrowserClientPageRendererIdentity,
releaseUploads = true
): Promise<void> {
page.releaseAvailabilityWatch?.()
page.releaseAvailabilityWatch = undefined
Expand All @@ -285,34 +294,23 @@ export class BrowserClientPageCommandExecutor {
routeWebContents: this.dependencies.routeWebContents,
retireAutomation: this.dependencies.retireAutomation,
releaseUploadStaging: async () => {
await this.dependencies.uploadStaging?.releasePage(page.inventory.browserPageId)
if (releaseUploads) {
await this.dependencies.uploadStaging?.releasePage(page.inventory.browserPageId)
}
}
},
previousRendererPage
)
}

private async closePages(): Promise<void> {
const failures: unknown[] = [
...(this.creatingPages.size > 0
? [new Error('browser_client_page_creation_still_running')]
: []),
...(this.failedPages.size > 0 ? [new Error('browser_client_page_cleanup_unresolved')] : [])
]
for (const [browserPageId, page] of this.pages) {
try {
page.retiring ??= this.cleanupPage(page)
await page.retiring
forgetBrowserClientRetainedPage(this.pages, browserPageId, page)
} catch (error) {
failures.push(error)
}
}
await this.dependencies.uploadStaging?.releaseAll().catch((error: unknown) => {
failures.push(error)
private closePages(): Promise<void> {
return closeBrowserClientExecutorPages({
retiredProfileCleanups: this.retiredProfileCleanups,
creatingPages: this.creatingPages,
failedPages: this.failedPages,
pages: this.pages,
cleanupPage: (page) => this.cleanupPage(page),
uploadStaging: this.dependencies.uploadStaging
})
if (failures.length > 0) {
throw new AggregateError(failures, 'Browser client page executor cleanup failed')
}
}
}
5 changes: 4 additions & 1 deletion src/main/browser/browser-client-page-creation.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { BrowserClientProfileMetadata } from '../../shared/browser-client-profile-switch-protocol'
import type { BrowserClientHostCommandEvent } from '../../shared/browser-client-host-protocol'
import {
cleanupBrowserClientPage,
Expand Down Expand Up @@ -41,7 +42,8 @@ export async function createReservedBrowserClientPage(
event: BrowserClientHostCommandEvent,
signal: AbortSignal,
assertAvailable: () => void,
commit: (page: BrowserClientRetainedPage) => void
commit: (page: BrowserClientRetainedPage) => void,
profileMetadata?: BrowserClientProfileMetadata
): Promise<BrowserClientRetainedPage> {
if (event.command.type !== 'createPage') {
throw new BrowserClientPageCommandError('browser_client_page_command_invalid')
Expand All @@ -67,6 +69,7 @@ export async function createReservedBrowserClientPage(
renderer = dependencies.selectRenderer()
assertCurrentBrowserClientPageRenderer(renderer)
routeSession = await dependencies.routeSessions.preparePage({
...(profileMetadata ? { profileMetadata } : {}),
identity: {
orcaProfileId: dependencies.orcaProfileId,
browserProfileId: event.command.browserProfileId,
Expand Down
36 changes: 36 additions & 0 deletions src/main/browser/browser-client-page-executor-close.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import type { BrowserClientRetainedPage } from './browser-client-page-retained-state'
import type { BrowserClientUploadStaging } from './browser-client-upload-staging'
import { forgetBrowserClientRetainedPage } from './browser-client-page-retained-state'

export async function closeBrowserClientExecutorPages(input: {
retiredProfileCleanups: ReadonlyMap<Promise<void>, BrowserClientRetainedPage>
creatingPages: ReadonlyMap<string, unknown>
failedPages: ReadonlyMap<string, unknown>
pages: Map<string, BrowserClientRetainedPage>
cleanupPage(page: BrowserClientRetainedPage): Promise<void>
uploadStaging?: BrowserClientUploadStaging
}): Promise<void> {
const retired = await Promise.allSettled(input.retiredProfileCleanups.keys())
const failures: unknown[] = [
...retired.filter((result) => result.status === 'rejected').map((result) => result.reason),
...(input.creatingPages.size > 0
? [new Error('browser_client_page_creation_still_running')]
: []),
...(input.failedPages.size > 0 ? [new Error('browser_client_page_cleanup_unresolved')] : [])
]
for (const [browserPageId, page] of input.pages) {
try {
page.retiring ??= input.cleanupPage(page)
await page.retiring
forgetBrowserClientRetainedPage(input.pages, browserPageId, page)
} catch (error) {
failures.push(error)
}
}
await input.uploadStaging?.releaseAll().catch((error: unknown) => {
failures.push(error)
})
if (failures.length > 0) {
throw new AggregateError(failures, 'Browser client page executor cleanup failed')
}
}
Loading