mirror of
https://git.sr.ht/~phw/scotty
synced 2025-04-29 21:27:05 +02:00
Refactored common rate limit code into separate module
This commit is contained in:
parent
857661ebf9
commit
0f5cb49b4c
4 changed files with 69 additions and 71 deletions
|
@ -23,15 +23,13 @@ package funkwhale
|
|||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/go-resty/resty/v2"
|
||||
"go.uploadedlobster.com/scotty/internal/ratelimit"
|
||||
)
|
||||
|
||||
const MaxItemsPerGet = 50
|
||||
const DefaultRateLimitWaitSeconds = 5
|
||||
|
||||
type Client struct {
|
||||
HttpClient *resty.Client
|
||||
|
@ -46,25 +44,7 @@ func NewClient(serverUrl string, token string) Client {
|
|||
client.SetHeader("Accept", "application/json")
|
||||
|
||||
// Handle rate limiting (see https://docs.funkwhale.audio/developer/api/rate-limit.html)
|
||||
client.SetRetryCount(5)
|
||||
client.AddRetryCondition(
|
||||
func(r *resty.Response, err error) bool {
|
||||
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) {
|
||||
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
|
||||
})
|
||||
ratelimit.EnableHTTPHeaderRateLimit(client, "Retry-After")
|
||||
|
||||
return Client{
|
||||
HttpClient: client,
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue