Files

109 lines
2.9 KiB
Go
Raw Permalink Normal View History

package transport
import (
"context"
"log/slog"
"net/http"
"strconv"
"sync"
"time"
)
// Adaptive throttling across all goroutines sharing one Client: a 429
// pauses every request until Retry-After and widens a shared minimum gap
// between request starts (multiplicative increase); each success narrows
// it again (slow decrease) until it is back to zero, i.e. only APIDelay
// applies. With parallel workers a 429 that only slept its own request
// would leave the others hammering the API.
const (
minInterval = 100 * time.Millisecond
maxInterval = 10 * time.Second
recoverFactor = 0.95
maxRateLimitRetries = 10
)
type throttle struct {
mu sync.Mutex
interval time.Duration // shared minimum gap between request starts
next time.Time // earliest start for the next request
pauseUntil time.Time // global pause after a 429
now func() time.Time
log *slog.Logger
}
func newThrottle(log *slog.Logger) *throttle {
return &throttle{now: time.Now, log: log}
}
// acquire blocks until this request may start, or ctx ends.
func (t *throttle) acquire(ctx context.Context, sleep func(context.Context, time.Duration) error) error {
t.mu.Lock()
at := t.now()
if t.pauseUntil.After(at) {
at = t.pauseUntil
}
if t.next.After(at) {
at = t.next
}
t.next = at.Add(t.interval)
wait := at.Sub(t.now())
t.mu.Unlock()
if wait > 0 {
return sleep(ctx, wait)
}
return ctx.Err()
}
// rateLimited records a 429: pause everyone for wait and slow down.
// Requests that hit the same burst while the pause is already active
// don't slow down any further, so N parallel 429s count as one signal.
func (t *throttle) rateLimited(wait time.Duration) {
t.mu.Lock()
defer t.mu.Unlock()
now := t.now()
if now.Before(t.pauseUntil) {
if until := now.Add(wait); until.After(t.pauseUntil) {
t.pauseUntil = until
}
return
}
t.pauseUntil = now.Add(wait)
t.interval = min(max(t.interval*2, minInterval), maxInterval)
t.log.Warn("atlassian rate limited (429)", "pause", wait, "interval", t.interval)
}
// succeeded narrows the gap again after a successful response.
func (t *throttle) succeeded() {
t.mu.Lock()
defer t.mu.Unlock()
if t.interval == 0 {
return
}
t.interval = time.Duration(float64(t.interval) * recoverFactor)
if t.interval < minInterval {
t.interval = 0
t.log.Info("atlassian rate limit recovered")
}
}
// retryAfter returns how long a 429 response asks us to wait: the
// Retry-After header (seconds or HTTP date), else exponential backoff.
func retryAfter(header http.Header, attempt int, now time.Time) time.Duration {
if ra := header.Get("Retry-After"); ra != "" {
if secs, err := strconv.Atoi(ra); err == nil && secs >= 0 {
return time.Duration(secs) * time.Second
}
if t, err := http.ParseTime(ra); err == nil {
if d := t.Sub(now); d > 0 {
return d
}
return 0
}
}
return backoff(attempt, 60)
}