-
Notifications
You must be signed in to change notification settings - Fork 11
feat: add APIError, rate limit parsing, and retry backoff #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -4,7 +4,10 @@ import ( | |||||
| "encoding/json" | ||||||
| "errors" | ||||||
| "fmt" | ||||||
| "io" | ||||||
| "net/http" | ||||||
| "strconv" | ||||||
| "time" | ||||||
| ) | ||||||
|
|
||||||
| var ErrorReqUnsuccessful = errors.New("request was not successful") | ||||||
|
|
@@ -13,6 +16,88 @@ type ErrorResponse struct { | |||||
| Error string `json:"error"` | ||||||
| } | ||||||
|
|
||||||
| type RateLimit struct { | ||||||
| Limit int | ||||||
| Remaining int | ||||||
| Reset int64 | ||||||
| } | ||||||
|
|
||||||
| type APIError struct { | ||||||
| StatusCode int | ||||||
| StatusText string | ||||||
| BodySnippet string | ||||||
| RateLimit *RateLimit | ||||||
| RetryAfter time.Duration | ||||||
| } | ||||||
|
|
||||||
| func (e *APIError) Error() string { | ||||||
| if e.BodySnippet != "" { | ||||||
| return fmt.Sprintf("http %d %s: %s", e.StatusCode, e.StatusText, e.BodySnippet) | ||||||
| } | ||||||
| return fmt.Sprintf("http %d %s", e.StatusCode, e.StatusText) | ||||||
| } | ||||||
|
|
||||||
| type RetryPolicy struct { | ||||||
| MaxAttempts int | ||||||
| InitialBackoff time.Duration | ||||||
| MaxBackoff time.Duration | ||||||
| Jitter time.Duration | ||||||
| RetryableStatusCodes []int | ||||||
| } | ||||||
|
|
||||||
| var defaultRetryPolicy = RetryPolicy{ | ||||||
| MaxAttempts: 3, | ||||||
| InitialBackoff: 500 * time.Millisecond, | ||||||
| MaxBackoff: 5 * time.Second, | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Given that rate limits apply on a minute basis, I think it makes sense to bump these a bit higher, as it's very possible that you'll still be rate limited after waiting only a couple of seconds |
||||||
| Jitter: 100 * time.Millisecond, | ||||||
| RetryableStatusCodes: []int{429, 500, 502, 503, 504}, | ||||||
| } | ||||||
|
|
||||||
| func parseRateLimitHeaders(h http.Header) *RateLimit { | ||||||
| limStr := h.Get("X-RateLimit-Limit") | ||||||
| remStr := h.Get("X-RateLimit-Remaining") | ||||||
| resetStr := h.Get("X-RateLimit-Reset") | ||||||
|
|
||||||
| var lim, rem int | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No need to shorten variable names :)
Suggested change
|
||||||
| var reset int64 | ||||||
|
|
||||||
| if limStr != "" { | ||||||
| if v, err := strconv.Atoi(limStr); err == nil { | ||||||
| lim = v | ||||||
| } | ||||||
| } | ||||||
| if remStr != "" { | ||||||
| if v, err := strconv.Atoi(remStr); err == nil { | ||||||
| rem = v | ||||||
| } | ||||||
| } | ||||||
| if resetStr != "" { | ||||||
| if v, err := strconv.ParseInt(resetStr, 10, 64); err == nil { | ||||||
| reset = v | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| if lim == 0 && rem == 0 && reset == 0 { | ||||||
| return nil | ||||||
| } | ||||||
| return &RateLimit{Limit: lim, Remaining: rem, Reset: reset} | ||||||
| } | ||||||
|
|
||||||
| func nextBackoff(attempt int, p RetryPolicy) time.Duration { | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. And would you mind moving the retry and backoff code into a separate file please (e.g. dune/retries.go) 🙏
Suggested change
|
||||||
| b := p.InitialBackoff | ||||||
| for i := 1; i < attempt; i++ { | ||||||
| b *= 2 | ||||||
| if b > p.MaxBackoff { | ||||||
| b = p.MaxBackoff | ||||||
| break | ||||||
| } | ||||||
| } | ||||||
| if p.Jitter > 0 { | ||||||
| b += p.Jitter | ||||||
| } | ||||||
| return b | ||||||
| } | ||||||
|
|
||||||
| func decodeBody(resp *http.Response, dest interface{}) error { | ||||||
| defer resp.Body.Close() | ||||||
| err := json.NewDecoder(resp.Body).Decode(dest) | ||||||
|
|
@@ -24,20 +109,61 @@ func decodeBody(resp *http.Response, dest interface{}) error { | |||||
|
|
||||||
| func httpRequest(apiKey string, req *http.Request) (*http.Response, error) { | ||||||
| req.Header.Add("X-DUNE-API-KEY", apiKey) | ||||||
| resp, err := http.DefaultClient.Do(req) | ||||||
| if err != nil { | ||||||
| return nil, fmt.Errorf("failed to send request: %w", err) | ||||||
| } | ||||||
| p := defaultRetryPolicy | ||||||
| attempt := 1 | ||||||
| for { | ||||||
| resp, err := http.DefaultClient.Do(req) | ||||||
| if err != nil { | ||||||
| if attempt >= p.MaxAttempts { | ||||||
| return nil, fmt.Errorf("failed to send request: %w", err) | ||||||
| } | ||||||
| time.Sleep(nextBackoff(attempt, p)) | ||||||
| attempt++ | ||||||
| continue | ||||||
| } | ||||||
|
|
||||||
| if resp.StatusCode == 200 { | ||||||
| return resp, nil | ||||||
| } | ||||||
|
|
||||||
| if resp.StatusCode != 200 { | ||||||
| defer resp.Body.Close() | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Bug: Defer in loop accumulates unclosed response bodiesThe |
||||||
| var errorResponse ErrorResponse | ||||||
| err := json.NewDecoder(resp.Body).Decode(&errorResponse) | ||||||
| if err != nil { | ||||||
| return nil, fmt.Errorf("failed to read error response body: %w", err) | ||||||
| snippetBytes, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) | ||||||
| var er ErrorResponse | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| _ = json.Unmarshal(snippetBytes, &er) | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This unmarshal could fail, since the body is capped at 1024 characters, so you'll need to handle the error here in that case |
||||||
| msg := string(snippetBytes) | ||||||
| if er.Error != "" { | ||||||
| msg = er.Error | ||||||
| } | ||||||
| return resp, fmt.Errorf("%w [%d]: %s", ErrorReqUnsuccessful, resp.StatusCode, errorResponse.Error) | ||||||
| rl := parseRateLimitHeaders(resp.Header) | ||||||
| retryAfter := time.Duration(0) | ||||||
| if ra := resp.Header.Get("Retry-After"); ra != "" { | ||||||
| if secs, err := strconv.Atoi(ra); err == nil { | ||||||
| retryAfter = time.Duration(secs) * time.Second | ||||||
| } | ||||||
| } | ||||||
| apiErr := &APIError{ | ||||||
| StatusCode: resp.StatusCode, | ||||||
| StatusText: resp.Status, | ||||||
| BodySnippet: msg, | ||||||
| RateLimit: rl, | ||||||
| RetryAfter: retryAfter, | ||||||
| } | ||||||
| retryable := false | ||||||
| for _, code := range p.RetryableStatusCodes { | ||||||
| if resp.StatusCode == code { | ||||||
| retryable = true | ||||||
| break | ||||||
| } | ||||||
| } | ||||||
| if retryable && attempt < p.MaxAttempts { | ||||||
| sleep := nextBackoff(attempt, p) | ||||||
| if apiErr.RetryAfter > 0 && apiErr.RetryAfter > sleep { | ||||||
| sleep = apiErr.RetryAfter | ||||||
| } | ||||||
| time.Sleep(sleep) | ||||||
| attempt++ | ||||||
| continue | ||||||
| } | ||||||
| return nil, fmt.Errorf("%w: %v", ErrorReqUnsuccessful, apiErr) | ||||||
| } | ||||||
|
|
||||||
| return resp, nil | ||||||
| } | ||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why remove the print here?