Skip to content

Commit 83cb173

Browse files
dapplionzbjornson
authored andcommitted
In gauge.inc/dec, default to 1 only if no arg is passed
Calling `.inc(value)` with a dynamic value that may be 0 or 1 will always cause to increase metrics by 1. This is very problematic and may distort the metrics in a non obvious way
1 parent a972f0c commit 83cb173

File tree

3 files changed

+15
-2
lines changed

3 files changed

+15
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ project adheres to [Semantic Versioning](http://semver.org/).
1919
### Added
2020

2121
- feat: added `zero()` to `Histogram` for setting the metrics for a given label combination to zero
22+
- fix: allow `Gauge.inc/dec(0)` without defaulting to 1
2223

2324
## [13.1.0] - 2021-01-24
2425

lib/gauge.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -146,14 +146,16 @@ function startTimer(startLabels) {
146146
function dec(labels) {
147147
return value => {
148148
const data = convertLabelsAndValues(labels, value);
149-
this.set(data.labels, this._getValue(data.labels) - (data.value || 1));
149+
if (data.value === undefined) data.value = 1;
150+
this.set(data.labels, this._getValue(data.labels) - data.value);
150151
};
151152
}
152153

153154
function inc(labels) {
154155
return value => {
155156
const data = convertLabelsAndValues(labels, value);
156-
this.set(data.labels, this._getValue(data.labels) + (data.value || 1));
157+
if (data.value === undefined) data.value = 1;
158+
this.set(data.labels, this._getValue(data.labels) + data.value);
157159
};
158160
}
159161

test/gaugeTest.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,16 @@ describe('gauge', () => {
4141
await expectValue(5);
4242
});
4343

44+
it('should set to exactly zero without defaulting to 1', async () => {
45+
instance.set(0);
46+
await expectValue(0);
47+
});
48+
49+
it('should inc by zero without defaulting to 1', async () => {
50+
instance.inc(0);
51+
await expectValue(10);
52+
});
53+
4454
it('should start a timer and set a gauge to elapsed in seconds', async () => {
4555
jest.useFakeTimers('modern');
4656
jest.setSystemTime(0);

0 commit comments

Comments
 (0)