Skip to content

Commit

Permalink
fix: avoid calling fallback function twice (#198)
Browse files Browse the repository at this point in the history
  • Loading branch information
duartemendes committed May 29, 2018
1 parent 1a61f56 commit 68d3655
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
10 changes: 6 additions & 4 deletions lib/circuit.js
Original file line number Diff line number Diff line change
Expand Up @@ -355,10 +355,12 @@ class CircuitBreaker extends EventEmitter {
}
})
.catch(error => {
this.semaphore.release();
const latencyEndTime = Date.now() - latencyStartTime;
handleError(
error, this, timeout, args, latencyEndTime, resolve, reject);
if (!timeoutError) {
this.semaphore.release();
const latencyEndTime = Date.now() - latencyStartTime;
handleError(
error, this, timeout, args, latencyEndTime, resolve, reject);
}
});
} catch (error) {
this.semaphore.release();
Expand Down
19 changes: 19 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,24 @@ test('Passes error as last argument to the fallback function', t => {
breaker.fire(fails).catch(t.fail);
});

test('Fallback is not called twice for the same execution when action fails after timing out', t => {
t.plan(1);

const actionDuration = 200;
const breaker = circuit(timedFailingFunction, { timeout: actionDuration / 2 });

breaker.fallback((ms, err) => {
t.ok(err);
return Promise.reject(err);
});

breaker.fire(actionDuration)
.catch((err) => noop(err));

// keep this test alive until action finishes
setTimeout(() => noop, actionDuration);
});

test('Passes arguments to the fallback function', t => {
t.plan(1);
const fails = -1;
Expand Down Expand Up @@ -774,6 +792,7 @@ const identity = common.identity;
const passFail = common.passFail;
const slowFunction = common.slowFunction;
const timedFunction = common.timedFunction;
const timedFailingFunction = common.timedFailingFunction;
const nonPromise = common.nonPromise;
const callbackFunction = common.callbackFunction;
const failedCallbackFunction = common.failedCallbackFunction;

0 comments on commit 68d3655

Please sign in to comment.