fix(browser): retain startup owners and coordinate retryable close

Validation: integrated changes passed formatting, typecheck, lint, resolved module-boundary verification and git diff --check. Tests and real-provider workflows were not run.
This commit is contained in:
morluto
2026-10-11 00:03:22 +08:00
parent d1235fadc9
commit 2a66ec9094
7 changed files with 184 additions and 81 deletions
@@ -6,6 +6,7 @@ import type { Result } from "../domain/result.js";
/** Provider-neutral application boundary for controlled browser scenarios. */
export interface BrowserScenarioCapturePort {
close?(): Promise<void>;
identity(): ProviderIdentity;
captureScenario(
scenario: BrowserScenario,
+4 -1
View File
@@ -38,5 +38,8 @@ export interface BrowserScenarioSessionPort {
/** Acquire one scenario session whose lifecycle the caller owns. */
export type BrowserScenarioSessionOpener = (
scenario: BrowserScenario,
options: { readonly signal?: AbortSignal },
options: {
readonly signal?: AbortSignal;
readonly retainCleanup?: (close: () => Promise<unknown>) => void;
},
) => Promise<BrowserScenarioSessionPort>;
+10 -2
View File
@@ -33,6 +33,7 @@ export class CdpConnection {
>();
#nextId = 1;
#closed = false;
#closePromise: Promise<void> | undefined;
#protocolFailed = false;
#transportFailure: "disconnected" | "payload_limit" = "disconnected";
@@ -151,8 +152,15 @@ export class CdpConnection {
}
/** Close only REA's socket; never close the browser or selected page. */
async close(): Promise<void> {
if (this.#closed) return;
close(): Promise<void> {
this.#closePromise ??= this.#closeTransport().catch((cause: unknown) => {
this.#closePromise = undefined;
throw cause;
});
return this.#closePromise;
}
async #closeTransport(): Promise<void> {
this.#closed = true;
this.#failPending("disconnected");
if (this.socket.readyState === WebSocket.CLOSED) return;
+32 -46
View File
@@ -50,54 +50,40 @@ export const closeCdpTargetSession = async (
signal?: AbortSignal,
): Promise<void> => {
const { connection, sessionId } = targetSession;
for (const [index, domain] of enabledDomains.entries()) {
if (signal?.aborted === true) {
await closeCancelledTargetSession(
targetSession,
enabledDomains.slice(index),
);
return;
}
try {
await connection.send(`${domain}.disable`, {}, sessionId, signal);
} catch (cause: unknown) {
// best-effort cleanup: domain disable continues to detach/close boundary.
void cause;
}
}
if (signal?.aborted === true) {
await closeCancelledTargetSession(targetSession, []);
return;
}
if (sessionId !== undefined)
try {
await connection.send(
"Target.detachFromTarget",
{ sessionId },
undefined,
signal,
);
} catch (cause: unknown) {
// best-effort cleanup: closing REA's socket is the final cleanup boundary.
void cause;
}
await connection.close();
};
const closeCancelledTargetSession = async (
{ connection, sessionId }: CdpTargetSession,
enabledDomains: readonly string[],
): Promise<void> => {
const commands = enabledDomains.map((domain) =>
connection.send(`${domain}.disable`, {}, sessionId),
);
if (sessionId !== undefined)
commands.push(connection.send("Target.detachFromTarget", { sessionId }));
const settled = Promise.allSettled(commands);
const cleanup = new AbortController();
const timeout = setTimeout(() => cleanup.abort(), 1_000);
timeout.unref();
try {
await connection.close();
if (signal?.aborted !== true) {
for (const domain of enabledDomains) {
if (cleanup.signal.aborted) break;
try {
await connection.send(
`${domain}.disable`,
{},
sessionId,
cleanup.signal,
);
} catch {
// Best-effort domain cleanup; transport close is the definitive boundary.
}
}
if (!cleanup.signal.aborted && sessionId !== undefined)
try {
await connection.send(
"Target.detachFromTarget",
{ sessionId },
undefined,
cleanup.signal,
);
} catch {
// Best-effort detach; transport close is the definitive boundary.
}
}
} finally {
await settled;
clearTimeout(timeout);
cleanup.abort();
await connection.close();
}
};
@@ -229,14 +229,15 @@ const runScenario = async (
openSession: BrowserScenarioSessionOpener,
scenario: BrowserScenario,
options: ExecutionOptions,
retainCleanup: (close: () => Promise<unknown>) => void,
): Promise<BrowserScenarioCapture> => {
if (options.signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
const startedAt = Date.now();
const session = await openSession(
scenario,
options.signal === undefined ? {} : { signal: options.signal },
);
const session = await openSession(scenario, {
...(options.signal === undefined ? {} : { signal: options.signal }),
retainCleanup,
});
const steps: BrowserScenarioStep[] = [];
let operationOutcome:
| { readonly ok: true }
@@ -279,6 +280,7 @@ const runScenario = async (
cleanupOutcome = { ok: true, cleanup: await session.close() };
} catch (cause: unknown) {
cleanupOutcome = { ok: false, cause };
retainCleanup(() => session.close());
}
if (!cleanupOutcome.ok) {
const cleanup = browserScenarioCleanupObservation(cleanupOutcome.cause);
@@ -337,18 +339,46 @@ const runScenario = async (
/** Controlled Playwright/CDP scenario driver with exact process ownership. */
export class PlaywrightBrowserScenarioProvider implements BrowserScenarioCapturePort {
#tail: Promise<void> = Promise.resolve();
#closing = false;
#closePromise: Promise<void> | undefined;
readonly #pendingCleanup = new Set<() => Promise<unknown>>();
constructor(private readonly openSession: BrowserScenarioSessionOpener) {}
identity(): ProviderIdentity {
return PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY;
}
async captureScenario(
captureScenario(
scenario: BrowserScenario,
options: ExecutionOptions = {},
): Promise<Result<BrowserScenarioCapture, AnalysisError>> {
if (this.#closing) return Promise.resolve(err(this.#closedError()));
const operation = this.#tail.then(() =>
this.#closing
? err(this.#closedError())
: this.#captureScenario(scenario, options),
);
this.#tail = operation.then(
() => undefined,
() => undefined,
);
return operation;
}
async #captureScenario(
scenario: BrowserScenario,
options: ExecutionOptions,
): Promise<Result<BrowserScenarioCapture, AnalysisError>> {
const pending = await this.#retryCleanup();
if (pending !== undefined) return err(pending);
try {
return ok(await runScenario(this.openSession, scenario, options));
return ok(
await runScenario(this.openSession, scenario, options, (close) => {
this.#pendingCleanup.add(close);
}),
);
} catch (cause: unknown) {
if (cause instanceof AnalysisError) return err(cause);
return err(
@@ -360,4 +390,43 @@ export class PlaywrightBrowserScenarioProvider implements BrowserScenarioCapture
);
}
}
async close(): Promise<void> {
this.#closing = true;
this.#closePromise ??= this.#tail
.then(async () => {
const failure = await this.#retryCleanup();
if (failure !== undefined) throw failure;
})
.catch((cause: unknown) => {
this.#closePromise = undefined;
throw cause;
});
return this.#closePromise;
}
#closedError(): AnalysisError {
return new BrowserObservationError(OPERATION, "cleanup_failed", {
detail: "Browser scenario provider is closing.",
cleanup: { reason: "Provider is closing", resources: [] },
});
}
async #retryCleanup(): Promise<AnalysisError | undefined> {
for (const pending of this.#pendingCleanup) {
try {
await pending();
this.#pendingCleanup.delete(pending);
} catch (cause: unknown) {
return cause instanceof AnalysisError
? cause
: new ProviderAdapterError(
PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY.id,
OPERATION,
{ cause },
);
}
}
return undefined;
}
}
+32 -8
View File
@@ -42,6 +42,7 @@ export class PlaywrightScenarioBrowserCleanupOwner {
#profileRemoved: boolean;
#closePromise: Promise<void> | undefined;
#eventFinalizationPromise: Promise<void> | undefined;
#eventFinalizationFailureReported = false;
/** Keep the narrow provider actions needed to release one opened browser. */
constructor(private readonly resources: PlaywrightScenarioCleanupResources) {
@@ -97,7 +98,10 @@ export class PlaywrightScenarioBrowserCleanupOwner {
try {
await eventFinalization;
} catch (cause: unknown) {
failures.push(cause);
if (!this.#eventFinalizationFailureReported) {
failures.push(cause);
this.#eventFinalizationFailureReported = true;
}
}
if (!this.#browserClosed) {
try {
@@ -380,6 +384,7 @@ const openAttachedScenarioBrowser = async (
environment: BrowserScenario["environment"],
launcher: ScenarioBrowserLauncher,
signal: AbortSignal | undefined,
retainCleanup: ((close: () => Promise<unknown>) => void) | undefined,
): Promise<OpenedScenarioBrowser> => {
const lease = await acquireAttachedScenario(browserRequest, signal);
let cleanupOwner: PlaywrightScenarioBrowserCleanupOwner | undefined;
@@ -431,7 +436,13 @@ const openAttachedScenarioBrowser = async (
throw cause;
}
const cleanup = cleanupOwner;
return failBrowserScenarioOperation(() => cleanup.close(), cause);
const close = () => cleanup.close();
try {
return await failBrowserScenarioOperation(close, cause);
} catch (failure: unknown) {
if (failure !== cause) retainCleanup?.(close);
throw failure;
}
}
};
@@ -442,6 +453,7 @@ export const openPlaywrightScenarioBrowser = async (
options: {
readonly launcher?: ScenarioBrowserLauncher;
readonly signal?: AbortSignal | undefined;
readonly retainCleanup?: (close: () => Promise<unknown>) => void;
} = {},
): Promise<OpenedScenarioBrowser> => {
const launcher = options.launcher ?? chromium;
@@ -451,6 +463,7 @@ export const openPlaywrightScenarioBrowser = async (
scenario.environment,
launcher,
options.signal,
options.retainCleanup,
);
const profilePath = await mkdtemp(join(tmpdir(), "rea-browser-scenario-"));
@@ -478,11 +491,16 @@ export const openPlaywrightScenarioBrowser = async (
timeout: 0,
});
} catch (cause: unknown) {
return failBrowserScenarioOperation(
() => rm(profilePath, { recursive: true, force: true, maxRetries: 3 }),
cause,
["browser_profile"],
);
const cleanup = () =>
rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
try {
return await failBrowserScenarioOperation(cleanup, cause, [
"browser_profile",
]);
} catch (failure: unknown) {
if (failure !== cause) options.retainCleanup?.(cleanup);
throw failure;
}
}
const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
closeBrowser: () => context.close(),
@@ -502,6 +520,12 @@ export const openPlaywrightScenarioBrowser = async (
cleanup,
};
} catch (cause: unknown) {
return failBrowserScenarioOperation(() => cleanup.close(), cause);
const close = () => cleanup.close();
try {
return await failBrowserScenarioOperation(close, cause);
} catch (failure: unknown) {
if (failure !== cause) options.retainCleanup?.(close);
throw failure;
}
}
};
+30 -18
View File
@@ -127,6 +127,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
environment: Readonly<Record<string, string | undefined>>,
options: {
readonly signal?: AbortSignal;
readonly retainCleanup?: (close: () => Promise<unknown>) => void;
},
): Promise<PlaywrightScenarioSession> {
if (options.signal?.aborted === true)
@@ -137,6 +138,9 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
const startedAt = Date.now();
const opening = openPlaywrightScenarioBrowser(scenario, environment, {
signal: options.signal,
...(options.retainCleanup === undefined
? {}
: { retainCleanup: options.retainCleanup }),
});
let opened: OpenedScenarioBrowser;
let events: PlaywrightScenarioEvents | undefined;
@@ -147,14 +151,18 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
options.signal,
);
} catch (cause: unknown) {
void opening
.then((lateOpened) =>
lateOpened.cleanup.close(undefined, options.signal),
)
.catch((cause: unknown) => {
// best-effort cleanup: late-open cleanup must not mask the boundary failure.
void cause;
});
const lateCleanup = () =>
opening.then(
(lateOpened) => lateOpened.cleanup.close(undefined, options.signal),
() => undefined,
);
options.retainCleanup?.(() =>
withPlaywrightExecutionBoundary(lateCleanup, 1_000),
);
void lateCleanup().catch((cleanupCause: unknown) => {
// best-effort cleanup: retainCleanup keeps the retry capability.
void cleanupCause;
});
throw cause;
}
let session: PlaywrightScenarioSession;
@@ -179,16 +187,19 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
eventCapture: events,
});
} catch (cause: unknown) {
return failBrowserScenarioOperation(
() =>
opened.cleanup.close(
events === undefined
? undefined
: () => events?.finish() ?? Promise.resolve(),
options.signal,
),
cause,
);
const cleanup = () =>
opened.cleanup.close(
events === undefined
? undefined
: () => events?.finish() ?? Promise.resolve(),
options.signal,
);
try {
return await failBrowserScenarioOperation(cleanup, cause);
} catch (failure: unknown) {
if (failure !== cause) options.retainCleanup?.(cleanup);
throw failure;
}
}
try {
await withPlaywrightExecutionBoundary(
@@ -212,6 +223,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
} catch (failure: unknown) {
cleanup = "incomplete";
cleanupFailure = { cause: failure };
options.retainCleanup?.(() => session.close());
}
throw browserScenarioOperationFailure(
cause,