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") } } func TestReload(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() 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("metro", ratelimit.URLFloor, "https://www.amazon.de/dp/B0HMX2FSTF", "https://www.amazon.co.uk/dp/B0HM497GJJ"), item("cable", ratelimit.URLFloor, "https://www.amazon.de/dp/B0DK51S84Z"), }}, host, f, limiter) if err != nil { t.Fatal(err) } for _, tg := range s.due() { s.check(ctx, tg) } s.Pause("metro", true) before := map[string]Status{} for _, st := range s.Statuses() { before[st.URL] = st } // The DE URL stays under a new spelling, the UK one goes, cable is // renamed and a new item comes in. _, err = s.Reload(ctx, &config.Config{Items: []config.Item{ item("metro", ratelimit.URLFloor, "https://www.amazon.de/dp/B0HMX2FSTF?th=1"), item("cable2", ratelimit.URLFloor, "https://www.amazon.de/dp/B0DK51S84Z"), item("disk", ratelimit.URLFloor, "https://www.amazon.de/dp/B076WS2WJ6"), }}, host) if err != nil { t.Fatal(err) } got := s.Statuses() if len(got) != 3 { t.Fatalf("%d URLs after reload, want 3", len(got)) } metro, cable, disk := got[0], got[1], got[2] if !metro.Paused || !metro.Last.Equal(before["https://www.amazon.de/dp/B0HMX2FSTF"].Last) { t.Errorf("metro lost its state: %+v", metro) } if cable.Item != "cable2" || !cable.Next.Equal(before["https://www.amazon.de/dp/B0DK51S84Z"].Next) { t.Errorf("cable lost its state: %+v", cable) } if disk.Paused || !disk.Last.IsZero() { t.Errorf("new item has old state: %+v", disk) } }