Files
dibs/internal/plugin/host.go
T
Overlord 2175c0e5aa 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.
2026-10-14 09:04:15 +02:00

162 lines
3.8 KiB
Go

package plugin
import (
"context"
"embed"
"errors"
"fmt"
"io/fs"
"log/slog"
"maps"
"os"
"slices"
"strings"
"git.security-command.org/Overlord/dibs/internal/fetch"
)
//go:embed builtin/*.lua
var builtinFS embed.FS
// ErrNoPlugin is returned when no plugin matches a URL.
var ErrNoPlugin = errors.New("no plugin matches the URL")
func Builtins() []string {
files, _ := fs.Glob(builtinFS, "builtin/*.lua")
names := make([]string, len(files))
for i, f := range files { names[i] = strings.TrimSuffix(strings.TrimPrefix(f, "builtin/"), ".lua") }
return names
}
func BuiltinSource(name string) ([]byte, error) {
return builtinFS.ReadFile("builtin/" + name + ".lua")
}
type Host struct {
plugins map[string]*Plugin
// order is the order ForURL tries plugins in: user plugins first, so
// they win over built-ins they don't replace.
order []string
}
// NewHost loads the built-in plugins and the user's (name -> file). A user
// plugin replaces a built-in one of the same name.
func NewHost(user map[string]string, limits Limits, logger *slog.Logger) (*Host, error) {
h := &Host{plugins: map[string]*Plugin{}}
var errs []error
for _, name := range slices.Sorted(maps.Keys(user)) {
code, err := os.ReadFile(user[name])
if err != nil {
errs = append(errs, fmt.Errorf("plugin %s: %w", name, err))
continue
}
p, err := Load(name, user[name], code, limits, logger)
if err != nil {
errs = append(errs, err)
continue
}
h.plugins[name] = p
h.order = append(h.order, name)
}
for _, name := range Builtins() {
if _, replaced := user[name]; replaced { continue }
code, err := BuiltinSource(name)
if err == nil {
var p *Plugin
if p, err = Load(name, "built-in", code, limits, logger); err == nil {
h.plugins[name] = p
h.order = append(h.order, name)
continue
}
}
errs = append(errs, err)
}
if len(errs) > 0 {
h.Close()
return nil, errors.Join(errs...)
}
return h, nil
}
func (h *Host) Plugin(name string) (*Plugin, bool) {
p, ok := h.plugins[name]
return p, ok
}
// ForURL returns the first plugin whose matches(url) is true.
func (h *Host) ForURL(ctx context.Context, url string) (*Plugin, error) {
for _, name := range h.order {
p := h.plugins[name]
ok, err := p.Matches(ctx, url)
if err != nil { return nil, err }
if ok { return p, nil }
}
return nil, ErrNoPlugin
}
func (h *Host) Close() {
for _, p := range h.plugins { p.Close() }
}
// Report is the outcome of checking one URL, as `dibs check` prints it.
type Report struct {
URL string `json:"url"`
FetchURL string `json:"fetch_url"`
FinalURL string `json:"final_url"`
Shop string `json:"shop"`
Status int `json:"status"`
Verdict string `json:"verdict"`
Challenge string `json:"challenge,omitempty"`
Result *Result `json:"result,omitempty"`
CartLink string `json:"cart_link,omitempty"`
ElapsedMS int64 `json:"elapsed_ms"`
}
// Evaluate turns a fetched page into a Report. Only pages with the OK
// verdict are parsed. A NotFound page is reported as unavailable without
// asking the plugin, and bot checks and errors have no result.
func Evaluate(ctx context.Context, p *Plugin, rawURL string, resp *fetch.Response) (*Report, error) {
r := &Report{
URL: rawURL,
FetchURL: resp.URL,
FinalURL: resp.FinalURL,
Shop: p.Name,
Status: resp.Status,
Verdict: resp.Verdict.String(),
Challenge: resp.Challenge,
ElapsedMS: resp.Elapsed.Milliseconds(),
}
switch resp.Verdict {
case fetch.OK:
res, err := p.Parse(ctx, resp.Body, resp.URL)
if err != nil { return r, err }
r.Result = res
link, err := p.CartLink(ctx, resp.URL, res.ID)
if err != nil { return r, err }
r.CartLink = link
case fetch.NotFound:
r.Result = &Result{Seller: SellerUnknown}
default:
// Challenge, Blocked or HTTPError: nothing to read.
}
return r, nil
}