fix(browser): retain scenario resources until cleanup succeeds

This commit is contained in:
morluto
2026-10-09 21:01:52 +08:00
parent 636b245f1b
commit 88640f60fe
4 changed files with 245 additions and 79 deletions
@@ -1,10 +1,11 @@
// Fake-backed composition coverage; real browser verification lives in
// `npm run verify:browser`.
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import type { BrowserScenarioSessionPort } from "./BrowserScenarioSessionPort.js";
import { PlaywrightBrowserScenarioProvider } from "./PlaywrightBrowserScenarioProvider.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import { PlaywrightScenarioBrowserCleanupOwner } from "./PlaywrightScenarioBrowser.js";
import {
browserScenarioSchema,
type BrowserScenario,
@@ -318,3 +319,56 @@ describe("PlaywrightBrowserScenarioProvider", () => {
expect(session.closeCalls).toBe(1);
});
});
it("shares concurrent close and retries browser cleanup after failure", async () => {
const browserClose = vi
.fn<() => Promise<void>>()
.mockRejectedValueOnce(new Error("browser close failed"))
.mockResolvedValue(undefined);
const removeProfile = vi
.fn<() => Promise<void>>()
.mockResolvedValue(undefined);
const finishEvents = vi
.fn<() => Promise<void>>()
.mockResolvedValue(undefined);
const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
closeBrowser: browserClose,
removeProfile,
});
const first = cleanup.close(finishEvents);
const concurrent = cleanup.close(finishEvents);
await expect(first).rejects.toMatchObject({ reason: "cleanup_failed" });
await expect(concurrent).rejects.toMatchObject({ reason: "cleanup_failed" });
expect(browserClose).toHaveBeenCalledTimes(1);
expect(removeProfile).not.toHaveBeenCalled();
expect(finishEvents).toHaveBeenCalledTimes(1);
await expect(cleanup.close(finishEvents)).resolves.toBeUndefined();
await expect(cleanup.close(finishEvents)).resolves.toBeUndefined();
expect(browserClose).toHaveBeenCalledTimes(2);
expect(removeProfile).toHaveBeenCalledTimes(1);
expect(finishEvents).toHaveBeenCalledTimes(1);
});
it("keeps failed event finalization failed across cleanup retries", async () => {
const finishEvents = vi
.fn<() => Promise<void>>()
.mockRejectedValue(new Error("event finalization failed"));
const closeBrowser = vi
.fn<() => Promise<void>>()
.mockResolvedValue(undefined);
const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
closeBrowser,
removeProfile: undefined,
});
await expect(cleanup.close(finishEvents)).rejects.toMatchObject({
reason: "cleanup_failed",
});
await expect(cleanup.close(finishEvents)).rejects.toMatchObject({
reason: "cleanup_failed",
});
expect(finishEvents).toHaveBeenCalledTimes(1);
expect(closeBrowser).toHaveBeenCalledTimes(1);
});
+13 -15
View File
@@ -2,8 +2,8 @@ import { afterEach, expect, it, vi } from "vitest";
import { browserScenarioSchema } from "../domain/browserScenario.js";
import {
closePlaywrightScenarioBrowser,
openPlaywrightScenarioBrowser,
PlaywrightScenarioBrowserCleanupOwner,
} from "./PlaywrightScenarioBrowser.js";
afterEach(() => vi.unstubAllEnvs());
@@ -42,23 +42,21 @@ it("passes the selected environment to the actual browser launch boundary", asyn
it("returns cancellation instead of success when an attached browser hangs on close", async () => {
const controller = new AbortController();
let closeStarted = false;
const closing = closePlaywrightScenarioBrowser(
{
browser: {
close: () => {
closeStarted = true;
return new Promise<void>(() => undefined);
},
},
context: { close: async () => undefined },
profilePath: undefined,
let resolveCloseStarted: () => void = () => undefined;
const closeStarted = new Promise<void>((resolve) => {
resolveCloseStarted = resolve;
});
const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
closeBrowser: () => {
resolveCloseStarted();
return new Promise<void>(() => undefined);
},
controller.signal,
);
removeProfile: undefined,
});
const closing = cleanup.close(undefined, controller.signal);
await closeStarted;
controller.abort();
expect(closeStarted).toBe(true);
await expect(closing).rejects.toMatchObject({
_tag: "BrowserObservationError",
reason: "cleanup_failed",
+162 -43
View File
@@ -10,6 +10,7 @@ import {
} from "playwright-core";
import type { BrowserScenario } from "../domain/browserScenario.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.js";
@@ -20,12 +21,98 @@ export interface OpenedScenarioBrowser {
readonly page: Page;
readonly browser: Browser;
readonly profilePath: string | undefined;
readonly cleanup: PlaywrightScenarioBrowserCleanupOwner;
}
interface CloseableScenarioBrowser {
readonly context: Pick<BrowserContext, "close">;
readonly browser: Pick<Browser, "close">;
readonly profilePath: string | undefined;
/** Provider actions retained until the owned browser and profile are released. */
export interface PlaywrightScenarioCleanupResources {
readonly closeBrowser: () => Promise<void>;
readonly removeProfile: (() => Promise<void>) | undefined;
}
/** Owns one browser connection and optional private profile through cleanup retries. */
export class PlaywrightScenarioBrowserCleanupOwner {
#browserClosed = false;
#profileRemoved: boolean;
#closePromise: Promise<void> | undefined;
#eventFinalizationPromise: Promise<void> | undefined;
/** Keep the narrow provider actions needed to release one opened browser. */
constructor(private readonly resources: PlaywrightScenarioCleanupResources) {
this.#profileRemoved = resources.removeProfile === undefined;
}
close(
finishEvents?: () => Promise<void>,
signal?: AbortSignal,
): Promise<void> {
const cleanup = this.#closePromise ?? this.#closeResources(finishEvents);
if (this.#closePromise === undefined) {
this.#closePromise = cleanup;
void cleanup.catch(() => {
if (this.#closePromise === cleanup) this.#closePromise = undefined;
});
}
return this.#awaitCleanup(cleanup, signal);
}
async #awaitCleanup(
cleanup: Promise<void>,
signal?: AbortSignal,
): Promise<void> {
try {
await withPlaywrightExecutionBoundary(() => cleanup, 1_000, signal);
} catch (cause: unknown) {
throw new BrowserObservationError(OPERATION, "cleanup_failed", {
cause,
cleanup: {
reason: cause instanceof Error ? cause.message : String(cause),
resources: [
"browser_transport",
...(this.resources.removeProfile === undefined
? []
: ["browser_profile"]),
],
},
});
}
}
async #closeResources(finishEvents?: () => Promise<void>): Promise<void> {
const failures: unknown[] = [];
const eventFinalization = (this.#eventFinalizationPromise ??=
Promise.resolve().then(async () => {
await finishEvents?.();
}));
try {
await eventFinalization;
} catch (cause: unknown) {
failures.push(cause);
}
if (!this.#browserClosed) {
try {
await this.resources.closeBrowser();
this.#browserClosed = true;
} catch (cause: unknown) {
failures.push(cause);
}
}
if (
this.#browserClosed &&
!this.#profileRemoved &&
this.resources.removeProfile !== undefined
) {
try {
await this.resources.removeProfile();
this.#profileRemoved = true;
} catch (cause: unknown) {
failures.push(cause);
}
}
if (failures.length === 1) throw failures[0];
if (failures.length > 1)
throw new AggregateError(failures, "Browser session cleanup failed");
}
}
const allowedBrowserEnvironment = (
@@ -54,7 +141,6 @@ const allowedBrowserEnvironment = (
),
);
};
const findConnectedPage = async (
browser: Browser,
targetId: string,
@@ -105,6 +191,41 @@ const configureAttachedEnvironment = async (
}
};
/** Preserve an operation failure while reporting any incomplete cleanup. */
export const failBrowserScenarioOperation = async (
cleanup: () => Promise<void>,
primaryFailure: unknown,
fallbackCleanupResources: readonly string[] = ["browser_transport"],
): Promise<never> => {
try {
await cleanup();
} catch (cleanupFailure: unknown) {
const cleanupDetails =
cleanupFailure instanceof AnalysisError &&
cleanupFailure.cleanup !== undefined
? cleanupFailure.cleanup
: {
reason:
cleanupFailure instanceof Error
? cleanupFailure.message
: String(cleanupFailure),
resources:
cleanupFailure instanceof AnalysisError
? cleanupFailure.cleanupResources
: fallbackCleanupResources,
};
throw new BrowserObservationError(OPERATION, "cleanup_failed", {
cause: new AggregateError(
[primaryFailure, cleanupFailure],
"Browser scenario operation and cleanup both failed",
{ cause: primaryFailure },
),
cleanup: cleanupDetails,
});
}
throw primaryFailure;
};
/** Launch or attach using the caller-selected environment and browser engine. */
export const openPlaywrightScenarioBrowser = async (
scenario: BrowserScenario,
@@ -119,23 +240,32 @@ export const openPlaywrightScenarioBrowser = async (
scenario.browser.cdp_endpoint,
{ timeout: 0 },
);
const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
closeBrowser: () => browser.close(),
removeProfile: undefined,
});
try {
const target = await findConnectedPage(
browser,
scenario.browser.target_id,
);
await configureAttachedEnvironment(target.context, target.page, scenario);
return { ...target, browser, profilePath: undefined };
return {
...target,
browser,
profilePath: undefined,
cleanup,
};
} catch (cause: unknown) {
await browser.close();
throw cause;
return failBrowserScenarioOperation(() => cleanup.close(), cause);
}
}
const profilePath = await mkdtemp(join(tmpdir(), "rea-browser-scenario-"));
await chmod(profilePath, 0o700);
let context: BrowserContext;
try {
const context = await launcher.launchPersistentContext(profilePath, {
await chmod(profilePath, 0o700);
context = await launcher.launchPersistentContext(profilePath, {
executablePath: resolve(scenario.browser.executable_path),
headless: scenario.browser.headless,
acceptDownloads: false,
@@ -155,42 +285,31 @@ export const openPlaywrightScenarioBrowser = async (
handleSIGTERM: false,
timeout: 0,
});
const browser = context.browser();
if (browser === null) {
await context.close();
throw new BrowserObservationError(OPERATION, "protocol_error");
}
const page = context.pages()[0] ?? (await context.newPage());
return { context, page, browser, profilePath };
} catch (cause: unknown) {
await rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
throw cause;
return failBrowserScenarioOperation(
() => rm(profilePath, { recursive: true, force: true, maxRetries: 3 }),
cause,
["browser_profile"],
);
}
};
export const closePlaywrightScenarioBrowser = async (
{ context, browser, profilePath }: CloseableScenarioBrowser,
signal?: AbortSignal,
): Promise<void> => {
const cleanup = (async () => {
try {
// In connect mode Playwright's Browser.close disconnects its CDP client;
// it does not close the externally owned browser process.
if (profilePath === undefined) await browser.close();
else await context.close();
} finally {
if (profilePath !== undefined)
await rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
}
})();
// best-effort cleanup: the bounded execution boundary below observes the
// same cleanup promise; this early attachment only prevents unhandled rejection.
void cleanup.catch(() => undefined);
// The shared execution boundary rejects cancellation/timeouts instead of
// returning a successful capture whose browser or profile may still exist.
const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
closeBrowser: () => context.close(),
removeProfile: () =>
rm(profilePath, { recursive: true, force: true, maxRetries: 3 }),
});
try {
await withPlaywrightExecutionBoundary(() => cleanup, 1_000, signal);
const browser = context.browser();
if (browser === null)
throw new BrowserObservationError(OPERATION, "protocol_error");
const page = context.pages()[0] ?? (await context.newPage());
return {
context,
page,
browser,
profilePath,
cleanup,
};
} catch (cause: unknown) {
throw new BrowserObservationError(OPERATION, "cleanup_failed", { cause });
return failBrowserScenarioOperation(() => cleanup.close(), cause);
}
};
+15 -20
View File
@@ -11,7 +11,7 @@ import type {
} from "./BrowserScenarioSessionPort.js";
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
import {
closePlaywrightScenarioBrowser,
failBrowserScenarioOperation,
openPlaywrightScenarioBrowser,
type OpenedScenarioBrowser,
} from "./PlaywrightScenarioBrowser.js";
@@ -103,10 +103,8 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
readonly product = "Chromium";
readonly version: string;
readonly initialUrl: string;
private closed = false;
private readonly secrets: BrowserScenarioSecrets;
private readonly eventCapture: PlaywrightScenarioEvents;
private readonly signal: AbortSignal | undefined;
private constructor(
private readonly opened: OpenedScenarioBrowser,
@@ -114,7 +112,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
readonly mode: BrowserScenario["browser"]["mode"];
readonly secrets: BrowserScenarioSecrets;
readonly eventCapture: PlaywrightScenarioEvents;
readonly signal?: AbortSignal;
},
) {
this.mode = options.mode;
@@ -122,7 +119,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
options.mode === "launch" ? "provider-owned" : "external";
this.secrets = options.secrets;
this.eventCapture = options.eventCapture;
this.signal = options.signal;
this.version = opened.browser.version();
this.initialUrl = opened.page.url();
}
@@ -141,6 +137,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
throw new BrowserObservationError(OPERATION, "secret_unavailable");
const opening = openPlaywrightScenarioBrowser(scenario, environment);
let opened: OpenedScenarioBrowser;
let events: PlaywrightScenarioEvents | undefined;
try {
opened = await withPlaywrightExecutionBoundary(
() => opening,
@@ -150,7 +147,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
} catch (cause: unknown) {
void opening
.then((lateOpened) =>
closePlaywrightScenarioBrowser(lateOpened, options.signal),
lateOpened.cleanup.close(undefined, options.signal),
)
.catch((cause: unknown) => {
// best-effort cleanup: late-open cleanup must not mask the boundary failure.
@@ -164,7 +161,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
undefined,
options.signal,
);
const events = new PlaywrightScenarioEvents({
events = new PlaywrightScenarioEvents({
page: opened.page,
context: opened.context,
ownsContext: scenario.browser.mode === "launch",
@@ -177,7 +174,6 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
mode: scenario.browser.mode,
secrets,
eventCapture: events,
...(options.signal === undefined ? {} : { signal: options.signal }),
});
await withPlaywrightExecutionBoundary(
() =>
@@ -190,8 +186,16 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
);
return session;
} catch (cause: unknown) {
await closePlaywrightScenarioBrowser(opened, options.signal);
throw cause;
return failBrowserScenarioOperation(
() =>
opened.cleanup.close(
events === undefined
? undefined
: () => events?.finish() ?? Promise.resolve(),
options.signal,
),
cause,
);
}
}
@@ -260,16 +264,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
}
async close() {
if (this.closed)
return this.mode === "launch"
? ("terminated-owned-process" as const)
: ("disconnected-external" as const);
this.closed = true;
try {
await this.eventCapture.finish();
} finally {
await closePlaywrightScenarioBrowser(this.opened, this.signal);
}
await this.opened.cleanup.close(() => this.eventCapture.finish());
return this.mode === "launch"
? ("terminated-owned-process" as const)
: ("disconnected-external" as const);