|
| 1 | +package client |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "regexp" |
| 6 | + "strconv" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/hashicorp/go-retryablehttp" |
| 10 | +) |
| 11 | + |
| 12 | +var ( |
| 13 | + rateLimitResetHeaders = []string{ |
| 14 | + "x-organization-rate-limit-reset", |
| 15 | + "x-instant-test-rate-limit-reset", |
| 16 | + } |
| 17 | + resetHeaderPattern = regexp.MustCompile(`^\s*[0-9]+\s*$`) |
| 18 | +) |
| 19 | + |
| 20 | +// Custom backoff function |
| 21 | +func customBackoff(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration { |
| 22 | + if resp == nil { |
| 23 | + return 0 |
| 24 | + } |
| 25 | + |
| 26 | + for _, header := range rateLimitResetHeaders { |
| 27 | + if resetTimeStr := resp.Header.Get(header); resetTimeStr != "" { |
| 28 | + if waitDuration := parseResetHeader(&resetTimeStr); waitDuration != nil { |
| 29 | + return *waitDuration |
| 30 | + } |
| 31 | + |
| 32 | + // Default backoff if no valid reset time is found |
| 33 | + return retryablehttp.DefaultBackoff(min, max, attemptNum, resp) |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + // Default case for no rateLimitResetHeaders |
| 38 | + return retryablehttp.DefaultBackoff(min, max, attemptNum, resp) |
| 39 | +} |
| 40 | + |
| 41 | +// Function to parse the reset header |
| 42 | +func parseResetHeader(value *string) *time.Duration { |
| 43 | + if value == nil || !resetHeaderPattern.MatchString(*value) { |
| 44 | + return nil |
| 45 | + } |
| 46 | + |
| 47 | + // Parse the header value to a Unix timestamp |
| 48 | + resetTimeUnix, err := strconv.ParseInt(*value, 10, 64) |
| 49 | + if err != nil { |
| 50 | + return nil |
| 51 | + } |
| 52 | + |
| 53 | + // Calculate the duration until the reset time |
| 54 | + resetTime := time.Unix(resetTimeUnix, 0) |
| 55 | + waitDuration := time.Until(resetTime) |
| 56 | + |
| 57 | + // Return nil if the reset time has already passed |
| 58 | + if waitDuration < 0 { |
| 59 | + zeroDuration := time.Duration(0) |
| 60 | + return &zeroDuration |
| 61 | + } |
| 62 | + return &waitDuration |
| 63 | +} |
0 commit comments