Files
dibs/internal/watch/watch.go
T
OverlordandClaude Bot a19e6fa711 Add the TUI.
A table with one row per URL, a level-colored log pane and a status bar.
New alerts flash their row and ring the bell. Keys pause, force checks,
open the product page or cart link, and reload the config, which is
validated first and applied in place, keeping each URL's timing.
Headless mode and the TUI now share one watcher.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 12:25:26 +02:00

377 lines
9.4 KiB
Go

// 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
// queue is how many checks a host's worker can have waiting. With the
// host floor of 10s, a full queue is over an hour of checks.
const queue = 512
// 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
FetchURL string
Host string
Last time.Time
Next time.Time
Paused bool
Checking bool
}
// target is one URL to check. Reload may change any field, so everything
// is guarded by Scheduler.mu.
type target struct {
item config.Item
url string // as configured
fetchURL string // normalized by the plugin
host string
plugin *plugin.Plugin
last time.Time
next time.Time
paused bool
inFlight bool
// removed is set when a reload drops the URL during its check.
removed 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),
}
targets, warnings, err := s.plan(ctx, cfg, host)
if err != nil { return nil, nil, err }
s.targets = targets
return s, warnings, nil
}
// Reload switches to a new config. URLs in both configs keep their timing
// and pause state; a changed interval applies from the next check. A
// failed reload changes nothing.
func (s *Scheduler) Reload(ctx context.Context, cfg *config.Config, host *plugin.Host) ([]string, error) {
targets, warnings, err := s.plan(ctx, cfg, host)
if err != nil { return nil, err }
s.mu.Lock()
defer s.mu.Unlock()
old := map[string]*target{}
for _, t := range s.targets { old[t.fetchURL] = t }
for i, t := range targets {
prev, ok := old[t.fetchURL]
if !ok { continue }
delete(old, t.fetchURL)
interval := prev.item.Interval.Duration
prev.item, prev.url, prev.plugin = t.item, t.url, t.plugin
if !prev.inFlight && t.item.Interval.Duration != interval { prev.next = t.next }
targets[i] = prev
}
for _, t := range old { t.removed = true }
s.targets = targets
s.poke()
return warnings, nil
}
// plan builds the targets of cfg.
func (s *Scheduler) plan(ctx context.Context, cfg *config.Config, host *plugin.Host) ([]*target, []string, error) {
var targets []*target
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 }
targets = append(targets, &target{
item: item,
url: raw,
fetchURL: fetchURL,
host: strings.ToLower(u.Hostname()),
plugin: p,
next: s.limiter.NextCheck(fetchURL, item.Interval.Duration),
})
}
}
return targets, 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 {
ch = make(chan *target, queue)
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 }
s.mu.Lock()
item, rawURL, fetchURL, p := t.item, t.url, t.fetchURL, t.plugin
s.mu.Unlock()
// The fetcher reserves the check with the limiter right before the request.
resp, err := s.fetcher.Get(ctx, 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, p, rawURL, resp) }
s.mu.Lock()
t.last = s.clock.Now()
t.next = s.limiter.NextCheck(fetchURL, t.item.Interval.Duration)
t.inFlight = false
last, next := t.last, t.next
removed := t.removed
s.mu.Unlock()
if removed { return }
r := Result{Item: item, URL: rawURL, Time: 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,
FetchURL: t.fetchURL,
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:
}
}