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

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

291 lines
8.1 KiB
Go

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...)
}
}