// Package ratelimit enforces how often dibs may talk to a shop. // // The floors are constants on purpose: no config value, flag or caller can // lower them. package ratelimit import ( "context" "math/rand/v2" "net/url" "strings" "sync" "time" ) const ( // URLFloor is the shortest time between two checks of one URL. URLFloor = 60 * time.Second // HostFloor is the shortest time between two requests to one host. HostFloor = 10 * time.Second // Jitter is the fraction intervals are randomly stretched or shrunk by. Jitter = 0.2 backoffBase = 2 * time.Minute backoffCap = 30 * time.Minute ) // HostState is what the limiter remembers about a host. It is persisted so // the floors hold across restarts and between dibs processes. type HostState struct { // Next is the earliest time of the next request. Next time.Time `json:"next"` // Failures counts bot checks and refusals in a row. Failures int `json:"failures,omitempty"` // BackoffUntil blocks the host after repeated failures. BackoffUntil time.Time `json:"backoff_until,omitzero"` } // Persister shares host and URL state with other dibs processes. The Load // methods return the newest state on disk, and the Store methods record this // process's. Lock serializes the limiters' decisions across processes and // returns the unlock function. type Persister interface { Lock() func() LoadHost(host string) (HostState, bool) StoreHost(host string, h HostState) LoadURL(pageURL string) (time.Time, bool) StoreURL(pageURL string, last time.Time) } // Clock abstracts time so tests can replace it. type Clock interface { Now() time.Time After(d time.Duration) <-chan time.Time } // SystemClock is the real clock. var SystemClock Clock = systemClock{} type systemClock struct{} func (systemClock) Now() time.Time { return time.Now() } func (systemClock) After(d time.Duration) <-chan time.Time { return time.After(d) } // Limiter spaces requests per host and checks per URL, and backs off from // hosts that keep answering with bot checks. It is safe for concurrent use. type Limiter struct { clock Clock persist Persister rand func() float64 mu sync.Mutex hosts map[string]HostState urls map[string]time.Time } type Option func(*Limiter) // WithClock replaces the system clock, for tests. func WithClock(c Clock) Option { return func(l *Limiter) { l.clock = c } } // WithRand replaces the jitter source, which returns values in [0, 1). func WithRand(r func() float64) Option { return func(l *Limiter) { l.rand = r } } // New returns a limiter. persist may be nil to keep state in memory only. func New(persist Persister, opts ...Option) *Limiter { l := &Limiter{ clock: SystemClock, persist: persist, rand: rand.Float64, hosts: map[string]HostState{}, urls: map[string]time.Time{}, } for _, o := range opts { o(l) } return l } func (l *Limiter) Clock() Clock { return l.clock } // Wait blocks until a request to host is allowed, then reserves the slot. // It is for requests that are not checks of a product page. func (l *Limiter) Wait(ctx context.Context, host string) error { return l.wait(ctx, strings.ToLower(host), "") } // WaitCheck blocks until url may be checked: its host's floor and backoff, // and the URL floor since its last check by any dibs process, all allow it. // It then reserves both at once, so the request must follow right away. func (l *Limiter) WaitCheck(ctx context.Context, rawURL string) error { u, err := url.Parse(rawURL) if err != nil { return err } return l.wait(ctx, strings.ToLower(u.Hostname()), rawURL) } func (l *Limiter) wait(ctx context.Context, host, checkURL string) error { for { var at time.Time reserved := false l.locked(func() { h := l.host(host) now := l.clock.Now() at = latest(h.Next, h.BackoffUntil) if checkURL != "" { at = latest(at, l.urlReady(checkURL)) } if now.Before(at) { return } // The host gap is stretched randomly, never below the floor. h.Next = now.Add(time.Duration(float64(HostFloor) * (1 + Jitter*l.rand()))) l.setHost(host, h) if checkURL != "" { l.urls[checkURL] = now if l.persist != nil { l.persist.StoreURL(checkURL, now) } } reserved = true }) if reserved { return nil } select { case <-l.clock.After(at.Sub(l.clock.Now())): case <-ctx.Done(): return ctx.Err() } } } // Delay is how long a request to host would have to wait now. func (l *Limiter) Delay(host string) time.Duration { l.mu.Lock() defer l.mu.Unlock() h := l.host(strings.ToLower(host)) return max(0, latest(h.Next, h.BackoffUntil).Sub(l.clock.Now())) } // Failure records a bot check or refusal from host and backs off // exponentially, from 2 minutes up to 30. func (l *Limiter) Failure(host string) time.Duration { host = strings.ToLower(host) var d time.Duration l.locked(func() { h := l.host(host) h.Failures++ d = min(backoffBase<