mirror of
https://github.com/morluto/rea.git
synced 2026-12-06 23:09:34 +00:00
* fix(browser): settle Frida, Playwright, CDP, and Electron cleanup races - Record an owed resume when a Frida spawn's script stays retained after its session detached, so a close retry resumes the target. - Give a clean Playwright open failure its bounded cleanup before reporting, and wrap only leases that remain unreleased. - Retire the main policy session when CDP reports it gone, instead of failing every service-worker cleanup retry. - Skip lifecycle enabling for a CDP capture that ended before arming, and report a termination observed after the window. - Capture only the Electron scripts parsed before capture, and give the CDP Electron provider its own ASAR descriptor owner. - Wait for any close that starts while V8 admission waits for one. * fix(browser): recover a gone main session in every command, report late scripts - Mark the main policy session detached whenever a command on it is rejected as session-gone, and stop a cancelled capture's navigation through the Playwright frame when Page.stopLoading finds the session gone, so cleanup retries no longer repeat the same failed command. - Count Electron scripts parsed after script capture, report them as dropped and include them in the total, as web capture does.
548 lines
17 KiB
TypeScript
548 lines
17 KiB
TypeScript
import { QueuedProviderClose } from "../providers/QueuedProviderClose.js";
|
|
import { finalizedResult, runOwned } from "../providers/runOwned.js";
|
|
import {
|
|
withPlaywrightExecutionBoundary,
|
|
PLAYWRIGHT_CLEANUP_CONFIRMATION_TIMEOUT_MS,
|
|
} from "./PlaywrightExecutionBoundary.js";
|
|
import {
|
|
analysisErrorWithCleanupDependencies,
|
|
providerCleanupErrorFromFailures,
|
|
} from "../domain/analysisErrorCleanup.js";
|
|
import {
|
|
AnalysisCleanupLease,
|
|
AnalysisCleanupLeaseGroup,
|
|
} from "../resources/index.js";
|
|
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
|
import type { BrowserScenarioCapturePort } from "../ports/BrowserScenarioCapturePort.js";
|
|
import type {
|
|
ExecutionOptions,
|
|
ProviderIdentity,
|
|
} from "../ports/AnalysisProvider.js";
|
|
import type { BrowserScenario } from "../domain/browserScenario.js";
|
|
import {
|
|
BROWSER_SCENARIO_START_STEP_ID,
|
|
type BrowserScenarioAction,
|
|
} from "../domain/browserScenarioValues.js";
|
|
import {
|
|
browserScenarioCaptureSchema,
|
|
type BrowserScenarioCapture,
|
|
type BrowserScenarioPartialObservation,
|
|
} from "../domain/browserScenarioCapture.js";
|
|
import {
|
|
classifyBrowserScenarioCompleteness,
|
|
type BrowserScenarioCompleteness,
|
|
type BrowserScenarioCompletenessSection,
|
|
type BrowserScenarioStep,
|
|
type BrowserScenarioStepOutcome,
|
|
type BrowserStepArtifacts,
|
|
} from "../domain/browserScenarioCaptureValues.js";
|
|
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
|
import {
|
|
AnalysisCancelledError,
|
|
AnalysisCapabilityUnavailableError,
|
|
} from "../domain/analysisErrorCore.js";
|
|
import {
|
|
BrowserObservationError,
|
|
browserCleanupObservation,
|
|
} from "../domain/browserObservationError.js";
|
|
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
|
import { err, ok, type Result } from "../domain/result.js";
|
|
import type {
|
|
RetainBrowserScenarioCleanup,
|
|
BrowserScenarioSessionOpener,
|
|
BrowserScenarioSessionPort,
|
|
} from "./BrowserScenarioSessionPort.js";
|
|
import {
|
|
notExecutedActionError,
|
|
type ScenarioActionStop,
|
|
} from "./ScenarioActionSequence.js";
|
|
import {
|
|
browserScenarioCaptureData,
|
|
browserScenarioGlobalCompleteness,
|
|
completedCaptureWithIncompleteCleanup,
|
|
} from "./BrowserScenarioPartialObservation.js";
|
|
|
|
const OPERATION = "capture_browser_scenario" as const;
|
|
import { PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY } from "./providerIdentities.js";
|
|
|
|
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
|
|
const SNAPSHOT_KINDS = [
|
|
"screenshot",
|
|
"dom",
|
|
"accessibility",
|
|
"url",
|
|
"history",
|
|
"storage",
|
|
] as const satisfies readonly SnapshotKind[];
|
|
|
|
const requestedForStep = (
|
|
scenario: BrowserScenario,
|
|
stepIndex: number,
|
|
): ReadonlySet<SnapshotKind> =>
|
|
new Set([
|
|
...scenario.capture.after_each_step,
|
|
...(stepIndex === scenario.actions.length ? scenario.capture.at_end : []),
|
|
]);
|
|
|
|
const unavailableArtifacts = (
|
|
requested: ReadonlySet<SnapshotKind>,
|
|
reason: string,
|
|
): BrowserStepArtifacts => {
|
|
const state = (kind: SnapshotKind) =>
|
|
requested.has(kind)
|
|
? { state: "missing" as const, reason }
|
|
: { state: "not_requested" as const };
|
|
return {
|
|
screenshot: state("screenshot"),
|
|
dom: state("dom"),
|
|
accessibility: state("accessibility"),
|
|
url: state("url"),
|
|
history: state("history"),
|
|
storage: state("storage"),
|
|
};
|
|
};
|
|
|
|
const stepCompleteness = (
|
|
artifacts: BrowserStepArtifacts,
|
|
status: BrowserScenarioStep["status"],
|
|
): BrowserScenarioCompleteness => {
|
|
const missing: BrowserScenarioCompletenessSection[] = SNAPSHOT_KINDS.filter(
|
|
(section) => artifacts[section].state === "missing",
|
|
);
|
|
const truncated = SNAPSHOT_KINDS.filter(
|
|
(section) => artifacts[section].state === "truncated",
|
|
);
|
|
if (status !== "completed") missing.push("action");
|
|
return classifyBrowserScenarioCompleteness(missing, truncated);
|
|
};
|
|
|
|
const createStep = (
|
|
input: {
|
|
readonly stepIndex: number;
|
|
readonly stepId: string;
|
|
readonly action: string;
|
|
readonly elapsedMs: number;
|
|
readonly beforeUrl: ReturnType<BrowserScenarioSessionPort["sanitizeUrl"]>;
|
|
readonly afterUrl: ReturnType<BrowserScenarioSessionPort["sanitizeUrl"]>;
|
|
readonly eventStart: number;
|
|
readonly eventEnd: number;
|
|
readonly artifacts: BrowserStepArtifacts;
|
|
} & BrowserScenarioStepOutcome,
|
|
): BrowserScenarioStep => {
|
|
const base = {
|
|
step_index: input.stepIndex,
|
|
step_id: input.stepId,
|
|
action: input.action,
|
|
elapsed_ms: input.elapsedMs,
|
|
before_url: input.beforeUrl,
|
|
after_url: input.afterUrl,
|
|
event_sequence_start: input.eventStart,
|
|
event_sequence_end: input.eventEnd,
|
|
artifacts: input.artifacts,
|
|
completeness: stepCompleteness(input.artifacts, input.status),
|
|
};
|
|
return input.status === "completed"
|
|
? { ...base, status: "completed", error: null }
|
|
: { ...base, status: input.status, error: input.error };
|
|
};
|
|
|
|
const initialStep = async (input: {
|
|
readonly session: BrowserScenarioSessionPort;
|
|
readonly scenario: BrowserScenario;
|
|
readonly elapsedMs: number;
|
|
readonly signal: AbortSignal | undefined;
|
|
}): Promise<BrowserScenarioStep> => {
|
|
const { session, scenario, elapsedMs, signal } = input;
|
|
const artifacts = await session.capture(
|
|
requestedForStep(scenario, 0),
|
|
signal,
|
|
);
|
|
return createStep({
|
|
stepIndex: 0,
|
|
stepId: BROWSER_SCENARIO_START_STEP_ID,
|
|
action: "goto_start",
|
|
status: "completed",
|
|
elapsedMs,
|
|
beforeUrl: session.sanitizeUrl(session.initialUrl),
|
|
afterUrl: session.sanitizeUrl(session.currentUrl()),
|
|
error: null,
|
|
eventStart: 1,
|
|
eventEnd: session.lastEventSequence(),
|
|
artifacts,
|
|
});
|
|
};
|
|
|
|
const executeStep = async (input: {
|
|
readonly session: BrowserScenarioSessionPort;
|
|
readonly scenario: BrowserScenario;
|
|
readonly action: BrowserScenarioAction;
|
|
readonly stepIndex: number;
|
|
readonly stoppedBy: ScenarioActionStop | undefined;
|
|
readonly signal: AbortSignal | undefined;
|
|
}): Promise<BrowserScenarioStep> => {
|
|
const { session, scenario, action, stepIndex, stoppedBy, signal } = input;
|
|
const beforeUrl = session.sanitizeUrl(session.currentUrl());
|
|
const eventStart = session.nextEventSequence();
|
|
const requested = requestedForStep(scenario, stepIndex);
|
|
if (stoppedBy !== undefined) {
|
|
const error = notExecutedActionError(stoppedBy);
|
|
return createStep({
|
|
stepIndex,
|
|
stepId: action.step_id,
|
|
action: action.action,
|
|
status: "cancelled",
|
|
elapsedMs: 0,
|
|
beforeUrl,
|
|
afterUrl: beforeUrl,
|
|
error,
|
|
eventStart,
|
|
eventEnd: session.lastEventSequence(),
|
|
artifacts: unavailableArtifacts(requested, error),
|
|
});
|
|
}
|
|
|
|
const actionStartedAt = performance.now();
|
|
session.setStep(stepIndex);
|
|
const requestCancelled = (): boolean => signal?.aborted === true;
|
|
let outcome: BrowserScenarioStepOutcome = {
|
|
status: "completed",
|
|
error: null,
|
|
};
|
|
if (requestCancelled()) {
|
|
outcome = { status: "cancelled", error: "scenario request cancelled" };
|
|
} else {
|
|
try {
|
|
await session.perform(action, signal);
|
|
} catch (cause: unknown) {
|
|
outcome = {
|
|
status:
|
|
cause instanceof AnalysisCancelledError ||
|
|
(cause instanceof AnalysisError && cause.userCategory === "cancelled")
|
|
? "cancelled"
|
|
: "failed",
|
|
error: session.redactError(cause),
|
|
};
|
|
}
|
|
}
|
|
const artifacts =
|
|
outcome.status === "cancelled" || requestCancelled()
|
|
? unavailableArtifacts(requested, "scenario request cancelled")
|
|
: await session.capture(requested, signal);
|
|
return createStep({
|
|
stepIndex,
|
|
stepId: action.step_id,
|
|
action: action.action,
|
|
...outcome,
|
|
elapsedMs: Math.max(0, Math.round(performance.now() - actionStartedAt)),
|
|
beforeUrl,
|
|
afterUrl: session.sanitizeUrl(session.currentUrl()),
|
|
eventStart,
|
|
eventEnd: session.lastEventSequence(),
|
|
artifacts,
|
|
});
|
|
};
|
|
|
|
const runScenario = async (
|
|
openSession: BrowserScenarioSessionOpener,
|
|
scenario: BrowserScenario,
|
|
options: ExecutionOptions,
|
|
retainCleanup: RetainBrowserScenarioCleanup,
|
|
): Promise<BrowserScenarioCapture> => {
|
|
if (options.signal?.aborted)
|
|
throw new BrowserObservationError(OPERATION, "cancelled", {
|
|
cause: options.signal.reason,
|
|
});
|
|
const startedAt = performance.now();
|
|
const session = await openSession(scenario, {
|
|
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
retainCleanup,
|
|
});
|
|
const steps: BrowserScenarioStep[] = [];
|
|
let cleanup: BrowserScenarioPartialObservation["capture"]["browser"]["cleanup"] =
|
|
"incomplete";
|
|
let primary: AnalysisError | undefined;
|
|
let incompleteCleanup:
|
|
| {
|
|
readonly reason: string;
|
|
readonly resources: readonly string[];
|
|
}
|
|
| undefined;
|
|
const completeCapture = (): BrowserScenarioCapture => {
|
|
if (incompleteCleanup !== undefined)
|
|
return completedCaptureWithIncompleteCleanup({
|
|
session,
|
|
scenario,
|
|
startedAt,
|
|
steps,
|
|
cleanup: incompleteCleanup,
|
|
});
|
|
const completeness = browserScenarioGlobalCompleteness(session, steps);
|
|
return browserScenarioCaptureSchema.parse({
|
|
...browserScenarioCaptureData({
|
|
session,
|
|
scenario,
|
|
startedAt,
|
|
steps,
|
|
cleanup,
|
|
}),
|
|
completeness,
|
|
});
|
|
};
|
|
const partial = (limitation: string): BrowserScenarioPartialObservation => ({
|
|
kind: "browser-scenario-observation",
|
|
capture: browserScenarioCaptureData({
|
|
session,
|
|
scenario,
|
|
startedAt,
|
|
steps,
|
|
cleanup,
|
|
limitations: [limitation],
|
|
}),
|
|
});
|
|
const cleanupLimitation =
|
|
"Scenario observations are partial because browser cleanup could not be confirmed.";
|
|
const finalized = await runOwned(
|
|
async () => {
|
|
steps.push(
|
|
await initialStep({
|
|
session,
|
|
scenario,
|
|
elapsedMs: Math.max(0, Math.round(performance.now() - startedAt)),
|
|
signal: options.signal,
|
|
}),
|
|
);
|
|
let stoppedBy: ScenarioActionStop | undefined;
|
|
for (const [offset, action] of scenario.actions.entries()) {
|
|
const step = await executeStep({
|
|
session,
|
|
scenario,
|
|
action,
|
|
stepIndex: offset + 1,
|
|
stoppedBy,
|
|
signal: options.signal,
|
|
});
|
|
steps.push(step);
|
|
if (stoppedBy === undefined && step.status !== "completed")
|
|
stoppedBy = step.status;
|
|
}
|
|
return ok(undefined);
|
|
},
|
|
{
|
|
providerId: PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY.id,
|
|
operation: OPERATION,
|
|
signal: options.signal,
|
|
inspectPrimary: (result) => {
|
|
if (!result.ok) primary = result.error;
|
|
},
|
|
close: async () => {
|
|
try {
|
|
cleanup = await session.close();
|
|
} catch (cause: unknown) {
|
|
primary?.retainPartialObservation(partial(cleanupLimitation));
|
|
const observation = browserCleanupObservation(cause);
|
|
const redactText = (value: string) =>
|
|
session.redactError(new Error(value));
|
|
retainCleanup(session.cleanupLease, redactText);
|
|
if (
|
|
primary === undefined &&
|
|
options.signal?.aborted !== true &&
|
|
steps.every(({ status }) => status === "completed") &&
|
|
session.captureFinalized?.() === true
|
|
) {
|
|
incompleteCleanup = {
|
|
reason: redactText(observation.reason),
|
|
resources: observation.resources.map(redactText),
|
|
};
|
|
return;
|
|
}
|
|
const failure = new BrowserObservationError(
|
|
OPERATION,
|
|
"cleanup_failed",
|
|
{
|
|
cause,
|
|
cleanup: observation,
|
|
detail: `Browser scenario cleanup could not be confirmed: ${observation.reason}. Collected steps and events are retained in partial_observation. Review the reported resources before retrying.`,
|
|
},
|
|
);
|
|
new AnalysisCleanupLeaseGroup(failure, [session.cleanupLease]);
|
|
throw failure;
|
|
}
|
|
primary?.retainPartialObservation(
|
|
partial(
|
|
"Scenario capture ended after an operation failed; uncollected steps are not represented.",
|
|
),
|
|
);
|
|
},
|
|
partial: () => {
|
|
if (cleanup === "incomplete") return partial(cleanupLimitation);
|
|
const capture = completeCapture();
|
|
return {
|
|
kind: "browser-scenario-observation",
|
|
capture: {
|
|
...capture,
|
|
limitations: [
|
|
...capture.limitations,
|
|
"Scenario capture was cancelled; collected steps, observations, and cleanup state are retained.",
|
|
],
|
|
},
|
|
};
|
|
},
|
|
},
|
|
);
|
|
const result = finalizedResult(finalized);
|
|
if (!result.ok) throw result.error;
|
|
return completeCapture();
|
|
};
|
|
|
|
/** Controlled Playwright/CDP scenario driver with exact process ownership. */
|
|
export class PlaywrightBrowserScenarioProvider implements BrowserScenarioCapturePort {
|
|
#tail: Promise<void> = Promise.resolve();
|
|
readonly #closeState = new QueuedProviderClose();
|
|
readonly #pendingCleanup = new Map<
|
|
AnalysisCleanupLease,
|
|
(value: string) => string
|
|
>();
|
|
|
|
constructor(private readonly openSession: BrowserScenarioSessionOpener) {}
|
|
|
|
identity(): ProviderIdentity {
|
|
return PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY;
|
|
}
|
|
|
|
captureScenario(
|
|
scenario: BrowserScenario,
|
|
options: ExecutionOptions = {},
|
|
): Promise<Result<BrowserScenarioCapture, AnalysisError>> {
|
|
if (this.#closeState.requested)
|
|
return Promise.resolve(err(this.#closedError()));
|
|
const operation = this.#tail.then(() =>
|
|
this.#closeState.requested
|
|
? 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);
|
|
const retained: AnalysisCleanupLease[] = [];
|
|
try {
|
|
return ok(
|
|
await runScenario(
|
|
this.openSession,
|
|
scenario,
|
|
options,
|
|
(lease, redactText = (value) => value) => {
|
|
this.#pendingCleanup.set(lease, redactText);
|
|
retained.push(lease);
|
|
},
|
|
),
|
|
);
|
|
} catch (cause: unknown) {
|
|
const primary =
|
|
cause instanceof AnalysisError
|
|
? cause
|
|
: new ProviderAdapterError(
|
|
PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY.id,
|
|
OPERATION,
|
|
{ cause },
|
|
);
|
|
// A lease the failed attempt already released is not retained cleanup.
|
|
for (const lease of retained)
|
|
if (lease.released) this.#pendingCleanup.delete(lease);
|
|
const unreleased = retained.filter((lease) => !lease.released);
|
|
if (unreleased.length === 0) return err(primary);
|
|
const cleanup = new ProviderCleanupError(
|
|
PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY.id,
|
|
unreleased.flatMap((lease) =>
|
|
(lease.cleanupResources ?? []).map(
|
|
this.#pendingCleanup.get(lease) ?? ((value) => value),
|
|
),
|
|
),
|
|
{ reason: "Browser scenario cleanup capabilities remain retained." },
|
|
{ operation: OPERATION, cause },
|
|
);
|
|
this.#bindCleanup(cleanup, unreleased);
|
|
return err(
|
|
analysisErrorWithCleanupDependencies(primary, cleanup, OPERATION),
|
|
);
|
|
}
|
|
}
|
|
|
|
async close(): Promise<void> {
|
|
return this.#closeState.closeAfter(this.#tail, () => this.#retryCleanup());
|
|
}
|
|
|
|
#closedError(): AnalysisError {
|
|
return new AnalysisCapabilityUnavailableError(
|
|
PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY.id,
|
|
OPERATION,
|
|
"Browser scenario provider is closing.",
|
|
);
|
|
}
|
|
|
|
#bindCleanup(
|
|
error: AnalysisError,
|
|
leases: readonly AnalysisCleanupLease[],
|
|
): void {
|
|
new AnalysisCleanupLeaseGroup(error, leases);
|
|
const projections = this.#pendingCleanup;
|
|
error.bindCleanupResourceOwner({
|
|
get cleanupResources() {
|
|
const pending = leases.filter((lease) => !lease.released);
|
|
if (pending.some((lease) => lease.cleanupResources === undefined))
|
|
return undefined;
|
|
return [
|
|
...new Set(
|
|
pending.flatMap((lease) =>
|
|
(lease.cleanupResources ?? []).map(
|
|
projections.get(lease) ?? ((value) => value),
|
|
),
|
|
),
|
|
),
|
|
];
|
|
},
|
|
});
|
|
}
|
|
|
|
async #retryCleanup(): Promise<AnalysisError | undefined> {
|
|
const failures: AnalysisError[] = [];
|
|
for (const [pending, redactText] of this.#pendingCleanup) {
|
|
try {
|
|
await withPlaywrightExecutionBoundary(
|
|
() => pending.release(),
|
|
PLAYWRIGHT_CLEANUP_CONFIRMATION_TIMEOUT_MS,
|
|
);
|
|
this.#pendingCleanup.delete(pending);
|
|
} catch (cause: unknown) {
|
|
const failure = new ProviderCleanupError(
|
|
PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY.id,
|
|
(pending.cleanupResources ?? []).map(redactText),
|
|
{
|
|
reason: redactText(browserCleanupObservation(cause).reason),
|
|
},
|
|
{ operation: OPERATION, cause },
|
|
);
|
|
this.#bindCleanup(failure, [pending]);
|
|
failures.push(failure);
|
|
}
|
|
}
|
|
if (failures.length === 0) return undefined;
|
|
if (failures.length === 1) return failures[0];
|
|
return providerCleanupErrorFromFailures(
|
|
PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY.id,
|
|
failures,
|
|
"One or more browser scenario resources remain owned.",
|
|
{ operation: OPERATION, message: "Browser scenario cleanup failed" },
|
|
);
|
|
}
|
|
}
|