/** * In-process `UnitRunner`, used when the config cannot cross a process * boundary — a supplied `rawConfig` may hold live engine handles and * closures. Execution still goes through the scheduler and the same * `TargetWorker` core; only the transport and pair resolution differ, and the * scheduler is capped at one worker so nothing overlaps in this process. */ import type { ModuleRegistration } from '../collect/registry.ts'; import type { Selection, TestTargetPair } from '../collect/select.ts'; import type { ResolvedConfig, ResolvedTarget } from '@e2e-dev/core/lib/config/resolve'; import { isAbandonedRejection } from '@e2e-dev/core/lib/internal/abandoned'; import { classifyError, ConfigurationError, serializeError } from '@e2e-dev/core/lib/internal/errors'; import type { DebugTrace } from '@e2e-dev/core/lib/internal/debug'; import type { InMemoryAttempts } from './execute.ts'; import type { SessionStore } from '@e2e-dev/core/lib/run/sessions'; import type { SpawnUnitRunner, UnitRunner, UnitRunnerEvents, WorkerSlots } from './unit-runner.ts'; import { pairKey } from './units.ts'; import { copyServiceValues, type RunServices } from './services.ts'; import type { MainToWorker, RunUnitMessage, WirePair } from './worker/protocol.ts'; import { TargetWorker, type ResolvedUnitPairs, type TargetWorkerDeps } from './worker/session.ts'; export interface InProcessRunnerOptions { readonly config: ResolvedConfig; readonly selection: Selection; /** * The tests supplied in memory (`RunOptions.tests`). There is no file to * re-import, so the unit of their virtual file adopts this registration as * its realm; it is one unit with no retries, so nothing asks for a second * realm of it. The units of real files, a setup test the in-memory tests * need, import their file as always. Their attempts run as described by * `InMemoryAttempts`. */ readonly inMemory?: (InMemoryAttempts & { readonly registration: ModuleRegistration }) | undefined; readonly runId: string; readonly artifactsRoot: string; /** See `TargetExecutorOptions.rerunDir`. */ readonly rerunDir: string | undefined; readonly sessionStore: SessionStore; readonly headed: boolean; readonly debug: DebugTrace; /** See `TargetWorkerDeps.holdSteps`. */ readonly holdSteps: boolean; /** Started services from the runner. Each worker receives a copy of their values, the same as a worker process. */ readonly services: Pick; /** The environment each target's workers run with; see `EngineInitInfo.env`. */ readonly envFor: (targetName: string) => Readonly>; } /** * The slots of live in-process runners, oldest first. One run caps its * in-process workers at 1, but two programmatic runs in one process may be * live at once, and `process.env` holds one value: it names the newest live * runner's slots, and the values from before the first are back once the * last ends. `testInfo` carries each attempt's own slots either way. */ const liveSlots: WorkerSlots[] = []; let envBeforeInProcessRuns: Readonly> | undefined; function claimWorkerEnv(slots: WorkerSlots): void { envBeforeInProcessRuns ??= { TEST_WORKER_INDEX: process.env['TEST_WORKER_INDEX'], TEST_PARALLEL_INDEX: process.env['TEST_PARALLEL_INDEX'], }; liveSlots.push(slots); writeWorkerEnv(slots); } function releaseWorkerEnv(slots: WorkerSlots): void { const index = liveSlots.indexOf(slots); if (index !== -1) liveSlots.splice(index, 1); const newest = liveSlots.at(-1); if (newest !== undefined) { writeWorkerEnv(newest); return; } if (envBeforeInProcessRuns === undefined) return; for (const [name, value] of Object.entries(envBeforeInProcessRuns)) { if (value === undefined) delete process.env[name]; else process.env[name] = value; } envBeforeInProcessRuns = undefined; } function writeWorkerEnv(slots: WorkerSlots): void { process.env['TEST_WORKER_INDEX'] = String(slots.workerIndex); process.env['TEST_PARALLEL_INDEX'] = String(slots.parallelIndex); } class InProcessRunner implements UnitRunner { readonly exit: Promise; private readonly worker: TargetWorker; private readonly finish: () => void; private exited = false; private closing = false; /** * Set by a fatal error: the worker is dead to the scheduler from then on, * as a crashed process would be, so nothing it reports about its unit * while it winds down counts, and the unit's results are synthesized when * it exits. Unlike a dead process it still disposes its engine, so the * failures of that disposal (`shutdown-done`) are still reported. */ private crashed = false; /** Takes what this process failed to catch while the runner lives; see `catchStrays`. */ private readonly onRejection = (cause: unknown): void => { if (isAbandonedRejection(cause)) return; if (!this.worker.strayRejection(cause)) this.fail(cause); }; private readonly onException = (cause: unknown): void => this.fail(cause); constructor( private readonly targetName: string, private readonly slots: WorkerSlots, private readonly events: UnitRunnerEvents, private readonly options: InProcessRunnerOptions, ) { claimWorkerEnv(slots); let finish = (): void => undefined; this.exit = new Promise((resolve) => { finish = resolve; }); this.finish = finish; this.worker = new TargetWorker( { emit: (message) => { if (this.exited || (this.crashed && message.type !== 'shutdown-done')) return; this.events.onMessage(message); }, fatal: (cause) => this.fail(cause), finished: () => this.end('shut down'), }, () => this.bootstrap(), ); this.catchStrays(); this.worker.start(); } get alive(): boolean { return !this.exited; } send(message: MainToWorker): void { if (this.exited) return; // A unit dispatched while a fatal error is closing the worker would run // after its exit; everything else still lands, and shutdown is idempotent. if (this.closing && message.type === 'run-unit') return; // There is no process to take an abandoned unit down with it, so a forced // teardown here is the graceful one: dispose once the unit — whose // harness calls the interrupt already aborted — has wound down. if (message.type === 'terminate') { this.close(); return; } this.worker.handle(message); } /** * There is no process to signal, so an in-process worker cannot be forced to * stop mid-test: the best available equivalent is to stop accepting units and * wind down after the current one. `exit` therefore always means "this * worker's work has actually stopped", which the scheduler relies on when * draining and when synthesizing results for a lost unit. */ kill(): void { this.close(); } /** * Catches what a test leaves uncaught the way a worker process does * (`worker/entry.ts`): a rejection nobody handled is charged to the attempt * in flight, or recorded against the last test that finished, and is * otherwise fatal to this worker, as an uncaught exception is (see * `fail`). The * listeners live exactly as long as the runner, so a host process keeps its * own handling before and after the run. The scheduler keeps at most one * in-process runner alive at a time, so nothing is charged twice. */ private catchStrays(): void { process.on('unhandledRejection', this.onRejection); process.on('uncaughtException', this.onException); } /** * Reports an unrecoverable failure and ends the worker the way a process * dies: its unit is interrupted and nothing more it reports is passed on, * so on exit the scheduler fails the test in flight with `WORKER_CRASH` * and skips the unit's others, as it does for a worker process. */ private fail(cause: unknown): void { if (this.exited || this.crashed) return; this.events.onMessage({ type: 'fatal', error: serializeError(classifyError(cause)) }); this.crashed = true; this.worker.handle({ type: 'interrupt' }); this.close(); } /** Stops accepting work and asks the queue to wind down. */ private close(): void { if (this.exited) return; this.closing = true; this.worker.handle({ type: 'shutdown' }); } private end(detail: string): void { if (this.exited) return; this.exited = true; releaseWorkerEnv(this.slots); process.off('unhandledRejection', this.onRejection); process.off('uncaughtException', this.onException); this.events.onExit(detail); this.finish(); } private async bootstrap(): Promise { const { config } = this.options; const target = config.targets.find((candidate) => candidate.name === this.targetName); if (target === undefined) { throw new ConfigurationError('UNKNOWN_TARGET', `unknown target "${this.targetName}"`); } return { config, target, sessionStore: this.options.sessionStore, runId: this.options.runId, artifactsRoot: this.options.artifactsRoot, rerunDir: this.options.rerunDir, headed: this.options.headed, slots: this.slots, env: { ...this.options.envFor(this.targetName), TEST_WORKER_INDEX: String(this.slots.workerIndex), TEST_PARALLEL_INDEX: String(this.slots.parallelIndex), }, isolated: false, debug: this.options.debug, holdSteps: this.options.holdSteps, inMemory: this.options.inMemory, services: copyServiceValues(this.options.services.wire, this.options.services.call), resolvePairs: (unit, reusable) => resolveFromSelection( this.options.selection, target, unit, this.options.inMemory?.file === unit.file ? this.options.inMemory.registration : reusable, ), }; } } /** Looks the unit's pairs up in the selection the runner already collected. */ async function resolveFromSelection( selection: Selection, target: ResolvedTarget, unit: RunUnitMessage, registration: ModuleRegistration | undefined, ): Promise { const selected = selection.perTarget.find((entry) => entry.target.name === target.name); const available = new Map(); for (const pair of selected?.pairs ?? []) available.set(pairKey(pair.test.id, pair.agent, pair.repeat), pair); const pairs: TestTargetPair[] = []; const missing: WirePair[] = []; for (const wire of unit.pairs) { const pair = available.get(pairKey(wire.test.id, wire.agent, wire.repeat)); if (pair === undefined) missing.push(wire); else pairs.push(pair); } return { pairs, missing, ...(registration === undefined ? {} : { registration }) }; } /** Creates the spawn factory the scheduler uses for in-process execution. */ export function inProcessSpawner(options: InProcessRunnerOptions): SpawnUnitRunner { return (targetName, slots, events) => new InProcessRunner(targetName, slots, events, options); }