-
Notifications
You must be signed in to change notification settings - Fork 4
/
gauge.ts
99 lines (90 loc) · 2.3 KB
/
gauge.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { Collector } from "./collector.ts";
import { Dec, Inc, Labels, Metric, Set, Value } from "./metric.ts";
import { Registry } from "./registry.ts";
export class Gauge extends Metric implements Inc, Dec, Value {
private collector: Collector;
private _value?: number;
static with(
config: {
name: string;
help: string;
labels?: string[];
registry?: Registry[];
},
): Gauge {
const collector = new Collector(
config.name,
config.help,
"gauge",
config.registry,
);
const labels = config.labels || [];
return new Gauge(collector, labels);
}
private constructor(
collector: Collector,
labels: string[] = [],
) {
super(labels, new Array(labels.length).fill(undefined));
this.collector = collector;
this._value = undefined;
this.collector.getOrSetMetric(this);
}
get description(): string {
const labels = this.getLabelsAsString();
return `${this.collector.name}${labels}`;
}
expose(): string | undefined {
if (this._value !== undefined) {
return `${this.description} ${this._value}`;
}
return undefined;
}
labels(labels: Labels): Inc & Dec & Set & Value {
let child = new Gauge(this.collector, this.labelNames);
for (const key of Object.keys(labels)) {
const index = child.labelNames.indexOf(key);
if (index === -1) {
throw new Error(`label with name ${key} not defined`);
}
child.labelValues[index] = labels[key];
}
child = child.collector.getOrSetMetric(child) as Gauge;
return {
// deno-lint-ignore no-inferrable-types
inc: (n: number = 1) => {
child.inc(n);
},
// deno-lint-ignore no-inferrable-types
dec: (n: number = 1) => {
child.dec(n);
},
set: (n: number) => {
child.set(n);
},
value: () => {
return child._value;
},
};
}
// deno-lint-ignore no-inferrable-types
inc(n: number = 1) {
if (this._value === undefined) {
this._value = 0;
}
this._value += n;
}
// deno-lint-ignore no-inferrable-types
dec(n: number = 1) {
if (this._value === undefined) {
this._value = 0;
}
this._value -= n;
}
set(n: number) {
this._value = n;
}
value(): number | undefined {
return this._value;
}
}