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>
This commit is contained in:
1 parent
8f0eda5d4d
commit
a19e6fa711
14 files changed
+1359
-105
No files matched your search
@@ -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 }
|
||||
@@ -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
|
||||
}
|
||||
+219
-52
@@ -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...)
|
||||
}
|
||||
Reference in new issue
Block a user