Skip to content

Commit

Permalink
fix: do not close if preexisting task resolves when state is not OPEN (
Browse files Browse the repository at this point in the history
…#382)

The breaker would close if an earlier task resolved after a later one closed it.
This fixes that and adds a test case.
  • Loading branch information
tjenkinson authored and lance committed Oct 26, 2019
1 parent 7b97914 commit 7b92602
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/circuit.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,11 @@ class CircuitBreaker extends EventEmitter {
}

this.on('open', _startTimer(this));
this.on('success', _ => this.close());
this.on('success', _ => {
if (this.halfOpen) {
this.close();
}
});
if (this.options.cache) {
CACHE.set(this, undefined);
}
Expand Down
54 changes: 54 additions & 0 deletions test/closed-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
'use strict';

const test = require('tape');
const CircuitBreaker = require('../');

test(
'When closed, an existing request resolving does not reopen circuit',
t => {
t.plan(6);
const options = {
errorThresholdPercentage: 1,
resetTimeout: 60000
};

const breaker = new CircuitBreaker(function (shouldPass, time) {
return new Promise((resolve, reject) => {
const timer = setTimeout(
shouldPass
? () => resolve('success')
: () => reject(new Error('test-error')),
time || 0
);
if (typeof timer.unref === 'function') {
timer.unref();
}
});
}, options);

const promises = [];

promises.push(breaker.fire(true, 100)
.then(res => t.equals(res, 'success')));

promises.push(breaker.fire(false)
.then(t.fail)
.catch(e => {
t.equals(e.message, 'test-error');
})
.then(() => {
t.ok(breaker.opened, 'should be open after initial fire');
t.notOk(breaker.pendingClose,
'should not be pending close after initial fire');
}));

Promise.all(promises)
.then(() => {
t.ok(breaker.opened,
'should still be open even after first fire resolved');
t.notOk(breaker.pendingClose,
'should still not be pending close');
})
.then(() => t.end());
}
);

0 comments on commit 7b92602

Please sign in to comment.