generated from NdoleStudio/go-http-client
-
Notifications
You must be signed in to change notification settings - Fork 2
/
round_tripper.go
234 lines (202 loc) · 7.27 KB
/
round_tripper.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
package otelroundtripper
import (
"context"
"errors"
"go.opentelemetry.io/otel/attribute"
api "go.opentelemetry.io/otel/metric"
semconv "go.opentelemetry.io/otel/semconv/v1.18.0"
"net"
"net/http"
"strings"
"time"
)
type otelHTTPMetrics struct {
attemptsCounter api.Int64Counter
noRequestCounter api.Int64Counter
errorsCounter api.Int64Counter
successesCounter api.Int64Counter
failureCounter api.Int64Counter
redirectCounter api.Int64Counter
timeoutsCounter api.Int64Counter
canceledCounter api.Int64Counter
deadlineExceededCounter api.Int64Counter
totalDurationCounter api.Int64Histogram
inFlightCounter api.Int64UpDownCounter
}
// otelRoundTripper is the http.RoundTripper which emits open telemetry metrics
type otelRoundTripper struct {
parent http.RoundTripper
attributes []attribute.KeyValue
metrics otelHTTPMetrics
}
// New creates a new instance of the http.RoundTripper
func New(options ...Option) http.RoundTripper {
cfg := defaultConfig()
for _, option := range options {
option.apply(cfg)
}
return &otelRoundTripper{
parent: cfg.parent,
attributes: cfg.attributes,
metrics: otelHTTPMetrics{
noRequestCounter: mustCounter(cfg.meter.Int64Counter(cfg.name + ".no_request")),
errorsCounter: mustCounter(cfg.meter.Int64Counter(cfg.name + ".errors")),
successesCounter: mustCounter(cfg.meter.Int64Counter(cfg.name + ".success")),
timeoutsCounter: mustCounter(cfg.meter.Int64Counter(cfg.name + ".timeouts")),
canceledCounter: mustCounter(cfg.meter.Int64Counter(cfg.name + ".cancelled")),
deadlineExceededCounter: mustCounter(cfg.meter.Int64Counter(cfg.name + ".deadline_exceeded")),
totalDurationCounter: mustHistogram(cfg.meter.Int64Histogram(cfg.name + ".total_duration")),
inFlightCounter: mustUpDownCounter(cfg.meter.Int64UpDownCounter(cfg.name + ".in_flight")),
attemptsCounter: mustCounter(cfg.meter.Int64Counter(cfg.name + ".attempts")),
failureCounter: mustCounter(cfg.meter.Int64Counter(cfg.name + ".failures")),
redirectCounter: mustCounter(cfg.meter.Int64Counter(cfg.name + ".redirects")),
},
}
}
func mustCounter(counter api.Int64Counter, err error) api.Int64Counter {
if err != nil {
panic(err)
}
return counter
}
func mustUpDownCounter(counter api.Int64UpDownCounter, err error) api.Int64UpDownCounter {
if err != nil {
panic(err)
}
return counter
}
func mustHistogram(histogram api.Int64Histogram, err error) api.Int64Histogram {
if err != nil {
panic(err)
}
return histogram
}
// RoundTrip executes a single HTTP transaction, returning a Response for the provided Request.
func (roundTripper *otelRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
ctx := roundTripper.extractCtx(request)
attributes := roundTripper.requestAttributes(request)
roundTripper.beforeHook(ctx, attributes, request)
start := time.Now()
response, err := roundTripper.parent.RoundTrip(request)
duration := time.Since(start).Milliseconds()
if err != nil {
roundTripper.errorHook(ctx, err, attributes)
return response, err
}
attributes = roundTripper.responseAttributes(attributes, response)
roundTripper.afterHook(ctx, duration, attributes)
if roundTripper.isRedirection(response) {
roundTripper.redirectHook(ctx, attributes)
return response, err
}
if roundTripper.isFailure(response) {
roundTripper.failureHook(ctx, attributes)
return response, err
}
roundTripper.successHook(ctx, attributes)
return response, err
}
func (roundTripper *otelRoundTripper) isFailure(response *http.Response) bool {
if response == nil {
return false
}
return response.StatusCode >= http.StatusBadRequest
}
func (roundTripper *otelRoundTripper) isRedirection(response *http.Response) bool {
if response == nil {
return false
}
return response.StatusCode >= http.StatusMultipleChoices && response.StatusCode < http.StatusBadRequest
}
func (roundTripper *otelRoundTripper) failureHook(
ctx context.Context,
attributes []attribute.KeyValue,
) {
roundTripper.metrics.inFlightCounter.Add(ctx, -1, api.WithAttributes(attributes...))
roundTripper.metrics.failureCounter.Add(ctx, 1, api.WithAttributes(attributes...))
}
func (roundTripper *otelRoundTripper) redirectHook(
ctx context.Context,
attributes []attribute.KeyValue,
) {
roundTripper.metrics.inFlightCounter.Add(ctx, -1, api.WithAttributes(attributes...))
roundTripper.metrics.redirectCounter.Add(ctx, 1, api.WithAttributes(attributes...))
}
func (roundTripper *otelRoundTripper) successHook(
ctx context.Context,
attributes []attribute.KeyValue,
) {
roundTripper.metrics.inFlightCounter.Add(ctx, -1, api.WithAttributes(attributes...))
roundTripper.metrics.successesCounter.Add(ctx, 1, api.WithAttributes(attributes...))
}
func (roundTripper *otelRoundTripper) beforeHook(
ctx context.Context,
attributes []attribute.KeyValue,
request *http.Request,
) {
roundTripper.metrics.inFlightCounter.Add(ctx, 1, api.WithAttributes(attributes...))
roundTripper.metrics.attemptsCounter.Add(ctx, 1, api.WithAttributes(attributes...))
if request == nil {
roundTripper.metrics.noRequestCounter.Add(ctx, 1, api.WithAttributes(attributes...))
}
}
func (roundTripper *otelRoundTripper) afterHook(
ctx context.Context,
duration int64,
attributes []attribute.KeyValue,
) {
roundTripper.metrics.totalDurationCounter.Record(ctx, duration, api.WithAttributes(attributes...))
}
func (roundTripper *otelRoundTripper) responseAttributes(
attributes []attribute.KeyValue,
response *http.Response,
) []attribute.KeyValue {
return append(
append([]attribute.KeyValue{}, attributes...),
roundTripper.extractResponseAttributes(response)...,
)
}
func (roundTripper *otelRoundTripper) requestAttributes(request *http.Request) []attribute.KeyValue {
return append(
append(
[]attribute.KeyValue{},
roundTripper.attributes...,
),
roundTripper.extractRequestAttributes(request)...,
)
}
func (roundTripper *otelRoundTripper) errorHook(ctx context.Context, err error, attributes []attribute.KeyValue) {
roundTripper.metrics.inFlightCounter.Add(ctx, -1, api.WithAttributes(attributes...))
roundTripper.metrics.errorsCounter.Add(ctx, 1, api.WithAttributes(attributes...))
var timeoutErr net.Error
if errors.As(err, &timeoutErr) && timeoutErr.Timeout() {
roundTripper.metrics.timeoutsCounter.Add(ctx, 1, api.WithAttributes(attributes...))
}
if strings.HasSuffix(err.Error(), context.Canceled.Error()) {
roundTripper.metrics.canceledCounter.Add(ctx, 1, api.WithAttributes(attributes...))
}
}
func (roundTripper *otelRoundTripper) extractResponseAttributes(response *http.Response) []attribute.KeyValue {
if response != nil {
return []attribute.KeyValue{
semconv.HTTPStatusCodeKey.Int(response.StatusCode),
semconv.HTTPFlavorKey.String(response.Proto),
}
}
return nil
}
func (roundTripper *otelRoundTripper) extractRequestAttributes(request *http.Request) []attribute.KeyValue {
if request != nil {
return []attribute.KeyValue{
semconv.HTTPURLKey.String(request.URL.String()),
semconv.HTTPMethodKey.String(request.Method),
}
}
return nil
}
func (roundTripper *otelRoundTripper) extractCtx(request *http.Request) context.Context {
if request != nil && request.Context() != nil {
return request.Context()
}
return context.Background()
}