summaryrefslogtreecommitdiff
path: root/u/trace/metric/metric.ts
blob: 8ef339fba0a32d736c7dda992435461cd88c590c (plain)
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
import { EmittableMetric, IMetric, IMetricTag, IResultMetric, Unit } from './index.js';

class _Tagged {
    protected constructor(public readonly _tag = IMetricTag) {}
}

export class Metric extends _Tagged implements IMetric {
    private static DELIM = '.';

    protected constructor(
        public readonly name: string,
        public readonly parent: undefined | IMetric = undefined,
        public readonly count = new EmittableMetric(Metric.join(name, 'count'), Unit.COUNT),
        public readonly time = new EmittableMetric(Metric.join(name, 'time'), Unit.MILLISECONDS),
    ) {
        super();
    }

    public child(_name: string): Metric {
        const childName = Metric.join(this.name, _name);
        return new Metric(childName, this);
    }

    public asResult() {
        return ResultMetric.from(this);
    }

    static join(...name: Array<string>) {
        return name.join(Metric.DELIM);
    }

    static fromName(name: string): Metric {
        return new Metric(name);
    }
}

export class ResultMetric extends Metric implements IResultMetric {
    protected constructor(
        public readonly name: string,
        public readonly parent: undefined | IMetric = undefined,
        public readonly failure: IMetric,
        public readonly success: IMetric,
        public readonly warn: IMetric,
    ) {
        super(name, parent);
    }

    static from(metric: Metric) {
        const failure = metric.child('failure');
        const success = metric.child('success');
        const warn = metric.child('warn');
        return new ResultMetric(metric.name, metric.parent, failure, success, warn);
    }
}