histoire
Version:
A fast story book powered by Vite
157 lines (156 loc) • 8.88 kB
JavaScript
import { fork } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { getHistoireTargetKey, HistoireSdkError, validateBridgeResult, validateProjectTestCollection, validateWireValue } from '@histoire/protocol';
import { waitForChildExit } from '../runtime/child-process.js';
import { ExecutionError } from '../runtime/execution-types.js';
import { throwIfTestAborted } from '../util/test-abort.js';
import { getCollectTimeout, getRunStallTimeout } from '../util/test-timeouts.js';
import { captureTestContextFiles } from './context-transfer.js';
/** Existing runner executes in owned process; caller's cwd/env/handlers/exitCode never borrowed. */
export function runIsolatedHistoireTests(ctx, options) {
return isolatedTestOperation(ctx, options, 'run');
}
/** Collection borrows the same owned process and confirmed teardown as execution. */
export function collectIsolatedHistoireTests(ctx, options) {
return isolatedTestOperation(ctx, { ...options, collectionRunId: options.collectionRunId ?? randomUUID() }, 'collect');
}
/** Discriminated worker operation prevents process effects from entering library caller. */
async function isolatedTestOperation(ctx, options, operation) {
throwIfTestAborted(options.signal);
const child = fork(new URL('./worker.js', import.meta.url), [], { cwd: ctx.root, execArgv: [], serialization: 'advanced', stdio: ['ignore', 'pipe', 'pipe', 'ipc'] });
child.stdout?.pipe(process.stderr, { end: false });
child.stderr?.pipe(process.stderr, { end: false });
const exited = new Promise(resolve => child.once('exit', () => resolve()));
let received = false;
let cleanupConfirmed = false;
let timer;
let result;
let failure;
let failed = false;
let rejectOperation;
const targets = ctx.storyFiles.filter(file => file.story && !file.story.docsOnly && (!options.storyId || file.story.id === options.storyId)).flatMap(file => file.story.variants.map(variant => ({ storyId: file.story.id, variantId: variant.id })));
const admitted = new Set(targets.map(getHistoireTargetKey));
const seen = new Set();
/** Only finite cancellation travels to existing runner; never release lane here. */
const abort = () => {
if (child.connected)
child.send({ type: 'cancel' }, () => { });
// Collection abort starts bounded cleanup immediately, even if worker is
// stuck before acquiring a cancellable Vitest handle. Lane stays owned.
if (operation === 'collect')
rejectOperation?.(new ExecutionError('CANCELLED', 'Histoire test run cancelled'));
};
options.signal?.addEventListener('abort', abort, { once: true });
try {
result = await new Promise((resolve, reject) => {
rejectOperation = reject;
/** (Re)starts the worker guard: a collection deadline, or a run stall timeout plus margin for the worker's own. */
const arm = () => {
clearTimeout(timer);
timer = setTimeout(() => {
reject(new HistoireSdkError('TIMEOUT', 'Histoire test worker timed out'));
abort();
}, operation === 'collect' ? Math.max(0, (options.collectionDeadline ?? Date.now() + getCollectTimeout(ctx)) - Date.now()) : getRunStallTimeout(ctx) + 60_000);
};
arm();
child.once('error', reject);
child.once('exit', () => {
if (!received)
reject(new HistoireSdkError('INTERNAL_ERROR', 'Test worker exited without confirmed result'));
});
child.on('message', (message) => {
if (!received && message?.type === 'run-progress' && operation === 'run' && !options.signal?.aborted) {
// A progressing run is not stuck, however long it takes.
arm();
// Counts only; malformed values are dropped rather than failing the run.
const { phase, completed, total } = message.progress ?? {};
if ((phase === 'collect' || phase === 'run') && Number.isSafeInteger(completed) && Number.isSafeInteger(total) && completed >= 0 && completed <= total)
options.onRunProgress?.({ phase, completed, total });
return;
}
if (!received && message?.type === 'progress' && operation === 'collect' && !options.signal?.aborted) {
try {
const progress = message.collection;
validateProjectTestCollection(progress);
if (progress.execution.runId !== options.collectionRunId || progress.execution.mode !== 'server')
throw new Error('Collection operation changed');
for (const entry of progress.variants) {
const key = getHistoireTargetKey(entry.target);
if (!admitted.has(key) || seen.has(key))
throw new Error('Invalid collection progress target');
seen.add(key);
}
const variants = progress.variants.filter((entry) => !options.knownEmptyStoryIds?.includes(entry.target.storyId));
if (variants.length)
options.onProgress?.({ ...progress, variants });
}
catch (error) {
abort();
reject(error);
}
return;
}
if (received || !['result', 'error'].includes(message?.type))
return;
received = true;
cleanupConfirmed = message.cleanupConfirmed === true;
try {
validateWireValue(message, { kind: 'response', name: 'tests.run' });
if (!cleanupConfirmed)
throw new ExecutionError('CLEANUP_UNCONFIRMED', 'Test worker cleanup could not be confirmed');
if (message.type === 'error')
throw new HistoireSdkError(message.error.code, message.error.message);
if (operation === 'collect') {
validateProjectTestCollection(message.collection, targets);
if (message.collection.execution.runId !== options.collectionRunId || message.collection.execution.mode !== 'server')
throw new Error('Collection operation changed');
resolve(message.collection);
}
else {
validateBridgeResult('tests.run', message.summary);
resolve(message.summary);
}
}
catch (error) {
reject(error);
}
});
// Metadata capture prevents queued target contamination. Plugin functions
// reload in owned child; no live server/config object crosses IPC.
const files = options.skipStoryScan ? captureTestContextFiles(ctx) : undefined;
child.send({ type: 'run', operation, root: ctx.root, configFile: ctx.configFile, files, options: { storyId: options.storyId, variantId: options.variantId, knownEmptyStoryIds: options.knownEmptyStoryIds, collectionRunId: options.collectionRunId, collectionDeadline: options.collectionDeadline, collectionOptimizerEntries: options.collectionOptimizerEntries, skipStoryScan: options.skipStoryScan, maxRetries: 0, strictCleanup: true, strictTarget: true } }, (error) => {
if (error)
reject(error);
});
if (options.signal?.aborted)
abort();
});
throwIfTestAborted(options.signal);
}
catch (error) {
failure = error;
failed = true;
}
finally {
clearTimeout(timer);
options.signal?.removeEventListener('abort', abort);
if (!received)
abort();
if (!await waitForChildExit(child, exited, 10_000)) {
child.kill('SIGTERM');
if (!await waitForChildExit(child, exited, 2_000)) {
child.kill('SIGKILL');
await waitForChildExit(child, exited, 2_000);
}
failure = new ExecutionError('CLEANUP_UNCONFIRMED', 'Test worker required termination; descendant cleanup unknown', failure);
failed = true;
}
else if (!cleanupConfirmed) {
failure = new ExecutionError('CLEANUP_UNCONFIRMED', 'Test worker exited without confirmed cleanup', failure);
failed = true;
}
}
if (failed)
throw failure;
return result;
}