|
7 | 7 | "strings" |
8 | 8 | "time" |
9 | 9 |
|
10 | | - "k8s.io/apimachinery/pkg/util/wait" |
| 10 | + "github.com/cenkalti/backoff/v4" |
11 | 11 | ) |
12 | 12 |
|
13 | 13 | const ( |
@@ -55,31 +55,34 @@ func Do(client *http.Client, req *http.Request, cfg *RetryConfig) (resp *http.Re |
55 | 55 | client = &http.Client{} |
56 | 56 | } |
57 | 57 | client.Timeout = cfg.ClientTimeout |
| 58 | + |
58 | 59 | maxRetries := cfg.MaxRetries |
59 | | - err = wait.PollUntilContextTimeout(context.Background(), cfg.WaitBetweenCalls, cfg.RetryTimeout, true, wait.ConditionFunc( |
60 | | - func() (bool, error) { |
61 | | - resp, err = client.Do(req) //nolint:bodyclose // body is closed by the caller functions |
62 | | - if err != nil { |
63 | | - if maxRetries > 0 { |
64 | | - if errorIsOneOf(err, ClientTimeoutErr, ClientContextDeadlineErr, ClientConnectionRefusedErr) || |
65 | | - (req.Method == http.MethodGet && strings.Contains(err.Error(), ClientEOFError)) { |
66 | | - // reduce retries counter and retry |
67 | | - maxRetries-- |
68 | | - return false, nil |
69 | | - } |
70 | | - } |
71 | | - return false, err |
72 | | - } |
73 | | - if maxRetries > 0 && resp != nil { |
74 | | - if resp.StatusCode == http.StatusBadGateway || |
75 | | - resp.StatusCode == http.StatusGatewayTimeout { |
| 60 | + ctx, cancel := context.WithTimeout(context.Background(), cfg.RetryTimeout) |
| 61 | + defer cancel() |
| 62 | + b := backoff.WithContext(backoff.NewConstantBackOff(cfg.WaitBetweenCalls), ctx) |
| 63 | + |
| 64 | + err = backoff.Retry(func() error { |
| 65 | + resp, err = client.Do(req) //nolint:bodyclose // body is closed by the caller functions |
| 66 | + if err != nil { |
| 67 | + if maxRetries > 0 { |
| 68 | + if errorIsOneOf(err, ClientTimeoutErr, ClientContextDeadlineErr, ClientConnectionRefusedErr) || |
| 69 | + (req.Method == http.MethodGet && strings.Contains(err.Error(), ClientEOFError)) { |
| 70 | + // reduce retries counter and retry |
76 | 71 | maxRetries-- |
77 | | - return false, nil |
| 72 | + return err |
78 | 73 | } |
79 | 74 | } |
80 | | - return true, nil |
81 | | - }).WithContext(), |
82 | | - ) |
| 75 | + return backoff.Permanent(err) |
| 76 | + } |
| 77 | + if maxRetries > 0 && resp != nil { |
| 78 | + if resp.StatusCode == http.StatusBadGateway || |
| 79 | + resp.StatusCode == http.StatusGatewayTimeout { |
| 80 | + maxRetries-- |
| 81 | + return fmt.Errorf("requested returned a gateway error") |
| 82 | + } |
| 83 | + } |
| 84 | + return nil |
| 85 | + }, b) |
83 | 86 | if err != nil { |
84 | 87 | return resp, fmt.Errorf("url: %s\nmethod: %s\n err: %w", req.URL.String(), req.Method, err) |
85 | 88 | } |
|
0 commit comments