Improve `killSignal` option (#728)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent a61a028 · Browse files · 9 files·+99 added−49 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+99 added−49 removed
- tests:+70 added−26 removed
- other:+29 added−23 removed
Provenance
- Commit
cf36c1d- Tree
398f522- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
a61a028
9 files changed+99 added−49 removed
modified:lib/kill.js+15 added-17 removed
3 unmodified lines4567889101011121314151415161718192021222324252526272829272829303132333435369 unmodified lines4647484947505149525354555655565758575859606061626162636412 unmodified lines3 unmodified lines
const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
// Monkey-patches `childProcess.kill()` to add `forceKillAfterDelay` behaviorexport const spawnedKill = (kill, {forceKillAfterDelay}, controller, signal) => {export const spawnedKill = (kill, {forceKillAfterDelay, killSignal}, controller, signal = killSignal) => { const killResult = kill(signal); setKillTimeout({kill, signal, forceKillAfterDelay, killResult, controller}); setKillTimeout({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}); return killResult;};
const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killResult, controller}) => { if (!shouldForceKill(signal, forceKillAfterDelay, killResult)) {const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}) => { if (!shouldForceKill(signal, forceKillAfterDelay, killSignal, killResult)) { return; }
try { await setTimeout(forceKillAfterDelay, undefined, {signal: controller.signal}); kill('SIGKILL'); } catch {}};
const shouldForceKill = (signal, forceKillAfterDelay, killResult) => isSigterm(signal) && forceKillAfterDelay !== false && killResult;const shouldForceKill = (signal, forceKillAfterDelay, killSignal, killResult) => normalizeSignal(signal) === normalizeSignal(killSignal) && forceKillAfterDelay !== false && killResult;
const isSigterm = signal => signal === undefined || signal === os.constants.signals.SIGTERM || (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');const normalizeSignal = signal => typeof signal === 'string' ? os.constants.signals[signal.toUpperCase()] : signal;
export const normalizeForceKillAfterDelay = forceKillAfterDelay => { if (forceKillAfterDelay === false) { return forceKillAfterDelay;9 unmodified lines
return forceKillAfterDelay;};
const killAfterTimeout = async ({spawned, timeout, killSignal, context, controller}) => {const killAfterTimeout = async (timeout, context, controller) => { await setTimeout(timeout, undefined, {signal: controller.signal}); spawned.kill(killSignal); context.timedOut = true; throw new Error('Timed out');};
// `timeout` option handlingexport const throwOnTimeout = ({spawned, timeout, killSignal, context, controller}) => { if (timeout === 0 || timeout === undefined) { return []; }export const throwOnTimeout = (timeout, context, controller) => timeout === 0 || timeout === undefined ? [] : [killAfterTimeout(timeout, context, controller)];
return [killAfterTimeout({spawned, timeout, killSignal, context, controller})];};
export const validateTimeout = ({timeout}) => { if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); }12 unmodified linesmodified:lib/stream.js+2 added-2 removed
129 unmodified lines130 131 // Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)132 export const getSpawnedResult = async ({133 spawned,134- options: {encoding, buffer, maxBuffer, timeoutDuration: timeout, killSignal, cleanup, detached},134+ options: {encoding, buffer, maxBuffer, timeoutDuration: timeout, cleanup, detached},135 context,136 stdioStreamsGroups,137 controller,138 }) => {19 unmodified lines158 ]),159 throwOnProcessError(processErrorPromise),160 ...throwOnCustomStreamsError(customStreams),161 ...throwIfStreamError(spawned.stdin),162- ...throwOnTimeout({spawned, timeout, killSignal, context, controller}),162+ ...throwOnTimeout(timeout, context, controller),163 ]);164 } catch (error) {165 spawned.kill();166 const results = await Promise.all([13 unmodified linesadded:test/fixtures/noop-forever.js+5 added
12345#!/usr/bin/env nodeimport process from 'node:process';
console.log(process.argv[2]);setTimeout(() => {}, 1e8);modified:test/error.js+7 added-7 removed
156 unmodified lines157 t.true(failed);158 });159 160 test('error.isTerminated is true if process was killed directly', async t => {161- const subprocess = execa('forever.js');161+ const subprocess = execa('forever.js', {killSignal: 'SIGINT'});162 163 subprocess.kill();164 165- const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});165+ const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});166 t.true(isTerminated);167- t.is(signal, 'SIGTERM');167+ t.is(signal, 'SIGINT');168 });169 170 test('error.isTerminated is true if process was killed indirectly', async t => {171- const subprocess = execa('forever.js');171+ const subprocess = execa('forever.js', {killSignal: 'SIGHUP'});172 173 process.kill(subprocess.pid, 'SIGINT');174 175 // `process.kill()` is emulated by Node.js on Windows65 unmodified lines241 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});242 t.is(signal, 'SIGTERM');243 });244 245- test('custom error.signal', async t => {246- const {signal} = await t.throwsAsync(execa('forever.js', {killSignal: 'SIGHUP', timeout: 1, message: TIMEOUT_REGEXP}));247- t.is(signal, 'SIGHUP');245+ test('error.signal uses killSignal', async t => {246+ const {signal} = await t.throwsAsync(execa('forever.js', {killSignal: 'SIGINT', timeout: 1, message: TIMEOUT_REGEXP}));247+ t.is(signal, 'SIGINT');248 });249 250 test('exitCode is undefined on signal termination', async t => {251 const subprocess = execa('forever.js');43 unmodified linesmodified:test/kill.js+41 added-13 removed
1 import process from 'node:process';2 import {once} from 'node:events';3+import {constants} from 'node:os';4 import {setTimeout} from 'node:timers/promises';5 import test from 'ava';6 import {pEvent} from 'p-event';7 import isRunning from 'is-running';26 unmodified lines34 35 // `SIGTERM` cannot be caught on Windows, and it always aborts the process (like `SIGKILL` on Unix).36 // Therefore, this feature and those tests do not make sense on Windows.37 if (process.platform !== 'win32') {37- const testNoForceKill = async (t, forceKillAfterDelay, killArgument) => {38- const {subprocess} = await spawnNoKillable(forceKillAfterDelay);38+ const testNoForceKill = async (t, forceKillAfterDelay, killArgument, options) => {39+ const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);40 41 subprocess.kill(killArgument);42 43 await setTimeout(6e3);6 unmodified lines50 };51 52 test('`forceKillAfterDelay: false` should not kill after a timeout', testNoForceKill, false);53 test('`forceKillAfterDelay` should not kill after a timeout with other signals', testNoForceKill, true, 'SIGINT');54+ test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal string', testNoForceKill, true, 'SIGTERM', {killSignal: 'SIGINT'});55+ test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal number', testNoForceKill, true, constants.signals.SIGTERM, {killSignal: constants.signals.SIGINT});56 54- const testForceKill = async (t, forceKillAfterDelay, killArgument) => {55- const {subprocess} = await spawnNoKillable(forceKillAfterDelay);57+ const testForceKill = async (t, forceKillAfterDelay, killArgument, options) => {58+ const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);59 60 subprocess.kill(killArgument);61 62 const {isTerminated, signal} = await t.throwsAsync(subprocess);3 unmodified lines66 67 test('`forceKillAfterDelay: number` should kill after a timeout', testForceKill, 50);68 test('`forceKillAfterDelay: true` should kill after a timeout', testForceKill, true);69 test('`forceKillAfterDelay: undefined` should kill after a timeout', testForceKill, undefined);67- test('`forceKillAfterDelay` should kill after a timeout with the killSignal', testForceKill, 50, 'SIGTERM');70+ test('`forceKillAfterDelay` should kill after a timeout with SIGTERM', testForceKill, 50, 'SIGTERM');71+ test('`forceKillAfterDelay` should kill after a timeout with the killSignal string', testForceKill, 50, 'SIGINT', {killSignal: 'SIGINT'});72+ test('`forceKillAfterDelay` should kill after a timeout with the killSignal number', testForceKill, 50, constants.signals.SIGINT, {killSignal: constants.signals.SIGINT});73 74 const testInvalidForceKill = async (t, forceKillAfterDelay) => {75 t.throws(() => {76 execa('empty.js', {forceKillAfterDelay});4 unmodified lines81 test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);82 83 test('`forceKillAfterDelay` works with the "signal" option', async t => {84 const abortController = new AbortController();80- const {subprocess} = await spawnNoKillable(1, {signal: abortController.signal});85+ const subprocess = execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, signal: abortController.signal});86+ await once(subprocess, 'spawn');87 abortController.abort();88 const {isTerminated, signal, isCanceled} = await t.throwsAsync(subprocess);89 t.true(isTerminated);90 t.is(signal, 'SIGKILL');91 t.true(isCanceled);92 });93 88- // For this test to work, the process needs to spawn and setup its `SIGTERM` handler before `timeout` terminates it.89- // This creates a race condition that we can only work around by using `test.serial()` and a higher timeout.90- test.serial('`forceKillAfterDelay` works with the "timeout" option', async t => {91- const {subprocess} = await spawnNoKillable(1, {timeout: 5e3});94+ test('`forceKillAfterDelay` works with the "timeout" option', async t => {95+ const subprocess = execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, timeout: 1});96 const {isTerminated, signal, timedOut} = await t.throwsAsync(subprocess);97 t.true(isTerminated);98 t.is(signal, 'SIGKILL');99 t.true(timedOut);100 });101 102 test('`forceKillAfterDelay` works with the "maxBuffer" option', async t => {99- const {subprocess} = await spawnNoKillable(1, {maxBuffer: 1});103+ const subprocess = execa('noop-forever.js', ['.'], {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, maxBuffer: 1});104 const {isTerminated, signal} = await t.throwsAsync(subprocess);105 t.true(isTerminated);106 t.is(signal, 'SIGKILL');107 });108 109 test('`forceKillAfterDelay` works with "error" events on childProcess', async t => {106- const {subprocess} = await spawnNoKillable(1);110+ const subprocess = execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1});111+ await once(subprocess, 'spawn');112 subprocess.emit('error', new Error('test'));113 const {isTerminated, signal} = await t.throwsAsync(subprocess);114 t.true(isTerminated);115 t.is(signal, 'SIGKILL');116 });117 118 test('`forceKillAfterDelay` works with "error" events on childProcess.stdout', async t => {114- const {subprocess} = await spawnNoKillable(1);119+ const subprocess = execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1});120+ await once(subprocess, 'spawn');121 subprocess.stdout.destroy(new Error('test'));122 const {isTerminated, signal} = await t.throwsAsync(subprocess);123 t.true(isTerminated);124 t.is(signal, 'SIGKILL');26 unmodified lines151 const {timedOut} = await execa('delay.js', ['500'], {timeout: 1e8});152 t.false(timedOut);153 });154 155+test('timeout uses killSignal', async t => {156+ const {isTerminated, signal, timedOut} = await t.throwsAsync(execa('forever.js', {timeout: 1, killSignal: 'SIGINT'}));157+ t.true(isTerminated);158+ t.is(signal, 'SIGINT');159+ t.true(timedOut);160+});161+162 const INVALID_TIMEOUT_REGEXP = /`timeout` option to be a non-negative integer/;163 164 const testTimeoutValidation = (t, timeout, execaMethod) => {165 t.throws(() => {161 unmodified lines327 const result = await subprocess;328 abortController.abort();329 t.false(result.isCanceled);330 });331+332+test('child process errors are handled', async t => {333+ const subprocess = execa('forever.js');334+ subprocess.emit('error', new Error('test'));335+ await t.throwsAsync(subprocess, {message: 'Command failed: forever.js\ntest'});336+});337+338+test('child process errors use killSignal', async t => {339+ const subprocess = execa('forever.js', {killSignal: 'SIGINT'});340+ await once(subprocess, 'spawn');341+ subprocess.emit('error', new Error('test'));342+ const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /test/});343+ t.true(isTerminated);344+ t.is(signal, 'SIGINT');345+});modified:test/stream.js+17 added
133 unmodified lines134 test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, 2, false);135 test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, 3, false);136 test('maxBuffer does not affect all if too high', testMaxBufferSuccess, 1, true);137 138+test('maxBuffer uses killSignal', async t => {139+ const {isTerminated, signal} = await t.throwsAsync(140+ execa('noop-forever.js', ['.'.repeat(maxBuffer + 1)], {maxBuffer, killSignal: 'SIGINT'}),141+ {message: /maxBuffer exceeded/},142+ );143+ t.true(isTerminated);144+ t.is(signal, 'SIGINT');145+});146+147 const testMaxBufferLimit = async (t, index, all) => {148 const length = all ? maxBuffer * 2 : maxBuffer;149 const result = await t.throwsAsync(150 execa('max-buffer.js', [`${index}`, `${length + 1}`], {...fullStdio, maxBuffer, all}),155 unmodified lines306 test('Errors on stdout should make the process exit', testStreamError, 1);307 test('Errors on stderr should make the process exit', testStreamError, 2);308 test('Errors on stdio[*] should make the process exit', testStreamError, 3);309 310+test('Errors on streams use killSignal', async t => {311+ const childProcess = execa('forever.js', {killSignal: 'SIGINT'});312+ childProcess.stdout.destroy(new Error('test'));313+ const {isTerminated, signal} = await t.throwsAsync(childProcess, {message: /test/});314+ t.true(isTerminated);315+ t.is(signal, 'SIGINT');316+});317+318 const testWaitOnStreamEnd = async (t, index) => {319 const childProcess = execa('stdin-fd.js', [`${index}`], fullStdio);320 await setTimeout(100);321 childProcess.stdio[index].end('foobar');46 unmodified linesmodified:test/test.js-6 removed
145 unmodified lines146 147 test.serial('execPath option', testExecPath, identity);148 test.serial('execPath option can be a file URL', testExecPath, pathToFileURL);149 150-test('child process errors are handled', async t => {151- const subprocess = execa('noop.js');152- subprocess.emit('error', new Error('test'));153- await t.throwsAsync(subprocess, {message: /test/});154-});155-150 test('execa() returns a promise with pid', async t => {151 const subprocess = execa('noop.js', ['foo']);152 t.is(typeof subprocess.pid, 'number');153 await subprocess;157 unmodified linesmodified:index.d.ts+6 added-2 removed
446 unmodified lines447 */448 readonly encoding?: EncodingOption;449 450 /**451- If `timeout` is greater than `0`, the parent will send the signal identified by the `killSignal` property (the default is `SIGTERM`) if the child runs longer than `timeout` milliseconds.451+ If `timeout`` is greater than `0`, the child process will be [terminated](#killsignal) if it runs for longer than that amount of milliseconds.452 453 @default 0454 */455 readonly timeout?: number;5 unmodified lines461 */462 readonly maxBuffer?: number;463 464 /**465- Signal value to be used when the spawned process will be killed.465+ Signal used to terminate the child process when:466+ - using the `signal`, `timeout`, `maxBuffer` or `cleanup` option467+ - calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with no arguments468 469+ This can be either a name (like `"SIGTERM"`) or a number (like `9`).470+471 @default 'SIGTERM'472 */473 readonly killSignal?: string | number;474 815 unmodified linesmodified:readme.md+6 added-2 removed
736 unmodified lines737 738 Type: `number`\739 Default: `0`740 741-If timeout is greater than `0`, the parent will send the signal identified by the `killSignal` property (the default is `SIGTERM`) if the child runs longer than timeout milliseconds.741+If `timeout`` is greater than `0`, the child process will be [terminated](#killsignal) if it runs for longer than that amount of milliseconds.742 743 #### maxBuffer744 745 Type: `number`\5 unmodified lines751 752 Type: `string | number`\753 Default: `SIGTERM`754 755-Signal value to be used when the spawned process will be killed.755+Signal used to terminate the child process when:756+- using the [`signal`](#signal-1), [`timeout`](#timeout), [`maxBuffer`](#maxbuffer) or [`cleanup`](#cleanup) option757+- calling [`subprocess.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal) with no arguments758 759+This can be either a name (like `"SIGTERM"`) or a number (like `9`).760+761 #### forceKillAfterDelay762 763 Type: `number | false`\764 Default: `5000`180 unmodified lines