Skip to content

fix(core): add registerExitHandler utility #31132

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion packages/detox/src/executors/build/build.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ export function runCliBuild(

// Ensure the child process is killed when the parent exits
process.on('exit', () => childProcess.kill());
process.on('SIGTERM', () => childProcess.kill());

childProcess.on('error', (err) => {
reject(err);
Expand Down
1 change: 0 additions & 1 deletion packages/detox/src/executors/test/test.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ function runCliTest(

// Ensure the child process is killed when the parent exits
process.on('exit', () => childProcess.kill());
process.on('SIGTERM', () => childProcess.kill());

childProcess.on('error', (err) => {
reject(err);
Expand Down
15 changes: 1 addition & 14 deletions packages/esbuild/src/executors/esbuild/esbuild.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ export async function* esbuildExecutor(
})
);

registerCleanupCallback(() => {
process.once('exit', () => {
assetsResult?.stop();
packageJsonResult?.stop();
disposeFns.forEach((fn) => fn());
Expand Down Expand Up @@ -269,17 +269,4 @@ async function runTypeCheck(
return { errors, warnings };
}

function registerCleanupCallback(callback: () => void) {
const wrapped = () => {
callback();
process.off('SIGINT', wrapped);
process.off('SIGTERM', wrapped);
process.off('exit', wrapped);
};

process.on('SIGINT', wrapped);
process.on('SIGTERM', wrapped);
process.on('exit', wrapped);
}

export default esbuildExecutor;
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ export function runCliBuildList(

// Ensure the child process is killed when the parent exits
process.on('exit', () => childProcess.kill());
process.on('SIGTERM', () => childProcess.kill());

let output = '';
childProcess.stdout.on('data', (message) => {
Expand Down
1 change: 0 additions & 1 deletion packages/expo/src/executors/build/build.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ function runCliBuild(

// Ensure the child process is killed when the parent exits
process.on('exit', () => childProcess.kill());
process.on('SIGTERM', () => childProcess.kill());

childProcess.on('error', (err) => {
reject(err);
Expand Down
1 change: 0 additions & 1 deletion packages/expo/src/executors/export/export.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ function exportAsync(

// Ensure the child process is killed when the parent exits
process.on('exit', () => childProcess.kill());
process.on('SIGTERM', () => childProcess.kill());

childProcess.on('error', (err) => {
reject(err);
Expand Down
1 change: 0 additions & 1 deletion packages/expo/src/executors/prebuild/prebuild.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ export function prebuildAsync(

// Ensure the child process is killed when the parent exits
process.on('exit', () => childProcess.kill());
process.on('SIGTERM', () => childProcess.kill());

childProcess.on('error', (err) => {
reject(err);
Expand Down
1 change: 0 additions & 1 deletion packages/expo/src/executors/run/run.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ function runCliRun(

// Ensure the child process is killed when the parent exits
process.on('exit', () => childProcess.kill());
process.on('SIGTERM', () => childProcess.kill());

childProcess.on('error', (err) => {
reject(err);
Expand Down
1 change: 0 additions & 1 deletion packages/expo/src/executors/start/start.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ function startAsync(

// Ensure the child process is killed when the parent exits
process.on('exit', () => childProcess.kill());
process.on('SIGTERM', () => childProcess.kill());

childProcess.on('error', (err) => {
reject(err);
Expand Down
1 change: 0 additions & 1 deletion packages/expo/src/executors/submit/submit.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ function runCliSubmit(

// Ensure the child process is killed when the parent exits
process.on('exit', () => childProcess.kill());
process.on('SIGTERM', () => childProcess.kill());

childProcess.on('error', (err) => {
reject(err);
Expand Down
1 change: 0 additions & 1 deletion packages/expo/src/executors/update/update.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ function runCliUpdate(

// Ensure the child process is killed when the parent exits
process.on('exit', () => childProcess.kill());
process.on('SIGTERM', () => childProcess.kill());

childProcess.on('error', (err) => {
reject(err);
Expand Down
18 changes: 6 additions & 12 deletions packages/js/src/executors/node/node.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { killTree } from './lib/kill-tree';
import { fileExists } from 'nx/src/utils/fileutils';
import { getRelativeDirectoryToProjectRoot } from '../../utils/get-main-file-dir';
import { interpolate } from 'nx/src/tasks-runner/utils';
import { registerExitHandler } from 'nx/src/utils/signals';

interface ActiveTask {
id: string;
Expand Down Expand Up @@ -233,18 +234,11 @@ export async function* nodeExecutor(
}
};

process.on('SIGTERM', async () => {
await stopAllTasks('SIGTERM');
process.exit(128 + 15);
});
process.on('SIGINT', async () => {
await stopAllTasks('SIGINT');
process.exit(128 + 2);
});
process.on('SIGHUP', async () => {
await stopAllTasks('SIGHUP');
process.exit(128 + 1);
});
for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) {
registerExitHandler('SIGTERM', async () => {
await stopAllTasks(signal);
});
}

registerCleanup(async () => {
await stopAllTasks('SIGTERM');
Expand Down
5 changes: 3 additions & 2 deletions packages/js/src/executors/swc/swc.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { compileSwc, compileSwcWatch } from '../../utils/swc/compile-swc';
import { getSwcrcPath } from '../../utils/swc/get-swcrc-path';
import { generateTmpSwcrc } from '../../utils/swc/inline';
import { isUsingTsSolutionSetup } from '../../utils/typescript/ts-solution-setup';
import { registerExitHandler } from 'nx/src/utils/signals';

function normalizeOptions(
options: SwcExecutorOptions,
Expand Down Expand Up @@ -186,8 +187,8 @@ export async function* swcExecutor(

if (options.watch) {
let disposeFn: () => void;
process.on('SIGINT', () => disposeFn());
process.on('SIGTERM', () => disposeFn());
registerExitHandler('SIGINT', (s) => disposeFn());
registerExitHandler('SIGTERM', (s) => disposeFn());

return yield* compileSwcWatch(context, options, async () => {
const assetResult = await copyAssets(options, context);
Expand Down
8 changes: 4 additions & 4 deletions packages/js/src/executors/tsc/tsc.batch-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
watchTaskProjectsPackageJsonFileChanges,
} from './lib/batch';
import { createEntryPoints } from '../../utils/package-json/create-entry-points';
import { registerExitHandler } from 'nx/src/utils/signals';

export async function* tscBatchExecutor(
taskGraph: TaskGraph,
Expand Down Expand Up @@ -150,13 +151,12 @@ export async function* tscBatchExecutor(
}
);

const handleTermination = async (exitCode: number) => {
const handleTermination = async () => {
watchAssetsChangesDisposer();
watchProjectsChangesDisposer();
process.exit(exitCode);
};
process.on('SIGINT', () => handleTermination(128 + 2));
process.on('SIGTERM', () => handleTermination(128 + 15));
registerExitHandler('SIGINT', (s) => handleTermination());
registerExitHandler('SIGTERM', (s) => handleTermination());

return yield* mapAsyncIterable(typescriptCompilation, async (iterator) => {
// drain the iterator, we don't use the results
Expand Down
8 changes: 4 additions & 4 deletions packages/js/src/executors/tsc/tsc.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { watchForSingleFileChanges } from '../../utils/watch-for-single-file-cha
import { getCustomTrasformersFactory, normalizeOptions } from './lib';
import { readTsConfig } from '../../utils/typescript/ts-config';
import { createEntryPoints } from '../../utils/package-json/create-entry-points';
import { registerExitHandler } from 'nx/src/utils/signals';

export function determineModuleFormatFromTsConfig(
absolutePathToTsConfig: string
Expand Down Expand Up @@ -169,14 +170,13 @@ export async function* tscExecutor(
)
);
}
const handleTermination = async (exitCode: number) => {
const handleTermination = async () => {
await typescriptCompilation.close();
disposeWatchAssetChanges();
disposePackageJsonChanges?.();
process.exit(exitCode);
};
process.on('SIGINT', () => handleTermination(128 + 2));
process.on('SIGTERM', () => handleTermination(128 + 15));
registerExitHandler('SIGINT', (s) => handleTermination());
registerExitHandler('SIGTERM', (s) => handleTermination());
}

return yield* typescriptCompilation.iterator;
Expand Down
3 changes: 0 additions & 3 deletions packages/js/src/executors/verdaccio/verdaccio.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,6 @@ export async function verdaccioExecutor(
}
};
process.on('exit', processExitListener);
process.on('SIGTERM', processExitListener);
process.on('SIGINT', processExitListener);
process.on('SIGHUP', processExitListener);

try {
await startVerdaccio(options, context.root);
Expand Down
2 changes: 0 additions & 2 deletions packages/js/src/utils/swc/compile-swc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,6 @@ export async function* compileSwcWatch(
swcWatcher.stdout.on('data', stdoutOnData);
swcWatcher.stderr.on('data', stderrOnData);

process.on('SIGINT', processOnExit);
process.on('SIGTERM', processOnExit);
process.on('exit', processOnExit);

swcWatcher.on('exit', watcherOnExit);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ export async function buildStaticRemotes(
res();
}
});
process.on('SIGTERM', () => staticProcess.kill('SIGTERM'));
process.on('exit', () => staticProcess.kill('SIGTERM'));
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,6 @@ export class NxModuleFederationSSRDevServerPlugin
process.on('exit', () => {
this.devServerProcess?.kill('SIGKILL');
});
process.on('SIGINT', () => {
this.devServerProcess?.kill('SIGKILL');
});
callback();
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ export async function buildStaticRemotes(
res();
}
});
process.on('SIGTERM', () => staticProcess.kill('SIGTERM'));
process.on('exit', () => staticProcess.kill('SIGTERM'));
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ export function startRemoteProxies(
const proxyServer = (sslCert ? https : http)
.createServer({ cert: sslCert, key: sslKey }, expressProxy)
.listen(appConfig.port);
process.on('SIGTERM', () => proxyServer.close());
process.on('exit', () => proxyServer.close());
}
console.info(`NX Static remotes proxies started successfully`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,5 @@ export function startStaticRemotesFileServer(
},
}
);
process.on('SIGTERM', () => httpServerProcess.kill('SIGTERM'));
process.on('exit', () => httpServerProcess.kill('SIGTERM'));
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ export function startRemoteProxies(
const proxyServer = (sslCert ? https : http)
.createServer({ cert: sslCert, key: sslKey }, expressProxy)
.listen(staticRemotesConfig.config[app].port);
process.on('SIGTERM', () => proxyServer.close());
process.on('exit', () => proxyServer.close());
}
logger.info(`NX Static remotes proxies started successfully`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ export function startSsrRemoteProxies(
const proxyServer = (sslCert ? https : http)
.createServer({ cert: sslCert, key: sslKey }, expressProxy)
.listen(staticRemotesConfig.config[app].port);
process.on('SIGTERM', () => proxyServer.close());
process.on('exit', () => proxyServer.close());
}
logger.info(`Nx SSR Static remotes proxies started successfully`);
Expand Down
12 changes: 6 additions & 6 deletions packages/next/src/executors/build/build.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { NextBuildBuilderOptions } from '../../utils/types';
import { ChildProcess, fork } from 'child_process';
import { createCliOptions } from '../../utils/create-cli-options';
import { signalToCode } from 'nx/src/utils/exit-codes';
import { registerExitHandler } from 'nx/src/utils/signals';

let childProcess: ChildProcess;

Expand Down Expand Up @@ -157,12 +158,11 @@ function runCliBuild(
// Ensure the child process is killed when the parent exits
process.on('exit', () => childProcess.kill());

process.on('SIGTERM', (signal) => {
reject({ code: signalToCode(signal), signal });
});
process.on('SIGINT', (signal) => {
reject({ code: signalToCode(signal), signal });
});
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
registerExitHandler(signal, () => {
reject({ code: signalToCode(signal), signal });
});
}

childProcess.on('error', (err) => {
reject({ error: err });
Expand Down
3 changes: 0 additions & 3 deletions packages/next/src/executors/server/server.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,6 @@ export default async function* serveExecutor(
}
};
process.on('exit', () => killServer());
process.on('SIGINT', () => killServer());
process.on('SIGTERM', () => killServer());
process.on('SIGHUP', () => killServer());

await waitForPortOpen(options.port, { host: options.hostname });

Expand Down
25 changes: 6 additions & 19 deletions packages/nx/bin/nx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { performance } from 'perf_hooks';
import { setupWorkspaceContext } from '../src/utils/workspace-context';
import { daemonClient } from '../src/daemon/client/client';
import { removeDbConnections } from '../src/utils/db-connection';
import { signalToCode } from '../src/utils/exit-codes';
import { registerExitHandler } from '../src/utils/signals';

// In case Nx Cloud forcibly exits while the TUI is running, ensure the terminal is restored etc.
process.on('exit', (...args) => {
Expand Down Expand Up @@ -283,26 +283,13 @@ const getLatestVersionOfNx = ((fn: () => string) => {
return () => cache || (cache = fn());
})(_getLatestVersionOfNx);

function nxCleanup(signal?: NodeJS.Signals) {
function nxCleanup() {
removeDbConnections();
if (signal) {
process.exit(signalToCode(signal));
} else {
process.exit();
}
}

process.on('exit', () => {
nxCleanup();
});
process.on('SIGINT', () => {
nxCleanup('SIGINT');
});
process.on('SIGTERM', () => {
nxCleanup('SIGTERM');
});
process.on('SIGHUP', () => {
nxCleanup('SIGHUP');
});
registerExitHandler('SIGINT', nxCleanup);
registerExitHandler('SIGTERM', nxCleanup);
registerExitHandler('SIGHUP', nxCleanup);
registerExitHandler('exit', nxCleanup);

main();
5 changes: 4 additions & 1 deletion packages/nx/bin/run-executor.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { appendFileSync, openSync, writeFileSync } from 'fs';
import { Target, run } from '../src/command-line/run/run';
import { TaskGraph } from '../src/config/task-graph';

import { Target, run } from '../src/command-line/run/run';

import '../src/utils/signals';

if (process.env.NX_TERMINAL_OUTPUT_PATH) {
setUpOutputWatching(
process.env.NX_TERMINAL_CAPTURE_STDERR === 'true',
Expand Down
Loading
Loading