Add scheduler, rate limiting and headless mode.
Hard-coded 60s URL and 10s host floors with jitter and per-host backoff, shared between dibs processes through a locked state file. The scheduler shuffles due URLs each round and runs one worker per host; 'dibs --headless' watches and logs JSON.
This commit is contained in:
1 parent
bb010356a0
commit
2175c0e5aa
30 files changed
+1434
-126
No files matched your search
+3
-3
@@ -48,10 +48,10 @@ func runCheck(args []string, stdout, stderr io.Writer) int {
|
||||
fetchURL, err := p.Normalize(ctx, url)
|
||||
if err != nil { return fail(stderr, "check", err) }
|
||||
|
||||
client, err := fetch.New(fetch.Options{})
|
||||
e, err := openEnv(logger)
|
||||
if err != nil { return fail(stderr, "check", err) }
|
||||
|
||||
resp, err := client.Get(ctx, fetchURL)
|
||||
resp, err := e.fetch(ctx, fetchURL, logger)
|
||||
if err != nil { return fail(stderr, "check", err) }
|
||||
|
||||
report, err := plugin.Evaluate(ctx, p, url, resp)
|
||||
@@ -62,7 +62,7 @@ func runCheck(args []string, stdout, stderr io.Writer) int {
|
||||
}
|
||||
|
||||
// runPlugin implements `dibs plugin test [--status CODE] <file.lua>
|
||||
// <fixture.html> [url]`: run a plugin on a saved page.
|
||||
// <fixture.html> [url]`: it runs a plugin on a saved page.
|
||||
func runPlugin(args []string, stdout, stderr io.Writer) int {
|
||||
if len(args) == 0 || args[0] != "test" {
|
||||
_, _ = fmt.Fprintf(stderr, "dibs plugin: expected \"test\"\n\n%s", usage)
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||
"git.security-command.org/Overlord/dibs/internal/ratelimit"
|
||||
"git.security-command.org/Overlord/dibs/internal/state"
|
||||
"git.security-command.org/Overlord/dibs/internal/watch"
|
||||
)
|
||||
|
||||
// env is what every command that talks to shops shares with every other
|
||||
// dibs process: the state file behind the rate limits, and the cookies.
|
||||
type env struct {
|
||||
dir string
|
||||
store *state.Store
|
||||
limiter *ratelimit.Limiter
|
||||
jar *fetch.Jar
|
||||
client *fetch.Client
|
||||
}
|
||||
|
||||
func openEnv(logger *slog.Logger) (*env, error) {
|
||||
dir, err := state.Dir()
|
||||
if err != nil { return nil, fmt.Errorf("no config dir for the state file: %w", err) }
|
||||
|
||||
store := state.Open(dir)
|
||||
limiter := ratelimit.New(store)
|
||||
|
||||
jar := fetch.NewJar()
|
||||
if err := jar.Load(filepath.Join(dir, "cookies.json")); err != nil { logger.Warn("ignoring saved cookies", "err", err) }
|
||||
|
||||
client, err := fetch.New(fetch.Options{Limiter: limiter, Jar: jar})
|
||||
if err != nil { return nil, err }
|
||||
|
||||
return &env{dir: dir, store: store, limiter: limiter, jar: jar, client: client}, nil
|
||||
}
|
||||
|
||||
// save writes the cookies, and reports trouble with the state file.
|
||||
func (e *env) save(logger *slog.Logger) {
|
||||
if err := e.jar.Save(filepath.Join(e.dir, "cookies.json")); err != nil { logger.Warn("saving cookies failed", "err", err) }
|
||||
if err := e.store.Err(); err != nil { logger.Warn("state file unusable, rate limits only hold within this process", "err", err) }
|
||||
}
|
||||
|
||||
// explainWait says why the next check of fetchURL will take a while, if it
|
||||
// will: it was checked less than a minute ago, by this or another dibs
|
||||
// process, or its host is busy or backed off.
|
||||
func (e *env) explainWait(fetchURL string, logger *slog.Logger) {
|
||||
if wait := time.Until(e.limiter.URLReady(fetchURL)); wait > time.Second {
|
||||
logger.Info("URL was checked recently, waiting", "url", fetchURL, "wait", wait.Round(time.Second))
|
||||
return
|
||||
}
|
||||
|
||||
u, err := url.Parse(fetchURL)
|
||||
if err != nil { return }
|
||||
|
||||
if wait := e.limiter.Delay(u.Hostname()); wait > time.Second {
|
||||
logger.Info("waiting for the host's rate limit", "host", u.Hostname(), "wait", wait.Round(time.Second))
|
||||
}
|
||||
}
|
||||
|
||||
// fetch makes a single check of fetchURL that counts like a scheduled one:
|
||||
// the client waits for its turn, and the outcome is recorded for every dibs
|
||||
// process.
|
||||
func (e *env) fetch(ctx context.Context, fetchURL string, logger *slog.Logger) (*fetch.Response, error) {
|
||||
e.explainWait(fetchURL, logger)
|
||||
|
||||
resp, err := e.client.Get(ctx, fetchURL)
|
||||
if ctx.Err() == nil {
|
||||
if u, perr := url.Parse(fetchURL); perr == nil {
|
||||
if d := watch.RecordOutcome(e.limiter, u.Hostname(), resp, err); d > 0 { logger.Warn("host backed off", "host", u.Hostname(), "for", d.Round(time.Second)) }
|
||||
}
|
||||
|
||||
e.save(logger)
|
||||
}
|
||||
|
||||
return resp, err
|
||||
}
|
||||
+10
-27
@@ -5,21 +5,15 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"time"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||
"git.security-command.org/Overlord/dibs/internal/fixtures"
|
||||
"git.security-command.org/Overlord/dibs/internal/plugin"
|
||||
)
|
||||
|
||||
// fixtureSpacing is the pause between two requests to the same host.
|
||||
const fixtureSpacing = 12 * time.Second
|
||||
|
||||
// runFixtures implements `dibs fixtures [--dir DIR] [--only NAME]`: fetch the
|
||||
// pages listed in DIR/<shop>/cases.toml for the plugin tests.
|
||||
// runFixtures implements `dibs fixtures [--dir DIR] [--only NAME]`: it fetches
|
||||
// the pages listed in DIR/<shop>/cases.toml for the plugin tests.
|
||||
func runFixtures(args []string, stdout, stderr io.Writer) int {
|
||||
flags, configPath := newFlagSet("dibs fixtures", stderr)
|
||||
dir := flags.String("dir", "testdata", "directory with <shop>/cases.toml files")
|
||||
@@ -42,15 +36,16 @@ func runFixtures(args []string, stdout, stderr io.Writer) int {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
defer stop()
|
||||
|
||||
host, err := newHost(cfg, slog.New(slog.NewTextHandler(stderr, nil)))
|
||||
logger := slog.New(slog.NewTextHandler(stderr, nil))
|
||||
|
||||
host, err := newHost(cfg, logger)
|
||||
if err != nil { return fail(stderr, "fixtures", err) }
|
||||
defer host.Close()
|
||||
|
||||
client, err := fetch.New(fetch.Options{})
|
||||
e, err := openEnv(logger)
|
||||
if err != nil { return fail(stderr, "fixtures", err) }
|
||||
|
||||
lastRequest := map[string]time.Time{}
|
||||
failed := 0
|
||||
failed := 0
|
||||
|
||||
for _, suite := range suites {
|
||||
p, ok := host.Plugin(suite.Shop)
|
||||
@@ -62,7 +57,7 @@ func runFixtures(args []string, stdout, stderr io.Writer) int {
|
||||
for _, c := range suite.Cases {
|
||||
if *only != "" && c.Name != *only { continue }
|
||||
|
||||
if err := fetchFixture(ctx, client, p, suite, c, lastRequest, stdout); err != nil {
|
||||
if err := fetchFixture(ctx, e, p, suite, c, logger, stdout); err != nil {
|
||||
if ctx.Err() != nil { return fail(stderr, "fixtures", ctx.Err()) }
|
||||
|
||||
_, _ = fmt.Fprintf(stderr, "dibs fixtures: %s: %v\n", c.Name, err)
|
||||
@@ -76,23 +71,11 @@ func runFixtures(args []string, stdout, stderr io.Writer) int {
|
||||
return 0
|
||||
}
|
||||
|
||||
func fetchFixture(ctx context.Context, client *fetch.Client, p *plugin.Plugin, suite fixtures.Suite, c fixtures.Case, lastRequest map[string]time.Time, stdout io.Writer) error {
|
||||
func fetchFixture(ctx context.Context, e *env, p *plugin.Plugin, suite fixtures.Suite, c fixtures.Case, logger *slog.Logger, stdout io.Writer) error {
|
||||
fetchURL, err := p.Normalize(ctx, c.URL)
|
||||
if err != nil { return err }
|
||||
|
||||
u, err := url.Parse(fetchURL)
|
||||
if err != nil { return err }
|
||||
|
||||
if wait := time.Until(lastRequest[u.Host].Add(fixtureSpacing)); wait > 0 {
|
||||
select {
|
||||
case <-time.After(wait):
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
lastRequest[u.Host] = time.Now()
|
||||
|
||||
resp, err := client.Get(ctx, fetchURL)
|
||||
resp, err := e.fetch(ctx, fetchURL, logger)
|
||||
if err != nil { return err }
|
||||
|
||||
report, err := plugin.Evaluate(ctx, p, c.URL, resp)
|
||||
|
||||
+4
-4
@@ -52,7 +52,7 @@ func run(args []string, stdout, stderr io.Writer) int {
|
||||
}
|
||||
|
||||
flags, configPath := newFlagSet("dibs", stderr)
|
||||
flags.Bool("headless", false, "run without the TUI, log to stdout")
|
||||
headless := flags.Bool("headless", false, "run without the TUI, log JSON to stdout")
|
||||
|
||||
if err := flags.Parse(args); err != nil { return 2 }
|
||||
|
||||
@@ -61,10 +61,10 @@ func run(args []string, stdout, stderr io.Writer) int {
|
||||
return 2
|
||||
}
|
||||
|
||||
if _, ok := loadConfig(*configPath, stderr); !ok { return 1 }
|
||||
cfg, ok := loadConfig(*configPath, stderr)
|
||||
if !ok { return 1 }
|
||||
|
||||
_, _ = fmt.Fprintln(stderr, "dibs: watching is not implemented yet")
|
||||
return 1
|
||||
return runWatch(cfg, *headless, stdout, stderr)
|
||||
}
|
||||
|
||||
func runConfig(args []string, stdout, stderr io.Writer) int {
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/config"
|
||||
"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
|
||||
}
|
||||
|
||||
logger := slog.New(slog.NewJSONHandler(stdout, nil))
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
e, err := openEnv(logger)
|
||||
if err != nil { return fail(stderr, "watch", err) }
|
||||
|
||||
host, err := newHost(cfg, logger)
|
||||
if err != nil { return fail(stderr, "watch", err) }
|
||||
defer host.Close()
|
||||
|
||||
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) }
|
||||
|
||||
statuses := sched.Statuses()
|
||||
logger.Info("watching", "items", len(cfg.Items), "urls", len(statuses))
|
||||
|
||||
go sched.Run(ctx)
|
||||
|
||||
for r := range sched.Results() {
|
||||
logResult(logger, r)
|
||||
e.save(logger)
|
||||
}
|
||||
|
||||
logger.Info("stopped")
|
||||
return 0
|
||||
}
|
||||
|
||||
func logResult(logger *slog.Logger, 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) }
|
||||
}
|
||||
}
|
||||
|
||||
if r.Err != nil {
|
||||
logger.Warn("check failed", append(attrs, "err", r.Err.Error())...)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Info("checked", attrs...)
|
||||
}
|
||||
Reference in new issue
Block a user