Moved ratelimit to pkg

This commit is contained in:
Philipp Wolfer 2023-12-11 23:21:29 +01:00
parent c4da3a40cc
commit 6ac2b4f142
No known key found for this signature in database
GPG key ID: 8FDF744D4919943B
4 changed files with 12 additions and 3 deletions

View file

@ -26,8 +26,8 @@ import (
"strconv"
"github.com/go-resty/resty/v2"
"go.uploadedlobster.com/scotty/internal/ratelimit"
"go.uploadedlobster.com/scotty/internal/version"
"go.uploadedlobster.com/scotty/pkg/ratelimit"
)
const MaxItemsPerGet = 50

View file

@ -27,8 +27,8 @@ import (
"time"
"github.com/go-resty/resty/v2"
"go.uploadedlobster.com/scotty/internal/ratelimit"
"go.uploadedlobster.com/scotty/internal/version"
"go.uploadedlobster.com/scotty/pkg/ratelimit"
)
const (

View file

@ -29,8 +29,8 @@ import (
"time"
"github.com/go-resty/resty/v2"
"go.uploadedlobster.com/scotty/internal/ratelimit"
"go.uploadedlobster.com/scotty/internal/version"
"go.uploadedlobster.com/scotty/pkg/ratelimit"
"golang.org/x/oauth2"
)

View file

@ -1,52 +0,0 @@
/*
Copyright © 2023 Philipp Wolfer <phw@uploadedlobster.com>
Scotty is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later version.
Scotty is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
Scotty. If not, see <https://www.gnu.org/licenses/>.
*/
package ratelimit
import (
"net/http"
"strconv"
"time"
"github.com/go-resty/resty/v2"
)
const (
RetryCount = 5
DefaultRateLimitWaitSeconds = 5
MaxWaitTimeSeconds = 60
)
func EnableHTTPHeaderRateLimit(client *resty.Client, resetInHeader string) {
client.SetRetryCount(RetryCount)
client.AddRetryCondition(
func(r *resty.Response, err error) bool {
code := r.StatusCode()
return code == http.StatusTooManyRequests || code >= http.StatusInternalServerError
},
)
client.SetRetryMaxWaitTime(time.Duration(MaxWaitTimeSeconds * time.Second))
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(resetInHeader))
if err != nil {
retryAfter = DefaultRateLimitWaitSeconds
}
}
return time.Duration(retryAfter * int(time.Second)), err
})
}