diff --git a/CHANGELOG.md b/CHANGELOG.md index 882b2c4e..c6684e72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ project adheres to [Semantic Versioning](http://semver.org/). ### Changed +- fix: avoid mutation bug in registry + ### Added ## [11.5.0] - 2019-06-04 diff --git a/lib/registry.js b/lib/registry.js index 4946cacc..515fd7b0 100644 --- a/lib/registry.js +++ b/lib/registry.js @@ -36,6 +36,12 @@ class Registry { let values = ''; for (const val of item.values || []) { val.labels = val.labels || {}; + + if (defaultLabelNames.length > 0) { + // Make a copy before mutating + val.labels = Object.assign({}, val.labels); + } + for (const labelName of defaultLabelNames) { val.labels[labelName] = val.labels[labelName] || this._defaultLabels[labelName]; diff --git a/test/registerTest.js b/test/registerTest.js index 64c6f109..2002349e 100644 --- a/test/registerTest.js +++ b/test/registerTest.js @@ -336,6 +336,46 @@ describe('register', () => { }); }); + describe('Registry with default labels', () => { + const Registry = require('../lib/registry'); + + it('should not throw with default labels', () => { + const r = new Registry(); + r.setDefaultLabels({ + env: 'development' + }); + + const hist = new Histogram({ + name: 'my_histogram', + help: 'my histogram', + registers: [r], + labelNames: ['type'] + }); + + const myHist = hist.labels('myType'); + + myHist.observe(1); + + const metrics = r.metrics(); + const lines = metrics.split('\n'); + expect( + lines.indexOf( + 'my_histogram_bucket{le="1",type="myType",env="development"} 1' + ) >= 0 + ).toEqual(true); + + myHist.observe(1); + + const metrics2 = r.metrics(); + const lines2 = metrics2.split('\n'); + expect( + lines2.indexOf( + 'my_histogram_bucket{le="1",type="myType",env="development"} 2' + ) >= 0 + ).toEqual(true); + }); + }); + describe('merging', () => { const Registry = require('../lib/registry'); let registryOne;