~egtann/retryablehttp

ref: 680c00f7f0abdbe1318e4d9278155464d71f6aed retryablehttp/client.go -rw-r--r-- 3.9 KiB
680c00f7 — Evan Tann fix panic 1 year, 5 months ago
                                                                                
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
package retryablehttp

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"sync"
	"time"

	"golang.org/x/time/rate"
)

// Client does auto-retries. If passed a logger, it logs the start and end of
// requests for observability.
type Client struct {
	c           *http.Client
	shouldRetry ShouldRetryFn
	limiter     *rate.Limiter
	retries     int
	log         Logger
	mu          sync.RWMutex
}

type Logger interface {
	Printf(string, ...interface{})
}

func NewClient(client *http.Client) *Client {
	return &Client{c: client, shouldRetry: defaultRetrier}
}

func (c *Client) WithLogger(log Logger) *Client {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.log = log
	return c
}

func (c *Client) WithRetries(r int) *Client {
	c.mu.Lock()
	defer c.mu.Unlock()

	if r < 0 {
		panic("retries must be greater than 0")
	}
	c.retries = r
	return c
}

func (c *Client) WithLimiter(l *rate.Limiter) *Client {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.limiter = l
	return c
}

// ShouldRetryFn allows specifying a custom function which should return true
// if a retry should be done, or false if no retries should be done. This
// allows you to handle specific status codes differently.
type ShouldRetryFn func(resp *http.Response) bool

func defaultRetrier(resp *http.Response) bool {
	if resp.StatusCode >= 400 && resp.StatusCode < 500 {
		return true
	}

	// Also retry on reverse proxy issues
	return resp.StatusCode == http.StatusBadGateway
}

func (c *Client) WithShouldRetry(fn ShouldRetryFn) *Client {
	c.mu.Lock()
	defer c.mu.Unlock()

	c.shouldRetry = fn
	return c
}

func (c *Client) Do(req *http.Request) (*http.Response, error) {
	if c.retries == 0 {
		return c.do(req)
	}
	c.mu.RLock()
	defer c.mu.RUnlock()

	var (
		rsp *http.Response
		byt []byte
		err error
	)
	if req.Body != nil {
		byt, err = ioutil.ReadAll(req.Body)
		if err != nil {
			return nil, fmt.Errorf("read body: %s", err.Error())
		}
	}
	safeURL := removeURLAuth(req.URL.String())
	header := req.Header
	ctx := req.Context()
	for i := 0; i < c.retries-1; i++ {
		rsp, err = c.retry(ctx, req, header, byt)
		if err != nil {
			if c.log != nil {
				c.log.Printf("failed with err: retry %d: %s %s", i,
					req.Method, safeURL)
			}
			time.Sleep(time.Second * time.Duration(i+1))
			continue
		}
		if c.shouldRetry(rsp) {
			if c.log != nil {
				c.log.Printf("failed with code: retry %d: %s %s",
					i, req.Method, safeURL)
				lr := io.LimitReader(rsp.Body, 1024*64)
				byt, err := ioutil.ReadAll(lr)
				if err != nil {
					c.log.Printf("failed to read resp body: %s", err)
				} else {
					c.log.Printf("response body: %s", string(byt))
				}
			}
			rsp.Body.Close()
			time.Sleep(time.Second * time.Duration(i+1))
			continue
		}
		return rsp, nil
	}
	return c.retry(ctx, req, header, byt)
}

func (c *Client) retry(
	ctx context.Context,
	req *http.Request,
	header http.Header,
	byt []byte,
) (*http.Response, error) {
	rdr := bytes.NewReader(byt)
	req, err := http.NewRequest(req.Method, req.URL.String(), rdr)
	if err != nil {
		return nil, fmt.Errorf("new request: %s", err.Error())
	}
	req = req.WithContext(ctx)
	req.Header = header
	return c.do(req)
}

// RemoveURLAuth details before logging.
func removeURLAuth(s string) string {
	ul, err := url.Parse(s)
	if err != nil {
		return ""
	}
	ul.User = nil
	return ul.String()
}

func (c *Client) do(req *http.Request) (*http.Response, error) {
	if c.log != nil {
		// Log start and end times for observability
		safeURL := removeURLAuth(req.URL.String())
		c.log.Printf("start: http: %s %s", req.Method, safeURL)
		defer c.log.Printf("end: http: %s %s", req.Method, safeURL)
	}
	if c.limiter != nil {
		if err := c.limiter.Wait(req.Context()); err != nil {
			return nil, fmt.Errorf("wait: %s", err.Error())
		}
	}
	return c.c.Do(req)
}

func retryable(statusCode int) bool {
	if statusCode >= 400 && statusCode < 500 {
		return true
	}

	// Also retry on reverse proxy issues
	return statusCode == http.StatusBadGateway
}