-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
264 lines (216 loc) · 8.67 KB
/
client.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package http
import (
"context"
"fmt"
"io"
"net/http"
"time"
"github.com/hashicorp/go-retryablehttp"
"github.com/gsmcwhirter/go-util/v11/deferutil"
"github.com/gsmcwhirter/go-util/v11/errors"
"github.com/gsmcwhirter/go-util/v11/json"
"github.com/gsmcwhirter/go-util/v11/logging"
"github.com/gsmcwhirter/go-util/v11/telemetry"
)
type (
Request = retryablehttp.Request
ResponseHandlerFunc = retryablehttp.ResponseHandlerFunc
)
type RetryOptions struct {
RetryWaitMin time.Duration // Minimum time to wait
RetryWaitMax time.Duration // Maximum time to wait
RetryMax *int // Maximum number of retries
}
type HTTPResponseError struct { //nolint:revive // ok with stutter
Repsonse *http.Response
Body []byte
Cause error
}
func (e *HTTPResponseError) Error() string {
code := -1
if e.Repsonse != nil {
code = e.Repsonse.StatusCode
}
msg := fmt.Sprintf("HTTP Response Error: %d", code)
if e.Cause != nil {
msg += fmt.Sprintf(", cause=%v", e.Cause.Error())
}
return msg
}
//counterfeiter:generate . Client
type Client interface {
ConfigureRetries(opts RetryOptions)
GetJSON(ctx context.Context, target interface{}, reqURL string, opts ...ClientOpt) (*http.Response, error)
PostJSON(ctx context.Context, target interface{}, reqURL string, opts ...ClientOpt) (*http.Response, error)
PutJSON(ctx context.Context, target interface{}, reqURL string, opts ...ClientOpt) (*http.Response, error)
PatchJSON(ctx context.Context, target interface{}, reqURL string, opts ...ClientOpt) (*http.Response, error)
DeleteJSON(ctx context.Context, target interface{}, reqURL string, opts ...ClientOpt) (*http.Response, error)
RequestJSON(ctx context.Context, target interface{}, method, reqURL string, opts ...ClientOpt) (*http.Response, error)
GetBody(ctx context.Context, reqURL string, opts ...ClientOpt) ([]byte, *http.Response, error)
PostBody(ctx context.Context, reqURL string, opts ...ClientOpt) ([]byte, *http.Response, error)
PutBody(ctx context.Context, reqURL string, opts ...ClientOpt) ([]byte, *http.Response, error)
PatchBody(ctx context.Context, reqURL string, opts ...ClientOpt) ([]byte, *http.Response, error)
DeleteBody(ctx context.Context, reqURL string, opts ...ClientOpt) ([]byte, *http.Response, error)
RequestBody(ctx context.Context, method, reqURL string, opts ...ClientOpt) ([]byte, *http.Response, error)
}
type TelemeterClient struct {
client *retryablehttp.Client
telemeter *telemetry.Telemeter
telemeterOpts []telemetry.StartSpanOption
logger logging.Logger
}
var (
_ Client = (*TelemeterClient)(nil)
_ retryablehttp.LeveledLogger = (*HTTPLogger)(nil)
)
func NewTelemeterClient(logger logging.Logger, tel *telemetry.Telemeter, opts ...telemetry.StartSpanOption) *TelemeterClient {
client := retryablehttp.NewClient()
if client.HTTPClient.Transport == nil {
client.HTTPClient.Transport = http.DefaultTransport
}
rt := NewTelemeterRoundTripper(client.HTTPClient.Transport, tel, opts...)
client.HTTPClient.Transport = rt
client.Logger = &HTTPLogger{
Logger: logger,
}
return &TelemeterClient{
client: client,
telemeter: tel,
telemeterOpts: opts,
logger: logger,
}
}
func (c *TelemeterClient) ConfigureRetries(opts RetryOptions) {
if opts.RetryWaitMin > 0 {
c.client.RetryWaitMin = opts.RetryWaitMin
}
if opts.RetryWaitMax > 0 {
c.client.RetryWaitMax = opts.RetryWaitMax
}
if opts.RetryMax != nil && *opts.RetryMax >= 0 {
c.client.RetryMax = *opts.RetryMax
}
}
func (c *TelemeterClient) HTTPClient() *http.Client {
return c.client.StandardClient()
}
func (c *TelemeterClient) GetJSON(ctx context.Context, target interface{}, reqURL string, opts ...ClientOpt) (*http.Response, error) {
return c.RequestJSON(ctx, target, http.MethodGet, reqURL, opts...)
}
func (c *TelemeterClient) PostJSON(ctx context.Context, target interface{}, reqURL string, opts ...ClientOpt) (*http.Response, error) {
return c.RequestJSON(ctx, target, http.MethodPost, reqURL, opts...)
}
func (c *TelemeterClient) PutJSON(ctx context.Context, target interface{}, reqURL string, opts ...ClientOpt) (*http.Response, error) {
return c.RequestJSON(ctx, target, http.MethodPut, reqURL, opts...)
}
func (c *TelemeterClient) PatchJSON(ctx context.Context, target interface{}, reqURL string, opts ...ClientOpt) (*http.Response, error) {
return c.RequestJSON(ctx, target, http.MethodPatch, reqURL, opts...)
}
func (c *TelemeterClient) DeleteJSON(ctx context.Context, target interface{}, reqURL string, opts ...ClientOpt) (*http.Response, error) {
return c.RequestJSON(ctx, target, http.MethodDelete, reqURL, opts...)
}
func (c *TelemeterClient) RequestJSON(ctx context.Context, target interface{}, method, reqURL string, opts ...ClientOpt) (*http.Response, error) {
respHandlerFunc := func(httpResp *http.Response) error {
if httpResp.StatusCode < 400 {
err := json.UnmarshalFromReader(httpResp.Body, target)
return errors.Wrap(err, "could not unmarshal reponse")
}
return nil
}
opts = append(opts, WithResponseHandler(respHandlerFunc))
httpResp, err := c.prepareAndSendRequest(ctx, method, reqURL, opts)
if err != nil {
return httpResp, errors.Wrap(err, "could not prepareAndSendRequest")
}
logger := logging.WithContext(ctx, c.logger)
logger = logging.WithClientRequest(logger, httpResp.Request)
defer deferutil.CheckDeferLog(logger, httpResp.Body.Close)
if httpResp.StatusCode >= 400 {
body, errBody := io.ReadAll(httpResp.Body)
if errBody != nil {
logger.Err("could not read response body", errBody)
}
return httpResp, &HTTPResponseError{
Repsonse: httpResp,
Body: body,
}
}
return httpResp, nil
}
func (c *TelemeterClient) GetBody(ctx context.Context, reqURL string, opts ...ClientOpt) ([]byte, *http.Response, error) {
return c.RequestBody(ctx, http.MethodGet, reqURL, opts...)
}
func (c *TelemeterClient) PostBody(ctx context.Context, reqURL string, opts ...ClientOpt) ([]byte, *http.Response, error) {
return c.RequestBody(ctx, http.MethodPost, reqURL, opts...)
}
func (c *TelemeterClient) PutBody(ctx context.Context, reqURL string, opts ...ClientOpt) ([]byte, *http.Response, error) {
return c.RequestBody(ctx, http.MethodPut, reqURL, opts...)
}
func (c *TelemeterClient) PatchBody(ctx context.Context, reqURL string, opts ...ClientOpt) ([]byte, *http.Response, error) {
return c.RequestBody(ctx, http.MethodPatch, reqURL, opts...)
}
func (c *TelemeterClient) DeleteBody(ctx context.Context, reqURL string, opts ...ClientOpt) ([]byte, *http.Response, error) {
return c.RequestBody(ctx, http.MethodDelete, reqURL, opts...)
}
func (c *TelemeterClient) RequestBody(ctx context.Context, method, reqURL string, opts ...ClientOpt) ([]byte, *http.Response, error) {
var body []byte
respHandlerFunc := func(httpResp *http.Response) error {
if httpResp.StatusCode < 400 {
var err error
body, err = io.ReadAll(httpResp.Body)
return errors.Wrap(err, "could not read response body")
}
return nil
}
opts = append(opts, WithResponseHandler(respHandlerFunc))
httpResp, err := c.prepareAndSendRequest(ctx, method, reqURL, opts)
if err != nil {
return nil, httpResp, errors.Wrap(err, "could not prepareAndSendRequest")
}
logger := logging.WithContext(ctx, c.logger)
logger = logging.WithClientRequest(logger, httpResp.Request)
defer deferutil.CheckDeferLog(logger, httpResp.Body.Close)
if httpResp.StatusCode >= 400 {
errBody, errBodyRead := io.ReadAll(httpResp.Body)
if errBodyRead != nil {
logger.Err("could not read response body", errBodyRead)
}
return nil, httpResp, &HTTPResponseError{
Repsonse: httpResp,
Body: errBody,
}
}
return body, httpResp, nil
}
func (c *TelemeterClient) prepareAndSendRequest(ctx context.Context, method, reqURL string, opts []ClientOpt) (httpResp *http.Response, err error) {
ctx, span := c.telemeter.StartSpan(ctx, "http", "prepareAndSendRequest", c.telemeterOpts...)
defer span.End()
defer func() {
if httpResp != nil {
span.SetAttributes(telemetry.HTTPAttributesFromHTTPStatusCode(httpResp)...)
}
if err != nil {
span.SetStatus(telemetry.CodeError, err.Error())
} else if httpResp != nil {
code, reason := telemetry.SpanStatusFromHTTPStatusCode(httpResp.StatusCode)
span.SetStatus(code, reason)
}
}()
req, err := retryablehttp.NewRequestWithContext(ctx, method, reqURL, http.NoBody)
if err != nil {
return nil, errors.Wrap(err, "could not create request")
}
span.SetAttributes(
telemetry.HTTPClientAttributesFromHTTPRequest(req.Request)...,
)
for _, opt := range opts {
if err := opt(req); err != nil {
return nil, errors.Wrap(err, "could not apply request options")
}
}
httpResp, err = c.client.Do(req)
if err != nil {
return httpResp, errors.Wrap(err, "could not issue request")
}
return httpResp, nil
}