Skip to content

Commit

Permalink
fix: handle worker termination after worker exit
Browse files Browse the repository at this point in the history
  • Loading branch information
Robert Steilberg committed Jul 28, 2020
1 parent 17ccbfa commit 625ca14
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,9 @@ class Bree extends EventEmitter {
if (Number.isFinite(closeWorkerAfterMs) && closeWorkerAfterMs > 0) {
debug('worker has close set', name, closeWorkerAfterMs);
this.closeWorkerAfterMs[name] = setTimeout(() => {
this.workers[name].terminate();
if (this.workers[name]) {
this.workers[name].terminate();
}
}, closeWorkerAfterMs);
}

Expand Down
36 changes: 29 additions & 7 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,6 @@ test('run > job already running', (t) => {
});

test.serial('run > job terminates after set time', async (t) => {
// this test may fail sometimes due to timing issues.
const logger = _.cloneDeep(console);
logger.info = () => {};
logger.error = () => {};
Expand All @@ -425,22 +424,45 @@ test.serial('run > job terminates after set time', async (t) => {
logger
});

const clock = FakeTimers.install({ now: Date.now() });

bree.run('infinite');
t.true(typeof bree.closeWorkerAfterMs.infinite === 'object');

// eslint-disable-next-line no-new
new Promise((resolve, reject) => {
const listeners = new Promise((resolve, reject) => {
bree.workers.infinite.on('error', reject);
bree.workers.infinite.on('exit', (code) => {
t.true(code === 1);
resolve();
});
});
await clock.nextAsync();

clock.uninstall();
await delay(100);
await listeners;
});

test.serial('run > job terminates before set time', async (t) => {
const logger = _.cloneDeep(console);
logger.info = () => {};
logger.error = () => {};

const bree = new Bree({
root,
jobs: [{ name: 'basic', closeWorkerAfterMs: 150 }],
logger
});

bree.run('basic');
t.true(typeof bree.closeWorkerAfterMs.basic === 'object');

const listeners = new Promise((resolve, reject) => {
bree.workers.basic.on('error', reject);
bree.workers.basic.on('exit', (code) => {
t.true(code === 0);
resolve();
});
});

await delay(150);
await listeners;
});

test('run > job terminates on message "done"', async (t) => {
Expand Down

0 comments on commit 625ca14

Please sign in to comment.