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:
1 parent
bb010356a0
commit
2175c0e5aa
30 files changed
+1434
-126
No files matched your search
@@ -0,0 +1,317 @@
|
||||
// Package watch schedules the checks of every configured URL.
|
||||
package watch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/config"
|
||||
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||
"git.security-command.org/Overlord/dibs/internal/plugin"
|
||||
"git.security-command.org/Overlord/dibs/internal/ratelimit"
|
||||
)
|
||||
|
||||
// tick is how often the scheduler looks for due URLs.
|
||||
const tick = time.Second
|
||||
|
||||
// Fetcher fetches pages. *fetch.Client is the real one; it waits for the
|
||||
// limiter's WaitCheck itself.
|
||||
type Fetcher interface {
|
||||
Get(ctx context.Context, url string) (*fetch.Response, error)
|
||||
}
|
||||
|
||||
// Result is one finished check.
|
||||
type Result struct {
|
||||
Item config.Item
|
||||
// URL is the URL as configured.
|
||||
URL string
|
||||
Time time.Time
|
||||
Report *plugin.Report
|
||||
Err error
|
||||
// Backoff is how long the host is avoided after this result, if at all.
|
||||
Backoff time.Duration
|
||||
// Next is when the URL is checked next.
|
||||
Next time.Time
|
||||
}
|
||||
|
||||
// Status is a snapshot of one URL for display.
|
||||
type Status struct {
|
||||
Item string
|
||||
Shop string
|
||||
URL string
|
||||
Host string
|
||||
Last time.Time
|
||||
Next time.Time
|
||||
Paused bool
|
||||
Checking bool
|
||||
}
|
||||
|
||||
type target struct {
|
||||
item config.Item
|
||||
url string // as configured
|
||||
fetchURL string // normalized by the plugin
|
||||
host string
|
||||
plugin *plugin.Plugin
|
||||
|
||||
// Guarded by Scheduler.mu.
|
||||
last time.Time
|
||||
next time.Time
|
||||
paused bool
|
||||
inFlight bool
|
||||
}
|
||||
|
||||
// Scheduler checks every URL at its interval. Each round, the due URLs are
|
||||
// shuffled and handed to one worker per host, so hosts are checked in
|
||||
// parallel and each host's requests in sequence.
|
||||
type Scheduler struct {
|
||||
fetcher Fetcher
|
||||
limiter *ratelimit.Limiter
|
||||
clock ratelimit.Clock
|
||||
results chan Result
|
||||
wake chan struct{}
|
||||
|
||||
mu sync.Mutex
|
||||
targets []*target
|
||||
}
|
||||
|
||||
// New plans a check for every URL of every item. It returns warnings about
|
||||
// URLs a plugin's matches() rejects; they are still checked.
|
||||
func New(ctx context.Context, cfg *config.Config, host *plugin.Host, fetcher Fetcher, limiter *ratelimit.Limiter) (*Scheduler, []string, error) {
|
||||
s := &Scheduler{
|
||||
fetcher: fetcher,
|
||||
limiter: limiter,
|
||||
clock: limiter.Clock(),
|
||||
results: make(chan Result, 64),
|
||||
wake: make(chan struct{}, 1),
|
||||
}
|
||||
|
||||
var warnings []string
|
||||
|
||||
seen := map[string]string{}
|
||||
|
||||
for _, item := range cfg.Items {
|
||||
p, ok := host.Plugin(item.Shop)
|
||||
if !ok { return nil, nil, fmt.Errorf("item %q: no plugin named %q", item.Name, item.Shop) }
|
||||
|
||||
for _, raw := range item.URLs {
|
||||
if p.Has("matches") {
|
||||
ok, err := p.Matches(ctx, raw)
|
||||
if err != nil { return nil, nil, err }
|
||||
if !ok { warnings = append(warnings, fmt.Sprintf("item %q: %s does not look like a %s URL", item.Name, raw, item.Shop)) }
|
||||
}
|
||||
|
||||
fetchURL, err := p.Normalize(ctx, raw)
|
||||
if err != nil { return nil, nil, err }
|
||||
|
||||
// Two spellings of one product would be checked twice as often.
|
||||
if prev, dup := seen[fetchURL]; dup { return nil, nil, fmt.Errorf("item %q: %s is the same page as %s", item.Name, raw, prev) }
|
||||
seen[fetchURL] = raw
|
||||
|
||||
u, err := url.Parse(fetchURL)
|
||||
if err != nil { return nil, nil, err }
|
||||
|
||||
s.targets = append(s.targets, &target{
|
||||
item: item,
|
||||
url: raw,
|
||||
fetchURL: fetchURL,
|
||||
host: strings.ToLower(u.Hostname()),
|
||||
plugin: p,
|
||||
next: limiter.NextCheck(fetchURL, item.Interval.Duration),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return s, warnings, nil
|
||||
}
|
||||
|
||||
// Results delivers every finished check. It is closed when Run returns.
|
||||
func (s *Scheduler) Results() <-chan Result { return s.results }
|
||||
|
||||
// Run checks URLs until ctx is done.
|
||||
func (s *Scheduler) Run(ctx context.Context) {
|
||||
workers := map[string]chan *target{}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
defer func() {
|
||||
for _, ch := range workers { close(ch) }
|
||||
wg.Wait()
|
||||
close(s.results)
|
||||
}()
|
||||
|
||||
for {
|
||||
due := s.due()
|
||||
rand.Shuffle(len(due), func(i, j int) { due[i], due[j] = due[j], due[i] })
|
||||
|
||||
for _, t := range due {
|
||||
ch, ok := workers[t.host]
|
||||
if !ok {
|
||||
// Room for every target, so handing work over never blocks.
|
||||
ch = make(chan *target, len(s.targets))
|
||||
workers[t.host] = ch
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for t := range ch { s.check(ctx, t) }
|
||||
}()
|
||||
}
|
||||
|
||||
ch <- t
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-s.clock.After(tick):
|
||||
case <-s.wake:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// due marks and returns the targets whose time has come.
|
||||
func (s *Scheduler) due() []*target {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
now := s.clock.Now()
|
||||
|
||||
var due []*target
|
||||
for _, t := range s.targets {
|
||||
if t.paused || t.inFlight || now.Before(t.next) { continue }
|
||||
|
||||
// Another dibs process may have checked the URL since this check was
|
||||
// planned.
|
||||
if ready := s.limiter.URLReady(t.fetchURL); now.Before(ready) {
|
||||
t.next = s.limiter.NextCheck(t.fetchURL, t.item.Interval.Duration)
|
||||
continue
|
||||
}
|
||||
|
||||
t.inFlight = true
|
||||
due = append(due, t)
|
||||
}
|
||||
|
||||
return due
|
||||
}
|
||||
|
||||
func (s *Scheduler) check(ctx context.Context, t *target) {
|
||||
if ctx.Err() != nil { return }
|
||||
|
||||
// The fetcher reserves the check with the limiter right before the request.
|
||||
resp, err := s.fetcher.Get(ctx, t.fetchURL)
|
||||
if ctx.Err() != nil { return }
|
||||
|
||||
backoff := RecordOutcome(s.limiter, t.host, resp, err)
|
||||
|
||||
var report *plugin.Report
|
||||
if err == nil { report, err = plugin.Evaluate(ctx, t.plugin, t.url, resp) }
|
||||
|
||||
s.mu.Lock()
|
||||
t.last = s.clock.Now()
|
||||
t.next = s.limiter.NextCheck(t.fetchURL, t.item.Interval.Duration)
|
||||
t.inFlight = false
|
||||
next := t.next
|
||||
s.mu.Unlock()
|
||||
|
||||
r := Result{Item: t.item, URL: t.url, Time: t.last, Report: report, Err: err, Backoff: backoff, Next: next}
|
||||
|
||||
select {
|
||||
case s.results <- r:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}
|
||||
|
||||
// RecordOutcome tells the limiter how a request to host went: bot checks,
|
||||
// refusals and failed requests back the host off, anything else clears its
|
||||
// backoff. It returns the backoff, or 0.
|
||||
func RecordOutcome(l *ratelimit.Limiter, host string, resp *fetch.Response, err error) time.Duration {
|
||||
switch {
|
||||
case errors.Is(err, context.Canceled):
|
||||
return 0
|
||||
case err != nil:
|
||||
return l.Failure(host)
|
||||
case resp.Verdict == fetch.Challenge || resp.Verdict == fetch.Blocked || resp.Verdict == fetch.HTTPError:
|
||||
return l.Failure(host)
|
||||
default:
|
||||
l.Success(host)
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// Pause pauses or resumes the item called name. It reports whether there is
|
||||
// such an item.
|
||||
func (s *Scheduler) Pause(name string, paused bool) bool {
|
||||
found := s.each(func(t *target) bool { return t.item.Name == name }, func(t *target) { t.paused = paused })
|
||||
s.poke()
|
||||
|
||||
return found
|
||||
}
|
||||
|
||||
func (s *Scheduler) PauseAll(paused bool) {
|
||||
s.each(func(*target) bool { return true }, func(t *target) { t.paused = paused })
|
||||
s.poke()
|
||||
}
|
||||
|
||||
// CheckNow moves the checks of the item called name forward, as far as the
|
||||
// URL floor allows. It reports whether there is such an item.
|
||||
func (s *Scheduler) CheckNow(name string) bool {
|
||||
found := s.each(func(t *target) bool { return t.item.Name == name }, func(t *target) {
|
||||
ready := s.limiter.URLReady(t.fetchURL)
|
||||
if now := s.clock.Now(); ready.Before(now) { ready = now }
|
||||
if ready.Before(t.next) { t.next = ready }
|
||||
})
|
||||
s.poke()
|
||||
|
||||
return found
|
||||
}
|
||||
|
||||
// Statuses returns a snapshot of every URL, in config order.
|
||||
func (s *Scheduler) Statuses() []Status {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
out := make([]Status, len(s.targets))
|
||||
for i, t := range s.targets {
|
||||
out[i] = Status{
|
||||
Item: t.item.Name,
|
||||
Shop: t.item.Shop,
|
||||
URL: t.url,
|
||||
Host: t.host,
|
||||
Last: t.last,
|
||||
Next: t.next,
|
||||
Paused: t.paused,
|
||||
Checking: t.inFlight,
|
||||
}
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Scheduler) each(match func(*target) bool, change func(*target)) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
found := false
|
||||
for _, t := range s.targets {
|
||||
if !match(t) { continue }
|
||||
|
||||
change(t)
|
||||
found = true
|
||||
}
|
||||
|
||||
return found
|
||||
}
|
||||
|
||||
// poke makes Run look for due URLs right away.
|
||||
func (s *Scheduler) poke() {
|
||||
select {
|
||||
case s.wake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package watch
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/config"
|
||||
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||
"git.security-command.org/Overlord/dibs/internal/plugin"
|
||||
"git.security-command.org/Overlord/dibs/internal/ratelimit"
|
||||
"git.security-command.org/Overlord/dibs/internal/state"
|
||||
)
|
||||
|
||||
// clock moves forward only when something waits on it.
|
||||
type clock struct {
|
||||
mu sync.Mutex
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func (c *clock) Now() time.Time {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
return c.now
|
||||
}
|
||||
|
||||
func (c *clock) 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
|
||||
}
|
||||
|
||||
// fetcher waits for the limiter like fetch.Client does, records when each
|
||||
// request went out, and answers 404 so no plugin has to parse anything.
|
||||
type fetcher struct {
|
||||
limiter *ratelimit.Limiter
|
||||
clock *clock
|
||||
requests map[string][]time.Time // by URL
|
||||
hosts map[string][]time.Time
|
||||
}
|
||||
|
||||
func (f *fetcher) Get(ctx context.Context, rawURL string) (*fetch.Response, error) {
|
||||
u, _ := url.Parse(rawURL)
|
||||
if err := f.limiter.WaitCheck(ctx, rawURL); err != nil { return nil, err }
|
||||
|
||||
now := f.clock.Now()
|
||||
f.requests[rawURL] = append(f.requests[rawURL], now)
|
||||
f.hosts[u.Hostname()] = append(f.hosts[u.Hostname()], now)
|
||||
|
||||
return fetch.NewResponse(rawURL, rawURL, 404, nil, nil), nil
|
||||
}
|
||||
|
||||
func item(name string, interval time.Duration, urls ...string) config.Item {
|
||||
it := config.Item{Name: name, Shop: "amazon", URLs: urls, Seller: config.SellerFulfilled}
|
||||
it.Interval.Duration = interval
|
||||
|
||||
return it
|
||||
}
|
||||
|
||||
// TestSchedulerFloors runs the scheduler's rounds by hand for two simulated
|
||||
// hours and checks no URL or host was ever asked too often.
|
||||
func TestSchedulerFloors(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
clk := &clock{now: time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)}
|
||||
|
||||
limiter := ratelimit.New(nil, ratelimit.WithClock(clk))
|
||||
|
||||
host, err := plugin.NewHost(nil, plugin.DefaultLimits(), slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
if err != nil { t.Fatal(err) }
|
||||
defer host.Close()
|
||||
|
||||
cfg := &config.Config{Items: []config.Item{
|
||||
item("metro", ratelimit.URLFloor, "https://www.amazon.de/dp/B0HMX2FSTF?th=1", "https://www.amazon.co.uk/dp/B0HM497GJJ"),
|
||||
item("cable", ratelimit.URLFloor, "https://www.amazon.de/dp/B0DK51S84Z"),
|
||||
item("disk", 5*time.Minute, "https://www.amazon.de/dp/B076WS2WJ6"),
|
||||
item("held", ratelimit.URLFloor, "https://www.amazon.de/dp/B0948LPGNG"),
|
||||
}}
|
||||
|
||||
f := &fetcher{limiter: limiter, clock: clk, requests: map[string][]time.Time{}, hosts: map[string][]time.Time{}}
|
||||
|
||||
s, _, err := New(ctx, cfg, host, f, limiter)
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
s.Pause("held", true)
|
||||
|
||||
end := clk.Now().Add(2 * time.Hour)
|
||||
for clk.Now().Before(end) {
|
||||
for _, tg := range s.due() { s.check(ctx, tg) }
|
||||
for len(s.results) > 0 { <-s.results }
|
||||
|
||||
<-clk.After(tick)
|
||||
}
|
||||
|
||||
for u, times := range f.requests {
|
||||
if len(times) < 10 { t.Errorf("%s: only %d checks in two hours", u, len(times)) }
|
||||
|
||||
for i := 1; i < len(times); i++ {
|
||||
if gap := times[i].Sub(times[i-1]); gap < ratelimit.URLFloor { t.Errorf("%s: checks %s apart", u, gap) }
|
||||
}
|
||||
}
|
||||
|
||||
for h, times := range f.hosts {
|
||||
for i := 1; i < len(times); i++ {
|
||||
if gap := times[i].Sub(times[i-1]); gap < ratelimit.HostFloor { t.Errorf("%s: requests %s apart", h, gap) }
|
||||
}
|
||||
}
|
||||
|
||||
if n := len(f.requests["https://www.amazon.de/dp/B0948LPGNG"]); n > 0 { t.Errorf("paused item was checked %d times", n) }
|
||||
if _, ok := f.requests["https://www.amazon.de/dp/B0HMX2FSTF"]; !ok { t.Errorf("URLs are not fetched normalized: %v", f.requests) }
|
||||
|
||||
// A forced check still waits for the URL floor.
|
||||
s.CheckNow("cable")
|
||||
for _, st := range s.Statuses() {
|
||||
if st.Item == "cable" && st.Next.Sub(st.Last) < ratelimit.URLFloor-tick { t.Errorf("forced check at %s, only %s after the last", st.Next, st.Next.Sub(st.Last)) }
|
||||
}
|
||||
}
|
||||
|
||||
// A `dibs check` of a URL between two scheduled checks pushes the next one
|
||||
// back to the URL floor.
|
||||
func TestSchedulerSeesOtherProcess(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
dir := t.TempDir()
|
||||
clk := &clock{now: time.Now()} // the state file forgets entries older than a week
|
||||
|
||||
limiter := ratelimit.New(state.Open(dir), ratelimit.WithClock(clk))
|
||||
other := ratelimit.New(state.Open(dir), ratelimit.WithClock(clk))
|
||||
|
||||
host, err := plugin.NewHost(nil, plugin.DefaultLimits(), slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
if err != nil { t.Fatal(err) }
|
||||
defer host.Close()
|
||||
|
||||
const u = "https://www.amazon.de/dp/B0DK51S84Z"
|
||||
|
||||
f := &fetcher{limiter: limiter, clock: clk, requests: map[string][]time.Time{}, hosts: map[string][]time.Time{}}
|
||||
|
||||
s, _, err := New(ctx, &config.Config{Items: []config.Item{item("cable", ratelimit.URLFloor, u)}}, host, f, limiter)
|
||||
if err != nil { t.Fatal(err) }
|
||||
|
||||
for _, tg := range s.due() { s.check(ctx, tg) }
|
||||
|
||||
// Before the next scheduled check, the other process checks the URL as
|
||||
// soon as the floor allows.
|
||||
<-clk.After(30 * time.Second)
|
||||
if err := other.WaitCheck(ctx, u); err != nil { t.Fatal(err) }
|
||||
checkedByOther := clk.Now()
|
||||
|
||||
for clk.Now().Before(checkedByOther.Add(2 * time.Minute)) {
|
||||
for _, tg := range s.due() { s.check(ctx, tg) }
|
||||
for len(s.results) > 0 { <-s.results }
|
||||
|
||||
<-clk.After(tick)
|
||||
}
|
||||
|
||||
times := f.requests[u]
|
||||
if len(times) < 2 { t.Fatalf("checked %d times, want at least 2", len(times)) }
|
||||
if gap := times[1].Sub(checkedByOther); gap < ratelimit.URLFloor { t.Errorf("checked %s after the other process did", gap) }
|
||||
}
|
||||
|
||||
func TestDuplicateURLs(t *testing.T) {
|
||||
host, err := plugin.NewHost(nil, plugin.DefaultLimits(), slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
if err != nil { t.Fatal(err) }
|
||||
defer host.Close()
|
||||
|
||||
cfg := &config.Config{Items: []config.Item{
|
||||
item("a", ratelimit.URLFloor, "https://www.amazon.de/dp/B0HMX2FSTF"),
|
||||
item("b", ratelimit.URLFloor, "https://www.amazon.de/Metro/dp/B0HMX2FSTF/ref=x"),
|
||||
}}
|
||||
|
||||
if _, _, err := New(context.Background(), cfg, host, nil, ratelimit.New(nil)); err == nil { t.Error("two spellings of one product were accepted") }
|
||||
}
|
||||
Reference in new issue
Block a user