-
Notifications
You must be signed in to change notification settings - Fork 2
/
ratelimitretry.go
77 lines (64 loc) · 1.85 KB
/
ratelimitretry.go
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
package common
import (
"compress/flate"
"compress/gzip"
"fmt"
"io"
"net/http"
"time"
"github.com/tencentcloud/tencentcloud-sdk-go-intl-en/tencentcloud/common/errors"
tchttp "github.com/tencentcloud/tencentcloud-sdk-go-intl-en/tencentcloud/common/http"
)
const (
codeLimitExceeded = "RequestLimitExceeded"
tplRateLimitRetry = "[WARN] rate limit exceeded, retrying (%d/%d) in %f seconds: %s"
)
func (c *Client) sendWithRateLimitRetry(req *http.Request, retryable bool) (resp *http.Response, err error) {
// make sure maxRetries is more than 0
maxRetries := maxInt(c.profile.RateLimitExceededMaxRetries, 0)
durationFunc := safeDurationFunc(c.profile.RateLimitExceededRetryDuration)
for idx := 0; idx <= maxRetries; idx++ {
resp, err = c.sendWithNetworkFailureRetry(req, retryable)
if err != nil {
return
}
err = decompressBodyReader(resp)
if err != nil {
return resp, err
}
err = tchttp.TryReadErr(resp)
// should not sleep on last request
if err, ok := err.(*errors.TencentCloudSDKError); ok && err.Code == codeLimitExceeded && idx < maxRetries {
duration := durationFunc(idx)
if c.debug {
c.logger.Printf(tplRateLimitRetry, idx, maxRetries, duration.Seconds(), err.Error())
}
time.Sleep(duration)
continue
}
return resp, err
}
return resp, err
}
func decompressBodyReader(resp *http.Response) error {
var readCloser io.ReadCloser
var err error
enc := resp.Header.Get("Content-Encoding")
switch enc {
case "":
readCloser = resp.Body
case "deflate":
readCloser = flate.NewReader(resp.Body)
case "gzip":
readCloser, err = gzip.NewReader(resp.Body)
if err != nil {
return err
}
default:
return fmt.Errorf("Content-Encoding not support: %s", enc)
}
resp.Body = readCloser
// delete the header in case the caller mistake the body being encoded
delete(resp.Header, "Content-Encoding")
return nil
}