Skip to content

Commit 2857fd3

Browse files
authored
Merge pull request #87 from Teamwork/httpx-exp-backoff
Feature: HTTP exponential backoff
2 parents 03c517e + 21e3791 commit 2857fd3

10 files changed

Lines changed: 366 additions & 46 deletions

File tree

.github/workflows/build.yml

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,25 @@ jobs:
77
lint:
88
runs-on: ubuntu-latest
99
steps:
10-
- uses: actions/checkout@v4
10+
- uses: actions/checkout@v6
1111

1212
- name: Lint
13-
uses: golangci/golangci-lint-action@v6
13+
uses: golangci/golangci-lint-action@v9
1414
with:
15-
version: v1.64
15+
version: v2.7
1616
only-new-issues: true
1717

1818
test:
1919
runs-on: ubuntu-latest
2020
env:
2121
GORACE: history_size=4
2222
steps:
23-
- uses: actions/checkout@v4
23+
- uses: actions/checkout@v6
2424

2525
- name: Set up Go
26-
uses: actions/setup-go@v5
26+
uses: actions/setup-go@v6
2727
with:
28-
go-version: '1.23'
28+
go-version: '1.25'
2929

3030
- name: Test
3131
run: |

.golangci.yml

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,35 @@
1+
version: "2"
12
run:
2-
timeout: 240s
33
tests: true
4-
54
linters:
6-
disable-all: true
5+
default: none
76
enable:
7+
- errcheck
8+
- gocritic
89
- govet
10+
- ineffassign
11+
- lll
12+
- misspell
13+
- nakedret
914
- revive
10-
- unused
11-
- errcheck
1215
- staticcheck
13-
- ineffassign
1416
- unconvert
17+
- unused
18+
settings:
19+
revive:
20+
rules:
21+
- name: var-naming
22+
disabled: true
23+
staticcheck:
24+
# Disable SA1019 (using deprecated code) as the existing use of CFB is
25+
# required for backwards compatibility.
26+
checks: ["all", "-SA1019"]
27+
lll:
28+
line-length: 240
29+
exclusions:
30+
generated: lax
31+
formatters:
32+
enable:
1533
- goimports
16-
- misspell
17-
- lll
18-
- nakedret
19-
- gocritic
20-
21-
linters-settings:
22-
lll:
23-
line-length: 240 # Exceptional case its usually 120
24-
issues:
25-
exclude-use-default: false
34+
exclusions:
35+
generated: lax

go.mod

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
module github.com/teamwork/utils/v2
22

3-
go 1.20
3+
go 1.25
44

55
require (
6-
github.com/mattn/goveralls v0.0.11
6+
github.com/mattn/goveralls v0.0.12
77
github.com/pkg/errors v0.9.1
88
github.com/teamwork/test v0.0.0-20200108114543-02621bae84ad
9-
golang.org/x/tools v0.8.0
9+
golang.org/x/tools v0.39.0
1010
)
1111

1212
require (
1313
github.com/Strum355/go-difflib v1.1.0 // indirect
1414
github.com/davecgh/go-spew v1.1.1 // indirect
1515
github.com/teamwork/utils v1.0.0 // indirect
16-
golang.org/x/mod v0.10.0 // indirect
17-
golang.org/x/sys v0.7.0 // indirect
16+
golang.org/x/mod v0.30.0 // indirect
17+
golang.org/x/sync v0.18.0 // indirect
1818
)

