Files
Overlord e2cbc1a55c Add the Chrome fallback and the needs-human flow.
Bot checks escalate to headless Chrome with stealth, which claims the
same identity as tls-client and hands its cookies back to the jar. The
visit counts against the rate limits. If Chrome can't clear a check,
the URL is marked needs-human. Pressing Enter on it in the TUI, or
running 'dibs solve', opens a visible window; dibs carries on once the
page loads. Processes now merge the cookie file on save, with the
newest cookie winning.
2026-10-14 14:08:56 +02:00

291 lines
7.7 KiB
Go

// 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
// recheck caps each sleep of a waiting request, so that a cleared
// backoff lets it go soon.
recheck = 5 * time.Second
)
// 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(min(at.Sub(l.clock.Now()), recheck)):
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<<min(h.Failures-1, 10), backoffCap)
d = min(l.Jittered(d, 0), backoffCap)
h.BackoffUntil = l.clock.Now().Add(d)
l.setHost(host, h)
})
return d
}
// Success clears the backoff of host.
func (l *Limiter) Success(host string) {
host = strings.ToLower(host)
l.locked(func() {
h := l.host(host)
if h.Failures == 0 && h.BackoffUntil.IsZero() { return }
h.Failures, h.BackoffUntil = 0, time.Time{}
l.setHost(host, h)
})
}
// NextCheck is when url may be checked next, given its interval: the
// interval jittered by ±20%, but never less than URLFloor after the last
// check, by this or another dibs process.
func (l *Limiter) NextCheck(pageURL string, interval time.Duration) time.Time {
l.mu.Lock()
defer l.mu.Unlock()
last := l.lastCheck(pageURL)
if last.IsZero() { return l.clock.Now() }
return last.Add(l.Jittered(interval, URLFloor))
}
// URLReady is the earliest time url may be checked at all.
func (l *Limiter) URLReady(pageURL string) time.Time {
l.mu.Lock()
defer l.mu.Unlock()
return l.urlReady(pageURL)
}
// LastCheck is when the URL was last checked by any dibs process, or zero.
func (l *Limiter) LastCheck(pageURL string) time.Time {
l.mu.Lock()
defer l.mu.Unlock()
return l.lastCheck(pageURL)
}
// Jittered stretches or shrinks d randomly by up to ±20%, but never below
// floor.
func (l *Limiter) Jittered(d, floor time.Duration) time.Duration {
return max(time.Duration(float64(d)*(1+Jitter*(2*l.rand()-1))), floor)
}
// locked runs fn holding the limiter's lock and, if there is one, the lock
// shared with other processes.
func (l *Limiter) locked(fn func()) {
l.mu.Lock()
defer l.mu.Unlock()
if l.persist != nil { defer l.persist.Lock()() }
fn()
}
// host returns what this and other processes know about host. Callers hold
// mu.
func (l *Limiter) host(host string) HostState {
h := l.hosts[host]
if l.persist == nil { return h }
if p, ok := l.persist.LoadHost(host); ok {
h.Next = latest(h.Next, p.Next)
h.BackoffUntil = latest(h.BackoffUntil, p.BackoffUntil)
h.Failures = max(h.Failures, p.Failures)
}
return h
}
func (l *Limiter) setHost(host string, h HostState) {
l.hosts[host] = h
if l.persist != nil { l.persist.StoreHost(host, h) }
}
// urlReady is when url may be checked again. Callers hold mu.
func (l *Limiter) urlReady(pageURL string) time.Time {
last := l.lastCheck(pageURL)
if last.IsZero() { return last }
return last.Add(URLFloor)
}
// lastCheck is the newest check of the URL that this or another process
// knows of. Callers hold mu.
func (l *Limiter) lastCheck(pageURL string) time.Time {
last := l.urls[pageURL]
if l.persist != nil {
if p, ok := l.persist.LoadURL(pageURL); ok { last = latest(last, p) }
}
return last
}
func latest(a, b time.Time) time.Time {
if a.After(b) { return a }
return b
}