diff --git a/lib/process/master.js b/lib/process/master.js index 60e690066..87991102b 100644 --- a/lib/process/master.js +++ b/lib/process/master.js @@ -10,13 +10,7 @@ let processor; let currentJobPromise; const { promisify } = require('util'); - -// same as process.send but waits until the send is complete - -// the async version is used below because otherwise -// the termination handler may exit before the parent -// process has recived the messages it requires -const processSendAsync = promisify(process.send.bind(process)); +const { asyncSend } = require('./utils'); // https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify if (!('toJSON' in Error.prototype)) { @@ -95,7 +89,7 @@ process.on('message', msg => { currentJobPromise = (async () => { try { const result = (await processor(wrapJob(msg.job))) || {}; - await processSendAsync({ + await asyncSend(process, { cmd: 'completed', value: result }); @@ -104,7 +98,7 @@ process.on('message', msg => { // eslint-disable-next-line no-ex-assign err = new Error(err); } - await processSendAsync({ + await asyncSend(process, { cmd: 'failed', value: err }); @@ -156,7 +150,7 @@ function wrapJob(job) { // so that we can return it from this process synchronously. progressValue = progress; // Send message to update job progress. - return processSendAsync({ + return asyncSend(process, { cmd: 'progress', value: progress }); @@ -178,7 +172,7 @@ function wrapJob(job) { * Emulate the real job `log` function. */ job.log = function(row) { - return processSendAsync({ + return asyncSend(process, { cmd: 'log', value: row }); diff --git a/lib/process/sandbox.js b/lib/process/sandbox.js index e6a38a739..d4efd0413 100644 --- a/lib/process/sandbox.js +++ b/lib/process/sandbox.js @@ -1,12 +1,14 @@ 'use strict'; +const { asyncSend } = require('./utils'); + module.exports = function(processFile, childPool) { return function process(job) { - return childPool.retain(processFile).then(child => { + return childPool.retain(processFile).then(async child => { let msgHandler; let exitHandler; - child.send({ + await asyncSend(child, { cmd: 'start', job: job }); diff --git a/lib/process/utils.js b/lib/process/utils.js index 240920f06..c5b8a1239 100644 --- a/lib/process/utils.js +++ b/lib/process/utils.js @@ -44,6 +44,27 @@ function killAsync(child, signal, timeoutMs) { return onExit; } +/* + asyncSend + Same as process.send but waits until the send is complete + the async version is used below because otherwise + the termination handler may exit before the parent + process has recived the messages it requires + */ + +const asyncSend = (proc, msg) => { + return new Promise((resolve, reject) => { + proc.send(msg, err => { + if (err) { + reject(err); + } else { + resolve(); + } + }); + }); +}; + module.exports = { - killAsync + killAsync, + asyncSend };