Skip to content

Commit

Permalink
feat: optional timeout (nodeshift#200)
Browse files Browse the repository at this point in the history
  • Loading branch information
duartemendes committed Jun 4, 2018
1 parent 1a61f56 commit f6b63b2
Showing 1 changed file with 21 additions and 18 deletions.
39 changes: 21 additions & 18 deletions lib/circuit.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ Please use options.errorThresholdPercentage`;
* There are **no default options** when you use the constructor directly. You
* must supply values for each of these.
* @param options.timeout {Number} The time in milliseconds that action should
* be allowed to execute before timing out.
* be allowed to execute before timing out. Timeout can be disabled by setting
* this to `false`.
* @param options.maxFailures {Number} The number of times the circuit can fail
* before opening.
* (deprecated - see {CircuitBreaker#options.errorThresholdPercentage})
Expand Down Expand Up @@ -315,23 +316,25 @@ class CircuitBreaker extends EventEmitter {
return new Promise((resolve, reject) => {
const latencyStartTime = Date.now();
if (this.semaphore.test()) {
timeout = setTimeout(
() => {
timeoutError = true;
const error =
new Error(`Timed out after ${this.options.timeout}ms`);
error.code = 'ETIMEDOUT';
/**
* Emitted when the circuit breaker action takes longer than
* `options.timeout`
* @event CircuitBreaker#timeout
*/
const latency = Date.now() - latencyStartTime;
this.semaphore.release();
this.emit('timeout', error, latency);
resolve(handleError(
error, this, timeout, args, latency, resolve, reject));
}, this.options.timeout);
if (this.options.timeout) {
timeout = setTimeout(
() => {
timeoutError = true;
const error =
new Error(`Timed out after ${this.options.timeout}ms`);
error.code = 'ETIMEDOUT';
/**
* Emitted when the circuit breaker action takes longer than
* `options.timeout`
* @event CircuitBreaker#timeout
*/
const latency = Date.now() - latencyStartTime;
this.semaphore.release();
this.emit('timeout', error, latency);
resolve(handleError(
error, this, timeout, args, latency, resolve, reject));
}, this.options.timeout);
}

try {
const result = this.action.apply(this.action, args);
Expand Down

0 comments on commit f6b63b2

Please sign in to comment.