1 // Copyright 2017 Google LLC
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
25 // Retry invokes the given function, retrying it multiple times if the connection failed or
26 // the HTTP status response indicates the request should be attempted again. ctx may be nil.
27 func Retry(ctx context.Context, f func() (*http.Response, error), backoff BackoffStrategy) (*http.Response, error) {
33 status = resp.StatusCode
36 // Return if we shouldn't retry.
37 pause, retry := backoff.Pause()
38 if !shouldRetry(status, err) || !retry {
42 // Ensure the response body is closed, if any.
43 if resp != nil && resp.Body != nil {
47 // Pause, but still listen to ctx.Done if context is not nil.
48 var done <-chan struct{}
55 case <-time.After(pause):
60 // DefaultBackoffStrategy returns a default strategy to use for retrying failed upload requests.
61 func DefaultBackoffStrategy() BackoffStrategy {
62 return &ExponentialBackoff{
63 Base: 250 * time.Millisecond,
64 Max: 16 * time.Second,
68 // shouldRetry returns true if the HTTP response / error indicates that the
69 // request should be attempted again.
70 func shouldRetry(status int, err error) bool {
71 if 500 <= status && status <= 599 {
74 if status == statusTooManyRequests {
77 if err == io.ErrUnexpectedEOF {
80 if err, ok := err.(net.Error); ok {
81 return err.Temporary()