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
+19
-9
@@ -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.
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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(": ")
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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, "")
|
||||
}
|
||||
+70
-11
@@ -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,
|
||||
|
||||
@@ -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) }
|
||||
}
|
||||
Reference in new issue
Block a user