Add config loading and validation.
Strict dibs.toml decoding with line-numbered errors, defaults, and a [sandbox] section for the Lua call limits. Adds `dibs config validate` and `dibs version`.
This commit is contained in:
1 parent
59e35c01f7
commit
463c013056
7 files changed
+1210
No files matched your search
@@ -0,0 +1,203 @@
|
||||
// Package config loads and validates dibs.toml.
|
||||
package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
)
|
||||
|
||||
// MinInterval is the shortest allowed polling interval per URL.
|
||||
const MinInterval = 60 * time.Second
|
||||
|
||||
const (
|
||||
SellerFirstParty = "first_party"
|
||||
SellerAny = "any"
|
||||
|
||||
CartModeDeeplink = "deeplink"
|
||||
CartModeSession = "session"
|
||||
|
||||
FormatDiscord = "discord"
|
||||
FormatNtfy = "ntfy"
|
||||
FormatJSON = "json"
|
||||
)
|
||||
|
||||
// Defaults for keys that may be omitted.
|
||||
const (
|
||||
DefaultInterval = 3 * time.Minute
|
||||
DefaultCooldown = 30 * time.Minute
|
||||
DefaultSandboxTimeout = 2 * time.Second
|
||||
DefaultSessionTimeout = 5 * time.Minute
|
||||
DefaultMemoryMB = 64
|
||||
DefaultCallStack = 200
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Items []Item `toml:"item"`
|
||||
Accounts map[string]Account `toml:"accounts"`
|
||||
Notify Notify `toml:"notify"`
|
||||
// Plugins maps a plugin name to its file. After Load the paths are absolute.
|
||||
Plugins map[string]string `toml:"plugins"`
|
||||
Sandbox Sandbox `toml:"sandbox"`
|
||||
|
||||
// Path is the absolute path of the loaded file.
|
||||
Path string `toml:"-"`
|
||||
}
|
||||
|
||||
type Item struct {
|
||||
Name string `toml:"name"`
|
||||
Shop string `toml:"shop"`
|
||||
URLs []string `toml:"urls"`
|
||||
MaxPrice *float64 `toml:"max_price"`
|
||||
Currency string `toml:"currency"`
|
||||
// FXMargin is added to a converted price before it is compared with
|
||||
// MaxPrice, to cover import fees and card exchange rates. 0.1 means 10%.
|
||||
FXMargin float64 `toml:"fx_margin"`
|
||||
Seller string `toml:"seller"`
|
||||
Interval Duration `toml:"interval"`
|
||||
}
|
||||
|
||||
type Account struct {
|
||||
Username string `toml:"username"`
|
||||
PasswordEnv string `toml:"password_env"`
|
||||
CartMode string `toml:"cart_mode"`
|
||||
LoginURL string `toml:"login_url"`
|
||||
CartURL string `toml:"cart_url"`
|
||||
TwoFA bool `toml:"twofa"`
|
||||
}
|
||||
|
||||
type Notify struct {
|
||||
Webhooks []Webhook `toml:"webhooks"`
|
||||
Desktop bool `toml:"desktop"`
|
||||
Cooldown Duration `toml:"cooldown"`
|
||||
}
|
||||
|
||||
type Webhook struct {
|
||||
URL string `toml:"url"`
|
||||
Format string `toml:"format"`
|
||||
}
|
||||
|
||||
// Sandbox holds the limits for Lua plugin calls.
|
||||
type Sandbox struct {
|
||||
// Timeout applies to matches, parse and cart_link.
|
||||
Timeout Duration `toml:"timeout"`
|
||||
// SessionTimeout applies to login and add_to_cart, which wait on the
|
||||
// network and on the user typing 2FA codes.
|
||||
SessionTimeout Duration `toml:"session_timeout"`
|
||||
// MemoryMB is the approximate heap growth one call may cause before it is
|
||||
// cancelled.
|
||||
MemoryMB int `toml:"memory_mb"`
|
||||
// CallStack is the maximum Lua call depth.
|
||||
CallStack int `toml:"call_stack"`
|
||||
}
|
||||
|
||||
// Duration is a time.Duration written as a string such as "3m" or "90s".
|
||||
type Duration struct {
|
||||
time.Duration
|
||||
set bool
|
||||
}
|
||||
|
||||
func (d *Duration) UnmarshalText(b []byte) error {
|
||||
v, err := time.ParseDuration(string(b))
|
||||
if err != nil {
|
||||
return fmt.Errorf(`invalid duration %q: use a number with a unit, such as "90s", "3m" or "1h30m"`, b)
|
||||
}
|
||||
|
||||
d.Duration, d.set = v, true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d Duration) MarshalText() ([]byte, error) {
|
||||
return []byte(d.String()), nil
|
||||
}
|
||||
|
||||
// IsSet reports whether the value came from the config file.
|
||||
func (d Duration) IsSet() bool { return d.set }
|
||||
|
||||
// Options control validation that depends on the environment.
|
||||
type Options struct {
|
||||
// Builtins are the names of the embedded plugins.
|
||||
Builtins []string
|
||||
// LookupEnv resolves password_env. Defaults to os.LookupEnv.
|
||||
LookupEnv func(string) (string, bool)
|
||||
}
|
||||
|
||||
// DefaultPath returns dibs.toml in the user config dir.
|
||||
func DefaultPath() (string, error) {
|
||||
dir, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(dir, "dibs", "dibs.toml"), nil
|
||||
}
|
||||
|
||||
// Load reads, decodes and validates the config at path. All problems found
|
||||
// are returned together as Errors.
|
||||
func Load(path string, opts Options) (*Config, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
abs, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if opts.LookupEnv == nil {
|
||||
opts.LookupEnv = os.LookupEnv
|
||||
}
|
||||
|
||||
cfg := &Config{
|
||||
Path: abs,
|
||||
Notify: Notify{
|
||||
Desktop: true,
|
||||
Cooldown: Duration{Duration: DefaultCooldown},
|
||||
},
|
||||
Sandbox: Sandbox{
|
||||
Timeout: Duration{Duration: DefaultSandboxTimeout},
|
||||
SessionTimeout: Duration{Duration: DefaultSessionTimeout},
|
||||
MemoryMB: DefaultMemoryMB,
|
||||
CallStack: DefaultCallStack,
|
||||
},
|
||||
}
|
||||
|
||||
v := &validator{file: path, pos: indexPositions(data)}
|
||||
|
||||
dec := toml.NewDecoder(bytes.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
err = dec.Decode(cfg)
|
||||
|
||||
var strict *toml.StrictMissingError
|
||||
var decErr *toml.DecodeError
|
||||
|
||||
switch {
|
||||
case err == nil:
|
||||
case errors.As(err, &strict):
|
||||
// The rest of the document was decoded, so keep validating it.
|
||||
for _, e := range strict.Errors {
|
||||
msg := "unknown key"
|
||||
if k := e.Key(); len(k) > 0 && k[len(k)-1] == "quantity" {
|
||||
msg = "unknown key: quantity is always 1 and cannot be configured"
|
||||
}
|
||||
v.decodeError(&e, msg)
|
||||
}
|
||||
case errors.As(err, &decErr):
|
||||
v.decodeError(decErr, "")
|
||||
return nil, v.errs
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
|
||||
v.validate(cfg, opts)
|
||||
if len(v.errs) > 0 {
|
||||
return nil, v.errs
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
Reference in new issue
Block a user