forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_interceptor.go
101 lines (85 loc) · 2.52 KB
/
api_interceptor.go
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
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package metric
import (
"context"
"net/http"
"time"
"github.com/gorilla/rpc/v2"
"github.com/prometheus/client_golang/prometheus"
"github.com/dim4egster/qmallgo/utils/wrappers"
)
type APIInterceptor interface {
InterceptRequest(i *rpc.RequestInfo) *http.Request
AfterRequest(i *rpc.RequestInfo)
}
type contextKey int
const requestTimestampKey contextKey = iota
type apiInterceptor struct {
requestDurationCount *prometheus.CounterVec
requestDurationSum *prometheus.GaugeVec
requestErrors *prometheus.CounterVec
}
func NewAPIInterceptor(namespace string, registerer prometheus.Registerer) (APIInterceptor, error) {
requestDurationCount := prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: namespace,
Name: "request_duration_count",
Help: "Number of times this type of request was made",
},
[]string{"method"},
)
requestDurationSum := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: namespace,
Name: "request_duration_sum",
Help: "Amount of time in nanoseconds that has been spent handling this type of request",
},
[]string{"method"},
)
requestErrors := prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: namespace,
Name: "request_error_count",
},
[]string{"method"},
)
errs := wrappers.Errs{}
errs.Add(
registerer.Register(requestDurationCount),
registerer.Register(requestDurationSum),
registerer.Register(requestErrors),
)
return &apiInterceptor{
requestDurationCount: requestDurationCount,
requestDurationSum: requestDurationSum,
requestErrors: requestErrors,
}, errs.Err
}
func (apr *apiInterceptor) InterceptRequest(i *rpc.RequestInfo) *http.Request {
ctx := i.Request.Context()
ctx = context.WithValue(ctx, requestTimestampKey, time.Now())
return i.Request.WithContext(ctx)
}
func (apr *apiInterceptor) AfterRequest(i *rpc.RequestInfo) {
timestampIntf := i.Request.Context().Value(requestTimestampKey)
timestamp, ok := timestampIntf.(time.Time)
if !ok {
return
}
durationMetricCount := apr.requestDurationCount.With(prometheus.Labels{
"method": i.Method,
})
durationMetricCount.Inc()
duration := time.Since(timestamp)
durationMetricSum := apr.requestDurationSum.With(prometheus.Labels{
"method": i.Method,
})
durationMetricSum.Add(float64(duration))
if i.Error != nil {
errMetric := apr.requestErrors.With(prometheus.Labels{
"method": i.Method,
})
errMetric.Inc()
}
}