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
|
|
@ -345,6 +345,28 @@ Exported from `@stock-bot/research` (`libs/research/src/notebook-snapshot.ts`).
|
|||
- **Fail-closed error codes (`NotebookSnapshotError`)** — `INVALID_OPTION`, `INVALID_PATH`, `NOTEBOOK_NOT_FOUND`, `CHECK_FAILED` (nonzero check exit, `summary.errored === true`, `type: 'error'`, or `severity: 'breaking'`), `CHECK_OUTPUT_INVALID` (non-JSON stdout on exit `0` or malformed `{ issues, summary }` / `summary.total_files !== 1`), `EXPORT_FAILED`, `EXPORT_EMPTY`, and `TIMEOUT`. Formatting and runtime advisories may accompany a clean check.
|
||||
- **Lexical roots & execution notice:** `allowedNotebookRoot` and `allowedOutputRoot` enforce lexical POSIX path-component containment (blocking `..` traversal and same-prefix sibling escapes); callers must supply trusted directories and keep the notebook file stable between check and export. Note that `marimo export html` **executes notebook cells**.
|
||||
|
||||
### Node/Bun Adapters (`@stock-bot/research/notebook-snapshot-node`)
|
||||
|
||||
Server-only adapters backed by `node:child_process` and `node:fs/promises` are exported exclusively from the `@stock-bot/research/notebook-snapshot-node` subpath (`libs/research/src/notebook-snapshot-node.ts`) so the default `@stock-bot/research` entrypoint remains browser-bundleable:
|
||||
|
||||
- **`createNodeNotebookCommandRunner(options?)`** — Implements `NotebookCommandRunner` via `spawn(command, [...args], { cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'] })`. Captures stdout and stderr independently up to `NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES` (`16 MiB` by default, configurable via `options.maxOutputBytes`), kills with `SIGKILL` on timeout (`ETIMEDOUT`) or overflow (`EOUTPUTLIMIT`), and settles only after `close`.
|
||||
- **`createNodeNotebookSnapshotFs()`** — Implements `NotebookSnapshotFs` over `node:fs/promises` (`stat` mapping only `ENOENT` to `null`, `open(..., 'wx')` exclusive create, binary `readFile`, atomic `rename`, and non-recursive `rm(..., { force: true })`).
|
||||
|
||||
```ts
|
||||
import { exportNotebookSnapshot } from '@stock-bot/research';
|
||||
import {
|
||||
createNodeNotebookCommandRunner,
|
||||
createNodeNotebookSnapshotFs,
|
||||
} from '@stock-bot/research/notebook-snapshot-node';
|
||||
|
||||
const receipt = await exportNotebookSnapshot({
|
||||
notebookPath: '/abs/path/to/study.py',
|
||||
outputPath: '/abs/path/to/study.html',
|
||||
runner: createNodeNotebookCommandRunner(),
|
||||
fs: createNodeNotebookSnapshotFs(),
|
||||
});
|
||||
```
|
||||
|
||||
### Manual Host Smoke Check (Director / Host Only)
|
||||
|
||||
Automated tests use fakes and never spawn `marimo`. On a host with the pinned `python/` `uv` environment (`marimo 0.26.0`):
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@
|
|||
"./market-data-store-questdb": "./src/market-data-store-questdb.ts",
|
||||
"./market-data-store-routed": "./src/market-data-store-routed.ts",
|
||||
"./mcp": "./src/mcp/index.ts",
|
||||
"./notebook-snapshot-node": "./src/notebook-snapshot-node.ts",
|
||||
"./results": "./src/results.ts",
|
||||
"./signal-panel": "./src/signal-panel.ts",
|
||||
"./signal-study": "./src/signal-study.ts",
|
||||
|
|
|
|||
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 });
|
||||
},
|
||||
};
|
||||
}
|
||||
600
libs/research/test/notebook-snapshot-node.test.ts
Normal file
600
libs/research/test/notebook-snapshot-node.test.ts
Normal file
|
|
@ -0,0 +1,600 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
chmod,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
readdir,
|
||||
readFile,
|
||||
realpath,
|
||||
rm,
|
||||
writeFile,
|
||||
} from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
createNodeNotebookCommandRunner,
|
||||
createNodeNotebookSnapshotFs,
|
||||
NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES,
|
||||
} from '@stock-bot/research/notebook-snapshot-node';
|
||||
import { exportNotebookSnapshot, NotebookSnapshotError } from '../src/notebook-snapshot';
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
async function expectReject(promise: Promise<unknown>): Promise<unknown> {
|
||||
try {
|
||||
await promise;
|
||||
} catch (err) {
|
||||
return err;
|
||||
}
|
||||
throw new Error('Expected promise to reject, but it resolved.');
|
||||
}
|
||||
|
||||
describe('notebook-snapshot-node adapters', () => {
|
||||
let workDir = '';
|
||||
|
||||
beforeEach(async () => {
|
||||
const rawDir = await mkdtemp(join(tmpdir(), 'notebook-snapshot-node-'));
|
||||
workDir = await realpath(rawDir);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (workDir) {
|
||||
await rm(workDir, { recursive: true, force: true });
|
||||
workDir = '';
|
||||
}
|
||||
});
|
||||
|
||||
describe('createNodeNotebookCommandRunner', () => {
|
||||
test('passes argv verbatim without shell interpretation (spaces, quotes, $(...), ;, *)', async () => {
|
||||
const scriptPath = join(workDir, 'echo-argv.js');
|
||||
await writeFile(
|
||||
scriptPath,
|
||||
'process.stdout.write(JSON.stringify(process.argv.slice(2)));\n',
|
||||
'utf8'
|
||||
);
|
||||
|
||||
const runner = createNodeNotebookCommandRunner();
|
||||
const args = [
|
||||
scriptPath,
|
||||
'hello world',
|
||||
`"double" and 'single' quotes`,
|
||||
'$(echo pwned)',
|
||||
'a;b',
|
||||
'*.ts',
|
||||
];
|
||||
const result = await runner.run(process.execPath, args, { timeoutMs: 10_000 });
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stderr).toBe('');
|
||||
expect(JSON.parse(result.stdout)).toEqual(args.slice(1));
|
||||
});
|
||||
|
||||
test('honours cwd, separates stdout/stderr with split multi-byte UTF-8, and resolves non-zero exit codes', async () => {
|
||||
const subDir = join(workDir, 'child-cwd');
|
||||
await mkdir(subDir);
|
||||
|
||||
const scriptPath = join(workDir, 'streams-and-exit.js');
|
||||
await writeFile(
|
||||
scriptPath,
|
||||
[
|
||||
// Split a 3-byte UTF-8 character ('€' = E2 82 AC) and a 4-byte emoji ('🚀' = F0 9F 9A 80) across writes.
|
||||
'process.stdout.write(Buffer.from([0x63, 0x77, 0x64, 0x3d]));',
|
||||
'process.stdout.write(process.cwd() + "\\n");',
|
||||
'process.stdout.write(Buffer.from([0xe2, 0x82]));',
|
||||
'process.stdout.write(Buffer.from([0xac, 0x0a]));',
|
||||
'process.stderr.write(Buffer.from([0xf0, 0x9f]));',
|
||||
'process.stderr.write(Buffer.from([0x9a, 0x80]));',
|
||||
'process.exit(42);',
|
||||
].join('\n'),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
const runner = createNodeNotebookCommandRunner();
|
||||
const result = await runner.run(process.execPath, [scriptPath], {
|
||||
cwd: subDir,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(42);
|
||||
expect(result.stdout).toBe(`cwd=${subDir}\n€\n`);
|
||||
expect(result.stderr).toBe('🚀');
|
||||
});
|
||||
|
||||
test('rejects with ENOENT when executable does not exist', async () => {
|
||||
const runner = createNodeNotebookCommandRunner();
|
||||
const missingPath = join(workDir, 'does-not-exist-binary');
|
||||
|
||||
const err = await expectReject(runner.run(missingPath, ['--version'], { timeoutMs: 10_000 }));
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(getErrorCode(err)).toBe('ENOENT');
|
||||
});
|
||||
|
||||
test('rejects signal exit with only command basename (no full path, argv, or env values)', async () => {
|
||||
const secretArg = 'SECRET_ARG_TOKEN_987654';
|
||||
const shimPath = join(workDir, 'signal-self.js');
|
||||
await writeFile(
|
||||
shimPath,
|
||||
[
|
||||
'#!/usr/bin/env bun',
|
||||
"process.kill(process.pid, 'SIGKILL');",
|
||||
'setInterval(() => {}, 10_000);',
|
||||
].join('\n'),
|
||||
'utf8'
|
||||
);
|
||||
await chmod(shimPath, 0o755);
|
||||
|
||||
const runner = createNodeNotebookCommandRunner();
|
||||
const err = await expectReject(runner.run(shimPath, [secretArg], { timeoutMs: 10_000 }));
|
||||
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
const message = (err as Error).message;
|
||||
expect(message).toContain('signal-self.js');
|
||||
expect(message).toContain('SIGKILL');
|
||||
expect(message).not.toContain(workDir);
|
||||
expect(message).not.toContain(secretArg);
|
||||
expect(message).not.toContain(process.env.PATH ?? '__no_path__');
|
||||
});
|
||||
|
||||
test('kills timed-out child with SIGKILL and rejects ETIMEDOUT only after child is dead (ESRCH)', async () => {
|
||||
const pidFile = join(workDir, 'sleeper.pid');
|
||||
const scriptPath = join(workDir, 'sleep-forever.js');
|
||||
await writeFile(
|
||||
scriptPath,
|
||||
[
|
||||
"import { writeFileSync } from 'node:fs';",
|
||||
'writeFileSync(process.argv[2], String(process.pid), "utf8");',
|
||||
'setInterval(() => {}, 10_000);',
|
||||
].join('\n'),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
const runner = createNodeNotebookCommandRunner();
|
||||
const err = await expectReject(
|
||||
runner.run(process.execPath, [scriptPath, pidFile], { timeoutMs: 800 })
|
||||
);
|
||||
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(getErrorCode(err)).toBe('ETIMEDOUT');
|
||||
|
||||
const pidText = await readFile(pidFile, 'utf8');
|
||||
const pid = Number.parseInt(pidText.trim(), 10);
|
||||
expect(Number.isInteger(pid) && pid > 0).toBe(true);
|
||||
|
||||
let probeError: unknown;
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
} catch (killErr) {
|
||||
probeError = killErr;
|
||||
}
|
||||
expect(getErrorCode(probeError)).toBe('ESRCH');
|
||||
});
|
||||
|
||||
test('handles timeoutMs beyond 32-bit setTimeout limit without firing immediately', async () => {
|
||||
const scriptPath = join(workDir, 'fast-ok.js');
|
||||
await writeFile(scriptPath, 'process.stdout.write("ok");\n', 'utf8');
|
||||
|
||||
const runner = createNodeNotebookCommandRunner();
|
||||
const result = await runner.run(process.execPath, [scriptPath], {
|
||||
timeoutMs: 3_000_000_000,
|
||||
});
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('ok');
|
||||
expect(result.stderr).toBe('');
|
||||
});
|
||||
|
||||
test('enforces NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES independently on stdout and stderr', async () => {
|
||||
const scriptPath = join(workDir, 'emit-bytes.js');
|
||||
await writeFile(
|
||||
scriptPath,
|
||||
[
|
||||
'const streamName = process.argv[2];',
|
||||
'const totalBytes = Number.parseInt(process.argv[3], 10);',
|
||||
'const chunkSize = 65536;',
|
||||
'const chunk = Buffer.alloc(chunkSize, 0x61);',
|
||||
'const target = streamName === "stderr" ? process.stderr : process.stdout;',
|
||||
'let remaining = totalBytes;',
|
||||
'function pump() {',
|
||||
' while (remaining > 0) {',
|
||||
' const size = Math.min(remaining, chunkSize);',
|
||||
' remaining -= size;',
|
||||
' const ok = target.write(size === chunkSize ? chunk : chunk.subarray(0, size));',
|
||||
' if (!ok) {',
|
||||
' target.once("drain", pump);',
|
||||
' return;',
|
||||
' }',
|
||||
' }',
|
||||
'}',
|
||||
'pump();',
|
||||
].join('\n'),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
const runner = createNodeNotebookCommandRunner();
|
||||
|
||||
// Exact cap on stdout succeeds.
|
||||
const stdoutExact = await runner.run(
|
||||
process.execPath,
|
||||
[scriptPath, 'stdout', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES)],
|
||||
{ timeoutMs: 30_000 }
|
||||
);
|
||||
expect(stdoutExact.exitCode).toBe(0);
|
||||
expect(stdoutExact.stdout.length).toBe(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES);
|
||||
expect(stdoutExact.stderr).toBe('');
|
||||
|
||||
// One byte over cap on stdout rejects with EOUTPUTLIMIT.
|
||||
const stdoutOverflow = await expectReject(
|
||||
runner.run(
|
||||
process.execPath,
|
||||
[scriptPath, 'stdout', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES + 1)],
|
||||
{ timeoutMs: 30_000 }
|
||||
)
|
||||
);
|
||||
expect(getErrorCode(stdoutOverflow)).toBe('EOUTPUTLIMIT');
|
||||
|
||||
// Exact cap on stderr succeeds.
|
||||
const stderrExact = await runner.run(
|
||||
process.execPath,
|
||||
[scriptPath, 'stderr', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES)],
|
||||
{ timeoutMs: 30_000 }
|
||||
);
|
||||
expect(stderrExact.exitCode).toBe(0);
|
||||
expect(stderrExact.stdout).toBe('');
|
||||
expect(stderrExact.stderr.length).toBe(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES);
|
||||
|
||||
// One byte over cap on stderr rejects with EOUTPUTLIMIT.
|
||||
const stderrOverflow = await expectReject(
|
||||
runner.run(
|
||||
process.execPath,
|
||||
[scriptPath, 'stderr', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES + 1)],
|
||||
{ timeoutMs: 30_000 }
|
||||
)
|
||||
);
|
||||
expect(getErrorCode(stderrOverflow)).toBe('EOUTPUTLIMIT');
|
||||
});
|
||||
|
||||
test('supports custom per-stream maxOutputBytes without sharing cap across streams', async () => {
|
||||
const scriptPath = join(workDir, 'both-streams.js');
|
||||
await writeFile(
|
||||
scriptPath,
|
||||
[
|
||||
'const n = Number.parseInt(process.argv[2], 10);',
|
||||
'process.stdout.write("a".repeat(n));',
|
||||
'process.stderr.write("b".repeat(n));',
|
||||
].join('\n'),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
const runner = createNodeNotebookCommandRunner({ maxOutputBytes: 128 });
|
||||
|
||||
const exactBoth = await runner.run(process.execPath, [scriptPath, '128'], {
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
expect(exactBoth.exitCode).toBe(0);
|
||||
expect(exactBoth.stdout.length).toBe(128);
|
||||
expect(exactBoth.stderr.length).toBe(128);
|
||||
|
||||
const overCap = await expectReject(
|
||||
runner.run(process.execPath, [scriptPath, '129'], { timeoutMs: 10_000 })
|
||||
);
|
||||
expect(getErrorCode(overCap)).toBe('EOUTPUTLIMIT');
|
||||
});
|
||||
|
||||
test('rejects invalid timeoutMs with RangeError before spawning and invalid maxOutputBytes on construction', async () => {
|
||||
const runner = createNodeNotebookCommandRunner();
|
||||
const invalidTimeouts = [
|
||||
0,
|
||||
-1,
|
||||
Number.NaN,
|
||||
Number.POSITIVE_INFINITY,
|
||||
Number.NEGATIVE_INFINITY,
|
||||
1.5,
|
||||
];
|
||||
|
||||
for (const timeoutMs of invalidTimeouts) {
|
||||
const err = await expectReject(
|
||||
runner.run(join(workDir, 'never-spawned'), [], { timeoutMs })
|
||||
);
|
||||
expect(err).toBeInstanceOf(RangeError);
|
||||
}
|
||||
|
||||
expect(() => createNodeNotebookCommandRunner({ maxOutputBytes: 0 })).toThrow(RangeError);
|
||||
expect(() => createNodeNotebookCommandRunner({ maxOutputBytes: -5 })).toThrow(RangeError);
|
||||
expect(() => createNodeNotebookCommandRunner({ maxOutputBytes: 1.5 })).toThrow(RangeError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createNodeNotebookSnapshotFs', () => {
|
||||
test('stat returns null for missing, { isFile, size } for file/dir, and propagates ENOTDIR', async () => {
|
||||
const fs = createNodeNotebookSnapshotFs();
|
||||
const missingPath = join(workDir, 'missing.txt');
|
||||
const filePath = join(workDir, 'sample.bin');
|
||||
const dirPath = join(workDir, 'nested-dir');
|
||||
|
||||
await writeFile(filePath, new Uint8Array([1, 2, 3, 4, 5]));
|
||||
await mkdir(dirPath);
|
||||
|
||||
expect(await fs.stat(missingPath)).toBeNull();
|
||||
expect(await fs.stat(filePath)).toEqual({ isFile: true, size: 5 });
|
||||
|
||||
const dirStat = await fs.stat(dirPath);
|
||||
expect(dirStat).not.toBeNull();
|
||||
expect(dirStat?.isFile).toBe(false);
|
||||
|
||||
const enotdirErr = await expectReject(fs.stat(join(filePath, 'child')));
|
||||
expect(getErrorCode(enotdirErr)).toBe('ENOTDIR');
|
||||
});
|
||||
|
||||
test('createExclusive creates an empty file and rejects EEXIST on collision', async () => {
|
||||
const fs = createNodeNotebookSnapshotFs();
|
||||
const target = join(workDir, 'exclusive.tmp');
|
||||
|
||||
await fs.createExclusive(target);
|
||||
expect(await fs.stat(target)).toEqual({ isFile: true, size: 0 });
|
||||
|
||||
const err = await expectReject(fs.createExclusive(target));
|
||||
expect(getErrorCode(err)).toBe('EEXIST');
|
||||
});
|
||||
|
||||
test('readBytes round-trips arbitrary binary bytes including 0x00 and 0xff', async () => {
|
||||
const fs = createNodeNotebookSnapshotFs();
|
||||
const target = join(workDir, 'binary.dat');
|
||||
const payload = new Uint8Array([0x00, 0x01, 0x7f, 0x80, 0xfe, 0xff, 0x00, 0x42]);
|
||||
await writeFile(target, payload);
|
||||
|
||||
const actual = await fs.readBytes(target);
|
||||
expect(actual).toBeInstanceOf(Uint8Array);
|
||||
expect(Array.from(actual)).toEqual(Array.from(payload));
|
||||
});
|
||||
|
||||
test('rename atomically replaces an existing destination file', async () => {
|
||||
const fs = createNodeNotebookSnapshotFs();
|
||||
const src = join(workDir, 'new.html');
|
||||
const dst = join(workDir, 'published.html');
|
||||
|
||||
await writeFile(dst, 'old content', 'utf8');
|
||||
await writeFile(src, 'new content', 'utf8');
|
||||
|
||||
await fs.rename(src, dst);
|
||||
|
||||
expect(await fs.stat(src)).toBeNull();
|
||||
expect(await readFile(dst, 'utf8')).toBe('new content');
|
||||
});
|
||||
|
||||
test('remove is a no-op when absent and rejects non-recursively on a non-empty directory', async () => {
|
||||
const fs = createNodeNotebookSnapshotFs();
|
||||
|
||||
await fs.remove(join(workDir, 'absent.tmp'));
|
||||
|
||||
const regularFile = join(workDir, 'deletable.tmp');
|
||||
await writeFile(regularFile, 'bye', 'utf8');
|
||||
await fs.remove(regularFile);
|
||||
expect(await fs.stat(regularFile)).toBeNull();
|
||||
|
||||
const nonEmptyDir = join(workDir, 'keep-dir');
|
||||
const innerFile = join(nonEmptyDir, 'inside.txt');
|
||||
await mkdir(nonEmptyDir);
|
||||
await writeFile(innerFile, 'precious', 'utf8');
|
||||
|
||||
const err = await expectReject(fs.remove(nonEmptyDir));
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(await readFile(innerFile, 'utf8')).toBe('precious');
|
||||
});
|
||||
});
|
||||
|
||||
describe('end-to-end exportNotebookSnapshot with real adapters and fake marimo shim', () => {
|
||||
async function writeFakeMarimoShim(
|
||||
name: string,
|
||||
mode: 'clean' | 'check_error' | 'hang_export',
|
||||
logPath: string,
|
||||
extra?: { readonly htmlContent?: string; readonly pidPath?: string }
|
||||
): Promise<string> {
|
||||
const shimPath = join(workDir, name);
|
||||
const htmlContent = extra?.htmlContent ?? '<!doctype html><html><body>OK</body></html>\n';
|
||||
const pidPath = extra?.pidPath ?? '';
|
||||
|
||||
const script = [
|
||||
'#!/usr/bin/env bun',
|
||||
"import { appendFileSync, writeFileSync } from 'node:fs';",
|
||||
'const args = process.argv.slice(2);',
|
||||
`const mode = ${JSON.stringify(mode)};`,
|
||||
`const logPath = ${JSON.stringify(logPath)};`,
|
||||
`const htmlContent = ${JSON.stringify(htmlContent)};`,
|
||||
`const pidPath = ${JSON.stringify(pidPath)};`,
|
||||
'appendFileSync(logPath, JSON.stringify({ args, pid: process.pid }) + "\\n", "utf8");',
|
||||
'if (args[0] === "check") {',
|
||||
' if (args[1] !== "--format=json" || args.length !== 3) {',
|
||||
' process.stderr.write("unexpected check argv: " + JSON.stringify(args));',
|
||||
' process.exit(2);',
|
||||
' }',
|
||||
' if (mode === "check_error") {',
|
||||
' process.stdout.write(JSON.stringify({',
|
||||
' issues: [{ type: "error", severity: "breaking", message: "undefined name" }],',
|
||||
' summary: { errored: true, total_files: 1 },',
|
||||
' }));',
|
||||
' process.exit(0);',
|
||||
' }',
|
||||
' process.stdout.write(JSON.stringify({',
|
||||
' issues: [],',
|
||||
' summary: { errored: false, total_files: 1 },',
|
||||
' }));',
|
||||
' process.exit(0);',
|
||||
'}',
|
||||
'if (args[0] === "export" && args[1] === "html") {',
|
||||
' if (args.length !== 6 || args[3] !== "-o" || args[5] !== "--force") {',
|
||||
' process.stderr.write("unexpected export argv: " + JSON.stringify(args));',
|
||||
' process.exit(2);',
|
||||
' }',
|
||||
' const outPath = args[4];',
|
||||
' if (mode === "hang_export") {',
|
||||
' writeFileSync(outPath, "<html>partial", "utf8");',
|
||||
' if (pidPath) writeFileSync(pidPath, String(process.pid), "utf8");',
|
||||
' setInterval(() => {}, 10_000);',
|
||||
' } else {',
|
||||
' writeFileSync(outPath, htmlContent, "utf8");',
|
||||
' process.exit(0);',
|
||||
' }',
|
||||
'} else {',
|
||||
' process.stderr.write("unknown command: " + JSON.stringify(args));',
|
||||
' process.exit(2);',
|
||||
'}',
|
||||
].join('\n');
|
||||
|
||||
await writeFile(shimPath, `${script}\n`, 'utf8');
|
||||
await chmod(shimPath, 0o755);
|
||||
return shimPath;
|
||||
}
|
||||
|
||||
test('clean check publishes HTML whose bytes and sha256 match the receipt with no leftover temp files', async () => {
|
||||
const notebookDir = join(workDir, 'notebooks');
|
||||
const outputDir = join(workDir, 'out');
|
||||
await mkdir(notebookDir);
|
||||
await mkdir(outputDir);
|
||||
|
||||
const notebookPath = join(notebookDir, 'study.py');
|
||||
const outputPath = join(outputDir, 'study.html');
|
||||
const logPath = join(workDir, 'clean.log.jsonl');
|
||||
const expectedHtml = '<!doctype html><html><body><h1>CA Shorts Study €</h1></body></html>\n';
|
||||
const expectedBytes = Buffer.from(expectedHtml, 'utf8');
|
||||
const expectedSha256 = createHash('sha256').update(expectedBytes).digest('hex');
|
||||
|
||||
await writeFile(notebookPath, '# marimo notebook fixture\n', 'utf8');
|
||||
const shimPath = await writeFakeMarimoShim('fake-marimo-clean', 'clean', logPath, {
|
||||
htmlContent: expectedHtml,
|
||||
});
|
||||
|
||||
const receipt = await exportNotebookSnapshot({
|
||||
notebookPath,
|
||||
outputPath,
|
||||
runner: createNodeNotebookCommandRunner(),
|
||||
fs: createNodeNotebookSnapshotFs(),
|
||||
marimoCommand: shimPath,
|
||||
timeoutMs: 10_000,
|
||||
allowedNotebookRoot: notebookDir,
|
||||
allowedOutputRoot: outputDir,
|
||||
});
|
||||
|
||||
expect(receipt.notebookPath).toBe(notebookPath);
|
||||
expect(receipt.outputPath).toBe(outputPath);
|
||||
expect(receipt.bytes).toBe(expectedBytes.byteLength);
|
||||
expect(receipt.sha256).toBe(expectedSha256);
|
||||
expect(receipt.checkDiagnostics).toEqual({
|
||||
issues: [],
|
||||
summary: { errored: false, total_files: 1 },
|
||||
});
|
||||
|
||||
const published = await readFile(outputPath);
|
||||
expect(published.byteLength).toBe(receipt.bytes);
|
||||
expect(createHash('sha256').update(published).digest('hex')).toBe(receipt.sha256);
|
||||
expect(await readdir(outputDir)).toEqual(['study.html']);
|
||||
|
||||
const invocations = (await readFile(logPath, 'utf8'))
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map(line => JSON.parse(line) as { args: string[] });
|
||||
expect(invocations).toHaveLength(2);
|
||||
expect(invocations[0]?.args).toEqual(['check', '--format=json', notebookPath]);
|
||||
expect(invocations[1]?.args[0]).toBe('export');
|
||||
expect(invocations[1]?.args[1]).toBe('html');
|
||||
expect(invocations[1]?.args[2]).toBe(notebookPath);
|
||||
expect(invocations[1]?.args[3]).toBe('-o');
|
||||
expect(invocations[1]?.args[5]).toBe('--force');
|
||||
});
|
||||
|
||||
test('blocking check report on exit 0 rejects CHECK_FAILED, skips export, and writes no output or temp files', async () => {
|
||||
const notebookDir = join(workDir, 'notebooks');
|
||||
const outputDir = join(workDir, 'out');
|
||||
await mkdir(notebookDir);
|
||||
await mkdir(outputDir);
|
||||
|
||||
const notebookPath = join(notebookDir, 'broken.py');
|
||||
const outputPath = join(outputDir, 'broken.html');
|
||||
const logPath = join(workDir, 'check-error.log.jsonl');
|
||||
|
||||
await writeFile(notebookPath, '# broken marimo notebook fixture\n', 'utf8');
|
||||
const shimPath = await writeFakeMarimoShim('fake-marimo-check-error', 'check_error', logPath);
|
||||
|
||||
const err = await expectReject(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath,
|
||||
outputPath,
|
||||
runner: createNodeNotebookCommandRunner(),
|
||||
fs: createNodeNotebookSnapshotFs(),
|
||||
marimoCommand: shimPath,
|
||||
timeoutMs: 10_000,
|
||||
})
|
||||
);
|
||||
|
||||
expect(err).toBeInstanceOf(NotebookSnapshotError);
|
||||
expect((err as NotebookSnapshotError).code).toBe('CHECK_FAILED');
|
||||
expect(await readdir(outputDir)).toEqual([]);
|
||||
|
||||
const invocations = (await readFile(logPath, 'utf8'))
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map(line => JSON.parse(line) as { args: string[] });
|
||||
expect(invocations).toHaveLength(1);
|
||||
expect(invocations[0]?.args).toEqual(['check', '--format=json', notebookPath]);
|
||||
});
|
||||
|
||||
test('hanging export rejects TIMEOUT, kills export child, and leaves no output or partial temp file', async () => {
|
||||
const notebookDir = join(workDir, 'notebooks');
|
||||
const outputDir = join(workDir, 'out');
|
||||
await mkdir(notebookDir);
|
||||
await mkdir(outputDir);
|
||||
|
||||
const notebookPath = join(notebookDir, 'hang.py');
|
||||
const outputPath = join(outputDir, 'hang.html');
|
||||
const logPath = join(workDir, 'hang.log.jsonl');
|
||||
const pidPath = join(workDir, 'hang-export.pid');
|
||||
|
||||
await writeFile(notebookPath, '# hanging export fixture\n', 'utf8');
|
||||
const shimPath = await writeFakeMarimoShim('fake-marimo-hang', 'hang_export', logPath, {
|
||||
pidPath,
|
||||
});
|
||||
|
||||
const err = await expectReject(
|
||||
exportNotebookSnapshot({
|
||||
notebookPath,
|
||||
outputPath,
|
||||
runner: createNodeNotebookCommandRunner(),
|
||||
fs: createNodeNotebookSnapshotFs(),
|
||||
marimoCommand: shimPath,
|
||||
timeoutMs: 800,
|
||||
})
|
||||
);
|
||||
|
||||
expect(err).toBeInstanceOf(NotebookSnapshotError);
|
||||
expect((err as NotebookSnapshotError).code).toBe('TIMEOUT');
|
||||
expect(await readdir(outputDir)).toEqual([]);
|
||||
|
||||
const invocations = (await readFile(logPath, 'utf8'))
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map(line => JSON.parse(line) as { args: string[]; pid: number });
|
||||
expect(invocations).toHaveLength(2);
|
||||
expect(invocations[0]?.args[0]).toBe('check');
|
||||
expect(invocations[1]?.args[0]).toBe('export');
|
||||
|
||||
const pid = Number.parseInt((await readFile(pidPath, 'utf8')).trim(), 10);
|
||||
expect(Number.isInteger(pid) && pid > 0).toBe(true);
|
||||
|
||||
let probeError: unknown;
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
} catch (killErr) {
|
||||
probeError = killErr;
|
||||
}
|
||||
expect(getErrorCode(probeError)).toBe('ESRCH');
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue