diff --git a/README.md b/README.md index e44b4af..066d333 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ The options object can have the following properties: - `signal` - an `AbortSignal` to allow aborting of the execution - `timeout` - time in milliseconds at which the process will be forcibly killed -- `persist` - if `true`, the process will continue after the host exits +- `persist` - if `true`, the child process can continue after the host exits. By default, tinyexec terminates running children when the host exits normally or receives an unhandled `SIGINT`, `SIGTERM`, or `SIGHUP` on a platform that delivers it. - `stdin` - `string` or another `Result` that will be used as the input to the process - `nodeOptions` - any valid options to node's underlying `spawn` function - `throwOnError` - if true, non-zero exit codes will throw an error diff --git a/src/host-exit.ts b/src/host-exit.ts new file mode 100644 index 0000000..e0439a8 --- /dev/null +++ b/src/host-exit.ts @@ -0,0 +1,69 @@ +import type {ChildProcess} from 'node:child_process'; + +const signals = ['SIGHUP', 'SIGINT', 'SIGTERM'] as const; +type HostSignal = (typeof signals)[number]; +const isHostSignal = (event: string | symbol): event is HostSignal => + signals.some((signal) => signal === event); + +// Bundled or separately installed copies must share one set of signal handlers. +const trackerKey = Symbol.for('tinyexec.trackChild'); +type TrackChild = (child: ChildProcess) => void; +const host = process as NodeJS.Process & {[trackerKey]?: TrackChild}; + +function createTracker(): TrackChild { + const children = new Set(); + const terminate = () => { + for (const child of children) child.kill('SIGKILL'); + }; + const onSignal = (signal: HostSignal, signum?: number) => { + // Node supplies the signal number for OS signals. Applications can also emit the event. + if (typeof signum !== 'number') return; + host.removeListener(signal, onSignal); + terminate(); + host.kill(host.pid, signal); + }; + + // Yield to application handlers, including one-shot handlers that do asynchronous + // work. Restore the default-exit fallback when the application removes its last one. + const onAdd = (event: string | symbol, listener: unknown) => { + if (isHostSignal(event) && listener !== onSignal) { + host.removeListener(event, onSignal); + } + }; + const onRemove = (event: string | symbol, listener: unknown) => { + if ( + isHostSignal(event) && + listener !== onSignal && + host.listenerCount(event) === 0 + ) { + host.on(event, onSignal); + } + }; + + return (child) => { + children.add(child); + if (children.size === 1) { + // Remove our fallback before Node starts watching a newly added application handler. + host.prependListener('newListener', onAdd); + host.on('removeListener', onRemove); + host.on('exit', terminate); + for (const signal of signals) { + if (host.listenerCount(signal) === 0) host.on(signal, onSignal); + } + } + child.once('exit', () => { + children.delete(child); + if (children.size > 0) return; + host.removeListener('newListener', onAdd); + host.removeListener('removeListener', onRemove); + host.removeListener('exit', terminate); + for (const signal of signals) host.removeListener(signal, onSignal); + Reflect.deleteProperty(host, trackerKey); + }); + }; +} + +export function trackChild(child: ChildProcess): void { + const track = (host[trackerKey] ??= createTracker()); + track(child); +} diff --git a/src/main.ts b/src/main.ts index 5fe1d05..1750fa8 100644 --- a/src/main.ts +++ b/src/main.ts @@ -8,6 +8,7 @@ import { import {type Readable} from 'node:stream'; import {cwd as getCwd} from 'node:process'; import {computeEnv} from './env.js'; +import {trackChild} from './host-exit.js'; import {combineStreams, readStream} from './stream.js'; import readline from 'node:readline'; import {normalizeSpawnCommand} from './normalize.js'; @@ -338,6 +339,9 @@ export class ExecProcess implements Result { } this._process = handle; + if (!options.persist && handle.pid !== undefined) { + trackChild(handle); + } handle.once('error', this._onError); handle.once('close', this._onClose); diff --git a/src/test/main_test.ts b/src/test/main_test.ts index 895d35e..50967de 100644 --- a/src/test/main_test.ts +++ b/src/test/main_test.ts @@ -10,6 +10,60 @@ const isWindows = os.platform() === 'win32'; const fixturesDir = path.join(import.meta.dirname, '../../test/fixtures'); const distDir = path.join(import.meta.dirname, '../../dist'); +describe('host exits', () => { + function runHost(persist: boolean, exit: string) { + return spawnSync( + process.execPath, + [path.join(fixturesDir, 'host_exit.mjs'), String(persist), exit], + {encoding: 'utf8', timeout: 5000} + ); + } + + test.each([false, true])('normal exit with persist=%s', (persist) => { + const result = runHost(persist, 'exit'); + expect(result.error).toBeUndefined(); + expect(result.status).toBe(0); + expect(result.stdout).toBe(persist ? 'continued' : ''); + }); + + test.skipIf(process.platform === 'win32')( + 'unhandled SIGTERM terminates the host and child', + () => { + const result = runHost(false, 'SIGTERM'); + expect(result.error).toBeUndefined(); + expect(result.signal).toBe('SIGTERM'); + expect(result.stdout).toBe(''); + } + ); + + test.skipIf(process.platform === 'win32')( + 'a one-shot SIGTERM handler can finish using the child', + () => { + const result = runHost(false, 'caught'); + expect(result.error).toBeUndefined(); + expect(result.status).toBe(31); + expect(result.stdout).toBe(''); + } + ); + + test('emitting a signal event does not terminate the host', () => { + const result = runHost(false, 'synthetic'); + expect(result.error).toBeUndefined(); + expect(result.status).toBe(31); + }); + + test('separate copies release listeners after their children exit', () => { + const result = spawnSync( + process.execPath, + [path.join(fixturesDir, 'host_copies.mjs')], + {encoding: 'utf8', timeout: 5000} + ); + expect(result.error).toBeUndefined(); + expect(result.stderr).toBe(''); + expect(result.status).toBe(0); + }); +}); + const variants = [ {name: 'async', x, isAsync: true}, {name: 'sync', x: xSync, isAsync: false} diff --git a/test/fixtures/host_copies.mjs b/test/fixtures/host_copies.mjs new file mode 100644 index 0000000..9e53ea9 --- /dev/null +++ b/test/fixtures/host_copies.mjs @@ -0,0 +1,22 @@ +import assert from 'node:assert/strict'; +import {x as first} from '../../dist/main.mjs?first'; +import {x as second} from '../../dist/main.mjs?second'; + +const events = [ + 'exit', + 'SIGTERM', + 'SIGINT', + 'SIGHUP', + 'newListener', + 'removeListener' +]; +const counts = () => events.map((event) => process.listenerCount(event)); +const before = counts(); +const args = ['-e', 'setTimeout(() => {}, 2000)']; +const a = first(process.execPath, args); +const b = second(process.execPath, args); +b.kill(); +await b; +a.kill(); +await a; +assert.deepEqual(counts(), before); diff --git a/test/fixtures/host_exit.mjs b/test/fixtures/host_exit.mjs new file mode 100644 index 0000000..46d00ec --- /dev/null +++ b/test/fixtures/host_exit.mjs @@ -0,0 +1,29 @@ +import {x} from '../../dist/main.mjs'; + +const [persist, exit] = process.argv.slice(2); +const options = { + nodeOptions: {stdio: ['ignore', process.stdout, 'inherit', 'ipc']} +}; +if (persist === 'true') options.persist = true; +if (exit === 'caught') { + process.once('SIGTERM', () => child.process.send('ping')); +} +const onDisconnect = ` + process.on('message', () => process.send('pong')); + process.once('disconnect', () => process.stdout.write('continued')); + process.send('ready'); +`; +const child = x(process.execPath, ['-e', onDisconnect], options); + +child.process.on('message', (message) => { + if (message === 'pong') process.exit(31); + if (exit === 'synthetic') { + process.emit('SIGTERM'); + process.emit('SIGTERM', 'SIGTERM'); + child.process.send('ping'); + } else if (exit !== 'exit') { + process.kill(process.pid, 'SIGTERM'); + } else { + process.exit(0); + } +});