-
Notifications
You must be signed in to change notification settings - Fork 4
/
counter.ts
83 lines (76 loc) · 2.01 KB
/
counter.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
import { Collector } from "./collector.ts";
import { Inc, Labels, Metric, Value } from "./metric.ts";
import { Registry } from "./registry.ts";
export class Counter extends Metric implements Inc, Value {
private collector: Collector;
private _value?: number;
static with(
config: {
name: string;
help: string;
labels?: string[];
registry?: Registry[];
},
): Counter {
const collector = new Collector(
config.name,
config.help,
"counter",
config.registry,
);
const labels = config.labels || [];
return new Counter(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 & Value {
let child = new Counter(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 Counter;
return {
// deno-lint-ignore no-inferrable-types
inc: (n: number = 1) => {
child.inc(n);
},
value: () => {
return child._value;
},
};
}
// deno-lint-ignore no-inferrable-types
inc(n: number = 1) {
if (n < 0) {
throw new Error("it is not possible to deacrease a counter");
}
if (this._value === undefined) {
this._value = 0;
}
this._value += n;
}
value(): number | undefined {
return this._value;
}
}