From 19d650197679c4c943ca07db5ab52d5eca80c6fc Mon Sep 17 00:00:00 2001 From: Alexis Tyler Date: Mon, 3 Feb 2020 15:50:07 +1030 Subject: [PATCH] fix: make sure master doesnt die when worker does --- index.js | 60 +++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 44 insertions(+), 16 deletions(-) diff --git a/index.js b/index.js index 0778f8eec..5d76e6a65 100644 --- a/index.js +++ b/index.js @@ -1,58 +1,86 @@ const path = require('path'); const cluster = require('cluster'); -// Show real stack trace in development -if (process.env.NODE_ENV === 'development') { - try { - require('source-map-support').install({ - handleUncaughtExceptions: false - }); - } catch { - console.error(`Could not load "source-map-supoort", do you have it installed?`); - } -} +const log = process.env.NODE_ENV === 'production' ? { + info() { }, + log() { }, + debug() { }, + error() { } +} : console; // Set current working directory process.chdir(__dirname); const RESTART_ATTEMPTS = 10; let currentRestartAttempt = 0; +let currentWorker; +// Master if (cluster.isMaster) { - cluster.fork(); + // Show real stack trace in development + if (process.env.NODE_ENV === 'development') { + try { + require('source-map-support').install({ + handleUncaughtExceptions: false + }); + } catch { + log.error(`Could not load "source-map-supoort", do you have it installed?`); + } + } + + log.info(` pid = ${process.pid}`); + currentWorker = cluster.fork(); cluster.on('exit', (_, code) => { + if (code === null || code === 0) { + const newWorker = cluster.fork(); + newWorker.once('online', () => { + currentWorker = newWorker; + }); + return; + } + if (code !== 7) { process.exit(code); } if (currentRestartAttempt >= RESTART_ATTEMPTS) { - console.debug(`No restart attempts left. Exiting.`); + log.debug(`No restart attempts left. Exiting.`); process.exit(1); } currentRestartAttempt++; - cluster.fork(); + currentWorker = cluster.fork(); + }); + + // Allow reload on SIGHUP + process.on('SIGHUP', () => { + log.debug(' Reloading worker'); + currentWorker.send('shutdown'); }); } +// Worker if (cluster.isWorker) { + log.info(` pid = ${process.pid}`); + // @ts-ignore const package = require('./package.json'); const { main } = package; if (!main) { - console.error('Missing main field in package.json'); + log.error(' Missing main field in package.json'); process.exit(1); } const mainPath = path.resolve(__dirname, main); try { + log.info(' loaded'); require(mainPath); } catch (error) { - console.error(error); - console.error(`Could not load main field "${mainPath}".`); + log.error(error); + log.error(` Could not load main field "${mainPath}".`); process.exit(1); } } \ No newline at end of file