316 lines
9.7 KiB
TypeScript
316 lines
9.7 KiB
TypeScript
import { chmod, mkdtemp, rm } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import { join, resolve } from "node:path";
|
|
|
|
import {
|
|
chromium,
|
|
type Browser,
|
|
type BrowserContext,
|
|
type Page,
|
|
} 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";
|
|
|
|
const OPERATION = "capture_browser_scenario" as const;
|
|
|
|
export interface OpenedScenarioBrowser {
|
|
readonly context: BrowserContext;
|
|
readonly page: Page;
|
|
readonly browser: Browser;
|
|
readonly profilePath: string | undefined;
|
|
readonly cleanup: PlaywrightScenarioBrowserCleanupOwner;
|
|
}
|
|
|
|
/** Provider actions retained until the owned browser and profile are released. */
|
|
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 = (
|
|
environment: Readonly<Record<string, string | undefined>>,
|
|
): Record<string, string | undefined> => {
|
|
const allowed = [
|
|
"DBUS_SESSION_BUS_ADDRESS",
|
|
"DISPLAY",
|
|
"HOME",
|
|
"LANG",
|
|
"LD_LIBRARY_PATH",
|
|
"PATH",
|
|
"SystemRoot",
|
|
"TEMP",
|
|
"TMP",
|
|
"TMPDIR",
|
|
"WAYLAND_DISPLAY",
|
|
"XAUTHORITY",
|
|
"XDG_RUNTIME_DIR",
|
|
];
|
|
return Object.fromEntries(
|
|
allowed
|
|
.map((name) => [name, environment[name]] as const)
|
|
.filter(
|
|
(entry): entry is readonly [string, string] => entry[1] !== undefined,
|
|
),
|
|
);
|
|
};
|
|
const findConnectedPage = async (
|
|
browser: Browser,
|
|
targetId: string,
|
|
): Promise<{ readonly context: BrowserContext; readonly page: Page }> => {
|
|
for (const context of browser.contexts())
|
|
for (const page of context.pages()) {
|
|
const session = await context.newCDPSession(page);
|
|
try {
|
|
const { targetInfo } = await session.send("Target.getTargetInfo");
|
|
if (targetInfo.targetId !== targetId) continue;
|
|
return { context, page };
|
|
} finally {
|
|
await session.detach();
|
|
}
|
|
}
|
|
throw new BrowserObservationError(OPERATION, "target_not_found");
|
|
};
|
|
|
|
const configureAttachedEnvironment = async (
|
|
context: BrowserContext,
|
|
page: Page,
|
|
scenario: BrowserScenario,
|
|
): Promise<void> => {
|
|
await page.setViewportSize({
|
|
width: scenario.environment.viewport.width,
|
|
height: scenario.environment.viewport.height,
|
|
});
|
|
await page.emulateMedia({
|
|
colorScheme: scenario.environment.color_scheme,
|
|
reducedMotion: scenario.environment.reduced_motion,
|
|
});
|
|
const session = await context.newCDPSession(page);
|
|
try {
|
|
await session.send("Emulation.setDeviceMetricsOverride", {
|
|
width: scenario.environment.viewport.width,
|
|
height: scenario.environment.viewport.height,
|
|
deviceScaleFactor: scenario.environment.viewport.device_scale_factor,
|
|
mobile: false,
|
|
});
|
|
await session.send("Emulation.setLocaleOverride", {
|
|
locale: scenario.environment.locale,
|
|
});
|
|
await session.send("Emulation.setTimezoneOverride", {
|
|
timezoneId: scenario.environment.timezone,
|
|
});
|
|
} finally {
|
|
await session.detach();
|
|
}
|
|
};
|
|
|
|
/** 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,
|
|
environment: Readonly<Record<string, string | undefined>>,
|
|
launcher: Pick<
|
|
typeof chromium,
|
|
"connectOverCDP" | "launchPersistentContext"
|
|
> = chromium,
|
|
): Promise<OpenedScenarioBrowser> => {
|
|
if (scenario.browser.mode === "connect") {
|
|
const browser = await launcher.connectOverCDP(
|
|
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,
|
|
cleanup,
|
|
};
|
|
} catch (cause: unknown) {
|
|
return failBrowserScenarioOperation(() => cleanup.close(), cause);
|
|
}
|
|
}
|
|
|
|
const profilePath = await mkdtemp(join(tmpdir(), "rea-browser-scenario-"));
|
|
let context: BrowserContext;
|
|
try {
|
|
await chmod(profilePath, 0o700);
|
|
context = await launcher.launchPersistentContext(profilePath, {
|
|
executablePath: resolve(scenario.browser.executable_path),
|
|
headless: scenario.browser.headless,
|
|
acceptDownloads: false,
|
|
viewport: {
|
|
width: scenario.environment.viewport.width,
|
|
height: scenario.environment.viewport.height,
|
|
},
|
|
deviceScaleFactor: scenario.environment.viewport.device_scale_factor,
|
|
locale: scenario.environment.locale,
|
|
timezoneId: scenario.environment.timezone,
|
|
colorScheme: scenario.environment.color_scheme,
|
|
reducedMotion: scenario.environment.reduced_motion,
|
|
serviceWorkers: scenario.environment.service_workers,
|
|
env: allowedBrowserEnvironment(environment),
|
|
handleSIGHUP: false,
|
|
handleSIGINT: false,
|
|
handleSIGTERM: false,
|
|
timeout: 0,
|
|
});
|
|
} catch (cause: unknown) {
|
|
return failBrowserScenarioOperation(
|
|
() => rm(profilePath, { recursive: true, force: true, maxRetries: 3 }),
|
|
cause,
|
|
["browser_profile"],
|
|
);
|
|
}
|
|
const cleanup = new PlaywrightScenarioBrowserCleanupOwner({
|
|
closeBrowser: () => context.close(),
|
|
removeProfile: () =>
|
|
rm(profilePath, { recursive: true, force: true, maxRetries: 3 }),
|
|
});
|
|
try {
|
|
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) {
|
|
return failBrowserScenarioOperation(() => cleanup.close(), cause);
|
|
}
|
|
};
|