Compare commits

...
4 Commits
Author SHA1 Message Date
Overlord f2ea1297e8 Improve table resizing, add terminal workaround, and expose last check. 2026-10-14 12:37:27 +02:00
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
Overlord 8f0eda5d4d Add alerts, currency conversion and notifications.
Items fire when a page is available from an accepted seller at or below
max_price, converted with the ECB's daily rates when the page uses
another currency. A per-item cooldown, kept in the state file, holds
back repeat alerts unless the price drops. Alerts go to Discord, ntfy
and JSON webhooks with retries, and to the desktop;
'dibs notify test' sends a sample.
2026-10-14 11:55:27 +02:00
Overlord 2175c0e5aa 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.
2026-10-14 09:04:15 +02:00
45 changed files with 4128 additions and 134 deletions

No files matched your search

+3 -3
View File
@@ -48,10 +48,10 @@ func runCheck(args []string, stdout, stderr io.Writer) int {
fetchURL, err := p.Normalize(ctx, url) fetchURL, err := p.Normalize(ctx, url)
if err != nil { return fail(stderr, "check", err) } 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) } 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) } if err != nil { return fail(stderr, "check", err) }
report, err := plugin.Evaluate(ctx, p, url, resp) 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] <file.lua> // runPlugin implements `dibs plugin test [--status CODE] <file.lua>
// <fixture.html> [url]`: run a plugin on a saved page. // <fixture.html> [url]`: it runs a plugin on a saved page.
func runPlugin(args []string, stdout, stderr io.Writer) int { func runPlugin(args []string, stdout, stderr io.Writer) int {
if len(args) == 0 || args[0] != "test" { if len(args) == 0 || args[0] != "test" {
_, _ = fmt.Fprintf(stderr, "dibs plugin: expected \"test\"\n\n%s", usage) _, _ = fmt.Fprintf(stderr, "dibs plugin: expected \"test\"\n\n%s", usage)
+82
View File
@@ -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
}
+10 -27
View File
@@ -5,21 +5,15 @@ import (
"fmt" "fmt"
"io" "io"
"log/slog" "log/slog"
"net/url"
"os" "os"
"os/signal" "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/fixtures"
"git.security-command.org/Overlord/dibs/internal/plugin" "git.security-command.org/Overlord/dibs/internal/plugin"
) )
// fixtureSpacing is the pause between two requests to the same host. // runFixtures implements `dibs fixtures [--dir DIR] [--only NAME]`: it fetches
const fixtureSpacing = 12 * time.Second // the pages listed in DIR/<shop>/cases.toml for the plugin tests.
// runFixtures implements `dibs fixtures [--dir DIR] [--only NAME]`: fetch the
// pages listed in DIR/<shop>/cases.toml for the plugin tests.
func runFixtures(args []string, stdout, stderr io.Writer) int { func runFixtures(args []string, stdout, stderr io.Writer) int {
flags, configPath := newFlagSet("dibs fixtures", stderr) flags, configPath := newFlagSet("dibs fixtures", stderr)
dir := flags.String("dir", "testdata", "directory with <shop>/cases.toml files") dir := flags.String("dir", "testdata", "directory with <shop>/cases.toml files")
@@ -42,15 +36,16 @@ func runFixtures(args []string, stdout, stderr io.Writer) int {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop() 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) } if err != nil { return fail(stderr, "fixtures", err) }
defer host.Close() defer host.Close()
client, err := fetch.New(fetch.Options{}) e, err := openEnv(logger)
if err != nil { return fail(stderr, "fixtures", err) } if err != nil { return fail(stderr, "fixtures", err) }
lastRequest := map[string]time.Time{} failed := 0
failed := 0
for _, suite := range suites { for _, suite := range suites {
p, ok := host.Plugin(suite.Shop) p, ok := host.Plugin(suite.Shop)
@@ -62,7 +57,7 @@ func runFixtures(args []string, stdout, stderr io.Writer) int {
for _, c := range suite.Cases { for _, c := range suite.Cases {
if *only != "" && c.Name != *only { continue } 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()) } if ctx.Err() != nil { return fail(stderr, "fixtures", ctx.Err()) }
_, _ = fmt.Fprintf(stderr, "dibs fixtures: %s: %v\n", c.Name, 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 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) fetchURL, err := p.Normalize(ctx, c.URL)
if err != nil { return err } if err != nil { return err }
u, err := url.Parse(fetchURL) resp, err := e.fetch(ctx, fetchURL, logger)
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)
if err != nil { return err } if err != nil { return err }
report, err := plugin.Evaluate(ctx, p, c.URL, resp) report, err := plugin.Evaluate(ctx, p, c.URL, resp)
+9 -6
View File
@@ -23,7 +23,8 @@ const usage = `Usage:
dibs check [--shop NAME] <url> fetch and parse one URL, print JSON dibs check [--shop NAME] <url> fetch and parse one URL, print JSON
dibs plugin test [--status CODE] <file.lua> <fixture.html> [url] dibs plugin test [--status CODE] <file.lua> <fixture.html> [url]
dibs config validate [--config FILE] dibs config validate [--config FILE]
dibs fixtures [--dir testdata] [--only NAME] fetch real pages for the plugin tests dibs notify test [--config FILE] [--item NAME] send a sample alert to every channel
dibs fixtures [--dir testdata] [--only NAME] fetch real pages for the plugin tests
dibs version dibs version
` `
@@ -36,7 +37,7 @@ func run(args []string, stdout, stderr io.Writer) int {
switch args[0] { switch args[0] {
case "config": case "config":
return runConfig(args[1:], stdout, stderr) return runConfig(args[1:], stdout, stderr)
case "version": case "version", "-v", "--version":
printVersion(stdout) printVersion(stdout)
return 0 return 0
case "check": case "check":
@@ -45,6 +46,8 @@ func run(args []string, stdout, stderr io.Writer) int {
return runPlugin(args[1:], stdout, stderr) return runPlugin(args[1:], stdout, stderr)
case "fixtures": case "fixtures":
return runFixtures(args[1:], stdout, stderr) return runFixtures(args[1:], stdout, stderr)
case "notify":
return runNotify(args[1:], stdout, stderr)
case "help", "-h", "--help": case "help", "-h", "--help":
_, _ = fmt.Fprint(stdout, usage) _, _ = fmt.Fprint(stdout, usage)
return 0 return 0
@@ -52,7 +55,7 @@ func run(args []string, stdout, stderr io.Writer) int {
} }
flags, configPath := newFlagSet("dibs", stderr) 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 } if err := flags.Parse(args); err != nil { return 2 }
@@ -61,10 +64,10 @@ func run(args []string, stdout, stderr io.Writer) int {
return 2 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 runWatch(cfg, *headless, stdout, stderr)
return 1
} }
func runConfig(args []string, stdout, stderr io.Writer) int { func runConfig(args []string, stdout, stderr io.Writer) int {
+115
View File
@@ -0,0 +1,115 @@
package main
import (
"context"
"fmt"
"io"
"log/slog"
"os"
"os/signal"
"time"
"git.security-command.org/Overlord/dibs/internal/alert"
"git.security-command.org/Overlord/dibs/internal/config"
"git.security-command.org/Overlord/dibs/internal/notify"
"git.security-command.org/Overlord/dibs/internal/plugin"
)
// sendTimeout covers every retry of every channel of one alert.
const sendTimeout = time.Minute
// runNotify implements `dibs notify test [--item NAME]`: it sends a sample
// alert for one item to every configured channel.
func runNotify(args []string, stdout, stderr io.Writer) int {
if len(args) == 0 || args[0] != "test" {
_, _ = fmt.Fprintf(stderr, "dibs notify: expected \"test\"\n\n%s", usage)
return 2
}
flags, configPath := newFlagSet("dibs notify test", stderr)
name := flags.String("item", "", "item to build the sample alert from (default: the first)")
pos, ok := parseArgs(flags, args[1:])
if !ok { return 2 }
if len(pos) > 0 {
_, _ = fmt.Fprintf(stderr, "dibs notify test: unexpected argument %q\n\n%s", pos[0], usage)
return 2
}
cfg, ok := loadConfig(*configPath, stderr)
if !ok { return 1 }
item, ok := findItem(cfg, *name)
if !ok {
_, _ = fmt.Fprintf(stderr, "dibs notify test: no item named %q\n", *name)
return 1
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
logger := slog.New(slog.NewTextHandler(stderr, nil))
host, err := newHost(cfg, logger)
if err != nil { return fail(stderr, "notify test", err) }
defer host.Close()
a, err := sampleAlert(ctx, host, item)
if err != nil { return fail(stderr, "notify test", err) }
n := notify.New(cfg.Notify, userAgent())
if len(n.Channels()) == 0 {
_, _ = fmt.Fprintln(stderr, "dibs notify test: no webhooks configured and desktop notifications are off")
return 1
}
ctx, cancel := context.WithTimeout(ctx, sendTimeout)
defer cancel()
if err := n.Send(ctx, a); err != nil { return fail(stderr, "notify test", err) }
_, _ = fmt.Fprintf(stdout, "sent a test alert for %q to: %v\n", item.Name, n.Channels())
return 0
}
func findItem(cfg *config.Config, name string) (config.Item, bool) {
for _, it := range cfg.Items {
if name == "" || it.Name == name { return it, true }
}
return config.Item{}, false
}
// sampleAlert is what the item's first URL would send if it fired at its
// max_price.
func sampleAlert(ctx context.Context, host *plugin.Host, item config.Item) (alert.Alert, error) {
p, ok := host.Plugin(item.Shop)
if !ok { return alert.Alert{}, fmt.Errorf("no plugin named %q", item.Shop) }
pageURL, err := p.Normalize(ctx, item.URLs[0])
if err != nil { return alert.Alert{}, err }
cartLink, err := p.CartLink(ctx, pageURL, "")
if err != nil { return alert.Alert{}, err }
price := 99.99
if item.MaxPrice != nil { price = *item.MaxPrice }
currency := item.Currency
if currency == "" { currency = "EUR" }
return alert.Alert{
Item: item.Name,
Shop: item.Shop,
URL: pageURL,
Title: "Sample product title",
Price: &price,
Currency: currency,
Seller: plugin.SellerFirstParty,
CartLink: cartLink,
Time: time.Now(),
Test: true,
}, nil
}
func userAgent() string { return "dibs/" + version }
+67
View File
@@ -0,0 +1,67 @@
package main
import (
"context"
"errors"
"io"
"log/slog"
"os"
"os/signal"
"strings"
"syscall"
tea "charm.land/bubbletea/v2"
"github.com/charmbracelet/colorprofile"
"git.security-command.org/Overlord/dibs/internal/config"
"git.security-command.org/Overlord/dibs/internal/tui"
)
// runTUI watches every configured URL in the TUI until the user quits.
func runTUI(cfg *config.Config, stderr io.Writer) int {
// Ctrl-C reaches the TUI as a key press.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM)
defer stop()
logs := tui.NewLogHandler(slog.LevelInfo)
logger := slog.New(logs)
w, err := newWatcher(ctx, cfg, logger, slog.LevelDebug)
if err != nil { return fail(stderr, "watch", err) }
p := tea.NewProgram(tui.New(w, cfg.Path, logs), append(terminalOptions(), tea.WithContext(ctx))...)
done := make(chan struct{})
go func() {
defer close(done)
w.run(func(c check) { p.Send(tui.CheckMsg{Result: c.Result, Decision: c.Decision, PriceErr: c.PriceErr}) })
}()
_, err = p.Run()
logs.Redirect(stderr)
stop()
<-done
w.close()
if err != nil && !errors.Is(err, tea.ErrProgramKilled) { return fail(stderr, "tui", err) }
return 0
}
// terminalOptions works around terminals that claim to be xterm but are not.
// Under a TERM the renderer does not know, it redraws with plain writes only.
// The color profile is detected from the real environment first, so colors stay.
func terminalOptions() []tea.ProgramOption {
if os.Getenv("TERMINAL_EMULATOR") != "JetBrains-JediTerm" { return nil }
profile := colorprofile.Detect(os.Stdout, os.Environ())
env := []string{"TERM=jediterm"}
for _, kv := range os.Environ() {
if !strings.HasPrefix(kv, "TERM=") { env = append(env, kv) }
}
return []tea.ProgramOption{tea.WithEnvironment(env), tea.WithColorProfile(profile)}
}
+290
View File
@@ -0,0 +1,290 @@
package main
import (
"context"
"errors"
"io"
"log/slog"
"os"
"os/signal"
"sync"
"syscall"
"time"
"git.security-command.org/Overlord/dibs/internal/alert"
"git.security-command.org/Overlord/dibs/internal/config"
"git.security-command.org/Overlord/dibs/internal/fetch"
"git.security-command.org/Overlord/dibs/internal/fx"
"git.security-command.org/Overlord/dibs/internal/notify"
"git.security-command.org/Overlord/dibs/internal/plugin"
"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 { return runTUI(cfg, stderr) }
logger := slog.New(slog.NewJSONHandler(stdout, nil))
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
w, err := newWatcher(ctx, cfg, logger, slog.LevelInfo)
if err != nil { return fail(stderr, "watch", err) }
ring := isTerminal(stderr)
w.run(func(c check) {
if ring && c.Decision.Alert != nil { _, _ = io.WriteString(stderr, "\a") }
})
// A second Ctrl-C stops dibs without waiting for notifications.
stop()
w.close()
logger.Info("stopped")
return 0
}
// check is one finished check and what the alert engine made of it.
type check struct {
watch.Result
Decision alert.Decision
// PriceErr means the page was available but its price could not be
// checked.
PriceErr error
}
// watcher runs the scheduler and turns its results into alerts, for the
// TUI and headless mode alike.
type watcher struct {
ctx context.Context
logger *slog.Logger
env *env
sched *watch.Scheduler
rates *fx.Service
// checkLevel is the level checks are logged at. Failed checks are
// always warnings.
checkLevel slog.Level
reloadMu sync.Mutex
mu sync.Mutex
cfg *config.Config
host *plugin.Host
alerts *alert.Engine
notifier *notify.Notifier
// retired are the hosts reloads replaced. Checks that started before a
// reload may still use them, so they are closed on exit.
retired []*plugin.Host
sends sync.WaitGroup
}
func newWatcher(ctx context.Context, cfg *config.Config, logger *slog.Logger, checkLevel slog.Level) (*watcher, error) {
e, err := openEnv(logger)
if err != nil { return nil, err }
host, err := newHost(cfg, logger)
if err != nil { return nil, err }
sched, warnings, err := watch.New(ctx, cfg, host, e.client, e.limiter)
if err != nil {
host.Close()
return nil, err
}
for _, msg := range warnings { logger.Warn(msg) }
w := &watcher{
ctx: ctx,
logger: logger,
env: e,
sched: sched,
rates: fx.New(e.store, e.limiter),
checkLevel: checkLevel,
}
w.apply(cfg, host)
logger.Info("watching", "items", len(cfg.Items), "urls", len(sched.Statuses()), "notify", w.notifier.Channels())
return w, nil
}
// apply switches the alert settings and plugins to cfg's.
func (w *watcher) apply(cfg *config.Config, host *plugin.Host) {
if needsRates(cfg) { w.rates.Warm() }
w.mu.Lock()
defer w.mu.Unlock()
if w.host != nil { w.retired = append(w.retired, w.host) }
w.cfg = cfg
w.host = host
w.alerts = alert.NewEngine(cfg.Notify.Cooldown.Duration, w.rates, w.env.store)
w.notifier = notify.New(cfg.Notify, userAgent())
}
// run handles every check until the watcher's context ends. observe sees
// each check after it is logged and its alert is on its way.
func (w *watcher) run(observe func(check)) {
go w.sched.Run(w.ctx)
for r := range w.sched.Results() {
w.env.save(w.logger)
observe(w.consider(r))
}
}
func (w *watcher) consider(r watch.Result) check {
logResult(w.logger, w.checkLevel, r)
c := check{Result: r}
if r.Err != nil { return c }
w.mu.Lock()
alerts, notifier := w.alerts, w.notifier
w.mu.Unlock()
c.Decision, c.PriceErr = alerts.Consider(w.ctx, r.Item, r.Report, r.Time)
switch {
case c.PriceErr != nil:
w.logger.Warn("available, but the price cannot be checked", "item", r.Item.Name, "url", r.URL, "err", c.PriceErr)
case c.Decision.Alert != nil:
w.fire(notifier, *c.Decision.Alert)
case c.Decision.Reason != "":
w.logger.Info("available, not alerting", "item", r.Item.Name, "url", r.URL, "reason", c.Decision.Reason)
}
return c
}
// fire logs an alert and sends its notifications in the background.
func (w *watcher) fire(n *notify.Notifier, a alert.Alert) {
attrs := []any{"item", a.Item, "url", a.URL, "title", a.Title, "price", a.PriceText(), "seller", a.Seller}
if a.CartLink != "" { attrs = append(attrs, "cart_link", a.CartLink) }
if a.PreviousPrice != nil { attrs = append(attrs, "previous_price", alert.Money(*a.PreviousPrice, a.PreviousCurrency)) }
w.logger.Info("ALERT", attrs...)
if len(n.Channels()) == 0 { return }
w.sends.Go(func() {
// Alerts still go out when dibs is stopped right after one fires.
ctx, cancel := context.WithTimeout(context.Background(), sendTimeout)
defer cancel()
if err := n.Send(ctx, a); err != nil {
w.logger.Warn("notification failed", "item", a.Item, "err", err)
return
}
w.logger.Info("notified", "item", a.Item, "channels", n.Channels())
})
}
// close waits for the notifications still being sent and releases the
// plugins.
func (w *watcher) close() {
w.sends.Wait()
w.mu.Lock()
defer w.mu.Unlock()
for _, h := range w.retired { h.Close() }
w.host.Close()
}
func (w *watcher) Statuses() []watch.Status { return w.sched.Statuses() }
func (w *watcher) Pause(item string, paused bool) bool { return w.sched.Pause(item, paused) }
func (w *watcher) PauseAll(paused bool) { w.sched.PauseAll(paused) }
func (w *watcher) CheckNow(item string) bool { return w.sched.CheckNow(item) }
// Reload reads the config file again and switches to it. Plugins are
// loaded afresh, so edits to plugin files apply too. On error, nothing
// changes. It returns a summary of the changes.
func (w *watcher) Reload() ([]string, error) {
w.reloadMu.Lock()
defer w.reloadMu.Unlock()
w.mu.Lock()
old := w.cfg
w.mu.Unlock()
cfg, err := config.Load(old.Path, config.Options{Builtins: plugin.Builtins()})
if err != nil {
var errs config.Errors
if errors.As(err, &errs) {
for _, e := range errs { w.logger.Warn("config reload failed", "problem", e.Brief()) }
} else {
w.logger.Warn("config reload failed", "err", err)
}
return nil, err
}
host, err := newHost(cfg, w.logger)
if err != nil { return nil, err }
warnings, err := w.sched.Reload(w.ctx, cfg, host)
if err != nil {
host.Close()
return nil, err
}
w.apply(cfg, host)
summary := config.Diff(old, cfg)
if len(summary) == 0 { summary = []string{"no changes"} }
for _, line := range summary { w.logger.Info("config reloaded", "change", line) }
for _, msg := range warnings { w.logger.Warn(msg) }
return summary, nil
}
// needsRates reports whether any item may need a currency conversion.
func needsRates(cfg *config.Config) bool {
for _, it := range cfg.Items {
if it.Currency != "" { return true }
}
return false
}
func isTerminal(w io.Writer) bool {
f, ok := w.(*os.File)
if !ok { return false }
info, err := f.Stat()
return err == nil && info.Mode()&os.ModeCharDevice != 0
}
// logResult logs a check at level, or as a warning if it failed or ran into
// a bot check.
func logResult(logger *slog.Logger, level slog.Level, 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) }
}
}
switch {
case r.Err != nil:
logger.Warn("check failed", append(attrs, "err", r.Err.Error())...)
case r.Report.Verdict != fetch.OK.String() && r.Report.Verdict != fetch.NotFound.String():
logger.Warn("check got "+r.Report.Verdict, attrs...)
default:
logger.Log(context.Background(), level, "checked", attrs...)
}
}
+29 -1
View File
@@ -3,27 +3,55 @@ module git.security-command.org/Overlord/dibs
go 1.26.0 go 1.26.0
require ( require (
charm.land/bubbles/v2 v2.2.1
charm.land/bubbletea/v2 v2.1.0
charm.land/lipgloss/v2 v2.0.6
github.com/PuerkitoBio/goquery v1.13.0 github.com/PuerkitoBio/goquery v1.13.0
github.com/andybalholm/cascadia v1.3.4 github.com/andybalholm/cascadia v1.3.4
github.com/bogdanfinn/fhttp v0.6.9 github.com/bogdanfinn/fhttp v0.6.9
github.com/bogdanfinn/tls-client v1.16.0 github.com/bogdanfinn/tls-client v1.16.0
github.com/charmbracelet/colorprofile v0.4.3
github.com/charmbracelet/x/ansi v0.11.9
github.com/gen2brain/beeep v0.11.2
github.com/pelletier/go-toml/v2 v2.4.3 github.com/pelletier/go-toml/v2 v2.4.3
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c
github.com/yuin/gopher-lua v1.1.2 github.com/yuin/gopher-lua v1.1.2
golang.org/x/net v0.60.0 golang.org/x/net v0.60.0
golang.org/x/sys v0.48.0
) )
require ( require (
git.sr.ht/~jackmordaunt/go-toast v1.1.2 // indirect
github.com/andybalholm/brotli v1.2.0 // indirect github.com/andybalholm/brotli v1.2.0 // indirect
github.com/bdandy/go-errors v1.2.2 // indirect github.com/bdandy/go-errors v1.2.2 // indirect
github.com/bdandy/go-socks4 v1.2.3 // indirect github.com/bdandy/go-socks4 v1.2.3 // indirect
github.com/bogdanfinn/quic-go-utls v1.0.10-utls // indirect github.com/bogdanfinn/quic-go-utls v1.0.10-utls // indirect
github.com/bogdanfinn/utls v1.7.8-barnius // indirect github.com/bogdanfinn/utls v1.7.8-barnius // indirect
github.com/bogdanfinn/websocket v1.5.6-barnius // indirect github.com/bogdanfinn/websocket v1.5.6-barnius // indirect
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/cloudflare/circl v1.6.5 // indirect github.com/cloudflare/circl v1.6.5 // indirect
github.com/esiqveland/notify v0.13.3 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/godbus/dbus/v5 v5.1.0 // indirect
github.com/jackmordaunt/icns/v3 v3.0.1 // indirect
github.com/klauspost/compress v1.18.2 // indirect github.com/klauspost/compress v1.18.2 // indirect
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
github.com/mattn/go-runewidth v0.0.30 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect
github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/qpack v0.6.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/sergeymakinen/go-bmp v1.0.0 // indirect
github.com/sergeymakinen/go-ico v1.0.0-beta.0 // indirect
github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirect
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect
github.com/xo/terminfo v1.0.0 // indirect
golang.org/x/crypto v0.57.0 // indirect golang.org/x/crypto v0.57.0 // indirect
golang.org/x/sys v0.48.0 // indirect golang.org/x/sync v0.23.0 // indirect
golang.org/x/text v0.42.0 // indirect golang.org/x/text v0.42.0 // indirect
) )
+72
View File
@@ -1,9 +1,19 @@
charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU=
charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc=
charm.land/bubbletea/v2 v2.1.0 h1:A9fj9h5LFrvQhQHFNggp8K8rvY6CUfgn9dMbb6p2HIw=
charm.land/bubbletea/v2 v2.1.0/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q=
git.sr.ht/~jackmordaunt/go-toast v1.1.2 h1:/yrfI55LRt1M7H1vkaw+NaH1+L1CDxrqDltwm5euVuE=
git.sr.ht/~jackmordaunt/go-toast v1.1.2/go.mod h1:jA4OqHKTQ4AFBdwrSnwnskUIIS3HYzlJSgdzCKqfavo=
github.com/PuerkitoBio/goquery v1.13.0 h1:mqHbjD7Jmnul4DTR24LKTjo1uUmHUh072kteGV+xpFM= github.com/PuerkitoBio/goquery v1.13.0 h1:mqHbjD7Jmnul4DTR24LKTjo1uUmHUh072kteGV+xpFM=
github.com/PuerkitoBio/goquery v1.13.0/go.mod h1:Hip5mdBL8K2wEGKJdr27sRaNwIdDajmCwB/ExUPwW+g= github.com/PuerkitoBio/goquery v1.13.0/go.mod h1:Hip5mdBL8K2wEGKJdr27sRaNwIdDajmCwB/ExUPwW+g=
github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ= github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ=
github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg= github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg=
github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM= github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM=
github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ12Gv5o=
github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w=
github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11Q= github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11Q=
github.com/bdandy/go-errors v1.2.2/go.mod h1:NkYHl4Fey9oRRdbB1CoC6e84tuqQHiqrOcZpqFEkBxM= github.com/bdandy/go-errors v1.2.2/go.mod h1:NkYHl4Fey9oRRdbB1CoC6e84tuqQHiqrOcZpqFEkBxM=
github.com/bdandy/go-socks4 v1.2.3 h1:Q6Y2heY1GRjCtHbmlKfnwrKVU/k81LS8mRGLRlmDlic= github.com/bdandy/go-socks4 v1.2.3 h1:Q6Y2heY1GRjCtHbmlKfnwrKVU/k81LS8mRGLRlmDlic=
@@ -18,22 +28,77 @@ github.com/bogdanfinn/utls v1.7.8-barnius h1:wRT83mP4hmuMM1/lIpLKKhzaEuyEKjux7VS
github.com/bogdanfinn/utls v1.7.8-barnius/go.mod h1:o5v09jf+9ayMEfcP+8sssNdSMm278cyhBV25H8jb5Lw= github.com/bogdanfinn/utls v1.7.8-barnius/go.mod h1:o5v09jf+9ayMEfcP+8sssNdSMm278cyhBV25H8jb5Lw=
github.com/bogdanfinn/websocket v1.5.6-barnius h1:QpdWVEZ9rKtcT7C2pU19uE2KQw2XevuKTDTzLxfDi/I= github.com/bogdanfinn/websocket v1.5.6-barnius h1:QpdWVEZ9rKtcT7C2pU19uE2KQw2XevuKTDTzLxfDi/I=
github.com/bogdanfinn/websocket v1.5.6-barnius/go.mod h1:41/rXLDWpqJ5A4gOKSY/z4NLbW/hHZHneRcYM0kbpxA= github.com/bogdanfinn/websocket v1.5.6-barnius/go.mod h1:41/rXLDWpqJ5A4gOKSY/z4NLbW/hHZHneRcYM0kbpxA=
github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=
github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q=
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 h1:hISLzUbwcvJbGoNR6A3L/TpguRRnACBmZOee8LcHLJw=
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio=
github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM=
github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w=
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA=
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I=
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM=
github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=
github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA= github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA=
github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c= github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/esiqveland/notify v0.13.3 h1:QCMw6o1n+6rl+oLUfg8P1IIDSFsDEb2WlXvVvIJbI/o=
github.com/esiqveland/notify v0.13.3/go.mod h1:hesw/IRYTO0x99u1JPweAl4+5mwXJibQVUcP0Iu5ORE=
github.com/gen2brain/beeep v0.11.2 h1:+KfiKQBbQCuhfJFPANZuJ+oxsSKAYNe88hIpJuyKWDA=
github.com/gen2brain/beeep v0.11.2/go.mod h1:jQVvuwnLuwOcdctHn/uyh8horSBNJ8uGb9Cn2W4tvoc=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/jackmordaunt/icns/v3 v3.0.1 h1:xxot6aNuGrU+lNgxz5I5H0qSeCjNKp8uTXB1j8D4S3o=
github.com/jackmordaunt/icns/v3 v3.0.1/go.mod h1:5sHL59nqTd2ynTnowxB/MDQFhKNqkK8X687uKNygaSQ=
github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk= github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk=
github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4= github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss=
github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-runewidth v0.0.30 h1:+KUuiDA4fF0R1p5FeueHefjDm+GIM+kWfFnDjybOPgk=
github.com/mattn/go-runewidth v0.0.30/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY= github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdDPYVpY=
github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/sergeymakinen/go-bmp v1.0.0 h1:SdGTzp9WvCV0A1V0mBeaS7kQAwNLdVJbmHlqNWq0R+M=
github.com/sergeymakinen/go-bmp v1.0.0/go.mod h1:/mxlAQZRLxSvJFNIEGGLBE/m40f3ZnUifpgVDlcUIEY=
github.com/sergeymakinen/go-ico v1.0.0-beta.0 h1:m5qKH7uPKLdrygMWxbamVn+tl2HfiA3K6MFJw4GfZvQ=
github.com/sergeymakinen/go-ico v1.0.0-beta.0/go.mod h1:wQ47mTczswBO5F0NoDt7O0IXgnV4Xy3ojrroMQzyhUk=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG04SN9W+iWHCRyHqlVYILiSXziwk=
github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af/go.mod h1:4F09kP5F+am0jAwlQLddpoMDM+iewkxxt6nxUQ5nq5o=
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leXMWAEjS0mTZ5kUU9KRBriQJc= github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leXMWAEjS0mTZ5kUU9KRBriQJc=
github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5/go.mod h1:2JjD2zLQYH5HO74y5+aE3remJQvl6q4Sn6aWA2wD1Ng= github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5/go.mod h1:2JjD2zLQYH5HO74y5+aE3remJQvl6q4Sn6aWA2wD1Ng=
github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY=
github.com/xo/terminfo v1.0.0/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA= github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA=
@@ -42,11 +107,16 @@ go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko=
go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/net v0.0.0-20211104170005-ce137452f963/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211104170005-ce137452f963/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
@@ -54,5 +124,7 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+267
View File
@@ -0,0 +1,267 @@
// Package alert decides when an item fires: when one of its pages offers it
// from an accepted seller at an accepted price, and the item's cooldown
// allows another alert.
package alert
import (
"context"
"fmt"
"math"
"strconv"
"sync"
"time"
"git.security-command.org/Overlord/dibs/internal/config"
"git.security-command.org/Overlord/dibs/internal/plugin"
)
// Alert is one item becoming buyable.
type Alert struct {
Item string
Shop string
// URL is the product page, as the plugin normalized it.
URL string
Title string
Price *float64
Currency string
// Converted is Price in the item's currency, when the page uses another
// one and the conversion worked.
Converted *float64
ConvertedCurrency string
Seller string
CartLink string
Time time.Time
// PreviousPrice is the price of the last alert, when this one fires
// during the cooldown because the price dropped below it.
PreviousPrice *float64
PreviousCurrency string
// Test marks the sample alert of `dibs notify test`.
Test bool
}
// PriceText is the price as notifications show it, such as "129.99 EUR" or
// "149.99 USD (≈ 133.95 EUR)".
func (a Alert) PriceText() string {
if a.Price == nil { return "price unknown" }
s := Money(*a.Price, a.Currency)
if a.Converted != nil { s += " (≈ " + Money(*a.Converted, a.ConvertedCurrency) + ")" }
return s
}
// SellerText describes the seller for notifications.
func (a Alert) SellerText() string {
switch a.Seller {
case plugin.SellerFirstParty:
return "sold by " + a.Shop
case plugin.SellerFulfilled:
return "shipped by " + a.Shop
case plugin.SellerThirdParty:
return "marketplace seller"
default:
return "seller unknown"
}
}
func Money(amount float64, currency string) string {
s := strconv.FormatFloat(amount, 'f', 2, 64)
if currency != "" { s += " " + currency }
return s
}
// Converter is fx.Service.
type Converter interface {
Convert(ctx context.Context, amount float64, from, to string) (float64, error)
}
// Sent is what an item's cooldown remembers about its last alert.
type Sent struct {
Time time.Time `json:"time"`
Price *float64 `json:"price,omitempty"`
Currency string `json:"currency,omitempty"`
// ItemPrice is the price in the item's currency, so that pages in
// different currencies compare.
ItemPrice *float64 `json:"item_price,omitempty"`
ItemCurrency string `json:"item_currency,omitempty"`
}
// Store keeps the cooldowns between runs and shares them with other dibs
// processes. Lock is held from loading an item's last alert until the new
// one is stored, so two processes never both send it.
type Store interface {
Lock() func()
LoadAlert(item string) (Sent, bool)
StoreAlert(item string, s Sent)
}
// Engine turns check results into alerts. It is safe for concurrent use.
type Engine struct {
cooldown time.Duration
fx Converter
store Store
mu sync.Mutex
sent map[string]Sent // used when store is nil
}
// NewEngine returns an engine. store may be nil to keep cooldowns in memory.
func NewEngine(cooldown time.Duration, fx Converter, store Store) *Engine {
return &Engine{cooldown: cooldown, fx: fx, store: store, sent: map[string]Sent{}}
}
// Decision is what Consider made of a checked page.
type Decision struct {
// Alert is set when the item fires.
Alert *Alert
// Qualifies reports whether the page passed the seller and price checks,
// even if the cooldown held the alert back.
Qualifies bool
// Reason says why an available page did not fire.
Reason string
}
// Consider decides whether a checked page makes its item fire. A page that
// is not available decides nothing. An error means the price could not be
// checked, such as when no current exchange rate is available.
func (e *Engine) Consider(ctx context.Context, item config.Item, rep *plugin.Report, now time.Time) (Decision, error) {
if rep == nil || rep.Result == nil || !rep.Result.Available { return Decision{}, nil }
a, why, err := e.qualify(ctx, item, rep, now)
if a == nil { return Decision{Reason: why}, err }
unlock := e.lock()
defer unlock()
next := a.sent(item.Currency)
last, ok := e.load(item.Name)
allowed, drop := Allows(last, ok, next, e.cooldown)
switch {
case !allowed:
return Decision{Qualifies: true, Reason: "in cooldown until " + last.Time.Add(e.cooldown).Format(time.TimeOnly)}, nil
case drop && last.Currency == next.Currency:
a.PreviousPrice, a.PreviousCurrency = last.Price, last.Currency
case drop:
a.PreviousPrice, a.PreviousCurrency = last.ItemPrice, last.ItemCurrency
}
e.save(item.Name, next)
return Decision{Alert: a, Qualifies: true}, nil
}
// sent is what the cooldown remembers of a.
func (a *Alert) sent(itemCurrency string) Sent {
s := Sent{Time: a.Time, Price: a.Price, Currency: a.Currency}
switch {
case a.Converted != nil:
s.ItemPrice, s.ItemCurrency = a.Converted, a.ConvertedCurrency
case a.Price != nil && (a.Currency == itemCurrency || a.Currency == "" || itemCurrency == ""):
s.ItemPrice, s.ItemCurrency = a.Price, itemCurrency
}
return s
}
// qualify checks an available page against the item's seller policy and
// max_price.
func (e *Engine) qualify(ctx context.Context, item config.Item, rep *plugin.Report, now time.Time) (*Alert, string, error) {
res := rep.Result
if !item.AcceptsSeller(res.Seller) { return nil, fmt.Sprintf("seller is %s, the item accepts %s", res.Seller, item.Seller), nil }
a := &Alert{
Item: item.Name,
Shop: rep.Shop,
URL: rep.FetchURL,
Title: res.Title,
Price: res.Price,
Currency: res.Currency,
Seller: res.Seller,
CartLink: rep.CartLink,
Time: now,
}
// A page without a currency is taken to use the item's.
foreign := item.Currency != "" && res.Currency != "" && res.Currency != item.Currency
var convErr error
if foreign && res.Price != nil {
v, err := e.fx.Convert(ctx, *res.Price, res.Currency, item.Currency)
v = math.Round(v*100) / 100
if err == nil { a.Converted, a.ConvertedCurrency = &v, item.Currency } else { convErr = err }
}
if item.MaxPrice == nil { return a, "", nil }
limit := *item.MaxPrice
switch {
case res.Price == nil:
return nil, "no price on the page to compare with max_price", nil
case foreign && convErr != nil:
return nil, "", fmt.Errorf("cannot compare %s with max_price %s: %w", Money(*res.Price, res.Currency), Money(limit, item.Currency), convErr)
case foreign:
if p := *a.Converted * (1 + item.FXMargin); p > limit {
return nil, fmt.Sprintf("price %s with fx_margin is above max_price %s", Money(p, item.Currency), Money(limit, item.Currency)), nil
}
case *res.Price > limit:
return nil, fmt.Sprintf("price %s is above max_price %s", Money(*res.Price, res.Currency), Money(limit, item.Currency)), nil
}
return a, "", nil
}
// Allows applies an item's cooldown: after an alert, the item stays quiet
// for cooldown unless its price drops below the last alert's. It also
// reports whether next is for such a drop.
//
// Prices in the same page currency compare as they are, so that exchange
// rates moving overnight never look like a price drop. Prices in different
// currencies compare in the item's currency.
func Allows(last Sent, hasLast bool, next Sent, cooldown time.Duration) (allowed, drop bool) {
if !hasLast || !next.Time.Before(last.Time.Add(cooldown)) { return true, false }
switch {
case next.Price != nil && last.Price != nil && next.Currency == last.Currency:
drop = *next.Price < *last.Price
case next.ItemPrice != nil && last.ItemPrice != nil && next.ItemCurrency == last.ItemCurrency:
drop = *next.ItemPrice < *last.ItemPrice
default:
// Without a price in a shared currency, nothing compares.
}
return drop, drop
}
func (e *Engine) lock() func() {
if e.store == nil { return func() {} }
return e.store.Lock()
}
func (e *Engine) load(item string) (Sent, bool) {
if e.store != nil { return e.store.LoadAlert(item) }
e.mu.Lock()
defer e.mu.Unlock()
s, ok := e.sent[item]
return s, ok
}
func (e *Engine) save(item string, s Sent) {
if e.store != nil {
e.store.StoreAlert(item, s)
return
}
e.mu.Lock()
defer e.mu.Unlock()
e.sent[item] = s
}
+138
View File
@@ -0,0 +1,138 @@
package alert
import (
"context"
"errors"
"strings"
"testing"
"time"
"git.security-command.org/Overlord/dibs/internal/config"
"git.security-command.org/Overlord/dibs/internal/plugin"
)
// usdPerEUR converts USD and EUR at a fixed rate, or fails when down.
type usdPerEUR struct {
rate float64
down bool
}
func (c usdPerEUR) Convert(_ context.Context, amount float64, from, to string) (float64, error) {
switch {
case c.down:
return 0, errors.New("no rates")
case from == "USD" && to == "EUR":
return amount / c.rate, nil
case from == "EUR" && to == "USD":
return amount * c.rate, nil
default:
return 0, errors.New("unexpected conversion " + from + " to " + to)
}
}
func page(price float64, currency, seller string) *plugin.Report {
return &plugin.Report{
Shop: "amazon",
FetchURL: "https://www.amazon.de/dp/B0HMX2FSTF",
Result: &plugin.Result{Title: "Metro", Available: true, Price: &price, Currency: currency, Seller: seller},
}
}
func metro(maxPrice float64) config.Item {
return config.Item{Name: "metro", Shop: "amazon", MaxPrice: &maxPrice, Currency: "EUR", Seller: config.SellerFulfilled}
}
// TestCooldown follows one item through a day of restocks.
func TestCooldown(t *testing.T) {
ctx := context.Background()
start := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
fx := &usdPerEUR{rate: 1.25}
e := NewEngine(30*time.Minute, fx, nil)
it := metro(130)
steps := []struct {
name string
after time.Duration
report *plugin.Report
fires bool
prev string // the previous price a price-drop alert shows
} {
{"first alert", 0, page(129.99, "EUR", plugin.SellerFirstParty), true, ""},
{"same price in cooldown", 5 * time.Minute, page(129.99, "EUR", plugin.SellerFirstParty), false, ""},
{"higher price in cooldown", 10 * time.Minute, page(129.995, "EUR", plugin.SellerFulfilled), false, ""},
{"price drop in cooldown", 15 * time.Minute, page(119.99, "EUR", plugin.SellerFirstParty), true, "129.99 EUR"},
{"drop restarted the cooldown", 40 * time.Minute, page(119.99, "EUR", plugin.SellerFirstParty), false, ""},
{"cooldown over", 45 * time.Minute, page(125, "EUR", plugin.SellerFirstParty), true, ""},
// 140 USD is 112 EUR, cheaper than 125 EUR.
{"cheaper in another currency", 50 * time.Minute, page(140, "USD", plugin.SellerFirstParty), true, "125.00 EUR"},
// Same currency as the last alert: compared in USD, so the euro
// strengthening to 1.30 USD does not make it a drop to 107.69 EUR.
{"same USD price, new rate", 55 * time.Minute, page(140, "USD", plugin.SellerFirstParty), false, ""},
}
for _, st := range steps {
if strings.HasSuffix(st.name, "new rate") { fx.rate = 1.30 }
d, err := e.Consider(ctx, it, st.report, start.Add(st.after))
if err != nil { t.Fatalf("%s: %v", st.name, err) }
a := d.Alert
if fired := a != nil; fired != st.fires { t.Errorf("%s: fired = %v, want %v (%s)", st.name, fired, st.fires, d.Reason) }
if !d.Qualifies { t.Errorf("%s: does not qualify: %s", st.name, d.Reason) }
if a == nil { continue }
prev := ""
if a.PreviousPrice != nil { prev = Money(*a.PreviousPrice, a.PreviousCurrency) }
if prev != st.prev { t.Errorf("%s: previous price %q, want %q", st.name, prev, st.prev) }
}
}
func TestQualify(t *testing.T) {
ctx := context.Background()
now := time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)
noPrice := page(0, "EUR", plugin.SellerFirstParty)
noPrice.Result.Price = nil
withMargin := metro(120)
withMargin.FXMargin = 0.1
anySeller := metro(130)
anySeller.Seller = config.SellerAny
noLimit := config.Item{Name: "metro", Currency: "EUR", Seller: config.SellerAny}
cases := []struct {
name string
item config.Item
report *plugin.Report
fx usdPerEUR
want string // "fire", "error" or part of the reason
} {
{"at max_price", metro(129.99), page(129.99, "EUR", plugin.SellerFirstParty), usdPerEUR{}, "fire"},
{"above max_price", metro(129.99), page(130, "EUR", plugin.SellerFirstParty), usdPerEUR{}, "above max_price"},
{"marketplace seller", metro(130), page(99, "EUR", plugin.SellerThirdParty), usdPerEUR{}, "seller is third_party"},
{"unknown seller, any", anySeller, page(99, "EUR", plugin.SellerUnknown), usdPerEUR{}, "fire"},
{"no price", metro(130), noPrice, usdPerEUR{}, "no price"},
// 125 USD is 100 EUR, 110 EUR with the margin.
{"converted within", withMargin, page(125, "USD", plugin.SellerFirstParty), usdPerEUR{rate: 1.25}, "fire"},
// 140 USD is 112 EUR, 123.20 EUR with the margin.
{"margin tips it over", withMargin, page(140, "USD", plugin.SellerFirstParty), usdPerEUR{rate: 1.25}, "with fx_margin is above"},
{"no rates", metro(130), page(99, "USD", plugin.SellerFirstParty), usdPerEUR{down: true}, "error"},
{"no rates, no max_price", noLimit, page(99, "USD", plugin.SellerFirstParty), usdPerEUR{down: true}, "fire"},
}
for _, c := range cases {
d, err := NewEngine(time.Hour, c.fx, nil).Consider(ctx, c.item, c.report, now)
a, why := d.Alert, d.Reason
switch {
case c.want == "fire" && a == nil:
t.Errorf("%s: did not fire: %s %v", c.name, why, err)
case c.want == "error" && err == nil:
t.Errorf("%s: no error (fired: %v, reason %q)", c.name, a != nil, why)
case c.want != "fire" && c.want != "error" && !strings.Contains(why, c.want):
t.Errorf("%s: reason %q, want %q (fired: %v, err %v)", c.name, why, c.want, a != nil, err)
}
}
}
+14 -11
View File
@@ -10,14 +10,21 @@ import (
"time" "time"
"github.com/pelletier/go-toml/v2" "github.com/pelletier/go-toml/v2"
"git.security-command.org/Overlord/dibs/internal/ratelimit"
) )
// MinInterval is the shortest allowed polling interval per URL. // MinInterval is the shortest allowed polling interval per URL. The
const MinInterval = 60 * time.Second // scheduler enforces it too, whatever the config says.
const MinInterval = ratelimit.URLFloor
// MaxCooldown is the longest allowed cooldown. The state file forgets alerts
// after it.
const MaxCooldown = 7 * 24 * time.Hour
const ( const (
// Seller policies for an item: sold by the shop itself; sold or at least // The seller policies accept offers sold by the shop itself, offers it
// shipped by it (e.g. Fulfilled by Amazon); or anyone. // sells or only ships (such as Fulfilled by Amazon), or any offer.
SellerFirstParty = "first_party" SellerFirstParty = "first_party"
SellerFulfilled = "fulfilled" SellerFulfilled = "fulfilled"
SellerAny = "any" SellerAny = "any"
@@ -30,7 +37,6 @@ const (
FormatJSON = "json" FormatJSON = "json"
) )
// Defaults for keys that may be omitted.
const ( const (
DefaultInterval = 3 * time.Minute DefaultInterval = 3 * time.Minute
DefaultCooldown = 30 * time.Minute DefaultCooldown = 30 * time.Minute
@@ -48,7 +54,7 @@ type Config struct {
Items []Item `toml:"item"` Items []Item `toml:"item"`
Accounts map[string]Account `toml:"accounts"` Accounts map[string]Account `toml:"accounts"`
Notify Notify `toml:"notify"` 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"` Plugins map[string]string `toml:"plugins"`
Sandbox Sandbox `toml:"sandbox"` Sandbox Sandbox `toml:"sandbox"`
@@ -89,7 +95,6 @@ type Webhook struct {
Format string `toml:"format"` Format string `toml:"format"`
} }
// Sandbox holds the limits for Lua plugin calls.
type Sandbox struct { type Sandbox struct {
// Timeout applies to matches, parse and cart_link. // Timeout applies to matches, parse and cart_link.
Timeout Duration `toml:"timeout"` Timeout Duration `toml:"timeout"`
@@ -152,7 +157,6 @@ func (it Item) AcceptsSeller(seller string) bool {
return rank <= policyRanks[it.Seller] return rank <= policyRanks[it.Seller]
} }
// Options control validation that depends on the environment.
type Options struct { type Options struct {
// Builtins are the names of the embedded plugins. // Builtins are the names of the embedded plugins.
Builtins []string Builtins []string
@@ -167,8 +171,7 @@ func DefaultPath() (string, error) {
return filepath.Join(dir, "dibs", "dibs.toml"), nil return filepath.Join(dir, "dibs", "dibs.toml"), nil
} }
// Load reads, decodes and validates the config at path. All problems found // Load returns every problem it finds at once, as Errors.
// are returned together as Errors.
func Load(path string, opts Options) (*Config, error) { func Load(path string, opts Options) (*Config, error) {
data, err := os.ReadFile(path) data, err := os.ReadFile(path)
if err != nil { return nil, err } if err != nil { return nil, err }
@@ -206,7 +209,7 @@ func Load(path string, opts Options) (*Config, error) {
switch { switch {
case err == nil: case err == nil:
case errors.As(err, &strict): 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 { for _, e := range strict.Errors {
msg := "unknown key" msg := "unknown key"
if k := e.Key(); len(k) > 0 && k[len(k)-1] == "quantity" { if k := e.Key(); len(k) > 0 && k[len(k)-1] == "quantity" {
+1 -1
View File
@@ -288,7 +288,7 @@ call_stack = 1
wantErr(t, es, "accounts.ebay", 26, `no plugin named "ebay"`) wantErr(t, es, "accounts.ebay", 26, `no plugin named "ebay"`)
wantErr(t, es, "notify.webhooks[1].format", 31, `got "slack"`) wantErr(t, es, "notify.webhooks[1].format", 31, `got "slack"`)
wantErr(t, es, "notify.webhooks[2].url", 32, "missing required key") wantErr(t, es, "notify.webhooks[2].url", 32, "missing required key")
wantErr(t, es, "notify.cooldown", 34, "negative") wantErr(t, es, "notify.cooldown", 34, "between 0s and 168h")
wantErr(t, es, "plugins.Bad Name", 37, "plugin name") wantErr(t, es, "plugins.Bad Name", 37, "plugin name")
wantErr(t, es, "plugins.missing", 38, "cannot read plugin") wantErr(t, es, "plugins.missing", 38, "cannot read plugin")
wantErr(t, es, "sandbox.timeout", 41, "between 100ms and 30s") wantErr(t, es, "sandbox.timeout", 41, "between 100ms and 30s")
+102
View File
@@ -0,0 +1,102 @@
package config
import (
"fmt"
"maps"
"slices"
"strconv"
"strings"
)
// Diff summarizes what changed from old to cfg, one line per change, for
// the reload message.
func Diff(old, cfg *Config) []string {
var out []string
oldItems := map[string]Item{}
for _, it := range old.Items { oldItems[it.Name] = it }
for _, it := range cfg.Items {
prev, ok := oldItems[it.Name]
if !ok {
out = append(out, fmt.Sprintf("+ item %s (%s)", it.Name, countURLs(len(it.URLs))))
continue
}
delete(oldItems, it.Name)
if changes := itemChanges(prev, it); len(changes) > 0 { out = append(out, fmt.Sprintf("~ item %s: %s", it.Name, strings.Join(changes, ", "))) }
}
for _, it := range old.Items {
if _, gone := oldItems[it.Name]; gone { out = append(out, fmt.Sprintf("- item %s", it.Name)) }
}
if changes := notifyChanges(old.Notify, cfg.Notify); len(changes) > 0 { out = append(out, "~ notify: "+strings.Join(changes, ", ")) }
if !maps.Equal(old.Plugins, cfg.Plugins) { out = append(out, "~ plugins") }
if !maps.Equal(old.Accounts, cfg.Accounts) { out = append(out, "~ accounts") }
if !sameSandbox(old.Sandbox, cfg.Sandbox) { out = append(out, "~ sandbox") }
return out
}
func itemChanges(a, b Item) []string {
var out []string
change := func(key, from, to string) {
if from != to { out = append(out, fmt.Sprintf("%s %s → %s", key, from, to)) }
}
change("shop", a.Shop, b.Shop)
change("max_price", optPrice(a.MaxPrice), optPrice(b.MaxPrice))
change("currency", orNone(a.Currency), orNone(b.Currency))
change("fx_margin", strconv.FormatFloat(a.FXMargin, 'f', -1, 64), strconv.FormatFloat(b.FXMargin, 'f', -1, 64))
change("seller", a.Seller, b.Seller)
change("interval", a.Interval.String(), b.Interval.String())
added, removed := 0, 0
for _, u := range b.URLs {
if !slices.Contains(a.URLs, u) { added++ }
}
for _, u := range a.URLs {
if !slices.Contains(b.URLs, u) { removed++ }
}
if added > 0 { out = append(out, "+"+countURLs(added)) }
if removed > 0 { out = append(out, "-"+countURLs(removed)) }
return out
}
func notifyChanges(a, b Notify) []string {
var out []string
if !slices.Equal(a.Webhooks, b.Webhooks) { out = append(out, "webhooks") }
if a.Desktop != b.Desktop { out = append(out, fmt.Sprintf("desktop %v → %v", a.Desktop, b.Desktop)) }
if a.Cooldown.Duration != b.Cooldown.Duration { out = append(out, fmt.Sprintf("cooldown %s → %s", a.Cooldown, b.Cooldown)) }
return out
}
// sameSandbox compares the limits, not whether they were written out.
func sameSandbox(a, b Sandbox) bool {
return a.Timeout.Duration == b.Timeout.Duration && a.SessionTimeout.Duration == b.SessionTimeout.Duration &&
a.MemoryMB == b.MemoryMB && a.CallStack == b.CallStack
}
func countURLs(n int) string {
if n == 1 { return "1 URL" }
return strconv.Itoa(n) + " URLs"
}
func optPrice(p *float64) string {
if p == nil { return "none" }
return strconv.FormatFloat(*p, 'f', -1, 64)
}
func orNone(s string) string {
if s == "" { return "none" }
return s
}
+2 -2
View File
@@ -107,8 +107,8 @@ func (ps positions) keyAt(line, col int) string {
for path, p := range ps { for path, p := range ps {
if p.Line == line && p.Column <= col && p.Column >= bestCol { if p.Line == line && p.Column <= col && p.Column >= bestCol {
// Prefer the longer path when an array element and its first key // An array element and its first key can share a position; the
// share a position. // longer path wins.
if p.Column > bestCol || len(path) > len(best) { if p.Column > bestCol || len(path) > len(best) {
best, bestCol = path, p.Column best, bestCol = path, p.Column
} }
+14 -10
View File
@@ -16,7 +16,6 @@ import (
"github.com/pelletier/go-toml/v2" "github.com/pelletier/go-toml/v2"
) )
// Ranges for the [sandbox] limits.
const ( const (
minSandboxTimeout = 100 * time.Millisecond minSandboxTimeout = 100 * time.Millisecond
maxSandboxTimeout = 30 * time.Second maxSandboxTimeout = 30 * time.Second
@@ -47,7 +46,6 @@ var goTypeNames = map[string]string{
"config.Duration": `a duration string such as "3m"`, "config.Duration": `a duration string such as "3m"`,
} }
// Error is one problem in the config file.
type Error struct { type Error struct {
File string File string
Line int // 1-based; 0 if unknown Line int // 1-based; 0 if unknown
@@ -57,11 +55,17 @@ type Error struct {
} }
func (e Error) Error() string { func (e Error) Error() string {
if e.Line > 0 { return e.File + ":" + e.Brief() }
return e.File + ": " + e.Brief()
}
// Brief is the error without the file name, such as "12:3: item[0].shop:
// missing required key".
func (e Error) Brief() string {
var b strings.Builder var b strings.Builder
b.WriteString(e.File) if e.Line > 0 { _, _ = fmt.Fprintf(&b, "%d:%d: ", e.Line, e.Col) }
if e.Line > 0 { _, _ = fmt.Fprintf(&b, ":%d:%d", e.Line, e.Col) }
b.WriteString(": ")
if e.Key != "" { if e.Key != "" {
b.WriteString(e.Key) b.WriteString(e.Key)
b.WriteString(": ") b.WriteString(": ")
@@ -71,7 +75,7 @@ func (e Error) Error() string {
return b.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 type Errors []Error
func (es Errors) Error() string { func (es Errors) Error() string {
@@ -99,8 +103,8 @@ func (v *validator) decodeError(de *toml.DecodeError, msg string) {
msg = friendlyDecodeMsg(strings.TrimPrefix(de.Error(), "toml: ")) msg = friendlyDecodeMsg(strings.TrimPrefix(de.Error(), "toml: "))
} }
// The decoder's key has no array indexes, so prefer the indexed path of // The decoder's key has no array indexes; the key indexed at the same
// the key at that position. // position has them.
key := v.pos.keyAt(line, col) key := v.pos.keyAt(line, col)
if key == "" { if key == "" {
key = strings.Join(de.Key(), ".") key = strings.Join(de.Key(), ".")
@@ -316,8 +320,8 @@ func (v *validator) notify(n *Notify) {
} }
} }
if n.Cooldown.Duration < 0 { if n.Cooldown.Duration < 0 || n.Cooldown.Duration > MaxCooldown {
v.errorf("notify.cooldown", "must not be negative (got %s)", n.Cooldown) v.errorf("notify.cooldown", "must be between 0s and %gh (got %s)", MaxCooldown.Hours(), n.Cooldown)
} }
} }
+6 -7
View File
@@ -12,8 +12,7 @@ import (
) )
// chromeMajor must match chromeProfile: the TLS and HTTP/2 fingerprint come // chromeMajor must match chromeProfile: the TLS and HTTP/2 fingerprint come
// from the profile, the headers from the version. Bump both together when // from the profile, the headers from the version, so the two change together.
// updating tls-client.
const chromeMajor = 152 const chromeMajor = 152
var chromeProfile = profiles.Chrome_152 var chromeProfile = profiles.Chrome_152
@@ -26,8 +25,8 @@ type Browser struct {
Platform string // sec-ch-ua-platform, without quotes Platform string // sec-ch-ua-platform, without quotes
} }
// DefaultBrowser returns desktop Chrome on the current OS, so that cookies // DefaultBrowser returns desktop Chrome on the current OS, so that cookies a
// a real browser on this machine obtains later stay valid for us. // real browser on this machine obtains later stay valid for these requests.
func DefaultBrowser() Browser { func DefaultBrowser() Browser {
ua, platform := "Windows NT 10.0; Win64; x64", "Windows" ua, platform := "Windows NT 10.0; Win64; x64", "Windows"
@@ -37,7 +36,7 @@ func DefaultBrowser() Browser {
case "linux": case "linux":
ua, platform = "X11; Linux x86_64", "Linux" ua, platform = "X11; Linux x86_64", "Linux"
default: default:
// Windows, and anything else, which Chrome supports no better. // Windows. Other systems pass as Windows too.
} }
return Browser{ 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 // secCHUA builds Chrome's sec-ch-ua brand list. Chrome derives the GREASE
// brand and the brand order from its major version (GenerateBrandVersionList // 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 // in Chromium's user_agent_utils.cc), so a fixed string would stand out after
// after an update. // an update.
func secCHUA(major int) string { func secCHUA(major int) string {
chars := []string{" ", "(", ":", "-", ".", "/", ")", ";", "=", "?", "_"} chars := []string{" ", "(", ":", "-", ".", "/", ")", ";", "=", "?", "_"}
versions := []string{"8", "99", "24"} versions := []string{"8", "99", "24"}
+2 -2
View File
@@ -16,8 +16,8 @@ const (
NotFound NotFound
// Challenge is a bot check that a real browser may clear. // Challenge is a bot check that a real browser may clear.
Challenge Challenge
// Blocked is a refusal without a recognisable challenge, e.g. a plain 403 // Blocked is a refusal without a recognisable challenge, such as a plain
// or 429. Back off and retry later. // 403 or 429. The host is backed off and retried later.
Blocked Blocked
// HTTPError is any other non-2xx status. // HTTPError is any other non-2xx status.
HTTPError HTTPError
+23 -9
View File
@@ -13,6 +13,8 @@ import (
http "github.com/bogdanfinn/fhttp" http "github.com/bogdanfinn/fhttp"
tlsclient "github.com/bogdanfinn/tls-client" tlsclient "github.com/bogdanfinn/tls-client"
"git.security-command.org/Overlord/dibs/internal/ratelimit"
) )
const ( const (
@@ -23,14 +25,23 @@ const (
// ErrBodyTooLarge is returned when a response exceeds Options.MaxBody. // ErrBodyTooLarge is returned when a response exceeds Options.MaxBody.
var ErrBodyTooLarge = errors.New("response body too large") 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 { 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 Browser *Browser
// Jar holds the cookies. Defaults to a new, empty jar. // Jar defaults to a new, empty jar.
Jar *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 Timeout time.Duration
// MaxBody is the largest body read, after decompression. Defaults to // MaxBody limits the body after decompression. It defaults to
// DefaultMaxBody. // DefaultMaxBody.
MaxBody int64 MaxBody int64
} }
@@ -38,12 +49,12 @@ type Options struct {
// Client fetches pages. It is safe for concurrent use. // Client fetches pages. It is safe for concurrent use.
type Client struct { type Client struct {
http tlsclient.HttpClient http tlsclient.HttpClient
limiter Limiter
browser Browser browser Browser
jar *Jar jar *Jar
maxBody int64 maxBody int64
} }
// Response is a fetched page.
type Response struct { type Response struct {
URL string // as requested URL string // as requested
FinalURL string // after redirects FinalURL string // after redirects
@@ -60,6 +71,7 @@ type Response struct {
func New(opts Options) (*Client, error) { func New(opts Options) (*Client, error) {
browser := DefaultBrowser() browser := DefaultBrowser()
if opts.Browser != nil { browser = *opts.Browser } 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.Jar == nil { opts.Jar = NewJar() }
if opts.Timeout == 0 { opts.Timeout = DefaultTimeout } if opts.Timeout == 0 { opts.Timeout = DefaultTimeout }
if opts.MaxBody == 0 { opts.MaxBody = DefaultMaxBody } 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) } 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 } func (c *Client) Jar() *Jar { return c.jar }
// Get fetches rawURL the way Chrome opens a bookmark. A response with a bad // Get fetches rawURL the way Chrome opens a bookmark, once the limiter allows
// status is not an error: check Verdict. // 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) { func (c *Client) Get(ctx context.Context, rawURL string) (*Response, error) {
u, err := url.Parse(rawURL) u, err := url.Parse(rawURL)
if err != nil { return nil, err } if err != nil { return nil, err }
if u.Scheme != "http" && u.Scheme != "https" { return nil, fmt.Errorf("unsupported URL scheme %q", u.Scheme) } 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) req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil { return nil, err } if err != nil { return nil, err }
req.Header = c.browser.navigationHeaders(u) req.Header = c.browser.navigationHeaders(u)
+7
View File
@@ -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) } 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 { func newTestClient(t *testing.T, opts Options) *Client {
t.Helper() t.Helper()
if opts.Limiter == nil { opts.Limiter = noLimit{} }
c, err := New(opts) c, err := New(opts)
if err != nil { t.Fatal(err) } if err != nil { t.Fatal(err) }
+3 -28
View File
@@ -7,7 +7,6 @@ import (
"maps" "maps"
"net/url" "net/url"
"os" "os"
"path/filepath"
"slices" "slices"
"strings" "strings"
"sync" "sync"
@@ -16,6 +15,8 @@ import (
http "github.com/bogdanfinn/fhttp" http "github.com/bogdanfinn/fhttp"
"github.com/bogdanfinn/fhttp/cookiejar" "github.com/bogdanfinn/fhttp/cookiejar"
"golang.org/x/net/publicsuffix" "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 // 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) { func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie) {
j.mu.Lock() j.mu.Lock()
defer j.mu.Unlock() 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 { func (j *Jar) Cookies(u *url.URL) []*http.Cookie {
j.mu.Lock() j.mu.Lock()
defer j.mu.Unlock() defer j.mu.Unlock()
@@ -160,7 +159,7 @@ func (j *Jar) Save(path string) error {
data, err := json.MarshalIndent(j.Export(), "", " ") data, err := json.MarshalIndent(j.Export(), "", " ")
if err != nil { return err } 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. // 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] 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)
}
-1
View File
@@ -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) 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") } 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 { func (s Suite) Save(c Case, page []byte, report any) error {
data, err := EncodeReport(report) data, err := EncodeReport(report)
if err != nil { return err } if err != nil { return err }
+33
View File
@@ -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)
}
+26
View File
@@ -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
}
+11
View File
@@ -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) }
+17
View File
@@ -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))
}
+266
View File
@@ -0,0 +1,266 @@
// Package fx converts prices between currencies with the ECB's daily
// reference rates.
package fx
import (
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"sync"
"time"
)
// RatesURL is the ECB's feed of the latest reference rates. It needs no API
// key and changes once per working day, around 16:00 CET.
const RatesURL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
const (
// Rates fetched more than refreshAfter ago are refreshed in the
// background while still in use.
refreshAfter = 6 * time.Hour
// MaxAge is how long rates stay usable without a successful refresh.
MaxAge = 72 * time.Hour
// retryAfter spaces out refreshes after one fails.
retryAfter = 15 * time.Minute
fetchTimeout = 30 * time.Second
)
// Rates are the ECB reference rates of one day.
type Rates struct {
// Date is the ECB's publication day, as YYYY-MM-DD.
Date string `json:"date"`
// Fetched is when the rates were last downloaded, even if the ECB had
// not published newer ones.
Fetched time.Time `json:"fetched"`
// PerEUR is how much of each currency one euro buys.
PerEUR map[string]float64 `json:"per_eur"`
}
// Convert converts amount from one currency to another, through the euro.
func (r *Rates) Convert(amount float64, from, to string) (float64, error) {
if from == to { return amount, nil }
f, err := r.perEUR(from)
if err != nil { return 0, err }
t, err := r.perEUR(to)
if err != nil { return 0, err }
return amount / f * t, nil
}
func (r *Rates) perEUR(currency string) (float64, error) {
if currency == "EUR" { return 1, nil }
if rate, ok := r.PerEUR[currency]; ok && rate > 0 { return rate, nil }
return 0, fmt.Errorf("the ECB publishes no rate for %s", currency)
}
// Store keeps the rates between runs and shares them with other dibs
// processes.
type Store interface {
Lock() func()
LoadRates() (*Rates, bool)
StoreRates(r *Rates)
}
// Limiter is ratelimit.Limiter, which spaces out the requests to the ECB
// like every other request dibs makes.
type Limiter interface {
WaitCheck(ctx context.Context, url string) error
}
// Service hands out current rates and refreshes them when they are due. It
// is safe for concurrent use.
type Service struct {
store Store
limiter Limiter
client *http.Client
url string
now func() time.Time
mu sync.Mutex
rates *Rates
lastTry time.Time
lastErr error
inflight chan struct{} // closed when the running refresh ends
}
func New(store Store, limiter Limiter) *Service {
return &Service{
store: store,
limiter: limiter,
client: &http.Client{Timeout: fetchTimeout},
url: RatesURL,
now: time.Now,
}
}
// Warm starts a refresh in the background if the rates are due for one, so
// the first conversion does not wait for the network.
func (s *Service) Warm() {
s.mu.Lock()
defer s.mu.Unlock()
s.load()
if s.due() { s.startRefresh() }
}
// Convert converts amount with the newest usable rates. When the rates are
// older than MaxAge, it waits for a refresh; if that fails, it fails too.
func (s *Service) Convert(ctx context.Context, amount float64, from, to string) (float64, error) {
if from == to { return amount, nil }
r, err := s.current(ctx)
if err != nil { return 0, err }
return r.Convert(amount, from, to)
}
func (s *Service) current(ctx context.Context) (*Rates, error) {
s.mu.Lock()
s.load()
if s.due() { s.startRefresh() }
if s.usable() {
r := s.rates
s.mu.Unlock()
return r, nil
}
wait := s.inflight
s.mu.Unlock()
if wait != nil {
select {
case <-wait:
case <-ctx.Done():
return nil, ctx.Err()
}
}
s.mu.Lock()
defer s.mu.Unlock()
if s.usable() { return s.rates, nil }
var cause string
if s.lastErr != nil { cause = ": " + s.lastErr.Error() }
return nil, fmt.Errorf("no exchange rates younger than %s%s", MaxAge, cause)
}
// load picks up rates another dibs process may have fetched. Callers hold
// mu.
func (s *Service) load() {
if s.store == nil { return }
if r, ok := s.store.LoadRates(); ok && (s.rates == nil || r.Fetched.After(s.rates.Fetched)) { s.rates = r }
}
// due reports whether a refresh should start. Callers hold mu.
func (s *Service) due() bool {
now := s.now()
switch {
case s.inflight != nil:
return false
case !s.lastTry.IsZero() && now.Sub(s.lastTry) < retryAfter:
return false
case s.rates == nil:
return true
default:
return now.Sub(s.rates.Fetched) >= refreshAfter
}
}
// usable reports whether the rates are young enough to use. Callers hold
// mu.
func (s *Service) usable() bool {
return s.rates != nil && s.now().Sub(s.rates.Fetched) < MaxAge
}
// startRefresh fetches the rates in the background. Callers hold mu.
func (s *Service) startRefresh() {
done := make(chan struct{})
s.inflight = done
s.lastTry = s.now()
go func() {
defer close(done)
ctx, cancel := context.WithTimeout(context.Background(), fetchTimeout+time.Minute)
defer cancel()
r, err := s.fetch(ctx)
s.mu.Lock()
s.inflight, s.lastErr = nil, err
if err == nil { s.rates = r }
s.mu.Unlock()
if err == nil && s.store != nil {
unlock := s.store.Lock()
s.store.StoreRates(r)
unlock()
}
}()
}
func (s *Service) fetch(ctx context.Context) (*Rates, error) {
if s.limiter != nil {
if err := s.limiter.WaitCheck(ctx, s.url); err != nil { return nil, err }
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.url, nil)
if err != nil { return nil, err }
resp, err := s.client.Do(req)
if err != nil { return nil, fmt.Errorf("fetching exchange rates: %w", err) }
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("fetching exchange rates: %s", resp.Status) }
r, err := Parse(io.LimitReader(resp.Body, 1<<20))
if err != nil { return nil, err }
r.Fetched = s.now()
return r, nil
}
// Parse reads the ECB's eurofxref XML.
func Parse(rd io.Reader) (*Rates, error) {
var doc struct {
Days []struct {
Time string `xml:"time,attr"`
Rates []struct {
Currency string `xml:"currency,attr"`
Rate string `xml:"rate,attr"`
} `xml:"Cube"`
} `xml:"Cube>Cube"`
}
if err := xml.NewDecoder(rd).Decode(&doc); err != nil { return nil, fmt.Errorf("reading exchange rates: %w", err) }
if len(doc.Days) == 0 { return nil, errors.New("reading exchange rates: no rates in the feed") }
day := doc.Days[0]
r := &Rates{Date: day.Time, PerEUR: map[string]float64{}}
for _, c := range day.Rates {
rate, err := strconv.ParseFloat(c.Rate, 64)
if err != nil || rate <= 0 { return nil, fmt.Errorf("reading exchange rates: bad rate %q for %s", c.Rate, c.Currency) }
r.PerEUR[c.Currency] = rate
}
if len(r.PerEUR) == 0 { return nil, errors.New("reading exchange rates: no rates in the feed") }
return r, nil
}
+28
View File
@@ -0,0 +1,28 @@
package fx
import (
"math"
"testing"
)
func TestConvert(t *testing.T) {
r := &Rates{PerEUR: map[string]float64{"USD": 1.25, "GBP": 0.8}}
cases := []struct {
amount float64
from, to string
want float64
} {
{100, "EUR", "USD", 125},
{125, "USD", "EUR", 100},
{100, "GBP", "USD", 156.25},
{100, "GBP", "GBP", 100},
}
for _, c := range cases {
got, err := r.Convert(c.amount, c.from, c.to)
if err != nil || math.Abs(got-c.want) > 1e-9 { t.Errorf("%v %s in %s = %v, %v; want %v", c.amount, c.from, c.to, got, err, c.want) }
}
if _, err := r.Convert(1, "JPY", "EUR"); err == nil { t.Error("converted a currency without a rate") }
}
+291
View File
@@ -0,0 +1,291 @@
// Package notify delivers alerts to webhooks and the desktop.
package notify
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/gen2brain/beeep"
"git.security-command.org/Overlord/dibs/internal/alert"
"git.security-command.org/Overlord/dibs/internal/config"
)
const (
// retries follow the first attempt, with waits of 1s, 2s and 4s.
retries = 3
retryBase = 1 * time.Second
maxRetryAfter = 30 * time.Second
requestTimeout = 10 * time.Second
)
// Notifier sends alerts to every configured channel.
type Notifier struct {
webhooks []config.Webhook
desktop bool
userAgent string
client *http.Client
wait func(ctx context.Context, d time.Duration) error
showToast func(title, message string) error
}
// New returns a notifier for the [notify] config. Webhook requests are not
// rate limited: they go to the user's own services, and only when an item
// fires.
func New(cfg config.Notify, userAgent string) *Notifier {
beeep.AppName = "dibs"
return &Notifier{
webhooks: cfg.Webhooks,
desktop: cfg.Desktop,
userAgent: userAgent,
client: &http.Client{Timeout: requestTimeout},
wait: sleep,
showToast: func(title, message string) error { return beeep.Notify(title, message, "") },
}
}
// Send delivers a to every webhook and the desktop at once and returns when
// all are done. The error joins one error per failed channel.
func (n *Notifier) Send(ctx context.Context, a alert.Alert) error {
errs := make([]error, len(n.webhooks)+1)
var wg sync.WaitGroup
for i, wh := range n.webhooks {
wg.Go(func() {
if err := n.webhook(ctx, wh, a); err != nil { errs[i] = fmt.Errorf("webhook %d (%s, %s): %w", i, wh.Format, hostOf(wh.URL), err) }
})
}
if n.desktop {
wg.Go(func() {
title, message := desktopText(a)
if err := n.showToast(title, message); err != nil { errs[len(n.webhooks)] = fmt.Errorf("desktop notification: %w", err) }
})
}
wg.Wait()
return errors.Join(errs...)
}
// Channels says where alerts go, for the startup log.
func (n *Notifier) Channels() []string {
var out []string
for _, wh := range n.webhooks { out = append(out, wh.Format+" "+hostOf(wh.URL)) }
if n.desktop { out = append(out, "desktop") }
return out
}
// hostOf names a webhook in logs and errors. Its full URL often contains a
// secret token.
func hostOf(raw string) string {
if u, err := url.Parse(raw); err == nil { return u.Host }
return "invalid URL"
}
func (n *Notifier) webhook(ctx context.Context, wh config.Webhook, a alert.Alert) error {
var (
body []byte
header = http.Header{}
err error
)
switch wh.Format {
case config.FormatDiscord:
body, err = json.Marshal(discordPayload(a))
header.Set("Content-Type", "application/json")
case config.FormatNtfy:
body = []byte(ntfyMessage(a))
ntfyHeaders(header, a)
default:
body, err = json.Marshal(NewPayload(a))
header.Set("Content-Type", "application/json")
}
if err != nil { return err }
header.Set("User-Agent", n.userAgent)
return n.post(ctx, wh.URL, header, body)
}
// post sends body, retrying network errors, 429 and 5xx answers.
func (n *Notifier) post(ctx context.Context, rawURL string, header http.Header, body []byte) error {
var last error
for attempt := 0; ; attempt++ {
retryAfter, err := n.try(ctx, rawURL, header, body)
if err == nil { return nil }
last = err
if retryAfter < 0 || attempt == retries || ctx.Err() != nil { return last }
d := retryBase << attempt
if retryAfter > d { d = min(retryAfter, maxRetryAfter) }
if err := n.wait(ctx, d); err != nil { return last }
}
}
// try makes one request. A failed request returns how long the server asked
// to wait before the next one, 0 if it did not say, or -1 if retrying is
// pointless.
func (n *Notifier) try(ctx context.Context, rawURL string, header http.Header, body []byte) (time.Duration, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, rawURL, bytes.NewReader(body))
if err != nil { return -1, err }
req.Header = header.Clone()
resp, err := n.client.Do(req)
if err != nil { return 0, err }
defer func() { _ = resp.Body.Close() }()
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
if resp.StatusCode < 300 { return 0, nil }
err = fmt.Errorf("%s", resp.Status)
if text := strings.TrimSpace(string(msg)); text != "" { err = fmt.Errorf("%s: %s", resp.Status, text) }
switch {
case resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500:
secs, _ := strconv.Atoi(resp.Header.Get("Retry-After"))
return time.Duration(max(secs, 0)) * time.Second, err
default:
return -1, err
}
}
func sleep(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
return nil
}
}
// link is where tapping a notification leads: the cart link if the shop has
// one, otherwise the product page.
func link(a alert.Alert) string {
if a.CartLink != "" { return a.CartLink }
return a.URL
}
func headline(a alert.Alert) string {
h := "In stock: " + a.Item
if a.Test { h = "Test alert: " + a.Item }
return h
}
// summary is the price and seller line, with the price drop if there is one.
func summary(a alert.Alert) string {
s := a.PriceText() + ", " + a.SellerText()
if a.PreviousPrice != nil { s += ", down from " + alert.Money(*a.PreviousPrice, a.PreviousCurrency) }
return s
}
func desktopText(a alert.Alert) (string, string) {
lines := []string{summary(a)}
if a.Title != "" { lines = append(lines, a.Title) }
return headline(a), strings.Join(lines, "\n")
}
func ntfyMessage(a alert.Alert) string {
lines := []string{summary(a)}
if a.Title != "" { lines = append(lines, a.Title) }
if a.CartLink != "" { lines = append(lines, "Cart: "+a.CartLink) }
lines = append(lines, "Page: "+a.URL)
return strings.Join(lines, "\n")
}
func ntfyHeaders(h http.Header, a alert.Alert) {
// HTTP headers are ASCII. ntfy decodes RFC 2047 encoded words, which
// carry titles such as "Édition Limitée".
h.Set("Title", mime.BEncoding.Encode("utf-8", headline(a)))
h.Set("Click", link(a))
h.Set("Priority", "high")
h.Set("Tags", "shopping_cart")
}
type discordMessage struct {
Username string `json:"username"`
Content string `json:"content"`
Embeds []discordEmbed `json:"embeds"`
AllowedMentions map[string][]string `json:"allowed_mentions"`
}
type discordEmbed struct {
Title string `json:"title"`
URL string `json:"url"`
Description string `json:"description,omitempty"`
Color int `json:"color"`
Fields []discordField `json:"fields"`
Timestamp string `json:"timestamp"`
}
type discordField struct {
Name string `json:"name"`
Value string `json:"value"`
Inline bool `json:"inline"`
}
func discordPayload(a alert.Alert) discordMessage {
title := a.Title
if title == "" { title = a.Item }
price := a.PriceText()
if a.PreviousPrice != nil { price += ", down from " + alert.Money(*a.PreviousPrice, a.PreviousCurrency) }
desc := "[Product page](" + a.URL + ")"
if a.CartLink != "" { desc = "[Add to cart](" + a.CartLink + ") · " + desc }
return discordMessage{
Username: "dibs",
// The angle brackets keep Discord from adding a preview of the link.
Content: "**" + headline(a) + "** <" + link(a) + ">",
Embeds: []discordEmbed{{
Title: truncate(title, 256),
URL: link(a),
Description: desc,
Color: 0x2ecc71,
Fields: []discordField{
{Name: "Price", Value: price, Inline: true},
{Name: "Seller", Value: a.SellerText(), Inline: true},
},
Timestamp: a.Time.UTC().Format(time.RFC3339),
}},
// Page titles never ping anyone.
AllowedMentions: map[string][]string{"parse": {}},
}
}
func truncate(s string, n int) string {
if utf8.RuneCountInString(s) <= n { return s }
r := []rune(s)
return string(r[:n-1]) + "…"
}
+58
View File
@@ -0,0 +1,58 @@
package notify
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"git.security-command.org/Overlord/dibs/internal/alert"
"git.security-command.org/Overlord/dibs/internal/config"
)
// TestRetries sends one alert to a webhook that fails with each status
// until the last attempt.
func TestRetries(t *testing.T) {
price := 129.99
a := alert.Alert{Item: "metro", Shop: "amazon", URL: "https://www.amazon.de/dp/B0HMX2FSTF", Price: &price, Currency: "EUR", Time: time.Now()}
cases := []struct {
status int
requests int32
ok bool
} {
{http.StatusServiceUnavailable, retries + 1, false},
{http.StatusTooManyRequests, retries + 1, false},
{http.StatusNotFound, 1, false},
{http.StatusNoContent, 1, true},
}
for _, c := range cases {
var requests atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
w.WriteHeader(c.status)
}))
// The path stands in for a webhook token.
n := New(config.Notify{Webhooks: []config.Webhook{{URL: srv.URL + "/secret-token", Format: config.FormatJSON}}}, "dibs/test")
var waited time.Duration
n.wait = func(_ context.Context, d time.Duration) error {
waited += d
return nil
}
err := n.Send(context.Background(), a)
srv.Close()
if got := requests.Load(); got != c.requests { t.Errorf("%d: %d requests, want %d", c.status, got, c.requests) }
if (err == nil) != c.ok { t.Errorf("%d: err = %v", c.status, err) }
if err != nil && strings.Contains(err.Error(), "secret-token") { t.Errorf("%d: error shows the webhook URL: %v", c.status, err) }
if c.requests > 1 && waited != 7*time.Second { t.Errorf("%d: waited %s between attempts, want 7s", c.status, waited) }
}
}
+86
View File
@@ -0,0 +1,86 @@
package notify
import (
"time"
"git.security-command.org/Overlord/dibs/internal/alert"
)
// PayloadVersion changes only when a field is removed or changes meaning.
// New fields may appear in any version.
const PayloadVersion = 1
// Payload is the body of a "json" webhook, POSTed as application/json.
//
// {
// "version": 1,
// "test": false,
// "item": "Metro 2039 CE",
// "shop": "amazon",
// "url": "https://www.amazon.de/dp/B0HMX2FSTF",
// "title": "Metro 2039 Collector's Edition (PS5)",
// "price": 129.99,
// "currency": "EUR",
// "converted_price": null,
// "converted_currency": null,
// "previous_price": null,
// "previous_currency": null,
// "seller": "first_party",
// "cart_link": "https://www.amazon.de/gp/aws/cart/add.html?ASIN.1=B0HMX2FSTF&Quantity.1=1",
// "time": "2026-10-14T09:30:00Z"
// }
//
// Every key is always present; values that do not apply are null.
type Payload struct {
Version int `json:"version"`
// Test is true for the sample alert of `dibs notify test`.
Test bool `json:"test"`
Item string `json:"item"`
Shop string `json:"shop"`
// URL is the product page.
URL string `json:"url"`
Title *string `json:"title"`
// Price is null when the page shows none, which only fires items without
// max_price.
Price *float64 `json:"price"`
Currency *string `json:"currency"`
// ConvertedPrice is the price in the item's currency, when the page uses
// another one.
ConvertedPrice *float64 `json:"converted_price"`
ConvertedCurrency *string `json:"converted_currency"`
// PreviousPrice is set when the item fires again during its cooldown
// because the price dropped below the previous alert's.
PreviousPrice *float64 `json:"previous_price"`
PreviousCurrency *string `json:"previous_currency"`
// Seller is "first_party", "fulfilled", "third_party" or "unknown".
Seller string `json:"seller"`
CartLink *string `json:"cart_link"`
// Time is when the page was checked, in UTC.
Time time.Time `json:"time"`
}
func NewPayload(a alert.Alert) Payload {
return Payload{
Version: PayloadVersion,
Test: a.Test,
Item: a.Item,
Shop: a.Shop,
URL: a.URL,
Title: orNull(a.Title),
Price: a.Price,
Currency: orNull(a.Currency),
ConvertedPrice: a.Converted,
ConvertedCurrency: orNull(a.ConvertedCurrency),
PreviousPrice: a.PreviousPrice,
PreviousCurrency: orNull(a.PreviousCurrency),
Seller: a.Seller,
CartLink: orNull(a.CartLink),
Time: a.Time.UTC().Truncate(time.Second),
}
}
func orNull(s string) *string {
if s == "" { return nil }
return &s
}
+3 -4
View File
@@ -1,7 +1,6 @@
-- Built-in plugin for Amazon product pages (de, co.uk, fr, it, es, nl, com). -- 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
-- It uses only the public plugin API, so it doubles as the reference for -- implementation of a plugin.
-- writing your own: see "Writing a plugin" in README.md.
local tlds = { local tlds = {
["de"] = "EUR", ["de"] = "EUR",
@@ -26,7 +25,7 @@ local amazon_merchants = {
} }
-- Any of these buttons means a new item can go into the cart. The preorder -- 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 -- "#add-to-cart-button-ubb" is deliberately missing: it belongs to the used
-- buybox, which Amazon shows when only used copies are left. -- buybox, which Amazon shows when only used copies are left.
local buy_buttons = table.concat({ local buy_buttons = table.concat({
+4 -4
View File
@@ -12,9 +12,9 @@ import (
const nodeType = "dibs.node" const nodeType = "dibs.node"
// The methods of doc and of the nodes doc:all() returns. Each takes an // nodeMethods are the methods of doc and of the nodes doc:all() returns.
// optional CSS selector: without one it works on the node itself, with one // Each takes an optional CSS selector: without one it works on the node
// on the first match inside it. // itself, with one on the first match inside it.
var nodeMethods = map[string]lua.LGFunction{ var nodeMethods = map[string]lua.LGFunction{
"text": nodeText, "text": nodeText,
"attr": nodeAttr, "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 // 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, // 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 { func nodeText(L *lua.LState) int {
s := target(L, checkNode(L), 2).First() s := target(L, checkNode(L), 2).First()
-4
View File
@@ -21,7 +21,6 @@ var builtinFS embed.FS
// ErrNoPlugin is returned when no plugin matches a URL. // ErrNoPlugin is returned when no plugin matches a URL.
var ErrNoPlugin = errors.New("no plugin matches the URL") var ErrNoPlugin = errors.New("no plugin matches the URL")
// Builtins returns the names of the embedded plugins.
func Builtins() []string { func Builtins() []string {
files, _ := fs.Glob(builtinFS, "builtin/*.lua") files, _ := fs.Glob(builtinFS, "builtin/*.lua")
@@ -31,12 +30,10 @@ func Builtins() []string {
return names return names
} }
// BuiltinSource returns the code of an embedded plugin.
func BuiltinSource(name string) ([]byte, error) { func BuiltinSource(name string) ([]byte, error) {
return builtinFS.ReadFile("builtin/" + name + ".lua") return builtinFS.ReadFile("builtin/" + name + ".lua")
} }
// Host holds the loaded plugins.
type Host struct { type Host struct {
plugins map[string]*Plugin plugins map[string]*Plugin
// order is the order ForURL tries plugins in: user plugins first, so // 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 return h, nil
} }
// Plugin returns the plugin called name.
func (h *Host) Plugin(name string) (*Plugin, bool) { func (h *Host) Plugin(name string) (*Plugin, bool) {
p, ok := h.plugins[name] p, ok := h.plugins[name]
return p, ok return p, ok
+8 -11
View File
@@ -19,14 +19,14 @@ import (
lua "github.com/yuin/gopher-lua" lua "github.com/yuin/gopher-lua"
) )
// Who sells the item, as parse reports it. // The sellers parse reports.
const ( const (
// SellerFirstParty: the shop itself sells it. // SellerFirstParty means the shop itself sells the item.
SellerFirstParty = "first_party" SellerFirstParty = "first_party"
// SellerFulfilled: a marketplace seller sells it, but the shop ships it // SellerFulfilled means a marketplace seller sells the item and the shop
// (e.g. Fulfilled by Amazon). // ships it, as with Fulfilled by Amazon.
SellerFulfilled = "fulfilled" SellerFulfilled = "fulfilled"
// SellerThirdParty: a marketplace seller sells and ships it. // SellerThirdParty means a marketplace seller sells and ships the item.
SellerThirdParty = "third_party" SellerThirdParty = "third_party"
SellerUnknown = "unknown" SellerUnknown = "unknown"
) )
@@ -172,7 +172,6 @@ func (p *Plugin) readTable(tbl *lua.LTable) error {
return nil return nil
} }
// Has reports whether the plugin defines hook.
func (p *Plugin) Has(hook string) bool { func (p *Plugin) Has(hook string) bool {
p.mu.Lock() p.mu.Lock()
defer p.mu.Unlock() 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 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 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) } 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) { 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 // The HTML is parsed before the call, so parsing does not count against
// call's time and memory. // the call's time and memory.
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(page)) doc, err := goquery.NewDocumentFromReader(bytes.NewReader(page))
if err != nil { return nil, fmt.Errorf("parsing HTML: %w", err) } 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() { func (p *Plugin) Close() {
p.mu.Lock() p.mu.Lock()
defer p.mu.Unlock() defer p.mu.Unlock()
+286
View File
@@ -0,0 +1,286 @@
// Package ratelimit enforces how often dibs may talk to a shop.
//
// The floors are constants on purpose: no config value, flag or caller can
// lower them.
package ratelimit
import (
"context"
"math/rand/v2"
"net/url"
"strings"
"sync"
"time"
)
const (
// URLFloor is the shortest time between two checks of one URL.
URLFloor = 60 * time.Second
// HostFloor is the shortest time between two requests to one host.
HostFloor = 10 * time.Second
// Jitter is the fraction intervals are randomly stretched or shrunk by.
Jitter = 0.2
backoffBase = 2 * time.Minute
backoffCap = 30 * time.Minute
)
// HostState is what the limiter remembers about a host. It is persisted so
// the floors hold across restarts and between dibs processes.
type HostState struct {
// Next is the earliest time of the next request.
Next time.Time `json:"next"`
// Failures counts bot checks and refusals in a row.
Failures int `json:"failures,omitempty"`
// BackoffUntil blocks the host after repeated failures.
BackoffUntil time.Time `json:"backoff_until,omitzero"`
}
// Persister shares host and URL state with other dibs processes. The Load
// methods return the newest state on disk, and the Store methods record this
// process's. Lock serializes the limiters' decisions across processes and
// returns the unlock function.
type Persister interface {
Lock() func()
LoadHost(host string) (HostState, bool)
StoreHost(host string, h HostState)
LoadURL(pageURL string) (time.Time, bool)
StoreURL(pageURL string, last time.Time)
}
// Clock abstracts time so tests can replace it.
type Clock interface {
Now() time.Time
After(d time.Duration) <-chan time.Time
}
// SystemClock is the real clock.
var SystemClock Clock = systemClock{}
type systemClock struct{}
func (systemClock) Now() time.Time { return time.Now() }
func (systemClock) After(d time.Duration) <-chan time.Time { return time.After(d) }
// Limiter spaces requests per host and checks per URL, and backs off from
// hosts that keep answering with bot checks. It is safe for concurrent use.
type Limiter struct {
clock Clock
persist Persister
rand func() float64
mu sync.Mutex
hosts map[string]HostState
urls map[string]time.Time
}
type Option func(*Limiter)
// WithClock replaces the system clock, for tests.
func WithClock(c Clock) Option { return func(l *Limiter) { l.clock = c } }
// WithRand replaces the jitter source, which returns values in [0, 1).
func WithRand(r func() float64) Option { return func(l *Limiter) { l.rand = r } }
// New returns a limiter. persist may be nil to keep state in memory only.
func New(persist Persister, opts ...Option) *Limiter {
l := &Limiter{
clock: SystemClock,
persist: persist,
rand: rand.Float64,
hosts: map[string]HostState{},
urls: map[string]time.Time{},
}
for _, o := range opts { o(l) }
return l
}
func (l *Limiter) Clock() Clock { return l.clock }
// Wait blocks until a request to host is allowed, then reserves the slot.
// It is for requests that are not checks of a product page.
func (l *Limiter) Wait(ctx context.Context, host string) error {
return l.wait(ctx, strings.ToLower(host), "")
}
// WaitCheck blocks until url may be checked: its host's floor and backoff,
// and the URL floor since its last check by any dibs process, all allow it.
// It then reserves both at once, so the request must follow right away.
func (l *Limiter) WaitCheck(ctx context.Context, rawURL string) error {
u, err := url.Parse(rawURL)
if err != nil { return err }
return l.wait(ctx, strings.ToLower(u.Hostname()), rawURL)
}
func (l *Limiter) wait(ctx context.Context, host, checkURL string) error {
for {
var at time.Time
reserved := false
l.locked(func() {
h := l.host(host)
now := l.clock.Now()
at = latest(h.Next, h.BackoffUntil)
if checkURL != "" { at = latest(at, l.urlReady(checkURL)) }
if now.Before(at) { return }
// The host gap is stretched randomly, never below the floor.
h.Next = now.Add(time.Duration(float64(HostFloor) * (1 + Jitter*l.rand())))
l.setHost(host, h)
if checkURL != "" {
l.urls[checkURL] = now
if l.persist != nil { l.persist.StoreURL(checkURL, now) }
}
reserved = true
})
if reserved { return nil }
select {
case <-l.clock.After(at.Sub(l.clock.Now())):
case <-ctx.Done():
return ctx.Err()
}
}
}
// Delay is how long a request to host would have to wait now.
func (l *Limiter) Delay(host string) time.Duration {
l.mu.Lock()
defer l.mu.Unlock()
h := l.host(strings.ToLower(host))
return max(0, latest(h.Next, h.BackoffUntil).Sub(l.clock.Now()))
}
// Failure records a bot check or refusal from host and backs off
// exponentially, from 2 minutes up to 30.
func (l *Limiter) Failure(host string) time.Duration {
host = strings.ToLower(host)
var d time.Duration
l.locked(func() {
h := l.host(host)
h.Failures++
d = min(backoffBase<<min(h.Failures-1, 10), backoffCap)
d = min(l.Jittered(d, 0), backoffCap)
h.BackoffUntil = l.clock.Now().Add(d)
l.setHost(host, h)
})
return d
}
// Success clears the backoff of host.
func (l *Limiter) Success(host string) {
host = strings.ToLower(host)
l.locked(func() {
h := l.host(host)
if h.Failures == 0 && h.BackoffUntil.IsZero() { return }
h.Failures, h.BackoffUntil = 0, time.Time{}
l.setHost(host, h)
})
}
// NextCheck is when url may be checked next, given its interval: the
// interval jittered by ±20%, but never less than URLFloor after the last
// check, by this or another dibs process.
func (l *Limiter) NextCheck(pageURL string, interval time.Duration) time.Time {
l.mu.Lock()
defer l.mu.Unlock()
last := l.lastCheck(pageURL)
if last.IsZero() { return l.clock.Now() }
return last.Add(l.Jittered(interval, URLFloor))
}
// URLReady is the earliest time url may be checked at all.
func (l *Limiter) URLReady(pageURL string) time.Time {
l.mu.Lock()
defer l.mu.Unlock()
return l.urlReady(pageURL)
}
// LastCheck is when the URL was last checked by any dibs process, or zero.
func (l *Limiter) LastCheck(pageURL string) time.Time {
l.mu.Lock()
defer l.mu.Unlock()
return l.lastCheck(pageURL)
}
// Jittered stretches or shrinks d randomly by up to ±20%, but never below
// floor.
func (l *Limiter) Jittered(d, floor time.Duration) time.Duration {
return max(time.Duration(float64(d)*(1+Jitter*(2*l.rand()-1))), floor)
}
// locked runs fn holding the limiter's lock and, if there is one, the lock
// shared with other processes.
func (l *Limiter) locked(fn func()) {
l.mu.Lock()
defer l.mu.Unlock()
if l.persist != nil { defer l.persist.Lock()() }
fn()
}
// host returns what this and other processes know about host. Callers hold
// mu.
func (l *Limiter) host(host string) HostState {
h := l.hosts[host]
if l.persist == nil { return h }
if p, ok := l.persist.LoadHost(host); ok {
h.Next = latest(h.Next, p.Next)
h.BackoffUntil = latest(h.BackoffUntil, p.BackoffUntil)
h.Failures = max(h.Failures, p.Failures)
}
return h
}
func (l *Limiter) setHost(host string, h HostState) {
l.hosts[host] = h
if l.persist != nil { l.persist.StoreHost(host, h) }
}
// urlReady is when url may be checked again. Callers hold mu.
func (l *Limiter) urlReady(pageURL string) time.Time {
last := l.lastCheck(pageURL)
if last.IsZero() { return last }
return last.Add(URLFloor)
}
// lastCheck is the newest check of the URL that this or another process
// knows of. Callers hold mu.
func (l *Limiter) lastCheck(pageURL string) time.Time {
last := l.urls[pageURL]
if l.persist != nil {
if p, ok := l.persist.LoadURL(pageURL); ok { last = latest(last, p) }
}
return last
}
func latest(a, b time.Time) time.Time {
if a.After(b) { return a }
return b
}
+98
View File
@@ -0,0 +1,98 @@
package ratelimit
import (
"context"
"sync"
"testing"
"time"
)
// FakeClock moves forward only when something waits on it, by exactly the
// time waited.
type FakeClock struct {
mu sync.Mutex
now time.Time
}
func NewFakeClock() *FakeClock { return &FakeClock{now: time.Date(2026, 10, 14, 12, 0, 0, 0, time.UTC)} }
func (c *FakeClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
func (c *FakeClock) After(d time.Duration) <-chan time.Time {
c.mu.Lock()
defer c.mu.Unlock()
c.now = c.now.Add(d)
ch := make(chan time.Time, 1)
ch <- c.now
return ch
}
func fixedRand(v float64) Option { return WithRand(func() float64 { return v }) }
func TestHostFloor(t *testing.T) {
ctx := context.Background()
for _, r := range []float64{0, 0.5, 0.999} {
clock := NewFakeClock()
l := New(nil, WithClock(clock), fixedRand(r))
if err := l.Wait(ctx, "www.amazon.de"); err != nil { t.Fatal(err) }
first := clock.Now()
// Another host is not held up.
if err := l.Wait(ctx, "www.amazon.co.uk"); err != nil { t.Fatal(err) }
if !clock.Now().Equal(first) { t.Errorf("rand %v: a request to another host waited", r) }
if err := l.Wait(ctx, "WWW.AMAZON.DE"); err != nil { t.Fatal(err) }
gap := clock.Now().Sub(first)
if gap < HostFloor || gap > time.Duration(float64(HostFloor)*(1+Jitter)) { t.Errorf("rand %v: gap %s, want between %s and %s", r, gap, HostFloor, time.Duration(float64(HostFloor)*(1+Jitter))) }
}
}
func TestURLFloor(t *testing.T) {
clock := NewFakeClock()
l := New(nil, WithClock(clock), fixedRand(0)) // shortest jitter: -20%
const url = "https://www.amazon.de/dp/B0HMX2FSTF"
if next := l.NextCheck(url, time.Minute); !next.Equal(clock.Now()) { t.Errorf("never checked: next %s, want now", next) }
if err := l.WaitCheck(context.Background(), url); err != nil { t.Fatal(err) }
last := clock.Now()
// 60s - 20% would be 48s, and an interval below the floor (which the
// config rejects anyway) must not get through either.
for _, interval := range []time.Duration{time.Minute, time.Second} {
if next := l.NextCheck(url, interval); next.Sub(last) < URLFloor { t.Errorf("interval %s: next check %s after the last, below the floor", interval, next.Sub(last)) }
}
if ready := l.URLReady(url); ready.Sub(last) != URLFloor { t.Errorf("URLReady %s after the last check, want %s", ready.Sub(last), URLFloor) }
if next := l.NextCheck(url, 10*time.Minute); next.Sub(last) != 8*time.Minute { t.Errorf("10m interval at -20%%: next after %s, want 8m", next.Sub(last)) }
}
func TestBackoff(t *testing.T) {
ctx := context.Background()
clock := NewFakeClock()
l := New(nil, WithClock(clock), fixedRand(0.5)) // no jitter
for i, want := range []time.Duration{2, 4, 8, 16, 30, 30} {
if got := l.Failure("www.amazon.de"); got != want*time.Minute { t.Errorf("failure %d: backoff %s, want %dm", i+1, got, want) }
}
start := clock.Now()
if err := l.Wait(ctx, "www.amazon.de"); err != nil { t.Fatal(err) }
if waited := clock.Now().Sub(start); waited != 30*time.Minute { t.Errorf("waited %s for a backed-off host, want 30m", waited) }
l.Success("www.amazon.de")
if got := l.Failure("www.amazon.de"); got != 2*time.Minute { t.Errorf("after a success: backoff %s, want it to start over at 2m", got) }
}
+184
View File
@@ -0,0 +1,184 @@
// 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/alert"
"git.security-command.org/Overlord/dibs/internal/config"
"git.security-command.org/Overlord/dibs/internal/fsutil"
"git.security-command.org/Overlord/dibs/internal/fx"
"git.security-command.org/Overlord/dibs/internal/ratelimit"
)
// Hosts, URLs and alerts untouched for forgetAfter are dropped, such as URLs
// removed from the config. An alert is kept for as long as the longest
// cooldown lasts.
const forgetAfter = config.MaxCooldown
type file struct {
Hosts map[string]ratelimit.HostState `json:"hosts"`
URLs map[string]time.Time `json:"urls"`
Alerts map[string]alert.Sent `json:"alerts,omitempty"`
FX *fx.Rates `json:"fx,omitempty"`
}
// Store is the state file. It implements ratelimit.Persister, alert.Store
// and fx.Store.
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 }
})
}
func (s *Store) LoadAlert(item string) (alert.Sent, bool) {
s.mu.Lock()
defer s.mu.Unlock()
a, ok := s.read().Alerts[item]
return a, ok
}
func (s *Store) StoreAlert(item string, a alert.Sent) {
s.update(func(f *file) { f.Alerts[item] = a })
}
func (s *Store) LoadRates() (*fx.Rates, bool) {
s.mu.Lock()
defer s.mu.Unlock()
r := s.read().FX
return r, r != nil
}
func (s *Store) StoreRates(r *fx.Rates) {
s.update(func(f *file) {
if f.FX == nil || r.Fetched.After(f.FX.Fetched) { f.FX = r }
})
}
// 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{}, Alerts: map[string]alert.Sent{}}
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{} }
if f.Alerts == nil { f.Alerts = map[string]alert.Sent{} }
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) }
}
for item, a := range f.Alerts {
if a.Time.Before(cutoff) { delete(f.Alerts, item) }
}
data, err := json.MarshalIndent(f, "", " ")
if err == nil { err = fsutil.WriteFileAtomic(s.path, data, 0o600) }
s.err = err
}
+77
View File
@@ -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)
}
}
}
+121
View File
@@ -0,0 +1,121 @@
package tui
import (
"context"
"io"
"log/slog"
"strconv"
"strings"
"sync"
"time"
)
// LogLine is one log record, formatted for the log pane.
type LogLine struct {
Time time.Time
Level slog.Level
Msg string
// Attrs are the record's attributes as key=value pairs.
Attrs string
}
// LogHandler is a slog.Handler that feeds the log pane.
type LogHandler struct {
level slog.Level
sink *sink
attrs string
prefix string
}
// sink is shared by a handler and the handlers derived from it.
type sink struct {
lines chan LogLine
mu sync.Mutex
out io.Writer // set once the TUI is gone
}
// NewLogHandler returns a handler for records at level or above.
func NewLogHandler(level slog.Level) *LogHandler {
return &LogHandler{level: level, sink: &sink{lines: make(chan LogLine, 1024)}}
}
// Redirect sends all further lines to w, for after the TUI exits.
func (h *LogHandler) Redirect(w io.Writer) {
h.sink.mu.Lock()
defer h.sink.mu.Unlock()
h.sink.out = w
}
func (h *LogHandler) Enabled(_ context.Context, l slog.Level) bool { return l >= h.level }
// Handle never blocks. When the TUI falls 1024 lines behind, new lines are
// dropped.
func (h *LogHandler) Handle(_ context.Context, r slog.Record) error {
var b strings.Builder
b.WriteString(h.attrs)
r.Attrs(func(a slog.Attr) bool {
writeAttr(&b, h.prefix, a)
return true
})
l := LogLine{Time: r.Time, Level: r.Level, Msg: r.Message, Attrs: b.String()}
h.sink.mu.Lock()
defer h.sink.mu.Unlock()
if h.sink.out != nil {
_, err := io.WriteString(h.sink.out, l.Time.Format(time.TimeOnly)+" "+l.Level.String()+" "+l.Msg+" "+l.Attrs+"\n")
return err
}
select {
case h.sink.lines <- l:
default:
}
return nil
}
func (h *LogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
var b strings.Builder
b.WriteString(h.attrs)
for _, a := range attrs { writeAttr(&b, h.prefix, a) }
c := *h
c.attrs = b.String()
return &c
}
func (h *LogHandler) WithGroup(name string) slog.Handler {
c := *h
c.prefix = h.prefix + name + "."
return &c
}
func writeAttr(b *strings.Builder, prefix string, a slog.Attr) {
v := a.Value.Resolve()
if v.Kind() == slog.KindGroup {
for _, g := range v.Group() { writeAttr(b, prefix+a.Key+".", g) }
return
}
if a.Key == "" { return }
s := v.String()
switch v.Kind() {
case slog.KindTime:
s = v.Time().Local().Format(time.TimeOnly)
case slog.KindDuration:
s = v.Duration().Round(time.Second).String()
default:
// Strings, numbers and errors print as they are.
}
if s == "" || strings.ContainsAny(s, " =\"\n") { s = strconv.Quote(s) }
if b.Len() > 0 { b.WriteByte(' ') }
b.WriteString(prefix + a.Key + "=" + s)
}
+361
View File
@@ -0,0 +1,361 @@
// Package tui is the interactive view of dibs: a table with one row per
// URL, a log pane and a status bar.
package tui
import (
"errors"
"fmt"
"io"
"os"
"strings"
"time"
"charm.land/bubbles/v2/viewport"
tea "charm.land/bubbletea/v2"
"github.com/pkg/browser"
"git.security-command.org/Overlord/dibs/internal/alert"
"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/watch"
)
const (
// tick is how often the table refreshes. It is also the flash rate.
tick = 500 * time.Millisecond
flashFor = 30 * time.Second
noteFor = 10 * time.Second
)
// maxLines is how many lines the log pane keeps.
const maxLines = 2000
// Controller is the running watcher.
type Controller interface {
Statuses() []watch.Status
Pause(item string, paused bool) bool
PauseAll(paused bool)
CheckNow(item string) bool
Reload() ([]string, error)
}
// CheckMsg is one finished check and what the alert engine made of it.
type CheckMsg struct {
Result watch.Result
Decision alert.Decision
PriceErr error
}
type (
tickMsg time.Time
logMsg LogLine
reloadMsg struct {
summary []string
err error
}
openMsg struct {
url string
err error
}
)
// Status texts, as the STATUS column shows them.
const (
statusWatching = "watching"
statusAvailable = "AVAILABLE"
statusBlocked = "blocked"
statusError = "error"
statusPaused = "paused"
)
// result is what the last check of a URL found.
type result struct {
status string
price string
seller string
cartLink string
flash time.Time // the row flashes until then
}
type Model struct {
ctl Controller
path string
lines <-chan LogLine
now time.Time
rows []watch.Status
results map[string]*result // by configured URL
cursor int
offset int // the first table row on screen
widths []int // the column widths, reset by resizes and reloads
logs []LogLine
log viewport.Model
logFocus bool
width, height int
note string
noteError bool
noteTime time.Time
reloading bool
}
// New returns the TUI for ctl. path is the config file, and logs is the
// handler the watcher logs to.
func New(ctl Controller, path string, logs *LogHandler) *Model {
// The browser's own output would draw over the TUI.
browser.Stdout, browser.Stderr = io.Discard, io.Discard
if home, err := os.UserHomeDir(); err == nil && strings.HasPrefix(path, home+string(os.PathSeparator)) { path = "~" + path[len(home):] }
m := &Model{
ctl: ctl,
path: path,
lines: logs.sink.lines,
now: time.Now(),
results: map[string]*result{},
log: viewport.New(),
}
m.rows = ctl.Statuses()
return m
}
func (m *Model) Init() tea.Cmd {
return tea.Batch(m.tick(), m.nextLine())
}
func (m *Model) tick() tea.Cmd {
return tea.Tick(tick, func(t time.Time) tea.Msg { return tickMsg(t) })
}
func (m *Model) nextLine() tea.Cmd {
return func() tea.Msg { return logMsg(<-m.lines) }
}
func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width, m.height = msg.Width, msg.Height
m.widths = nil
m.layout()
case tickMsg:
m.now = time.Time(msg)
m.rows = m.ctl.Statuses()
m.clampCursor()
return m, m.tick()
case logMsg:
m.addLog(LogLine(msg))
return m, m.nextLine()
case CheckMsg:
return m, m.checked(msg)
case reloadMsg:
m.reloading = false
m.rows = m.ctl.Statuses()
m.widths = nil
m.clampCursor()
if msg.err != nil { m.setNote(reloadError(msg.err), true) } else { m.setNote(reloadNote(msg.summary), false) }
case openMsg:
if msg.err != nil { m.setNote("cannot open the browser: "+msg.err.Error(), true) } else { m.setNote("opened "+msg.url, false) }
case tea.KeyPressMsg:
return m, m.key(msg)
}
return m, nil
}
// checked records a check. A new alert flashes its row and rings the bell.
func (m *Model) checked(c CheckMsg) tea.Cmd {
r := m.results[c.Result.URL]
if r == nil {
r = &result{}
m.results[c.Result.URL] = r
}
r.status = statusOf(c)
if rep := c.Result.Report; rep != nil {
r.price, r.seller = "", ""
if res := rep.Result; res != nil {
if res.Price != nil { r.price = alert.Money(*res.Price, res.Currency) }
r.seller = sellerText(res.Seller)
}
if rep.CartLink != "" { r.cartLink = rep.CartLink }
}
m.rows = m.ctl.Statuses()
if c.Decision.Alert == nil { return nil }
r.flash = m.now.Add(flashFor)
return tea.Raw("\a")
}
func statusOf(c CheckMsg) string {
rep := c.Result.Report
switch {
case rep == nil:
return statusError
case rep.Verdict == fetch.Challenge.String() || rep.Verdict == fetch.Blocked.String():
return statusBlocked
case c.Result.Err != nil || rep.Verdict == fetch.HTTPError.String():
return statusError
case c.Decision.Qualifies:
return statusAvailable
default:
return statusWatching
}
}
func sellerText(seller string) string {
switch seller {
case plugin.SellerFirstParty:
return "first party"
case plugin.SellerFulfilled:
return "fulfilled"
case plugin.SellerThirdParty:
return "third party"
default:
return ""
}
}
func (m *Model) key(msg tea.KeyPressMsg) tea.Cmd {
k := msg.String()
switch k {
case "q", "ctrl+c":
return tea.Quit
case "l", "tab":
m.logFocus = !m.logFocus
return nil
case "r":
return m.reload()
}
if m.logFocus {
if k == "esc" {
m.logFocus = false
return nil
}
var cmd tea.Cmd
m.log, cmd = m.log.Update(msg)
return cmd
}
switch k {
case "up", "k":
m.cursor--
case "down", "j":
m.cursor++
case "home", "g":
m.cursor = 0
case "end", "G":
m.cursor = len(m.rows) - 1
case "P":
m.pauseAll()
default:
return m.rowKey(k)
}
m.clampCursor()
return nil
}
// rowKey handles the keys that act on the selected row.
func (m *Model) rowKey(k string) tea.Cmd {
if m.cursor >= len(m.rows) { return nil }
row := m.rows[m.cursor]
switch k {
case "p":
m.ctl.Pause(row.Item, !row.Paused)
if row.Paused { m.setNote("resumed "+row.Item, false) } else { m.setNote("paused "+row.Item, false) }
m.rows = m.ctl.Statuses()
case "c":
m.ctl.CheckNow(row.Item)
m.setNote("checking "+row.Item+" as soon as the rate limits allow", false)
m.rows = m.ctl.Statuses()
case "o":
return open(row.FetchURL)
case "enter":
if r := m.results[row.URL]; r != nil && r.cartLink != "" { return open(r.cartLink) }
m.setNote("no cart link yet, opening the product page", false)
return open(row.FetchURL)
}
return nil
}
// pauseAll pauses every URL, or resumes them all if all are paused.
func (m *Model) pauseAll() {
pause := false
for _, row := range m.rows {
if !row.Paused { pause = true }
}
m.ctl.PauseAll(pause)
m.rows = m.ctl.Statuses()
if pause { m.setNote("paused everything", false) } else { m.setNote("resumed everything", false) }
}
func (m *Model) reload() tea.Cmd {
if m.reloading { return nil }
m.reloading = true
m.setNote("reloading "+m.path, false)
return func() tea.Msg {
summary, err := m.ctl.Reload()
return reloadMsg{summary: summary, err: err}
}
}
func reloadNote(summary []string) string {
if len(summary) == 1 { return "reloaded: " + summary[0] }
return fmt.Sprintf("reloaded: %d changes (see log)", len(summary))
}
// reloadError shows the first problem in the config. The log has them all.
func reloadError(err error) string {
var errs config.Errors
if errors.As(err, &errs) && len(errs) > 0 {
msg := "reload failed, config unchanged: line " + errs[0].Brief()
if len(errs) > 1 { msg += fmt.Sprintf(" (+%d more)", len(errs)-1) }
return msg
}
return "reload failed, config unchanged: " + err.Error()
}
func open(url string) tea.Cmd {
return func() tea.Msg { return openMsg{url: url, err: browser.OpenURL(url)} }
}
func (m *Model) setNote(note string, isError bool) {
m.note, m.noteError, m.noteTime = note, isError, time.Now()
}
func (m *Model) addLog(l LogLine) {
follow := m.log.AtBottom()
m.logs = append(m.logs, l)
if len(m.logs) > maxLines { m.logs = m.logs[len(m.logs)-maxLines:] }
m.log.SetContentLines(m.logLines())
if follow { m.log.GotoBottom() }
}
func (m *Model) clampCursor() {
m.cursor = max(0, min(m.cursor, len(m.rows)-1))
}
+311
View File
@@ -0,0 +1,311 @@
package tui
import (
"fmt"
"log/slog"
"strings"
"time"
tea "charm.land/bubbletea/v2"
"charm.land/lipgloss/v2"
"github.com/charmbracelet/x/ansi"
"golang.org/x/net/publicsuffix"
"git.security-command.org/Overlord/dibs/internal/watch"
)
// The colors are ANSI palette entries, so they follow the terminal's theme.
var (
bold = lipgloss.NewStyle().Bold(true)
faint = lipgloss.NewStyle().Faint(true)
green = lipgloss.NewStyle().Foreground(lipgloss.Color("10")).Bold(true)
yellow = lipgloss.NewStyle().Foreground(lipgloss.Color("11"))
red = lipgloss.NewStyle().Foreground(lipgloss.Color("9"))
blue = lipgloss.NewStyle().Foreground(lipgloss.Color("12"))
selected = lipgloss.NewStyle().Reverse(true)
flashing = lipgloss.NewStyle().Background(lipgloss.Color("10")).Foreground(lipgloss.Color("0")).Bold(true)
)
// fixedLines are the lines around the table body and the log: the header,
// the column titles, the log title, the status bar and the key help.
const fixedLines = 5
var columns = []struct {
title string
min, max int
} {
{"ITEM", 8, 32},
{"SHOP", 4, 12},
{"TLD", 3, 6},
{"STATUS", 9, 9},
{"PRICE", 5, 16},
{"SELLER", 6, 11},
{"LAST", 10, 10},
{"NEXT", 9, 9},
}
// layout sizes the table and the log pane to the window.
func (m *Model) layout() {
avail := max(m.height-fixedLines, 2)
body := min(len(m.rows), max(3, avail*55/100), avail-1)
body = max(body, 1)
m.log.SetWidth(m.width)
m.log.SetHeight(max(avail-body, 1))
if m.cursor < m.offset { m.offset = m.cursor }
if m.cursor >= m.offset+body { m.offset = m.cursor - body + 1 }
m.offset = max(0, min(m.offset, len(m.rows)-body))
}
func (m *Model) bodyHeight() int {
return max(m.height-fixedLines, 2) - m.log.Height()
}
func (m *Model) View() tea.View {
v := tea.NewView("")
v.AltScreen = true
v.WindowTitle = "dibs"
if n := m.count(statusAvailable); n > 0 { v.WindowTitle = fmt.Sprintf("dibs · %d AVAILABLE", n) }
if m.width == 0 { return v }
m.layout()
var b strings.Builder
b.WriteString(fit(bold.Render("dibs")+" "+faint.Render(m.path), m.width) + "\n")
b.WriteString(m.table())
b.WriteString(m.logTitle() + "\n")
b.WriteString(m.log.View() + "\n")
b.WriteString(m.statusBar() + "\n")
b.WriteString(fit(faint.Render(m.help()), m.width))
v.SetContent(b.String())
return v
}
func (m *Model) table() string {
cells := make([][]string, len(m.rows))
widths := make([]int, len(columns))
for i, c := range columns { widths[i] = max(c.min, len(c.title)) }
for i, row := range m.rows {
cells[i] = m.cells(row)
for j, c := range cells[i] { widths[j] = max(widths[j], min(ansi.StringWidth(c), columns[j].max)) }
}
// Columns only grow, so they do not shift every time a price or a time
// gets shorter.
if len(m.widths) == len(widths) {
for i := range widths { widths[i] = max(widths[i], m.widths[i]) }
}
m.widths = append(m.widths[:0], widths...)
// The ITEM column gives way first when the window is narrow.
total := 2
for _, w := range widths { total += w + 2 }
if over := total - m.width; over > 0 { widths[0] = max(columns[0].min, widths[0]-over) }
var b strings.Builder
titles := make([]string, len(columns))
for i, c := range columns { titles[i] = c.title }
b.WriteString(fit(faint.Render(" "+joinCells(titles, widths)), m.width) + "\n")
body := m.bodyHeight()
for i := m.offset; i < m.offset+body; i++ {
if i >= len(m.rows) {
b.WriteString("\n")
continue
}
b.WriteString(m.rowLine(i, cells[i], widths) + "\n")
}
return b.String()
}
func (m *Model) rowLine(i int, cells []string, widths []int) string {
r := m.results[m.rows[i].URL]
switch {
case r != nil && m.now.Before(r.flash) && m.now.UnixMilli()/tick.Milliseconds()%2 == 0:
return flashing.Render(padRight(" "+joinCells(cells, widths), m.width))
case i == m.cursor && !m.logFocus:
return selected.Render(padRight("> "+joinCells(cells, widths), m.width))
}
// Only the status cell is colored.
status := statusStyle(cells[3]).Render(padRight(cells[3], widths[3]))
line := " " + joinCells(cells[:3], widths[:3]) + " " + status + " " + joinCells(cells[4:], widths[4:])
return fit(line, m.width)
}
func (m *Model) cells(row watch.Status) []string {
r := m.results[row.URL]
if r == nil { r = &result{status: statusWatching} }
status := r.status
if row.Paused { status = statusPaused }
return []string{row.Item, row.Shop, tld(row.Host), status, orDash(r.price), orDash(r.seller), m.ago(row.Last), m.until(row)}
}
func statusStyle(status string) lipgloss.Style {
switch status {
case statusAvailable:
return green
case statusBlocked:
return yellow
case statusError:
return red
case statusPaused:
return faint
default:
return lipgloss.NewStyle()
}
}
func (m *Model) logTitle() string {
title := "── log "
if m.logFocus { return fit(bold.Render(title+"(scrolling) "+strings.Repeat("─", m.width)), m.width) }
return fit(faint.Render(title+strings.Repeat("─", m.width)), m.width)
}
func (m *Model) logLines() []string {
out := make([]string, len(m.logs))
for i, l := range m.logs {
level := fmt.Sprintf("%-5s", l.Level)
switch {
case l.Level >= slog.LevelError:
level = red.Render(level)
case l.Level >= slog.LevelWarn:
level = yellow.Render(level)
case l.Level >= slog.LevelInfo:
level = blue.Render(level)
default:
level = faint.Render(level)
}
msg := l.Msg
if msg == "ALERT" { msg = green.Render(msg) }
out[i] = faint.Render(l.Time.Format(time.TimeOnly)) + " " + level + " " + msg + " " + faint.Render(l.Attrs)
}
return out
}
func (m *Model) statusBar() string {
parts := []string{fmt.Sprintf("%d URLs", len(m.rows))}
for _, s := range []struct {
status string
style lipgloss.Style
} {
{statusAvailable, green},
{statusBlocked, yellow},
{statusError, red},
{statusPaused, faint},
} {
if n := m.count(s.status); n > 0 { parts = append(parts, s.style.Render(fmt.Sprintf("%d %s", n, s.status))) }
}
left := strings.Join(parts, faint.Render(" · "))
note := ""
if m.note != "" && time.Since(m.noteTime) < noteFor {
note = m.note
if m.noteError { note = red.Render(note) }
}
gap := m.width - ansi.StringWidth(left) - ansi.StringWidth(note)
if gap < 2 { return fit(left+" "+note, m.width) }
return left + strings.Repeat(" ", gap) + note
}
func (m *Model) help() string {
if m.logFocus { return "↑↓ pgup pgdn scroll · l/esc back to the table · r reload · q quit" }
return "↑↓ select · p pause · P pause all · c check now · o open page · enter cart · l log · r reload · q quit"
}
// count is the number of rows showing status.
func (m *Model) count(status string) int {
n := 0
for _, row := range m.rows {
if m.cells(row)[3] == status { n++ }
}
return n
}
func (m *Model) ago(t time.Time) string {
if t.IsZero() { return "—" }
return short(m.now.Sub(t)) + " ago"
}
func (m *Model) until(row watch.Status) string {
switch {
case row.Paused:
return "—"
case row.Checking:
return "checking"
}
d := row.Next.Sub(m.now)
if d <= 0 { return "due" }
return "in " + short(d)
}
// short formats d as "45s", "3m05s" or "1h20m".
func short(d time.Duration) string {
d = max(d, 0).Round(time.Second)
switch {
case d < time.Minute:
return fmt.Sprintf("%ds", int(d.Seconds()))
case d < time.Hour:
return fmt.Sprintf("%dm%02ds", int(d.Minutes()), int(d.Seconds())%60)
default:
return fmt.Sprintf("%dh%02dm", int(d.Hours()), int(d.Minutes())%60)
}
}
func tld(host string) string {
suffix, _ := publicsuffix.PublicSuffix(host)
return suffix
}
func orDash(s string) string {
if s == "" { return "—" }
return s
}
func joinCells(cells []string, widths []int) string {
var b strings.Builder
for i, c := range cells {
if i > 0 { b.WriteString(" ") }
b.WriteString(padRight(ansi.Truncate(c, widths[i], "…"), widths[i]))
}
return b.String()
}
func padRight(s string, w int) string {
return s + strings.Repeat(" ", max(0, w-ansi.StringWidth(s)))
}
// fit cuts s to the window width.
func fit(s string, w int) string {
return ansi.Truncate(s, w, "")
}
+377
View File
@@ -0,0 +1,377 @@
// 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,
last: s.limiter.LastCheck(fetchURL),
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:
}
}
+223
View File
@@ -0,0 +1,223 @@
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) }
}
+3 -3
View File
@@ -1,9 +1,9 @@
# Real Amazon pages the amazon plugin is tested on. `dibs fixtures` fetches # Real Amazon pages the amazon plugin is tested on. `dibs fixtures` fetches
# them into pages/ (not tracked), together with the report dibs made for # 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 # each. Pages change over time, so a case that stops showing what its note
# another product. # 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]] [[case]]
name = "out-of-stock-de" name = "out-of-stock-de"