diff --git a/cmd/dibs/check.go b/cmd/dibs/check.go index c7946db..b3e144d 100644 --- a/cmd/dibs/check.go +++ b/cmd/dibs/check.go @@ -48,10 +48,10 @@ func runCheck(args []string, stdout, stderr io.Writer) int { fetchURL, err := p.Normalize(ctx, url) if err != nil { return fail(stderr, "check", err) } - client, err := fetch.New(fetch.Options{}) + e, err := openEnv(logger) if err != nil { return fail(stderr, "check", err) } - resp, err := client.Get(ctx, fetchURL) + resp, err := e.fetch(ctx, fetchURL, logger) if err != nil { return fail(stderr, "check", err) } report, err := plugin.Evaluate(ctx, p, url, resp) @@ -62,7 +62,7 @@ func runCheck(args []string, stdout, stderr io.Writer) int { } // runPlugin implements `dibs plugin test [--status CODE] -// [url]`: run a plugin on a saved page. +// [url]`: it runs a plugin on a saved page. func runPlugin(args []string, stdout, stderr io.Writer) int { if len(args) == 0 || args[0] != "test" { _, _ = fmt.Fprintf(stderr, "dibs plugin: expected \"test\"\n\n%s", usage) diff --git a/cmd/dibs/env.go b/cmd/dibs/env.go new file mode 100644 index 0000000..d296be1 --- /dev/null +++ b/cmd/dibs/env.go @@ -0,0 +1,82 @@ +package main + +import ( + "context" + "fmt" + "log/slog" + "net/url" + "path/filepath" + "time" + + "git.security-command.org/Overlord/dibs/internal/fetch" + "git.security-command.org/Overlord/dibs/internal/ratelimit" + "git.security-command.org/Overlord/dibs/internal/state" + "git.security-command.org/Overlord/dibs/internal/watch" +) + +// env is what every command that talks to shops shares with every other +// dibs process: the state file behind the rate limits, and the cookies. +type env struct { + dir string + store *state.Store + limiter *ratelimit.Limiter + jar *fetch.Jar + client *fetch.Client +} + +func openEnv(logger *slog.Logger) (*env, error) { + dir, err := state.Dir() + if err != nil { return nil, fmt.Errorf("no config dir for the state file: %w", err) } + + store := state.Open(dir) + limiter := ratelimit.New(store) + + jar := fetch.NewJar() + if err := jar.Load(filepath.Join(dir, "cookies.json")); err != nil { logger.Warn("ignoring saved cookies", "err", err) } + + client, err := fetch.New(fetch.Options{Limiter: limiter, Jar: jar}) + if err != nil { return nil, err } + + return &env{dir: dir, store: store, limiter: limiter, jar: jar, client: client}, nil +} + +// save writes the cookies, and reports trouble with the state file. +func (e *env) save(logger *slog.Logger) { + if err := e.jar.Save(filepath.Join(e.dir, "cookies.json")); err != nil { logger.Warn("saving cookies failed", "err", err) } + if err := e.store.Err(); err != nil { logger.Warn("state file unusable, rate limits only hold within this process", "err", err) } +} + +// explainWait says why the next check of fetchURL will take a while, if it +// will: it was checked less than a minute ago, by this or another dibs +// process, or its host is busy or backed off. +func (e *env) explainWait(fetchURL string, logger *slog.Logger) { + if wait := time.Until(e.limiter.URLReady(fetchURL)); wait > time.Second { + logger.Info("URL was checked recently, waiting", "url", fetchURL, "wait", wait.Round(time.Second)) + return + } + + u, err := url.Parse(fetchURL) + if err != nil { return } + + if wait := e.limiter.Delay(u.Hostname()); wait > time.Second { + logger.Info("waiting for the host's rate limit", "host", u.Hostname(), "wait", wait.Round(time.Second)) + } +} + +// fetch makes a single check of fetchURL that counts like a scheduled one: +// the client waits for its turn, and the outcome is recorded for every dibs +// process. +func (e *env) fetch(ctx context.Context, fetchURL string, logger *slog.Logger) (*fetch.Response, error) { + e.explainWait(fetchURL, logger) + + resp, err := e.client.Get(ctx, fetchURL) + if ctx.Err() == nil { + if u, perr := url.Parse(fetchURL); perr == nil { + if d := watch.RecordOutcome(e.limiter, u.Hostname(), resp, err); d > 0 { logger.Warn("host backed off", "host", u.Hostname(), "for", d.Round(time.Second)) } + } + + e.save(logger) + } + + return resp, err +} diff --git a/cmd/dibs/fixtures.go b/cmd/dibs/fixtures.go index 3ac0251..96d5b18 100644 --- a/cmd/dibs/fixtures.go +++ b/cmd/dibs/fixtures.go @@ -5,21 +5,15 @@ import ( "fmt" "io" "log/slog" - "net/url" "os" "os/signal" - "time" - "git.security-command.org/Overlord/dibs/internal/fetch" "git.security-command.org/Overlord/dibs/internal/fixtures" "git.security-command.org/Overlord/dibs/internal/plugin" ) -// fixtureSpacing is the pause between two requests to the same host. -const fixtureSpacing = 12 * time.Second - -// runFixtures implements `dibs fixtures [--dir DIR] [--only NAME]`: fetch the -// pages listed in DIR//cases.toml for the plugin tests. +// runFixtures implements `dibs fixtures [--dir DIR] [--only NAME]`: it fetches +// the pages listed in DIR//cases.toml for the plugin tests. func runFixtures(args []string, stdout, stderr io.Writer) int { flags, configPath := newFlagSet("dibs fixtures", stderr) dir := flags.String("dir", "testdata", "directory with /cases.toml files") @@ -42,15 +36,16 @@ func runFixtures(args []string, stdout, stderr io.Writer) int { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) defer stop() - host, err := newHost(cfg, slog.New(slog.NewTextHandler(stderr, nil))) + logger := slog.New(slog.NewTextHandler(stderr, nil)) + + host, err := newHost(cfg, logger) if err != nil { return fail(stderr, "fixtures", err) } defer host.Close() - client, err := fetch.New(fetch.Options{}) + e, err := openEnv(logger) if err != nil { return fail(stderr, "fixtures", err) } - lastRequest := map[string]time.Time{} - failed := 0 + failed := 0 for _, suite := range suites { p, ok := host.Plugin(suite.Shop) @@ -62,7 +57,7 @@ func runFixtures(args []string, stdout, stderr io.Writer) int { for _, c := range suite.Cases { if *only != "" && c.Name != *only { continue } - if err := fetchFixture(ctx, client, p, suite, c, lastRequest, stdout); err != nil { + if err := fetchFixture(ctx, e, p, suite, c, logger, stdout); err != nil { if ctx.Err() != nil { return fail(stderr, "fixtures", ctx.Err()) } _, _ = fmt.Fprintf(stderr, "dibs fixtures: %s: %v\n", c.Name, err) @@ -76,23 +71,11 @@ func runFixtures(args []string, stdout, stderr io.Writer) int { return 0 } -func fetchFixture(ctx context.Context, client *fetch.Client, p *plugin.Plugin, suite fixtures.Suite, c fixtures.Case, lastRequest map[string]time.Time, stdout io.Writer) error { +func fetchFixture(ctx context.Context, e *env, p *plugin.Plugin, suite fixtures.Suite, c fixtures.Case, logger *slog.Logger, stdout io.Writer) error { fetchURL, err := p.Normalize(ctx, c.URL) if err != nil { return err } - u, err := url.Parse(fetchURL) - if err != nil { return err } - - if wait := time.Until(lastRequest[u.Host].Add(fixtureSpacing)); wait > 0 { - select { - case <-time.After(wait): - case <-ctx.Done(): - return ctx.Err() - } - } - lastRequest[u.Host] = time.Now() - - resp, err := client.Get(ctx, fetchURL) + resp, err := e.fetch(ctx, fetchURL, logger) if err != nil { return err } report, err := plugin.Evaluate(ctx, p, c.URL, resp) diff --git a/cmd/dibs/main.go b/cmd/dibs/main.go index 1f54094..3a721bd 100644 --- a/cmd/dibs/main.go +++ b/cmd/dibs/main.go @@ -52,7 +52,7 @@ func run(args []string, stdout, stderr io.Writer) int { } flags, configPath := newFlagSet("dibs", stderr) - flags.Bool("headless", false, "run without the TUI, log to stdout") + headless := flags.Bool("headless", false, "run without the TUI, log JSON to stdout") if err := flags.Parse(args); err != nil { return 2 } @@ -61,10 +61,10 @@ func run(args []string, stdout, stderr io.Writer) int { return 2 } - if _, ok := loadConfig(*configPath, stderr); !ok { return 1 } + cfg, ok := loadConfig(*configPath, stderr) + if !ok { return 1 } - _, _ = fmt.Fprintln(stderr, "dibs: watching is not implemented yet") - return 1 + return runWatch(cfg, *headless, stdout, stderr) } func runConfig(args []string, stdout, stderr io.Writer) int { diff --git a/cmd/dibs/watch.go b/cmd/dibs/watch.go new file mode 100644 index 0000000..d28762a --- /dev/null +++ b/cmd/dibs/watch.go @@ -0,0 +1,75 @@ +package main + +import ( + "context" + "io" + "log/slog" + "os" + "os/signal" + "syscall" + "time" + + "git.security-command.org/Overlord/dibs/internal/config" + "git.security-command.org/Overlord/dibs/internal/watch" +) + +// runWatch watches every configured URL until interrupted. +func runWatch(cfg *config.Config, headless bool, stdout, stderr io.Writer) int { + if !headless { + _, _ = io.WriteString(stderr, "dibs: the TUI is not implemented yet; run with --headless\n") + return 1 + } + + logger := slog.New(slog.NewJSONHandler(stdout, nil)) + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + e, err := openEnv(logger) + if err != nil { return fail(stderr, "watch", err) } + + host, err := newHost(cfg, logger) + if err != nil { return fail(stderr, "watch", err) } + defer host.Close() + + sched, warnings, err := watch.New(ctx, cfg, host, e.client, e.limiter) + if err != nil { return fail(stderr, "watch", err) } + + for _, w := range warnings { logger.Warn(w) } + + statuses := sched.Statuses() + logger.Info("watching", "items", len(cfg.Items), "urls", len(statuses)) + + go sched.Run(ctx) + + for r := range sched.Results() { + logResult(logger, r) + e.save(logger) + } + + logger.Info("stopped") + return 0 +} + +func logResult(logger *slog.Logger, r watch.Result) { + attrs := []any{"item", r.Item.Name, "url", r.URL, "next", r.Next.Format(time.RFC3339)} + + if r.Backoff > 0 { attrs = append(attrs, "backoff", r.Backoff.Round(time.Second).String()) } + + if r.Report != nil { + attrs = append(attrs, "verdict", r.Report.Verdict, "status", r.Report.Status) + if r.Report.Challenge != "" { attrs = append(attrs, "challenge", r.Report.Challenge) } + + if res := r.Report.Result; res != nil { + attrs = append(attrs, "title", res.Title, "available", res.Available, "seller", res.Seller) + if res.Price != nil { attrs = append(attrs, "price", *res.Price, "currency", res.Currency) } + } + } + + if r.Err != nil { + logger.Warn("check failed", append(attrs, "err", r.Err.Error())...) + return + } + + logger.Info("checked", attrs...) +} diff --git a/go.mod b/go.mod index 5b279f6..bccf0a7 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ require ( github.com/pelletier/go-toml/v2 v2.4.3 github.com/yuin/gopher-lua v1.1.2 golang.org/x/net v0.60.0 + golang.org/x/sys v0.48.0 ) require ( @@ -24,6 +25,5 @@ require ( github.com/quic-go/qpack v0.6.0 // indirect github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect golang.org/x/crypto v0.57.0 // indirect - golang.org/x/sys v0.48.0 // indirect golang.org/x/text v0.42.0 // indirect ) diff --git a/internal/config/config.go b/internal/config/config.go index 402e46c..1939de4 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -10,14 +10,17 @@ import ( "time" "github.com/pelletier/go-toml/v2" + + "git.security-command.org/Overlord/dibs/internal/ratelimit" ) -// MinInterval is the shortest allowed polling interval per URL. -const MinInterval = 60 * time.Second +// MinInterval is the shortest allowed polling interval per URL. The +// scheduler enforces it too, whatever the config says. +const MinInterval = ratelimit.URLFloor const ( - // Seller policies for an item: sold by the shop itself; sold or at least - // shipped by it (e.g. Fulfilled by Amazon); or anyone. + // The seller policies accept offers sold by the shop itself, offers it + // sells or only ships (such as Fulfilled by Amazon), or any offer. SellerFirstParty = "first_party" SellerFulfilled = "fulfilled" SellerAny = "any" @@ -30,7 +33,6 @@ const ( FormatJSON = "json" ) -// Defaults for keys that may be omitted. const ( DefaultInterval = 3 * time.Minute DefaultCooldown = 30 * time.Minute @@ -48,7 +50,7 @@ type Config struct { Items []Item `toml:"item"` Accounts map[string]Account `toml:"accounts"` Notify Notify `toml:"notify"` - // Plugins maps a plugin name to its file. After Load the paths are absolute. + // Plugins maps plugin names to files. Load makes the paths absolute. Plugins map[string]string `toml:"plugins"` Sandbox Sandbox `toml:"sandbox"` @@ -89,7 +91,6 @@ type Webhook struct { Format string `toml:"format"` } -// Sandbox holds the limits for Lua plugin calls. type Sandbox struct { // Timeout applies to matches, parse and cart_link. Timeout Duration `toml:"timeout"` @@ -152,7 +153,6 @@ func (it Item) AcceptsSeller(seller string) bool { return rank <= policyRanks[it.Seller] } -// Options control validation that depends on the environment. type Options struct { // Builtins are the names of the embedded plugins. Builtins []string @@ -167,8 +167,7 @@ func DefaultPath() (string, error) { return filepath.Join(dir, "dibs", "dibs.toml"), nil } -// Load reads, decodes and validates the config at path. All problems found -// are returned together as Errors. +// Load returns every problem it finds at once, as Errors. func Load(path string, opts Options) (*Config, error) { data, err := os.ReadFile(path) if err != nil { return nil, err } @@ -206,7 +205,7 @@ func Load(path string, opts Options) (*Config, error) { switch { case err == nil: case errors.As(err, &strict): - // The rest of the document was decoded, so keep validating it. + // The rest of the document was decoded, so validation goes on. for _, e := range strict.Errors { msg := "unknown key" if k := e.Key(); len(k) > 0 && k[len(k)-1] == "quantity" { diff --git a/internal/config/positions.go b/internal/config/positions.go index 6c4ec40..7d005cf 100644 --- a/internal/config/positions.go +++ b/internal/config/positions.go @@ -107,8 +107,8 @@ func (ps positions) keyAt(line, col int) string { for path, p := range ps { if p.Line == line && p.Column <= col && p.Column >= bestCol { - // Prefer the longer path when an array element and its first key - // share a position. + // An array element and its first key can share a position; the + // longer path wins. if p.Column > bestCol || len(path) > len(best) { best, bestCol = path, p.Column } diff --git a/internal/config/validate.go b/internal/config/validate.go index 5a20b9d..9126d95 100644 --- a/internal/config/validate.go +++ b/internal/config/validate.go @@ -16,7 +16,6 @@ import ( "github.com/pelletier/go-toml/v2" ) -// Ranges for the [sandbox] limits. const ( minSandboxTimeout = 100 * time.Millisecond maxSandboxTimeout = 30 * time.Second @@ -47,7 +46,6 @@ var goTypeNames = map[string]string{ "config.Duration": `a duration string such as "3m"`, } -// Error is one problem in the config file. type Error struct { File string Line int // 1-based; 0 if unknown @@ -71,7 +69,7 @@ func (e Error) Error() string { return b.String() } -// Errors is every problem found in one config file, sorted by position. +// Errors is sorted by position in the file. type Errors []Error func (es Errors) Error() string { @@ -99,8 +97,8 @@ func (v *validator) decodeError(de *toml.DecodeError, msg string) { msg = friendlyDecodeMsg(strings.TrimPrefix(de.Error(), "toml: ")) } - // The decoder's key has no array indexes, so prefer the indexed path of - // the key at that position. + // The decoder's key has no array indexes; the key indexed at the same + // position has them. key := v.pos.keyAt(line, col) if key == "" { key = strings.Join(de.Key(), ".") diff --git a/internal/fetch/browser.go b/internal/fetch/browser.go index 4eccdd6..dcbc895 100644 --- a/internal/fetch/browser.go +++ b/internal/fetch/browser.go @@ -12,8 +12,7 @@ import ( ) // chromeMajor must match chromeProfile: the TLS and HTTP/2 fingerprint come -// from the profile, the headers from the version. Bump both together when -// updating tls-client. +// from the profile, the headers from the version, so the two change together. const chromeMajor = 152 var chromeProfile = profiles.Chrome_152 @@ -26,8 +25,8 @@ type Browser struct { Platform string // sec-ch-ua-platform, without quotes } -// DefaultBrowser returns desktop Chrome on the current OS, so that cookies -// a real browser on this machine obtains later stay valid for us. +// DefaultBrowser returns desktop Chrome on the current OS, so that cookies a +// real browser on this machine obtains later stay valid for these requests. func DefaultBrowser() Browser { ua, platform := "Windows NT 10.0; Win64; x64", "Windows" @@ -37,7 +36,7 @@ func DefaultBrowser() Browser { case "linux": ua, platform = "X11; Linux x86_64", "Linux" default: - // Windows, and anything else, which Chrome supports no better. + // Windows. Other systems pass as Windows too. } return Browser{ @@ -86,8 +85,8 @@ func (b Browser) navigationHeaders(u *url.URL) http.Header { // secCHUA builds Chrome's sec-ch-ua brand list. Chrome derives the GREASE // brand and the brand order from its major version (GenerateBrandVersionList -// in Chromium's user_agent_utils.cc), so a fixed string would give us away -// after an update. +// in Chromium's user_agent_utils.cc), so a fixed string would stand out after +// an update. func secCHUA(major int) string { chars := []string{" ", "(", ":", "-", ".", "/", ")", ";", "=", "?", "_"} versions := []string{"8", "99", "24"} diff --git a/internal/fetch/classify.go b/internal/fetch/classify.go index 15157fb..28bbd82 100644 --- a/internal/fetch/classify.go +++ b/internal/fetch/classify.go @@ -16,8 +16,8 @@ const ( NotFound // Challenge is a bot check that a real browser may clear. Challenge - // Blocked is a refusal without a recognisable challenge, e.g. a plain 403 - // or 429. Back off and retry later. + // Blocked is a refusal without a recognisable challenge, such as a plain + // 403 or 429. The host is backed off and retried later. Blocked // HTTPError is any other non-2xx status. HTTPError diff --git a/internal/fetch/client.go b/internal/fetch/client.go index f127af8..9ae7850 100644 --- a/internal/fetch/client.go +++ b/internal/fetch/client.go @@ -13,6 +13,8 @@ import ( http "github.com/bogdanfinn/fhttp" tlsclient "github.com/bogdanfinn/tls-client" + + "git.security-command.org/Overlord/dibs/internal/ratelimit" ) const ( @@ -23,14 +25,23 @@ const ( // ErrBodyTooLarge is returned when a response exceeds Options.MaxBody. var ErrBodyTooLarge = errors.New("response body too large") +// Limiter decides when a page may be fetched. Every request waits for it. +type Limiter interface { + WaitCheck(ctx context.Context, url string) error +} + type Options struct { - // Browser to impersonate. Defaults to DefaultBrowser(). + // Limiter defaults to a new in-memory ratelimit.Limiter, so requests are + // never unlimited. + Limiter Limiter + // Browser defaults to DefaultBrowser(). Browser *Browser - // Jar holds the cookies. Defaults to a new, empty jar. + // Jar defaults to a new, empty jar. Jar *Jar - // Timeout per request, including redirects. Defaults to DefaultTimeout. + // Timeout covers a request and its redirects. It defaults to + // DefaultTimeout. Timeout time.Duration - // MaxBody is the largest body read, after decompression. Defaults to + // MaxBody limits the body after decompression. It defaults to // DefaultMaxBody. MaxBody int64 } @@ -38,12 +49,12 @@ type Options struct { // Client fetches pages. It is safe for concurrent use. type Client struct { http tlsclient.HttpClient + limiter Limiter browser Browser jar *Jar maxBody int64 } -// Response is a fetched page. type Response struct { URL string // as requested FinalURL string // after redirects @@ -60,6 +71,7 @@ type Response struct { func New(opts Options) (*Client, error) { browser := DefaultBrowser() if opts.Browser != nil { browser = *opts.Browser } + if opts.Limiter == nil { opts.Limiter = ratelimit.New(nil) } if opts.Jar == nil { opts.Jar = NewJar() } if opts.Timeout == 0 { opts.Timeout = DefaultTimeout } if opts.MaxBody == 0 { opts.MaxBody = DefaultMaxBody } @@ -72,19 +84,21 @@ func New(opts Options) (*Client, error) { ) if err != nil { return nil, fmt.Errorf("creating HTTP client: %w", err) } - return &Client{http: hc, browser: browser, jar: opts.Jar, maxBody: opts.MaxBody}, nil + return &Client{http: hc, limiter: opts.Limiter, browser: browser, jar: opts.Jar, maxBody: opts.MaxBody}, nil } -// Jar returns the client's cookie jar. func (c *Client) Jar() *Jar { return c.jar } -// Get fetches rawURL the way Chrome opens a bookmark. A response with a bad -// status is not an error: check Verdict. +// Get fetches rawURL the way Chrome opens a bookmark, once the limiter allows +// a check of it. A response with a bad status is not an error; its Verdict +// says what it is. func (c *Client) Get(ctx context.Context, rawURL string) (*Response, error) { u, err := url.Parse(rawURL) if err != nil { return nil, err } if u.Scheme != "http" && u.Scheme != "https" { return nil, fmt.Errorf("unsupported URL scheme %q", u.Scheme) } + if err := c.limiter.WaitCheck(ctx, rawURL); err != nil { return nil, err } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) if err != nil { return nil, err } req.Header = c.browser.navigationHeaders(u) diff --git a/internal/fetch/fetch_test.go b/internal/fetch/fetch_test.go index 32ccb85..171b976 100644 --- a/internal/fetch/fetch_test.go +++ b/internal/fetch/fetch_test.go @@ -172,9 +172,16 @@ func TestJarSaveLoad(t *testing.T) { if err := NewJar().Load(filepath.Join(t.TempDir(), "missing.json")); err != nil { t.Errorf("missing file: %v", err) } } +// noLimit lets tests talk to their local server without the host floor. +type noLimit struct{} + +func (noLimit) WaitCheck(context.Context, string) error { return nil } + func newTestClient(t *testing.T, opts Options) *Client { t.Helper() + if opts.Limiter == nil { opts.Limiter = noLimit{} } + c, err := New(opts) if err != nil { t.Fatal(err) } diff --git a/internal/fetch/jar.go b/internal/fetch/jar.go index 9128433..c7f5b0f 100644 --- a/internal/fetch/jar.go +++ b/internal/fetch/jar.go @@ -7,7 +7,6 @@ import ( "maps" "net/url" "os" - "path/filepath" "slices" "strings" "sync" @@ -16,6 +15,8 @@ import ( http "github.com/bogdanfinn/fhttp" "github.com/bogdanfinn/fhttp/cookiejar" "golang.org/x/net/publicsuffix" + + "git.security-command.org/Overlord/dibs/internal/fsutil" ) // Cookie is a stored cookie, in a form that survives a restart and can be @@ -54,7 +55,6 @@ func NewJar() *Jar { } } -// SetCookies implements http.CookieJar. func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) { j.mu.Lock() defer j.mu.Unlock() @@ -91,7 +91,6 @@ func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) { } } -// Cookies implements http.CookieJar. func (j *Jar) Cookies(u *url.URL) []*http.Cookie { j.mu.Lock() defer j.mu.Unlock() @@ -160,7 +159,7 @@ func (j *Jar) Save(path string) error { data, err := json.MarshalIndent(j.Export(), "", " ") if err != nil { return err } - return writeFileAtomic(path, data, 0o600) + return fsutil.WriteFileAtomic(path, data, 0o600) } // Load imports the cookies saved at path. A missing file is not an error. @@ -186,27 +185,3 @@ func defaultPath(p string) string { return p[:i] } - -// writeFileAtomic replaces path with data, so a crash never leaves a -// half-written file behind. -func writeFileAtomic(path string, data []byte, perm fs.FileMode) error { - if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return err } - - tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*") - if err != nil { return err } - defer func() { _ = os.Remove(tmp.Name()) }() - - if err := tmp.Chmod(perm); err != nil { - _ = tmp.Close() - return err - } - - if _, err := tmp.Write(data); err != nil { - _ = tmp.Close() - return err - } - - if err := tmp.Close(); err != nil { return err } - - return os.Rename(tmp.Name(), path) -} diff --git a/internal/fixtures/fixtures.go b/internal/fixtures/fixtures.go index 519e9b1..24292e8 100644 --- a/internal/fixtures/fixtures.go +++ b/internal/fixtures/fixtures.go @@ -79,7 +79,6 @@ func Load(dir string) ([]Suite, error) { func (s Suite) PagePath(c Case) string { return filepath.Join(s.Dir, "pages", c.Name+".html") } func (s Suite) ReportPath(c Case) string { return filepath.Join(s.Dir, "pages", c.Name+".json") } -// Save writes a fetched page and its report. func (s Suite) Save(c Case, page []byte, report any) error { data, err := EncodeReport(report) if err != nil { return err } diff --git a/internal/fsutil/fsutil.go b/internal/fsutil/fsutil.go new file mode 100644 index 0000000..541de04 --- /dev/null +++ b/internal/fsutil/fsutil.go @@ -0,0 +1,33 @@ +// Package fsutil has file helpers shared by the packages that persist data. +package fsutil + +import ( + "io/fs" + "os" + "path/filepath" +) + +// WriteFileAtomic replaces path with data, so a crash never leaves a +// half-written file behind. Missing parent directories are created for the +// user only. +func WriteFileAtomic(path string, data []byte, perm fs.FileMode) error { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return err } + + tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*") + if err != nil { return err } + defer func() { _ = os.Remove(tmp.Name()) }() + + if err := tmp.Chmod(perm); err != nil { + _ = tmp.Close() + return err + } + + if _, err := tmp.Write(data); err != nil { + _ = tmp.Close() + return err + } + + if err := tmp.Close(); err != nil { return err } + + return os.Rename(tmp.Name(), path) +} diff --git a/internal/fsutil/lock.go b/internal/fsutil/lock.go new file mode 100644 index 0000000..97e61b1 --- /dev/null +++ b/internal/fsutil/lock.go @@ -0,0 +1,26 @@ +package fsutil + +import ( + "os" + "path/filepath" +) + +// Lock takes an exclusive lock on path, creating it if needed, and blocks +// until it gets it. The lock is shared with other processes. The returned +// function releases it. +func Lock(path string) (func(), error) { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return nil, err } + + f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600) + if err != nil { return nil, err } + + if err := lockFile(f); err != nil { + _ = f.Close() + return nil, err + } + + return func() { + _ = unlockFile(f) + _ = f.Close() + }, nil +} diff --git a/internal/fsutil/lock_unix.go b/internal/fsutil/lock_unix.go new file mode 100644 index 0000000..bf6b3fb --- /dev/null +++ b/internal/fsutil/lock_unix.go @@ -0,0 +1,11 @@ +//go:build unix + +package fsutil + +import ( + "os" + "syscall" +) + +func lockFile(f *os.File) error { return syscall.Flock(int(f.Fd()), syscall.LOCK_EX) } +func unlockFile(f *os.File) error { return syscall.Flock(int(f.Fd()), syscall.LOCK_UN) } diff --git a/internal/fsutil/lock_windows.go b/internal/fsutil/lock_windows.go new file mode 100644 index 0000000..bd79e3d --- /dev/null +++ b/internal/fsutil/lock_windows.go @@ -0,0 +1,17 @@ +//go:build windows + +package fsutil + +import ( + "os" + + "golang.org/x/sys/windows" +) + +func lockFile(f *os.File) error { + return windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, new(windows.Overlapped)) +} + +func unlockFile(f *os.File) error { + return windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, new(windows.Overlapped)) +} diff --git a/internal/plugin/builtin/amazon.lua b/internal/plugin/builtin/amazon.lua index a157cf8..6050e52 100644 --- a/internal/plugin/builtin/amazon.lua +++ b/internal/plugin/builtin/amazon.lua @@ -1,7 +1,6 @@ -- Built-in plugin for Amazon product pages (de, co.uk, fr, it, es, nl, com). --- --- It uses only the public plugin API, so it doubles as the reference for --- writing your own: see "Writing a plugin" in README.md. +-- It uses only the public plugin API, so it doubles as the reference +-- implementation of a plugin. local tlds = { ["de"] = "EUR", @@ -26,7 +25,7 @@ local amazon_merchants = { } -- Any of these buttons means a new item can go into the cart. The preorder --- selectors are a best guess until we have a real preorder page. +-- selectors are unverified: no real preorder page has been checked yet. -- "#add-to-cart-button-ubb" is deliberately missing: it belongs to the used -- buybox, which Amazon shows when only used copies are left. local buy_buttons = table.concat({ diff --git a/internal/plugin/doc.go b/internal/plugin/doc.go index da3cb7e..9a46416 100644 --- a/internal/plugin/doc.go +++ b/internal/plugin/doc.go @@ -12,9 +12,9 @@ import ( const nodeType = "dibs.node" -// The methods of doc and of the nodes doc:all() returns. Each takes an -// optional CSS selector: without one it works on the node itself, with one -// on the first match inside it. +// nodeMethods are the methods of doc and of the nodes doc:all() returns. +// Each takes an optional CSS selector: without one it works on the node +// itself, with one on the first match inside it. var nodeMethods = map[string]lua.LGFunction{ "text": nodeText, "attr": nodeAttr, @@ -72,7 +72,7 @@ func selector(L *lua.LState, arg int) cascadia.Selector { // node:text([sel]) is the visible text of the node or its first match, with // whitespace collapsed. It is nil if nothing matches or the text is empty, -// so `if doc:text(sel) then` means "has text". Use exists to test presence. +// so `if doc:text(sel) then` means "has text"; exists tests presence. func nodeText(L *lua.LState) int { s := target(L, checkNode(L), 2).First() diff --git a/internal/plugin/host.go b/internal/plugin/host.go index 127699f..12cc4bf 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -21,7 +21,6 @@ var builtinFS embed.FS // ErrNoPlugin is returned when no plugin matches a URL. var ErrNoPlugin = errors.New("no plugin matches the URL") -// Builtins returns the names of the embedded plugins. func Builtins() []string { files, _ := fs.Glob(builtinFS, "builtin/*.lua") @@ -31,12 +30,10 @@ func Builtins() []string { return names } -// BuiltinSource returns the code of an embedded plugin. func BuiltinSource(name string) ([]byte, error) { return builtinFS.ReadFile("builtin/" + name + ".lua") } -// Host holds the loaded plugins. type Host struct { plugins map[string]*Plugin // order is the order ForURL tries plugins in: user plugins first, so @@ -92,7 +89,6 @@ func NewHost(user map[string]string, limits Limits, logger *slog.Logger) (*Host, return h, nil } -// Plugin returns the plugin called name. func (h *Host) Plugin(name string) (*Plugin, bool) { p, ok := h.plugins[name] return p, ok diff --git a/internal/plugin/plugin.go b/internal/plugin/plugin.go index 7e0c470..7afaa07 100644 --- a/internal/plugin/plugin.go +++ b/internal/plugin/plugin.go @@ -19,14 +19,14 @@ import ( lua "github.com/yuin/gopher-lua" ) -// Who sells the item, as parse reports it. +// The sellers parse reports. const ( - // SellerFirstParty: the shop itself sells it. + // SellerFirstParty means the shop itself sells the item. SellerFirstParty = "first_party" - // SellerFulfilled: a marketplace seller sells it, but the shop ships it - // (e.g. Fulfilled by Amazon). + // SellerFulfilled means a marketplace seller sells the item and the shop + // ships it, as with Fulfilled by Amazon. SellerFulfilled = "fulfilled" - // SellerThirdParty: a marketplace seller sells and ships it. + // SellerThirdParty means a marketplace seller sells and ships the item. SellerThirdParty = "third_party" SellerUnknown = "unknown" ) @@ -172,7 +172,6 @@ func (p *Plugin) readTable(tbl *lua.LTable) error { return nil } -// Has reports whether the plugin defines hook. func (p *Plugin) Has(hook string) bool { p.mu.Lock() defer p.mu.Unlock() @@ -207,7 +206,7 @@ func (p *Plugin) call(ctx context.Context, hook string, nret int, args func(L *l return nil }) - // A killed call can stop anywhere, so start over with a clean state. + // A killed call can stop anywhere, so the state is rebuilt from scratch. if errors.Is(err, ErrTimeout) || errors.Is(err, ErrMemoryLimit) { if rerr := p.reset(); rerr != nil { p.logger.Error("reloading plugin failed", "plugin", p.Name, "err", rerr) } } @@ -245,10 +244,9 @@ func (p *Plugin) Normalize(ctx context.Context, url string) (string, error) { } } -// Parse runs parse(doc, url) on a page. func (p *Plugin) Parse(ctx context.Context, page []byte, url string) (*Result, error) { - // Parse the HTML before the call, so it does not count against the - // call's time and memory. + // The HTML is parsed before the call, so parsing does not count against + // the call's time and memory. doc, err := goquery.NewDocumentFromReader(bytes.NewReader(page)) if err != nil { return nil, fmt.Errorf("parsing HTML: %w", err) } @@ -284,7 +282,6 @@ func (p *Plugin) CartLink(ctx context.Context, url, id string) (string, error) { } } -// Close frees the Lua state. func (p *Plugin) Close() { p.mu.Lock() defer p.mu.Unlock() diff --git a/internal/ratelimit/ratelimit.go b/internal/ratelimit/ratelimit.go new file mode 100644 index 0000000..798500f --- /dev/null +++ b/internal/ratelimit/ratelimit.go @@ -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< 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) } +} diff --git a/internal/state/state.go b/internal/state/state.go new file mode 100644 index 0000000..8d0d3af --- /dev/null +++ b/internal/state/state.go @@ -0,0 +1,147 @@ +// Package state keeps what dibs must remember between runs in a JSON file in +// the user config dir. Every dibs process shares it, so a `dibs check` run +// next to a running watcher still respects the rate limits. +package state + +import ( + "encoding/json" + "errors" + "io/fs" + "os" + "path/filepath" + "sync" + "time" + + "git.security-command.org/Overlord/dibs/internal/fsutil" + "git.security-command.org/Overlord/dibs/internal/ratelimit" +) + +// Hosts and URLs untouched for forgetAfter are dropped, such as URLs removed +// from the config. +const forgetAfter = 7 * 24 * time.Hour + +type file struct { + Hosts map[string]ratelimit.HostState `json:"hosts"` + URLs map[string]time.Time `json:"urls"` +} + +// Store is the state file. It implements ratelimit.Persister. +type Store struct { + path string + lock string + + mu sync.Mutex + err error +} + +// Dir is the directory dibs keeps its files in. +func Dir() (string, error) { + dir, err := os.UserConfigDir() + if err != nil { return "", err } + + return filepath.Join(dir, "dibs"), nil +} + +// Open returns the store at dir/state.json. The file is created on the first +// write. +func Open(dir string) *Store { + return &Store{path: filepath.Join(dir, "state.json"), lock: filepath.Join(dir, "state.lock")} +} + +// Err returns the last error reading or writing the file, if any. The +// limiter still works in memory without the file. +func (s *Store) Err() error { + s.mu.Lock() + defer s.mu.Unlock() + + return s.err +} + +// Lock takes the lock shared by every dibs process using this directory. +// When that fails, the limiter carries on with only its in-process lock. +func (s *Store) Lock() func() { + unlock, err := fsutil.Lock(s.lock) + if err != nil { + s.mu.Lock() + s.err = err + s.mu.Unlock() + + return func() {} + } + + return unlock +} + +func (s *Store) LoadHost(host string) (ratelimit.HostState, bool) { + s.mu.Lock() + defer s.mu.Unlock() + + h, ok := s.read().Hosts[host] + return h, ok +} + +// StoreHost replaces the state of host. The limiter has already merged in +// what other processes stored. +func (s *Store) StoreHost(host string, h ratelimit.HostState) { + s.update(func(f *file) { f.Hosts[host] = h }) +} + +func (s *Store) LoadURL(url string) (time.Time, bool) { + s.mu.Lock() + defer s.mu.Unlock() + + t, ok := s.read().URLs[url] + return t, ok +} + +func (s *Store) StoreURL(url string, last time.Time) { + s.update(func(f *file) { + if last.After(f.URLs[url]) { f.URLs[url] = last } + }) +} + +// read returns the file's contents, or empty state if there is none yet. +// Callers hold mu. +func (s *Store) read() *file { + f := &file{Hosts: map[string]ratelimit.HostState{}, URLs: map[string]time.Time{}} + + data, err := os.ReadFile(s.path) + switch { + case errors.Is(err, fs.ErrNotExist): + return f + case err != nil: + s.err = err + return f + } + + if err := json.Unmarshal(data, f); err != nil { + s.err = err + return f + } + + if f.Hosts == nil { f.Hosts = map[string]ratelimit.HostState{} } + if f.URLs == nil { f.URLs = map[string]time.Time{} } + + return f +} + +func (s *Store) update(change func(f *file)) { + s.mu.Lock() + defer s.mu.Unlock() + + f := s.read() + change(f) + + cutoff := time.Now().Add(-forgetAfter) + for host, h := range f.Hosts { + if h.Next.Before(cutoff) && h.BackoffUntil.Before(cutoff) { delete(f.Hosts, host) } + } + for url, t := range f.URLs { + if t.Before(cutoff) { delete(f.URLs, url) } + } + + data, err := json.MarshalIndent(f, "", " ") + if err == nil { err = fsutil.WriteFileAtomic(s.path, data, 0o600) } + + s.err = err +} diff --git a/internal/state/state_test.go b/internal/state/state_test.go new file mode 100644 index 0000000..b8c8961 --- /dev/null +++ b/internal/state/state_test.go @@ -0,0 +1,77 @@ +package state + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "git.security-command.org/Overlord/dibs/internal/ratelimit" +) + +// Two dibs processes, such as a watcher and a `dibs check`, share the floors +// through the state file. +func TestFloorsHoldAcrossProcesses(t *testing.T) { + dir := t.TempDir() + ctx := context.Background() + + watcher := ratelimit.New(Open(dir)) + check := ratelimit.New(Open(dir)) + + const page = "https://www.amazon.de/dp/B0HMX2FSTF" + + if err := watcher.WaitCheck(ctx, page); err != nil { t.Fatal(err) } + + if d := check.Delay("www.amazon.de"); d < 9*time.Second { t.Errorf("the other process may request again in %s, want about %s", d, ratelimit.HostFloor) } + if wait := time.Until(check.URLReady(page)); wait < 59*time.Second { t.Errorf("the other process may check the URL again in %s, want about %s", wait, ratelimit.URLFloor) } + + watcher.Failure("www.amazon.de") + if d := check.Delay("www.amazon.de"); d < time.Minute { t.Errorf("the other process ignores the backoff: delay %s", d) } + + if err := Open(dir).Err(); err != nil { t.Error(err) } +} + +// stoppedClock never moves, so a limiter that has to wait blocks until its +// context ends. +type stoppedClock struct{ now time.Time } + +func (c stoppedClock) Now() time.Time { return c.now } +func (c stoppedClock) After(time.Duration) <-chan time.Time { return nil } + +// Two processes asking for the same host at the same instant: exactly one +// may get it. Without the file lock, both sometimes read "free" before +// either writes. +func TestReservationsAreExclusive(t *testing.T) { + clock := stoppedClock{now: time.Now()} + + for round := range 30 { + dir := t.TempDir() + + var ( + wg sync.WaitGroup + granted atomic.Int32 + ) + + for i := range 2 { + l := ratelimit.New(Open(dir), ratelimit.WithClock(clock)) + + wg.Add(1) + go func() { + defer wg.Done() + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + + page := []string{"https://www.amazon.de/dp/B0DK51S84Z", "https://www.amazon.de/dp/B076WS2WJ6"}[i] + if l.WaitCheck(ctx, page) == nil { granted.Add(1) } + }() + } + + wg.Wait() + + if n := granted.Load(); n != 1 { + t.Fatalf("round %d: %d processes got the host at once, want 1", round, n) + } + } +} diff --git a/internal/watch/watch.go b/internal/watch/watch.go new file mode 100644 index 0000000..f980394 --- /dev/null +++ b/internal/watch/watch.go @@ -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: + } +} diff --git a/internal/watch/watch_test.go b/internal/watch/watch_test.go new file mode 100644 index 0000000..718aff0 --- /dev/null +++ b/internal/watch/watch_test.go @@ -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") } +} diff --git a/testdata/amazon/cases.toml b/testdata/amazon/cases.toml index 0cf50d6..e14198c 100644 --- a/testdata/amazon/cases.toml +++ b/testdata/amazon/cases.toml @@ -1,9 +1,9 @@ # Real Amazon pages the amazon plugin is tested on. `dibs fixtures` fetches # them into pages/ (not tracked), together with the report dibs made for -# each. Pages change: when a case stops showing what its note says, pick -# another product. +# each. Pages change over time, so a case that stops showing what its note +# says needs another product. # -# Still wanted: a page sold by Amazon itself, and a preorder. +# No case covers a page sold by Amazon itself or a preorder yet. [[case]] name = "out-of-stock-de"