T-191: M2.1u — Real Node/Bun adapters for the notebook snapshot exporter: createNodeNotebookCommandRunner() + createNodeNotebookSnapshotFs() in libs/research/src/notebook-snapshot-node.ts (argv-only node:child_process.spawn, kill-then-settle ETIMEDOUT, O_EXCL create, real-subprocess + temp-dir tests with a fake marimo script; no new deps, no real marimo, no bin)
This commit is contained in:
parent
e50a08ff65
commit
309f442d5e
4 changed files with 911 additions and 0 deletions
288
libs/research/src/notebook-snapshot-node.ts
Normal file
288
libs/research/src/notebook-snapshot-node.ts
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
/**
|
||||
* Node/Bun subprocess and filesystem adapters for {@link exportNotebookSnapshot}.
|
||||
*
|
||||
* Intentionally exposed only via the `@stock-bot/research/notebook-snapshot-node`
|
||||
* subpath (never re-exported from `@stock-bot/research`) so the root package
|
||||
* stays browser-bundleable.
|
||||
*/
|
||||
|
||||
import { spawn } from 'node:child_process';
|
||||
import { rename as fsRename, stat as fsStat, open, readFile, rm } from 'node:fs/promises';
|
||||
import { basename } from 'node:path';
|
||||
import type {
|
||||
NotebookCommandResult,
|
||||
NotebookCommandRunner,
|
||||
NotebookCommandRunOptions,
|
||||
NotebookSnapshotFileStat,
|
||||
NotebookSnapshotFs,
|
||||
} from './notebook-snapshot';
|
||||
|
||||
/** Default per-stream (stdout / stderr) capture cap in bytes (16 MiB). */
|
||||
export const NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
|
||||
/** Maximum single-call delay supported by Node/Bun `setTimeout` (2^31 - 1 ms). */
|
||||
const MAX_TIMER_DELAY_MS = 2_147_483_647;
|
||||
|
||||
export interface NodeNotebookCommandRunnerOptions {
|
||||
/** Maximum captured bytes per stream (stdout and stderr independently). */
|
||||
readonly maxOutputBytes?: number;
|
||||
}
|
||||
|
||||
interface CodedError extends Error {
|
||||
code: string;
|
||||
}
|
||||
|
||||
function createCodedError(code: string, message: string): CodedError {
|
||||
const err = new Error(message) as CodedError;
|
||||
err.code = code;
|
||||
return err;
|
||||
}
|
||||
|
||||
function getErrorCode(err: unknown): string | undefined {
|
||||
if (typeof err === 'object' && err !== null && 'code' in err) {
|
||||
const code = (err as { code?: unknown }).code;
|
||||
if (typeof code === 'string') {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function assertPositiveSafeInteger(value: unknown, label: string): number {
|
||||
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
|
||||
throw new RangeError(`${label} must be a positive finite integer.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a real {@link NotebookCommandRunner} backed by `node:child_process.spawn`.
|
||||
*
|
||||
* - Always invokes `command` directly with `args` as argv (`shell: false`).
|
||||
* - Resolves any numeric exit code on `close`; rejects on spawn errors, signal
|
||||
* termination, timeout (`ETIMEDOUT`), or per-stream output overflow (`EOUTPUTLIMIT`).
|
||||
* - On timeout or output overflow, sends `SIGKILL` once and rejects only after
|
||||
* the child's `close` event has fired.
|
||||
*/
|
||||
export function createNodeNotebookCommandRunner(
|
||||
runnerOptions?: NodeNotebookCommandRunnerOptions
|
||||
): NotebookCommandRunner {
|
||||
const maxOutputBytes =
|
||||
runnerOptions?.maxOutputBytes === undefined
|
||||
? NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES
|
||||
: assertPositiveSafeInteger(runnerOptions.maxOutputBytes, 'maxOutputBytes');
|
||||
|
||||
return {
|
||||
run(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
options: NotebookCommandRunOptions
|
||||
): Promise<NotebookCommandResult> {
|
||||
let timeoutMs: number;
|
||||
try {
|
||||
timeoutMs = assertPositiveSafeInteger(options.timeoutMs, 'timeoutMs');
|
||||
} catch (err) {
|
||||
return Promise.reject(err);
|
||||
}
|
||||
|
||||
const commandName = basename(command) || command;
|
||||
|
||||
return new Promise<NotebookCommandResult>((resolve, reject) => {
|
||||
let settled = false;
|
||||
let terminalFailure: CodedError | null = null;
|
||||
let killSent = false;
|
||||
let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const stdoutChunks: Buffer[] = [];
|
||||
let stdoutBytes = 0;
|
||||
const stderrChunks: Buffer[] = [];
|
||||
let stderrBytes = 0;
|
||||
|
||||
const clearTimeoutHandle = (): void => {
|
||||
if (timeoutHandle !== undefined) {
|
||||
clearTimeout(timeoutHandle);
|
||||
timeoutHandle = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
let child: ReturnType<typeof spawn>;
|
||||
try {
|
||||
child = spawn(command, [...args], {
|
||||
...(options.cwd !== undefined ? { cwd: options.cwd } : {}),
|
||||
shell: false,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
} catch (err) {
|
||||
settled = true;
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
const triggerTerminalFailure = (err: CodedError): void => {
|
||||
if (settled || terminalFailure !== null) {
|
||||
return;
|
||||
}
|
||||
terminalFailure = err;
|
||||
clearTimeoutHandle();
|
||||
stdoutChunks.length = 0;
|
||||
stderrChunks.length = 0;
|
||||
if (!killSent) {
|
||||
killSent = true;
|
||||
try {
|
||||
child.kill('SIGKILL');
|
||||
} catch {
|
||||
// Child may have already exited before kill was delivered.
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const deadlineMs = performance.now() + timeoutMs;
|
||||
const scheduleTimeout = (): void => {
|
||||
if (settled || terminalFailure !== null) {
|
||||
return;
|
||||
}
|
||||
const remainingMs = deadlineMs - performance.now();
|
||||
if (remainingMs <= 0) {
|
||||
triggerTerminalFailure(
|
||||
createCodedError(
|
||||
'ETIMEDOUT',
|
||||
`Command '${commandName}' timed out after ${timeoutMs}ms.`
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
const delayMs = Math.min(Math.ceil(remainingMs), MAX_TIMER_DELAY_MS);
|
||||
timeoutHandle = setTimeout(scheduleTimeout, delayMs);
|
||||
};
|
||||
scheduleTimeout();
|
||||
|
||||
const attachStreamCollector = (
|
||||
stream: NodeJS.ReadableStream | null,
|
||||
streamName: 'stdout' | 'stderr',
|
||||
chunks: Buffer[],
|
||||
getBytes: () => number,
|
||||
setBytes: (next: number) => void
|
||||
): void => {
|
||||
if (!stream) {
|
||||
return;
|
||||
}
|
||||
stream.on('error', () => {
|
||||
// Drain/ignore pipe errors once the child is terminating.
|
||||
});
|
||||
stream.on('data', (chunk: Buffer | string) => {
|
||||
if (terminalFailure !== null || settled) {
|
||||
// Keep draining so a killed/exiting child never blocks on a full pipe.
|
||||
return;
|
||||
}
|
||||
const buf = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk;
|
||||
const nextBytes = getBytes() + buf.byteLength;
|
||||
if (nextBytes > maxOutputBytes) {
|
||||
triggerTerminalFailure(
|
||||
createCodedError(
|
||||
'EOUTPUTLIMIT',
|
||||
`Command '${commandName}' exceeded ${streamName} output limit of ${maxOutputBytes} bytes.`
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
setBytes(nextBytes);
|
||||
chunks.push(buf);
|
||||
});
|
||||
};
|
||||
|
||||
attachStreamCollector(
|
||||
child.stdout,
|
||||
'stdout',
|
||||
stdoutChunks,
|
||||
() => stdoutBytes,
|
||||
next => {
|
||||
stdoutBytes = next;
|
||||
}
|
||||
);
|
||||
attachStreamCollector(
|
||||
child.stderr,
|
||||
'stderr',
|
||||
stderrChunks,
|
||||
() => stderrBytes,
|
||||
next => {
|
||||
stderrBytes = next;
|
||||
}
|
||||
);
|
||||
|
||||
child.once('error', err => {
|
||||
clearTimeoutHandle();
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
reject(err);
|
||||
});
|
||||
|
||||
child.once('close', (code, signal) => {
|
||||
clearTimeoutHandle();
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
|
||||
if (terminalFailure !== null) {
|
||||
reject(terminalFailure);
|
||||
return;
|
||||
}
|
||||
|
||||
if (code === null) {
|
||||
reject(
|
||||
new Error(
|
||||
signal
|
||||
? `Command '${commandName}' terminated by signal ${signal}.`
|
||||
: `Command '${commandName}' terminated without an exit code.`
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const stdout = Buffer.concat(stdoutChunks, stdoutBytes).toString('utf8');
|
||||
const stderr = Buffer.concat(stderrChunks, stderrBytes).toString('utf8');
|
||||
resolve({ exitCode: code, stdout, stderr });
|
||||
});
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a real {@link NotebookSnapshotFs} backed by `node:fs/promises`.
|
||||
*/
|
||||
export function createNodeNotebookSnapshotFs(): NotebookSnapshotFs {
|
||||
return {
|
||||
async stat(path: string): Promise<NotebookSnapshotFileStat | null> {
|
||||
try {
|
||||
const info = await fsStat(path);
|
||||
return { isFile: info.isFile(), size: info.size };
|
||||
} catch (err) {
|
||||
if (getErrorCode(err) === 'ENOENT') {
|
||||
return null;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
|
||||
async createExclusive(path: string): Promise<void> {
|
||||
const handle = await open(path, 'wx');
|
||||
await handle.close();
|
||||
},
|
||||
|
||||
async readBytes(path: string): Promise<Uint8Array> {
|
||||
const data = await readFile(path);
|
||||
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
||||
},
|
||||
|
||||
async rename(sourcePath: string, destinationPath: string): Promise<void> {
|
||||
await fsRename(sourcePath, destinationPath);
|
||||
},
|
||||
|
||||
async remove(path: string): Promise<void> {
|
||||
await rm(path, { force: true });
|
||||
},
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue