Add scheduler, rate limiting and headless mode.

Hard-coded 60s URL and 10s host floors with jitter and per-host
backoff, shared between dibs processes through a locked state file.
The scheduler shuffles due URLs each round and runs one worker per
host; 'dibs --headless' watches and logs JSON.
This commit is contained in:
Overlord committed 2026-10-14 09:04:15 +02:00
1 parent bb010356a0
commit 2175c0e5aa
30 files changed
+1434 -126

No files matched your search

+278
View File
@@ -0,0 +1,278 @@
// 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<<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)
}
// 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
}
+98
View File
@@ -0,0 +1,98 @@
package ratelimit
import (
"context"
"sync"
"testing"
"time"
)
// FakeClock moves forward only when something waits on it, by exactly the
// time waited.
type FakeClock struct {
mu sync.Mutex
now time.Time
}
func NewFakeClock() *FakeClock { return &FakeClock{now: time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)} }
func (c *FakeClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
func (c *FakeClock) After(d time.Duration) <-chan time.Time {
c.mu.Lock()
defer c.mu.Unlock()
c.now = c.now.Add(d)
ch := make(chan time.Time, 1)
ch <- c.now
return ch
}
func fixedRand(v float64) Option { return WithRand(func() float64 { return v }) }
func TestHostFloor(t *testing.T) {
ctx := context.Background()
for _, r := range []float64{0, 0.5, 0.999} {
clock := NewFakeClock()
l := New(nil, WithClock(clock), fixedRand(r))
if err := l.Wait(ctx, "www.amazon.de"); err != nil { t.Fatal(err) }
first := clock.Now()
// Another host is not held up.
if err := l.Wait(ctx, "www.amazon.co.uk"); err != nil { t.Fatal(err) }
if !clock.Now().Equal(first) { t.Errorf("rand %v: a request to another host waited", r) }
if err := l.Wait(ctx, "WWW.AMAZON.DE"); err != nil { t.Fatal(err) }
gap := clock.Now().Sub(first)
if gap < HostFloor || gap > time.Duration(float64(HostFloor)*(1+Jitter)) { t.Errorf("rand %v: gap %s, want between %s and %s", r, gap, HostFloor, time.Duration(float64(HostFloor)*(1+Jitter))) }
}
}
func TestURLFloor(t *testing.T) {
clock := NewFakeClock()
l := New(nil, WithClock(clock), fixedRand(0)) // shortest jitter: -20%
const url = "https://www.amazon.de/dp/B0HMX2FSTF"
if next := l.NextCheck(url, time.Minute); !next.Equal(clock.Now()) { t.Errorf("never checked: next %s, want now", next) }
if err := l.WaitCheck(context.Background(), url); err != nil { t.Fatal(err) }
last := clock.Now()
// 60s - 20% would be 48s, and an interval below the floor (which the
// config rejects anyway) must not get through either.
for _, interval := range []time.Duration{time.Minute, time.Second} {
if next := l.NextCheck(url, interval); next.Sub(last) < URLFloor { t.Errorf("interval %s: next check %s after the last, below the floor", interval, next.Sub(last)) }
}
if ready := l.URLReady(url); ready.Sub(last) != URLFloor { t.Errorf("URLReady %s after the last check, want %s", ready.Sub(last), URLFloor) }
if next := l.NextCheck(url, 10*time.Minute); next.Sub(last) != 8*time.Minute { t.Errorf("10m interval at -20%%: next after %s, want 8m", next.Sub(last)) }
}
func TestBackoff(t *testing.T) {
ctx := context.Background()
clock := NewFakeClock()
l := New(nil, WithClock(clock), fixedRand(0.5)) // no jitter
for i, want := range []time.Duration{2, 4, 8, 16, 30, 30} {
if got := l.Failure("www.amazon.de"); got != want*time.Minute { t.Errorf("failure %d: backoff %s, want %dm", i+1, got, want) }
}
start := clock.Now()
if err := l.Wait(ctx, "www.amazon.de"); err != nil { t.Fatal(err) }
if waited := clock.Now().Sub(start); waited != 30*time.Minute { t.Errorf("waited %s for a backed-off host, want 30m", waited) }
l.Success("www.amazon.de")
if got := l.Failure("www.amazon.de"); got != 2*time.Minute { t.Errorf("after a success: backoff %s, want it to start over at 2m", got) }
}