From 6c981e90ad11325e6342a477dc4be4a51adaa37d Mon Sep 17 00:00:00 2001 From: Wei Li Date: Thu, 15 Dec 2016 13:27:55 +0000 Subject: [PATCH] remove PENDING_CLOSE flag --- lib/circuit.js | 5 +---- test/test.js | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/lib/circuit.js b/lib/circuit.js index 9f1fc8e5..228a2c15 100644 --- a/lib/circuit.js +++ b/lib/circuit.js @@ -7,7 +7,6 @@ const STATE = Symbol('state'); const OPEN = Symbol('open'); const CLOSED = Symbol('closed'); const HALF_OPEN = Symbol('half-open'); -const PENDING_CLOSE = Symbol('pending-close'); const FALLBACK_FUNCTION = Symbol('fallback'); const NUM_FAILURES = Symbol('num-failures'); const STATUS = Symbol('status'); @@ -46,7 +45,6 @@ class CircuitBreaker extends EventEmitter { this[STATUS] = new Status(this); this[STATE] = CLOSED; this[FALLBACK_FUNCTION] = null; - this[PENDING_CLOSE] = false; this[NUM_FAILURES] = 0; function _startTimer (circuit) { @@ -139,12 +137,11 @@ class CircuitBreaker extends EventEmitter { this.emit('fire'); const args = Array.prototype.slice.call(arguments); - if (this.opened || (this.halfOpen && this[PENDING_CLOSE])) { + if (this.opened) { this.emit('reject'); return failFast(this, 'Breaker is open', args); } - this[PENDING_CLOSE] = this.halfOpen; return new this.Promise((resolve, reject) => { const timeout = setTimeout( () => { diff --git a/test/test.js b/test/test.js index ab727601..ff0a3263 100644 --- a/test/test.js +++ b/test/test.js @@ -332,6 +332,44 @@ test('CircuitBreaker events', (t) => { .catch(t.fail); }); +test('circuit halfOpen', (t) => { + const options = { + maxFailures: 1, + resetTimeout: 100 + }; + + const breaker = circuitBreaker(passFail, options); + breaker.fire(-1) + .catch((e) => t.equals(e, 'Error: -1 is < 0', 'function should fail')) + .then(() => { + t.ok(breaker.opened, 'breaker should be open'); + }) + .then(() => { + setTimeout(() => { + t.ok(breaker.halfOpen, 'breaker should be halfOpen'); + // breaker should be half open, fail it again should open the circuit again + breaker + .fire(-1) + .catch((e) => t.equals(e, 'Error: -1 is < 0', 'function should fail again')) + .then(() => { + t.ok(breaker.opened, 'breaker should be open again'); + setTimeout(() => { + t.ok(breaker.halfOpen, 'breaker should be halfOpen again'); + // breaker should be half open again and it should allow the original function to be called, and it should pass this time. + breaker + .fire(1) + .then((result) => { + t.equals(1, result); + t.ok(breaker.closed, 'breaker should be closed'); + t.end(); + }) + .catch(t.fail); + }, options.resetTimeout * 1.1); + }); + }, options.resetTimeout * 1.1); + }); +}); + /** * Returns a promise that resolves if the parameter * 'x' evaluates to >= 0. Otherwise the returned promise fails.