Skip to content

Commit

Permalink
feat: circuits now have a name based on the action
Browse files Browse the repository at this point in the history
The name of the circuit can be supplied as an option.

```js
const circuit = circuitBreaker(() => {}, { name: 'identity' });
```

If not option is provided, the name will be based on the action's name
if there is one.

```js
const square = (x) => x*x;
const circuit = circuitBreaker(square);
circuit.name // 'square'
```

If no option is provided, and the circuit's action is an anonymous
function, then a UUID is generated.
  • Loading branch information
lance committed Mar 8, 2017
1 parent 6c14b39 commit f08d46e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/circuit.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const PENDING_CLOSE = Symbol('pending-close');
const FALLBACK_FUNCTION = Symbol('fallback');
const NUM_FAILURES = Symbol('num-failures');
const STATUS = Symbol('status');
const NAME = Symbol('name');

/**
* @class CircuitBreaker
Expand Down Expand Up @@ -38,6 +39,7 @@ class CircuitBreaker extends EventEmitter {
this[FALLBACK_FUNCTION] = null;
this[PENDING_CLOSE] = false;
this[NUM_FAILURES] = 0;
this[NAME] = options.name || action.name || nextName();

if (typeof action !== 'function') this.action = () => this.Promise.resolve(action);
else this.action = action;
Expand Down Expand Up @@ -100,6 +102,10 @@ class CircuitBreaker extends EventEmitter {
}
}

get name () {
return this[NAME];
}

/**
* True if the circuit is currently closed. False otherwise.
*/
Expand Down Expand Up @@ -262,4 +268,12 @@ function fail (circuit, err, args) {
return circuit.Promise.reject.apply(null, [err]);
}

// http://stackoverflow.com/a/2117523
const nextName = () =>
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});

module.exports = exports = CircuitBreaker;
19 changes: 19 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,25 @@ test('api', (t) => {
t.end();
});

test('has a name based on the function name', (t) => {
const breaker = cb(passFail);
t.equals(breaker.name, passFail.name);
t.end();
});

test('accepts a name as an option', (t) => {
const breaker = cb(passFail, {name: 'tacoMachine'});
t.equals(breaker.name, 'tacoMachine');
t.end();
});

test('uses UUID as a name when none is provided and the function is anonymoys',
(t) => {
const breaker = cb((_) => _);
t.ok(breaker.name);
t.end();
});

test('Passes parameters to the circuit function', (t) => {
t.plan(1);
const expected = 34;
Expand Down

0 comments on commit f08d46e

Please sign in to comment.