go.sum

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@ github.com/Strum355/go-difflib v1.1.0/go.mod h1:r1cVg1JkGsTWkaR7At56v7hfuMgiUL8m
33
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
44
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
55
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
6-
github.com/mattn/goveralls v0.0.11 h1:eJXea6R6IFlL1QMKNMzDvvHv/hwGrnvyig4N+0+XiMM=
7-
github.com/mattn/goveralls v0.0.11/go.mod h1:gU8SyhNswsJKchEV93xRQxX6X3Ei4PJdQk/6ZHvrvRk=
6+
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
7+
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
8+
github.com/mattn/goveralls v0.0.12 h1:PEEeF0k1SsTjOBQ8FOmrOAoCu4ytuMaWCnWe94zxbCg=
9+
github.com/mattn/goveralls v0.0.12/go.mod h1:44ImGEUfmqH8bBtaMrYKsM65LXfNLWmwaxFGjZwgMSQ=
810
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
911
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
1012
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
@@ -13,10 +15,45 @@ github.com/teamwork/test v0.0.0-20200108114543-02621bae84ad h1:25sEr0awm0ZPancg5
1315
github.com/teamwork/test v0.0.0-20200108114543-02621bae84ad/go.mod h1:TIbx7tx6WHBjQeLRM4eWQZBL7kmBZ7/KI4x4v7Y5YmA=
1416
github.com/teamwork/utils v1.0.0 h1:30WqhSbZ9nFhaJSx9HH+yFLiQvL64nqAOyyl5IxoYlY=
1517
github.com/teamwork/utils v1.0.0/go.mod h1:3Fn0qxFeRNpvsg/9T1+btOOOKkd1qG2nPYKKcOmNpcs=
16-
golang.org/x/mod v0.10.0 h1:lFO9qtOdlre5W1jxS3r/4szv2/6iXxScdzjoBMXNhYk=
18+
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
19+
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
20+
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
21+
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
22+
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
1723
golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
18-
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
19-
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
24+
golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=
25+
golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
26+
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
27+
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
28+
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
29+
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
30+
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
31+
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
32+
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
33+
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
34+
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
35+
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
36+
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
37+
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
38+
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
39+
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
40+
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
41+
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
2042
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
21-
golang.org/x/tools v0.8.0 h1:vSDcovVPld282ceKgDimkRSC8kpaH1dgyc9UMzlt84Y=
43+
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
44+
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
45+
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
46+
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
47+
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
48+
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
49+
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
50+
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
51+
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
52+
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
53+
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
54+
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
55+
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
2256
golang.org/x/tools v0.8.0/go.mod h1:JxBZ99ISMI5ViVkT1tr6tdNmXeTrcpVSD3vZ1RsRdN4=
57+
golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=
58+
golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=
59+
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

goutil/goutil_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,10 @@ func TestExpand(t *testing.T) {
4040
[]string{"net", "net/http", "net/http/cgi", "net/http/cookiejar",
4141
"net/http/fcgi", "net/http/httptest", "net/http/httptrace",
4242
"net/http/httputil", "net/http/internal", "net/http/internal/ascii",
43-
"net/http/internal/testcert", "net/http/pprof",
44-
"net/internal/cgotest", "net/internal/socktest", "net/mail",
45-
"net/netip", "net/rpc", "net/rpc/jsonrpc", "net/smtp", "net/textproto",
46-
"net/url",
43+
"net/http/internal/httpcommon", "net/http/internal/testcert",
44+
"net/http/pprof", "net/internal/cgotest", "net/internal/socktest",
45+
"net/mail", "net/netip", "net/rpc", "net/rpc/jsonrpc", "net/smtp",
46+
"net/textproto", "net/url",
4747
},
4848
"",
4949
},

