Skip to content

Commit

Permalink
feat: add function to get metrics for all circuits (#328)
Browse files Browse the repository at this point in the history
feat: add function to get metrics for all circuits

Prior to this, it was only possible to get metrics from the circuit itself. And if multiple circuits were created, the last one would have all metrics available, which isn't very intuitive. It makes more sense to obtain metrics for all circuits from the factory.

Fixes: #327
  • Loading branch information
lance authored Jun 12, 2019
1 parent f8918c4 commit ff29f2e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
17 changes: 16 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const CircuitBreaker = require('./lib/circuit');
const circuits = [];

const defaults = {
timeout: 10000, // 10 seconds
Expand Down Expand Up @@ -63,7 +64,10 @@ const defaults = {
* @return {CircuitBreaker} a newly created {@link CircuitBreaker} instance
*/
function factory (action, options) {
return new CircuitBreaker(action, Object.assign({}, defaults, options));
const circuit = new CircuitBreaker(action,
Object.assign({}, defaults, options));
circuits.push(circuit);
return circuit;
}

/**
Expand All @@ -80,6 +84,17 @@ function factory (action, options) {
* const breaker = circuitBreaker(readFilePromised);
*/
factory.promisify = require('./lib/promisify');

/**
* Get the Prometheus metrics for all circuits.
* @function factory.metrics
* @return {String} the metrics for all circuits
*/
factory.metrics = function metrics() {
const lastCircuit = circuits[circuits.length - 1];
if (lastCircuit.metrics) return lastCircuit.metrics.metrics;
}

let warningIssued = false;
Object.defineProperty(factory, 'stats', {
get: _ => {
Expand Down
11 changes: 11 additions & 0 deletions test/prometheus-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ test('Does not load Prometheus when the option is not provided', t => {
t.end();
});

test('The factory function provides access to metrics for all circuits', t => {
t.plan(4);
const c1 = cb(passFail, { usePrometheus: true, name: 'fred' });
const c2 = cb(passFail, { usePrometheus: true, name: 'bob' });
t.equal(c1.name, 'fred');
t.equal(c2.name, 'bob');
t.ok(/circuit_fred_/.test(cb.metrics()));
t.ok(/circuit_bob_/.test(cb.metrics()));
t.end();
});


// All of the additional tests only make sense when running in a Node.js context
if (!process.env.WEB) {
Expand Down

0 comments on commit ff29f2e

Please sign in to comment.