-
Notifications
You must be signed in to change notification settings - Fork 568
/
dataService.ts
121 lines (107 loc) 路 2.82 KB
/
dataService.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import { Config, Provide, Scope, ScopeEnum } from '@midwayjs/core';
import * as Client from 'prom-client';
import { Master } from '../decorator/master';
import * as PromClient from 'prom-client';
@Provide()
@Scope(ScopeEnum.Singleton)
export class DataService {
responseSummary: Client.Summary<any>;
responseHistogram: Client.Histogram<any>;
userDefinedMetrics: any = {};
metrics: any;
@Config('prometheus')
prometheusConfig;
bInit = false;
async init() {
this.responseSummary = new Client.Summary({
name: 'http_request_latency_milliseconds',
help: 'response time in millis',
labelNames: [
'method',
'status',
'uri',
...Object.keys(this.prometheusConfig.labels),
],
});
this.responseHistogram = new Client.Histogram({
name: 'http_request_duration_milliseconds',
help: 'http_request_duration_milliseconds histogram',
labelNames: [
'method',
'status',
'uri',
...Object.keys(this.prometheusConfig.labels),
],
buckets: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],
});
}
@Master()
async getUser(method, status, path, time) {
if (!this.bInit) {
this.init();
this.bInit = true;
}
this.responseSummary
.labels(
method,
status,
path,
...(Object.values(this.prometheusConfig.labels) as string[])
)
.observe(time);
this.responseHistogram
.labels(
method,
status,
path,
...(Object.values(this.prometheusConfig.labels) as string[])
)
.observe(time);
}
define(name, type, options) {
options.labelNames = options.labelNames
? [...options.labelNames, ...Object.keys(this.prometheusConfig.labels)]
: Object.keys(this.prometheusConfig.labels);
this.userDefinedMetrics[name] = new Client[type](options);
}
@Master()
async inc(name, labels, value = 1) {
this.userDefinedMetrics[name].inc(
{ ...labels, ...this.prometheusConfig.labels },
value
);
}
@Master()
async observe(name, labels, value) {
this.userDefinedMetrics[name]
.labels(
...labels,
...(Object.values(this.prometheusConfig.labels) as string[])
)
.observe(value);
}
@Master()
async set(name, value) {
this.userDefinedMetrics[name].set(
{ ...this.prometheusConfig.labels },
value
);
}
@Master()
async setDiff(name, diff) {
const current = await this.userDefinedMetrics[name].get();
let value = diff;
if (current.values.length !== 0) {
value = current.values[0].value + diff;
}
this.userDefinedMetrics[name].set(
{ ...this.prometheusConfig.labels },
value
);
}
@Master()
async getData() {
const Register = PromClient.register;
return Register.metrics();
}
}