"Fossies" - the Fresh Open Source Software Archive

Member "gdrive-2.1.1/vendor/google.golang.org/api/gensupport/retry.go" (28 May 2021, 1736 Bytes) of package /linux/misc/gdrive-2.1.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Go source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 package gensupport
    2 
    3 import (
    4     "io"
    5     "net"
    6     "net/http"
    7     "time"
    8 
    9     "golang.org/x/net/context"
   10 )
   11 
   12 // Retry invokes the given function, retrying it multiple times if the connection failed or
   13 // the HTTP status response indicates the request should be attempted again. ctx may be nil.
   14 func Retry(ctx context.Context, f func() (*http.Response, error), backoff BackoffStrategy) (*http.Response, error) {
   15     for {
   16         resp, err := f()
   17 
   18         var status int
   19         if resp != nil {
   20             status = resp.StatusCode
   21         }
   22 
   23         // Return if we shouldn't retry.
   24         pause, retry := backoff.Pause()
   25         if !shouldRetry(status, err) || !retry {
   26             return resp, err
   27         }
   28 
   29         // Ensure the response body is closed, if any.
   30         if resp != nil && resp.Body != nil {
   31             resp.Body.Close()
   32         }
   33 
   34         // Pause, but still listen to ctx.Done if context is not nil.
   35         var done <-chan struct{}
   36         if ctx != nil {
   37             done = ctx.Done()
   38         }
   39         select {
   40         case <-done:
   41             return nil, ctx.Err()
   42         case <-time.After(pause):
   43         }
   44     }
   45 }
   46 
   47 // DefaultBackoffStrategy returns a default strategy to use for retrying failed upload requests.
   48 func DefaultBackoffStrategy() BackoffStrategy {
   49     return &ExponentialBackoff{
   50         Base: 250 * time.Millisecond,
   51         Max:  16 * time.Second,
   52     }
   53 }
   54 
   55 // shouldRetry returns true if the HTTP response / error indicates that the
   56 // request should be attempted again.
   57 func shouldRetry(status int, err error) bool {
   58     // Retry for 5xx response codes.
   59     if 500 <= status && status < 600 {
   60         return true
   61     }
   62 
   63     // Retry on statusTooManyRequests{
   64     if status == statusTooManyRequests {
   65         return true
   66     }
   67 
   68     // Retry on unexpected EOFs and temporary network errors.
   69     if err == io.ErrUnexpectedEOF {
   70         return true
   71     }
   72     if err, ok := err.(net.Error); ok {
   73         return err.Temporary()
   74     }
   75 
   76     return false
   77 }