More resilient HTTP requests

Fixed rate limit check for ListenBrainz and Funkwhale. Also retry always
on server side errors.
This commit is contained in:
Philipp Wolfer 2023-11-15 08:40:55 +01:00
parent 240351dc3e
commit 4e9f50b6b6
No known key found for this signature in database
GPG key ID: 8FDF744D4919943B
3 changed files with 28 additions and 12 deletions

View file

@ -31,6 +31,7 @@ import (
)
const MaxItemsPerGet = 50
const DefaultRateLimitWaitSeconds = 5
type Client struct {
HttpClient *resty.Client
@ -48,12 +49,20 @@ func NewClient(serverUrl string, token string) Client {
client.SetRetryCount(5)
client.AddRetryCondition(
func(r *resty.Response, err error) bool {
return r.StatusCode() == http.StatusTooManyRequests
code := r.StatusCode()
return code == http.StatusTooManyRequests || code >= http.StatusInternalServerError
},
)
client.SetRetryMaxWaitTime(time.Duration(1 * time.Minute))
client.SetRetryAfter(func(client *resty.Client, resp *resty.Response) (time.Duration, error) {
retryAfter, err := strconv.Atoi(resp.Header().Get("X-RateLimit-Reset-In"))
var err error
var retryAfter int = DefaultRateLimitWaitSeconds
if resp.StatusCode() == http.StatusTooManyRequests {
retryAfter, err = strconv.Atoi(resp.Header().Get("Retry-After"))
if err != nil {
retryAfter = DefaultRateLimitWaitSeconds
}
}
return time.Duration(retryAfter * int(time.Second)), err
})