diff --git a/cmd/dibs/notify.go b/cmd/dibs/notify.go index 4dc4c48..1b7f203 100644 --- a/cmd/dibs/notify.go +++ b/cmd/dibs/notify.go @@ -7,7 +7,6 @@ import ( "log/slog" "os" "os/signal" - "sync" "time" "git.security-command.org/Overlord/dibs/internal/alert" @@ -113,29 +112,4 @@ func sampleAlert(ctx context.Context, host *plugin.Host, item config.Item) (aler }, nil } -// fire logs an alert, rings the bell and sends the notifications in the -// background. sends tracks the sending so dibs can wait for it on exit. -func fire(logger *slog.Logger, n *notify.Notifier, sends *sync.WaitGroup, bell io.Writer, 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)) } - - logger.Info("ALERT", attrs...) - - if bell != nil { _, _ = io.WriteString(bell, "\a") } - - 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 { - logger.Warn("notification failed", "item", a.Item, "err", err) - return - } - - logger.Info("notified", "item", a.Item, "channels", n.Channels()) - }) -} - func userAgent() string { return "dibs/" + version } diff --git a/cmd/dibs/tui.go b/cmd/dibs/tui.go new file mode 100644 index 0000000..926d16f --- /dev/null +++ b/cmd/dibs/tui.go @@ -0,0 +1,48 @@ +package main + +import ( + "context" + "errors" + "io" + "log/slog" + "os/signal" + "syscall" + + tea "charm.land/bubbletea/v2" + + "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), 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 +} diff --git a/cmd/dibs/watch.go b/cmd/dibs/watch.go index 60e5ec5..a30723f 100644 --- a/cmd/dibs/watch.go +++ b/cmd/dibs/watch.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "io" "log/slog" "os" @@ -12,76 +13,238 @@ import ( "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 { - _, _ = io.WriteString(stderr, "dibs: the TUI is not implemented yet; run with --headless\n") - return 1 - } + 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() - e, err := openEnv(logger) + w, err := newWatcher(ctx, cfg, logger, slog.LevelInfo) if err != nil { return fail(stderr, "watch", err) } - host, err := newHost(cfg, logger) - if err != nil { return fail(stderr, "watch", err) } - defer host.Close() + ring := isTerminal(stderr) - sched, warnings, err := watch.New(ctx, cfg, host, e.client, e.limiter) - if err != nil { return fail(stderr, "watch", err) } - - for _, w := range warnings { logger.Warn(w) } - - rates := fx.New(e.store, e.limiter) - if needsRates(cfg) { rates.Warm() } - - alerts := alert.NewEngine(cfg.Notify.Cooldown.Duration, rates, e.store) - notifier := notify.New(cfg.Notify, userAgent()) - - var bell io.Writer - if isTerminal(stderr) { bell = stderr } - - statuses := sched.Statuses() - logger.Info("watching", "items", len(cfg.Items), "urls", len(statuses), "notify", notifier.Channels()) - - go sched.Run(ctx) - - var sends sync.WaitGroup - - for r := range sched.Results() { - logResult(logger, r) - e.save(logger) - - if r.Err != nil { continue } - - a, why, err := alerts.Consider(ctx, r.Item, r.Report, r.Time) - switch { - case err != nil: - logger.Warn("available, but the price cannot be checked", "item", r.Item.Name, "url", r.URL, "err", err) - case why != "": - logger.Info("available, not alerting", "item", r.Item.Name, "url", r.URL, "reason", why) - case a != nil: - fire(logger, notifier, &sends, bell, *a) - } - } + 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() - sends.Wait() + 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 { @@ -99,7 +262,9 @@ func isTerminal(w io.Writer) bool { return err == nil && info.Mode()&os.ModeCharDevice != 0 } -func logResult(logger *slog.Logger, r watch.Result) { +// 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()) } @@ -114,10 +279,12 @@ func logResult(logger *slog.Logger, r watch.Result) { } } - if r.Err != nil { - logger.Warn("check failed", append(attrs, "err", r.Err.Error())...) - return + 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...) } - - logger.Info("checked", attrs...) } diff --git a/go.mod b/go.mod index 4f27491..3646925 100644 --- a/go.mod +++ b/go.mod @@ -3,11 +3,17 @@ module git.security-command.org/Overlord/dibs go 1.26.0 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/andybalholm/cascadia v1.3.4 github.com/bogdanfinn/fhttp v0.6.9 github.com/bogdanfinn/tls-client v1.16.0 + 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/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c github.com/yuin/gopher-lua v1.1.2 golang.org/x/net v0.60.0 golang.org/x/sys v0.48.0 @@ -21,19 +27,31 @@ require ( github.com/bogdanfinn/quic-go-utls v1.0.10-utls // indirect github.com/bogdanfinn/utls v1.7.8-barnius // indirect github.com/bogdanfinn/websocket v1.5.6-barnius // indirect + github.com/charmbracelet/colorprofile v0.4.3 // 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/esiqveland/notify v0.13.3 // indirect - github.com/gen2brain/beeep v0.11.2 // 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/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/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/xo/terminfo v1.0.0 // indirect golang.org/x/crypto v0.57.0 // indirect + golang.org/x/sync v0.23.0 // indirect golang.org/x/text v0.42.0 // indirect ) diff --git a/go.sum b/go.sum index 5c99e7d..2cfa751 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,9 @@ +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= @@ -6,6 +12,8 @@ github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwTo 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/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/go.mod h1:NkYHl4Fey9oRRdbB1CoC6e84tuqQHiqrOcZpqFEkBxM= github.com/bdandy/go-socks4 v1.2.3 h1:Q6Y2heY1GRjCtHbmlKfnwrKVU/k81LS8mRGLRlmDlic= @@ -20,6 +28,24 @@ 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/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/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/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -37,14 +63,24 @@ github.com/jackmordaunt/icns/v3 v3.0.1 h1:xxot6aNuGrU+lNgxz5I5H0qSeCjNKp8uTXB1j8 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/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/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/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 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/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= @@ -61,6 +97,8 @@ github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af h1:6yITBqGTE2lEeTPG0 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/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/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA= @@ -69,9 +107,13 @@ go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= 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/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.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= 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-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/internal/alert/alert.go b/internal/alert/alert.go index 42cf882..c409180 100644 --- a/internal/alert/alert.go +++ b/internal/alert/alert.go @@ -111,15 +111,25 @@ func NewEngine(cooldown time.Duration, fx Converter, store Store) *Engine { return &Engine{cooldown: cooldown, fx: fx, store: store, sent: map[string]Sent{}} } -// Consider decides whether a checked page makes its item fire. It returns -// the alert, or why an available page does not fire. A page that is not -// available returns neither. 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) (*Alert, string, error) { - if rep == nil || rep.Result == nil || !rep.Result.Available { return nil, "", nil } +// 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 nil, why, err } + if a == nil { return Decision{Reason: why}, err } unlock := e.lock() defer unlock() @@ -131,7 +141,7 @@ func (e *Engine) Consider(ctx context.Context, item config.Item, rep *plugin.Rep switch { case !allowed: - return nil, "in cooldown until " + last.Time.Add(e.cooldown).Format(time.TimeOnly), nil + 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: @@ -140,7 +150,7 @@ func (e *Engine) Consider(ctx context.Context, item config.Item, rep *plugin.Rep e.save(item.Name, next) - return a, "", nil + return Decision{Alert: a, Qualifies: true}, nil } // sent is what the cooldown remembers of a. diff --git a/internal/alert/alert_test.go b/internal/alert/alert_test.go index cbac9f4..535b659 100644 --- a/internal/alert/alert_test.go +++ b/internal/alert/alert_test.go @@ -73,10 +73,12 @@ func TestCooldown(t *testing.T) { for _, st := range steps { if strings.HasSuffix(st.name, "new rate") { fx.rate = 1.30 } - a, why, err := e.Consider(ctx, it, st.report, start.Add(st.after)) + d, err := e.Consider(ctx, it, st.report, start.Add(st.after)) if err != nil { t.Fatalf("%s: %v", st.name, err) } - if fired := a != nil; fired != st.fires { t.Errorf("%s: fired = %v, want %v (%s)", st.name, fired, st.fires, why) } + 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 := "" @@ -121,7 +123,8 @@ func TestQualify(t *testing.T) { } for _, c := range cases { - a, why, err := NewEngine(time.Hour, c.fx, nil).Consider(ctx, c.item, c.report, now) + 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: diff --git a/internal/config/diff.go b/internal/config/diff.go new file mode 100644 index 0000000..e03246f --- /dev/null +++ b/internal/config/diff.go @@ -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 +} diff --git a/internal/config/validate.go b/internal/config/validate.go index fb3bcbd..9c0575f 100644 --- a/internal/config/validate.go +++ b/internal/config/validate.go @@ -55,11 +55,17 @@ type Error struct { } 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 - 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 != "" { b.WriteString(e.Key) b.WriteString(": ") diff --git a/internal/tui/logs.go b/internal/tui/logs.go new file mode 100644 index 0000000..c100e2f --- /dev/null +++ b/internal/tui/logs.go @@ -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) +} diff --git a/internal/tui/model.go b/internal/tui/model.go new file mode 100644 index 0000000..f0fdc8a --- /dev/null +++ b/internal/tui/model.go @@ -0,0 +1,358 @@ +// 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 + + 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.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.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)) +} diff --git a/internal/tui/view.go b/internal/tui/view.go new file mode 100644 index 0000000..b59b352 --- /dev/null +++ b/internal/tui/view.go @@ -0,0 +1,304 @@ +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", 4, 9}, + {"NEXT", 4, 10}, +} + +// 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)) } + } + + // 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, "") +} diff --git a/internal/watch/watch.go b/internal/watch/watch.go index f980394..e4dbd04 100644 --- a/internal/watch/watch.go +++ b/internal/watch/watch.go @@ -20,6 +20,10 @@ import ( // 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 { @@ -45,6 +49,7 @@ type Status struct { Item string Shop string URL string + FetchURL string Host string Last time.Time Next time.Time @@ -52,6 +57,8 @@ type Status struct { 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 @@ -59,11 +66,12 @@ type target struct { host string plugin *plugin.Plugin - // Guarded by Scheduler.mu. 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 @@ -91,6 +99,50 @@ func New(ctx context.Context, cfg *config.Config, host *plugin.Host, fetcher Fet 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{} @@ -116,18 +168,18 @@ func New(ctx context.Context, cfg *config.Config, host *plugin.Host, fetcher Fet u, err := url.Parse(fetchURL) if err != nil { return nil, nil, err } - s.targets = append(s.targets, &target{ + targets = append(targets, &target{ item: item, url: raw, fetchURL: fetchURL, host: strings.ToLower(u.Hostname()), plugin: p, - next: limiter.NextCheck(fetchURL, item.Interval.Duration), + next: s.limiter.NextCheck(fetchURL, item.Interval.Duration), }) } } - return s, warnings, nil + return targets, warnings, nil } // Results delivers every finished check. It is closed when Run returns. @@ -152,8 +204,7 @@ func (s *Scheduler) Run(ctx context.Context) { for _, t := range due { ch, ok := workers[t.host] if !ok { - // Room for every target, so handing work over never blocks. - ch = make(chan *target, len(s.targets)) + ch = make(chan *target, queue) workers[t.host] = ch wg.Add(1) @@ -203,23 +254,30 @@ func (s *Scheduler) due() []*target { 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, t.fetchURL) + 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, t.plugin, t.url, resp) } + if err == nil { report, err = plugin.Evaluate(ctx, p, rawURL, resp) } s.mu.Lock() t.last = s.clock.Now() - t.next = s.limiter.NextCheck(t.fetchURL, t.item.Interval.Duration) + t.next = s.limiter.NextCheck(fetchURL, t.item.Interval.Duration) t.inFlight = false - next := t.next + last, next := t.last, t.next + removed := t.removed s.mu.Unlock() - r := Result{Item: t.item, URL: t.url, Time: t.last, Report: report, Err: err, Backoff: backoff, Next: next} + if removed { return } + + r := Result{Item: item, URL: rawURL, Time: last, Report: report, Err: err, Backoff: backoff, Next: next} select { case s.results <- r: @@ -282,6 +340,7 @@ func (s *Scheduler) Statuses() []Status { Item: t.item.Name, Shop: t.item.Shop, URL: t.url, + FetchURL: t.fetchURL, Host: t.host, Last: t.last, Next: t.next, diff --git a/internal/watch/watch_test.go b/internal/watch/watch_test.go index 718aff0..a3683e4 100644 --- a/internal/watch/watch_test.go +++ b/internal/watch/watch_test.go @@ -179,3 +179,45 @@ func TestDuplicateURLs(t *testing.T) { 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) } +}