httputilx/httputilx.go

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"bytes"
66
"fmt"
77
"io"
8+
"log/slog"
89
"net/http"
910
"net/http/httputil"
1011
"os"
@@ -145,3 +146,129 @@ func Save(url string, dir string, filename string) (string, error) {
145146

146147
return path, nil
147148
}
149+
150+
// ExponentialBackoffOptions contains options for the exponential backoff retry
151+
// mechanism.
152+
type ExponentialBackoffOptions struct {
153+
client *http.Client
154+
maxRetries int
155+
initialBackoff time.Duration
156+
maxBackoff time.Duration
157+
backoffMultiplier float64
158+
shouldRetry func(resp *http.Response, err error) bool
159+
logger *slog.Logger
160+
}
161+
162+
// ExponentialBackoffOption is a function that configures
163+
// ExponentialBackoffOptions.
164+
type ExponentialBackoffOption func(*ExponentialBackoffOptions)
165+
166+
// ExponentialBackoffWithClient sets the HTTP client to be used when sending the
167+
// API requests. By default, http.DefaultClient is used.
168+
func ExponentialBackoffWithClient(client *http.Client) ExponentialBackoffOption {
169+
return func(o *ExponentialBackoffOptions) {
170+
o.client = client
171+
}
172+
}
173+
174+
// ExponentialBackoffWithConfig sets the configuration for the exponential
175+
// backoff retry mechanism. By default, it will retry up to 3 times, starting
176+
// with a 100ms backoff, doubling each time up to a maximum of 5s.
177+
func ExponentialBackoffWithConfig(
178+
maxRetries int,
179+
initialBackoff, maxBackoff time.Duration,
180+
backoffMultiplier float64,
181+
) ExponentialBackoffOption {
182+
return func(o *ExponentialBackoffOptions) {
183+
o.maxRetries = maxRetries
184+
o.initialBackoff = initialBackoff
185+
o.maxBackoff = maxBackoff
186+
o.backoffMultiplier = backoffMultiplier
187+
}
188+
}
189+
190+
// ExponentialBackoffWithShouldRetry sets the function to determine whether a
191+
// request should be retried based on the response and error. By default, it
192+
// retries on any error, as well as on HTTP 5xx and 429 status codes.
193+
func ExponentialBackoffWithShouldRetry(
194+
shouldRetry func(resp *http.Response, err error) bool,
195+
) ExponentialBackoffOption {
196+
return func(o *ExponentialBackoffOptions) {
197+
o.shouldRetry = shouldRetry
198+
}
199+
}
200+
201+
// ExponentialBackoffWithLogger sets the logger to be used for logging retry
202+
// attempts. By default, a no-op logger is used.
203+
func ExponentialBackoffWithLogger(logger *slog.Logger) ExponentialBackoffOption {
204+
return func(o *ExponentialBackoffOptions) {
205+
o.logger = logger
206+
}
207+
}
208+
209+
// DoExponentialBackoff will send an API request using exponential backoff until
210+
// it either succeeds or the maximum number of retries is reached.
211+
func DoExponentialBackoff(req *http.Request, options ...ExponentialBackoffOption) (*http.Response, error) {
212+
o := ExponentialBackoffOptions{
213+
client: http.DefaultClient,
214+
maxRetries: 3,
215+
initialBackoff: 100 * time.Millisecond,
216+
maxBackoff: 5 * time.Second,
217+
backoffMultiplier: 2.0,
218+
shouldRetry: func(resp *http.Response, err error) bool {
219+
if err != nil {
220+
return true
221+
}
222+
if resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 {
223+
return true
224+
}
225+
return false
226+
},
227+
logger: slog.New(slog.DiscardHandler),
228+
}
229+
for _, option := range options {
230+
option(&o)
231+
}
232+
233+
backoff := o.initialBackoff
234+
235+
for attempt := 0; attempt <= o.maxRetries; attempt++ {
236+
reqClone := req.Clone(req.Context())
237+
if req.Body != nil {
238+
if seeker, ok := req.Body.(interface {
239+
Seek(int64, int) (int64, error)
240+
}); ok {
241+
_, _ = seeker.Seek(0, 0)
242+
}
243+
reqClone.Body = req.Body
244+
}
245+
246+
resp, err := o.client.Do(reqClone)
247+
if !o.shouldRetry(resp, err) || attempt >= o.maxRetries {
248+
return resp, nil
249+
}
250+
251+
logArgs := []any{
252+
slog.Int("attempt", attempt+1),
253+
slog.Duration("backoff", backoff),
254+
}
255+
if err != nil {
256+
logArgs = append(logArgs, slog.String("error", err.Error()))
257+
}
258+
if resp != nil {
259+
if err := resp.Body.Close(); err != nil {
260+
o.logger.Error("failed to close response body",
261+
slog.Int("attempt", attempt+1),
262+
slog.String("error", err.Error()),
263+
)
264+
}
265+
logArgs = append(logArgs, slog.Int("status_code", resp.StatusCode))
266+
}
267+
268+
o.logger.Debug("request failed", logArgs...)
269+
time.Sleep(backoff)
270+
backoff = min(time.Duration(float64(backoff)*o.backoffMultiplier), o.maxBackoff)
271+
}
272+
273+
return nil, fmt.Errorf("request failed after %d attempts", o.maxRetries+1)
274+
}

0 commit comments

Comments
 (0)