1
|
|
|
import addHooks from './helpers/add-hooks'; |
2
|
|
|
import findMetrics from './utils/find-metrics'; |
3
|
|
|
import findMetricsLabels from './utils/find-metrics-labels'; |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
a decorator to timing action execution time in both success/error cases |
7
|
|
|
and send metrics using the client attached in context |
8
|
|
|
*/ |
9
|
|
|
const metricsTimer = ({ extralabels = () => {}, count = false } = {}) => |
10
|
|
|
addHooks({ |
11
|
|
|
bypassHook: (p, m, { metrics }) => !metrics, |
12
|
|
|
storageHook: (param, meta, context, action) => { |
13
|
|
|
const { metrics } = context; |
14
|
|
|
const timer = findMetrics({ action, type: 'timer', metrics }); |
15
|
|
|
const labels = findMetricsLabels({ |
16
|
|
|
metric: timer, |
17
|
|
|
source: meta, |
18
|
|
|
extra: extralabels(param, meta, context), |
19
|
|
|
}); |
20
|
|
|
const stopTimer = timer.startTimer(labels); |
21
|
|
|
const countStart = () => |
22
|
|
|
count |
23
|
|
|
? findMetrics({ action, type: 'start', metrics }).inc(labels, 1) |
24
|
|
|
: undefined; |
25
|
|
|
const countSuccess = () => |
26
|
|
|
count |
27
|
|
|
? findMetrics({ |
28
|
|
|
action, |
29
|
|
|
type: 'success', |
30
|
|
|
metrics, |
31
|
|
|
}).inc(labels, 1) |
32
|
|
|
: undefined; |
33
|
|
|
const countError = () => |
34
|
|
|
count |
35
|
|
|
? findMetrics({ action, type: 'error', metrics }).inc(labels, 1) |
36
|
|
|
: undefined; |
37
|
|
|
return { countStart, countSuccess, countError, stopTimer }; |
38
|
|
|
}, |
39
|
|
|
beforeHook: (p, m, c, a, { countStart }) => countStart(), |
40
|
|
|
afterHook: (r, p, m, c, a, { countSuccess, stopTimer }) => { |
41
|
|
|
stopTimer(); |
42
|
|
|
countSuccess(); |
43
|
|
|
}, |
44
|
|
|
errorHook: (e, p, m, c, a, { countError, stopTimer }) => { |
45
|
|
|
stopTimer(); |
46
|
|
|
countError(); |
47
|
|
|
}, |
48
|
|
|
}); |
49
|
|
|
|
50
|
|
|
export default metricsTimer; |
51
|
|
|
|