-
Notifications
You must be signed in to change notification settings - Fork 0
/
cliex.go
415 lines (363 loc) · 11.7 KB
/
cliex.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
package cliex
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"math"
"math/rand/v2"
"net/http"
"strconv"
"strings"
"time"
"github.com/go-resty/resty/v2"
jsoniter "github.com/json-iterator/go"
"github.com/maxbolgarin/abstract"
"github.com/maxbolgarin/lang"
"github.com/sony/gobreaker/v2"
)
// HTTP is the resty wrapper for easy use.
type HTTP struct {
cli *resty.Client
cbs *abstract.SafeMap[string, *gobreaker.CircuitBreaker[*resty.Response]]
log Logger
cbCfg gobreaker.Settings
enableCB bool
}
// New returns a new HTTP client weith applied With* options to Config.
func New(optsFuncs ...func(*Config)) (*HTTP, error) {
var cfg Config
for _, optsFunc := range optsFuncs {
optsFunc(&cfg)
}
return NewWithConfig(cfg)
}
// MustNew returns a new HTTP client inited with provided config.
// Panics if an error occurs.
func MustNew(optsFuncs ...func(*Config)) *HTTP {
cli, err := New(optsFuncs...)
if err != nil {
panic(err)
}
return cli
}
// NewWithConfig returns a new HTTP client inited with provided config.
func NewWithConfig(cfg Config) (*HTTP, error) {
if err := cfg.prepareAndValidate(); err != nil {
return nil, err
}
cli := resty.New().
SetBaseURL(cfg.BaseURL).
SetLogger(cfg.RestyLogger).
SetHeader("User-Agent", cfg.UserAgent).
SetTimeout(cfg.RequestTimeout).
SetJSONMarshaler(jsoniter.ConfigCompatibleWithStandardLibrary.Marshal).
SetJSONUnmarshaler(jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal).
SetTLSClientConfig(&tls.Config{InsecureSkipVerify: cfg.Insecure}).
SetRedirectPolicy(resty.FlexibleRedirectPolicy(20)).
SetAllowGetMethodPayload(true).
SetDebug(cfg.Debug).
OnAfterResponse(errorHandler)
if cfg.AuthToken != "" {
cli.SetHeader("Authorization", cfg.AuthToken)
}
if cfg.ProxyAddress != "" {
cli.SetProxy(cfg.ProxyAddress)
}
if len(cfg.CAFiles) > 0 {
for _, caFile := range cfg.CAFiles {
cli.SetRootCertificate(caFile)
}
}
if cfg.ClientCertFile != "" && cfg.ClientKeyFile != "" {
cert1, err := tls.LoadX509KeyPair(cfg.ClientCertFile, cfg.ClientKeyFile)
if err != nil {
return nil, err
}
cli.SetCertificates(cert1)
}
out := &HTTP{
cli: cli,
cbs: abstract.NewSafeMap[string, *gobreaker.CircuitBreaker[*resty.Response]](),
log: cfg.Logger,
cbCfg: gobreaker.Settings{
Name: "HTTP Circuit Breaker",
Timeout: cfg.CircuitBreakerTimeout,
ReadyToTrip: func(counts gobreaker.Counts) bool {
return counts.ConsecutiveFailures >= cfg.CircuitBreakerFailures
},
},
enableCB: cfg.CircuitBreaker,
}
return out, nil
}
// C returns the resty client.
func (c *HTTP) C() *resty.Client {
return c.cli
}
// R returns the resty request with applied context.
func (c *HTTP) R(ctx context.Context) *resty.Request {
return c.cli.R().SetContext(ctx)
}
// Request makes HTTP request with the given options to the BaseURL + URL and returns response.
// It also applies circuit breaker if enabled.
func (c *HTTP) Request(ctx context.Context, url string, opts RequestOpts) (*resty.Response, error) {
if !c.enableCB {
return c.request(ctx, url, opts)
}
cb, ok := c.cbs.Lookup(url)
if !ok {
cb = gobreaker.NewCircuitBreaker[*resty.Response](c.cbCfg)
c.cbs.Set(url, cb)
}
resp, err := cb.Execute(func() (*resty.Response, error) {
return c.request(ctx, url, opts)
})
switch {
case errors.Is(err, gobreaker.ErrOpenState):
return nil, ErrCBOpenState
case errors.Is(err, gobreaker.ErrTooManyRequests):
return nil, ErrCBTooManyRequests
case err != nil:
return nil, err
}
return resp, nil
}
func (c *HTTP) request(ctx context.Context, url string, opts RequestOpts) (*resty.Response, error) {
req := c.R(ctx).SetBody(opts.Body).SetResult(opts.Result).SetAuthToken(opts.AuthToken).
SetHeaders(opts.Headers).SetQueryParams(opts.Query).SetCookies(opts.Cookies).
ForceContentType(opts.ForceContentType).SetFormData(opts.FormData)
if opts.BasicAuthUser != "" && opts.BasicAuthPass != "" {
req.SetBasicAuth(opts.BasicAuthUser, opts.BasicAuthPass)
}
if opts.EnableTrace {
req.EnableTrace()
}
if opts.Files != nil {
req.SetFiles(opts.Files)
}
if opts.OutputPath != "" {
req.SetOutput(opts.OutputPath)
}
opts.RequestName = lang.If(opts.RequestName != "", opts.RequestName+" ", "")
sender := getSender(req, opts.Method)
url = c.prepareURL(url)
resp, err := sender(url)
switch {
case err == nil:
return resp, nil
case (opts.RetryCount == 0 && !opts.InfiniteRetry) || (opts.RetryOnlyServerErrors && !IsServerError(err)):
return nil, fmt.Errorf("failed %srequest: %w", opts.RequestName, err)
}
// Start retry
opts.RetryCount = lang.If(opts.InfiniteRetry, math.MaxInt, opts.RetryCount)
opts.RetryWaitTime = lang.Check(opts.RetryWaitTime, defaultWaitTime)
opts.RetryMaxWaitTime = lang.Check(opts.RetryMaxWaitTime, defaultMaxWaitTime)
if !opts.NoLogRetryError {
msg := "failed " + opts.RequestName + "request, "
if opts.InfiniteRetry {
msg += "infinite retry"
} else {
msg += strconv.Itoa(opts.RetryCount) + " retries"
}
c.log.Error(msg, "error", err, "address", c.cli.BaseURL+url)
}
errs := abstract.NewSet[string]()
for retry := 1; retry < opts.RetryCount; retry++ {
sleepTime := getSleepTime(retry, opts.RetryWaitTime, opts.RetryMaxWaitTime)
select {
case <-ctx.Done():
return nil, fmt.Errorf("request canceled after %d retries, got errors: %s", retry, errors.Join(lang.Convert(errs.Values(), func(err string) error {
return errors.New(err)
})...))
case <-time.After(sleepTime):
}
resp, err = sender(url)
if err != nil {
if !opts.NoLogRetryError {
c.log.Warn("failed "+opts.RequestName+"request after retry", "error", err, "n", retry, "address", c.cli.BaseURL+url)
}
errs.Add(err.Error())
continue
}
return resp, nil
}
return nil, fmt.Errorf("failed %srequest after %d retries, got errors: %s", opts.RequestName, opts.RetryCount,
errors.Join(lang.Convert(errs.Values(), func(err string) error {
return errors.New(err)
})...))
}
// Req performs request with method to the BaseURL + URL and returns response
func (c *HTTP) Req(ctx context.Context, method string, url string, requestAndResponseBody ...any) (*resty.Response, error) {
return c.Request(ctx, url, RequestOpts{
Method: method,
Body: lang.First(requestAndResponseBody),
Result: lang.Index(requestAndResponseBody, 1)})
}
// Get performs GET request to the BaseURL + URL and returns response
func (c *HTTP) Get(ctx context.Context, url string, responseBody ...any) (*resty.Response, error) {
return c.Request(ctx, url, RequestOpts{
Result: lang.First(responseBody)})
}
// GetQ performs GET request to the BaseURL + URL with query and returns response
func (c *HTTP) GetQ(ctx context.Context, url string, responseBody any, queryPairs ...string) (*resty.Response, error) {
return c.Request(ctx, url, RequestOpts{
Result: responseBody,
Query: lang.PairsToMap(queryPairs)})
}
// Post performs POST request to the BaseURL + URL and returns response
func (c *HTTP) Post(ctx context.Context, url string, requestBody any, responseBody ...any) (*resty.Response, error) {
return c.Request(ctx, url, RequestOpts{
Method: http.MethodPost,
Body: requestBody,
Result: lang.First(responseBody)})
}
// PostQ performs POST request to the BaseURL + URL with query and returns response
func (c *HTTP) PostQ(ctx context.Context, url string, requestBody any, responseBody any, queryPairs ...string) (*resty.Response, error) {
return c.Request(ctx, url, RequestOpts{
Method: http.MethodPost,
Body: requestBody,
Result: responseBody,
Query: lang.PairsToMap(queryPairs)})
}
// Put performs PUT request to the BaseURL + URL and returns response
func (c *HTTP) Put(ctx context.Context, url string, requestBody any, responseBody ...any) (*resty.Response, error) {
return c.Request(ctx, url, RequestOpts{
Method: http.MethodPut,
Body: requestBody,
Result: lang.First(responseBody)})
}
// PutQ performs PUT request to the BaseURL + URL with query and returns response
func (c *HTTP) PutQ(ctx context.Context, url string, requestBody any, responseBody any, queryPairs ...string) (*resty.Response, error) {
return c.Request(ctx, url, RequestOpts{
Method: http.MethodPut,
Body: requestBody,
Result: responseBody,
Query: lang.PairsToMap(queryPairs)})
}
// Patch performs PATCH request to the BaseURL + URL and returns response
func (c *HTTP) Patch(ctx context.Context, url string, requestBody any, responseBody ...any) (*resty.Response, error) {
return c.Request(ctx, url, RequestOpts{
Method: http.MethodPatch,
Body: requestBody,
Result: lang.First(responseBody)})
}
// PatchQ performs PATCH request to the BaseURL + URL with query and returns response
func (c *HTTP) PatchQ(ctx context.Context, url string, requestBody any, responseBody any, queryPairs ...string) (*resty.Response, error) {
return c.Request(ctx, url, RequestOpts{
Method: http.MethodPatch,
Body: requestBody,
Result: responseBody,
Query: lang.PairsToMap(queryPairs)})
}
// Delete performs DELETE request to the BaseURL + URL and returns response
func (c *HTTP) Delete(ctx context.Context, url string, responseBody ...any) (*resty.Response, error) {
return c.Request(ctx, url, RequestOpts{
Method: http.MethodDelete,
Result: lang.First(responseBody)})
}
// DeleteQ performs DELETE request to the BaseURL + URL with query and returns response
func (c *HTTP) DeleteQ(ctx context.Context, url string, responseBody any, queryPairs ...string) (*resty.Response, error) {
return c.Request(ctx, url, RequestOpts{
Method: http.MethodDelete,
Result: responseBody,
Query: lang.PairsToMap(queryPairs)})
}
func (c *HTTP) prepareURL(url string) string {
if c.cli.BaseURL == "" && !strings.HasPrefix(url, "http") {
return "http://" + url
}
return url
}
func errorHandler(_ *resty.Client, r *resty.Response) error {
if r.StatusCode() < 400 {
return nil
}
apiErr, ok := ErrorMapping[r.StatusCode()]
if !ok {
apiErr = fmt.Errorf("code %d", r.StatusCode())
}
var errBody ServerErrorResponse
if err := json.Unmarshal(r.Body(), &errBody); err == nil {
errMsg := getErrorMessage(errBody)
if errBody.Code != 0 {
apiErr = lang.Check(ErrorMapping[errBody.Code], apiErr)
}
if errMsg != "" {
return fmt.Errorf("%w: %s", apiErr, errMsg)
}
}
if body := string(r.Body()); body != "" {
return fmt.Errorf("%w: %s", apiErr, maxLen(body, 100))
}
return apiErr
}
func maxLen(a string, b int) string {
if len(a) > b {
return a[:b]
}
return a
}
func getSleepTime(retry int, min, max time.Duration) time.Duration {
sleepTime := float64(min) * math.Pow(2, float64(retry))
sleepTime = rand.Float64()*(sleepTime-float64(min)) + float64(min)
if sleepTime > float64(max) {
sleepTime = float64(max)
}
return time.Duration(sleepTime)
}
func getSender(r *resty.Request, method string) func(string) (*resty.Response, error) {
switch method {
case http.MethodGet, "":
return r.Get
case http.MethodHead:
return r.Head
case http.MethodPost:
return r.Post
case http.MethodPut:
return r.Put
case http.MethodPatch:
return r.Patch
case http.MethodDelete:
return r.Delete
case http.MethodOptions:
return r.Options
}
return r.Get
}
func getErrorMessage(r ServerErrorResponse) string {
if r.Message != "" {
return r.Message
}
if r.Error != "" {
return r.Error
}
if r.Details != "" {
return r.Details
}
if r.Text != "" {
return r.Text
}
if r.Msg != "" {
return r.Msg
}
if r.Err != "" {
return r.Err
}
return ""
}
// IsServerError returns true if the error is a server error (5xx).
func IsServerError(err error) bool {
return err != nil && strings.Contains(err.Error(), "code 5")
}
// GetCodeFromError returns the error code from the error message.
func GetCodeFromError(err error) int {
errStr := err.Error()
index := strings.Index(errStr, "code ")
if index == -1 {
return 0
}
code, _ := strconv.Atoi(errStr[index+5 : index+8])
return code
}