- Add RawRule struct with Port *uint16, Protocol, Class fields - Add LoadResult struct with FreqCfgs, UserRules, ConfigPath fields - Change Load() signature to return LoadResult instead of bare map - Add validateRules: checks protocol required, class required, valid protocols - Add convertRules: converts RawRule slices to classify.Rule slices - Add autoAssignFreq: FNV-32a deterministic Hz in [1200-2350] range - Add addAutoFreqEntries: creates FreqConfig for new class names, skips built-ins - Reorder ops: addAutoFreqEntries before merge so sounds overrides apply to user classes - Update main.go call site to use LoadResult.FreqCfgs - Update all 8 existing tests to use LoadResult return type - Add 13 new tests covering rule parsing, validation, auto-freq, and LoadResult
277 lines
9.2 KiB
Go
277 lines
9.2 KiB
Go
// Package config loads, validates, and merges a TOML override file over the
|
|
// default synth.ClassFreqConfigs map. The single public entry point is Load.
|
|
package config
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"hash/fnv"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/BurntSushi/toml"
|
|
|
|
"github.com/netsynth/netsynth/classify"
|
|
"github.com/netsynth/netsynth/synth"
|
|
)
|
|
|
|
// SoundOverride holds optional per-class sound parameters decoded from TOML.
|
|
// Pointer fields: nil = not set by user (keep default), non-nil = user override.
|
|
type SoundOverride struct {
|
|
Frequency *float64 `toml:"frequency"`
|
|
Waveform *string `toml:"waveform"`
|
|
}
|
|
|
|
// RawRule holds a user-defined classification rule as decoded from TOML.
|
|
// Port is a pointer so we can distinguish "not set" (nil, matches any port) from port=0.
|
|
type RawRule struct {
|
|
Port *uint16 `toml:"port"`
|
|
Protocol string `toml:"protocol"`
|
|
Class string `toml:"class"`
|
|
}
|
|
|
|
// rawConfig is the top-level TOML decode target.
|
|
type rawConfig struct {
|
|
Sounds map[string]SoundOverride `toml:"sounds"`
|
|
Rules []RawRule `toml:"rules"`
|
|
}
|
|
|
|
// LoadResult is the return type from Load(). It carries the merged FreqConfig map,
|
|
// the user-defined classification rules (to be prepended before DefaultRules by the caller),
|
|
// and the resolved config file path (empty string if no config was found).
|
|
type LoadResult struct {
|
|
FreqCfgs map[classify.TrafficClass]synth.FreqConfig
|
|
UserRules []classify.Rule
|
|
ConfigPath string
|
|
}
|
|
|
|
// validWaveforms maps TOML waveform strings to WaveformType constants.
|
|
var validWaveforms = map[string]synth.WaveformType{
|
|
"sine": synth.WaveformSine,
|
|
"square": synth.WaveformSquare,
|
|
"sawtooth": synth.WaveformSawtooth,
|
|
"triangle": synth.WaveformTriangle,
|
|
}
|
|
|
|
// Load finds, parses, validates, and merges a TOML config file.
|
|
//
|
|
// configPath is the --config flag value; empty string triggers auto-discovery.
|
|
// Returns a LoadResult with the merged FreqConfig map, user-defined rules, and resolved path.
|
|
// Returns an error on: explicit file not found, parse errors, unknown keys,
|
|
// type mismatches, invalid waveform values, or invalid rule definitions.
|
|
// Returns no error (uses defaults) when no config is found during auto-discovery.
|
|
func Load(configPath string) (LoadResult, error) {
|
|
path, explicit, err := resolvePath(configPath)
|
|
if err != nil {
|
|
return LoadResult{}, err
|
|
}
|
|
if path == "" {
|
|
// No config found during auto-discovery — use defaults silently (CFG-02)
|
|
return LoadResult{FreqCfgs: copyDefaults(), UserRules: []classify.Rule{}, ConfigPath: ""}, nil
|
|
}
|
|
|
|
raw, err := parseFile(path)
|
|
if err != nil {
|
|
if explicit && errors.Is(err, fs.ErrNotExist) {
|
|
return LoadResult{}, fmt.Errorf("config file not found: %s", configPath)
|
|
}
|
|
return LoadResult{}, err
|
|
}
|
|
|
|
if err := validate(raw); err != nil {
|
|
return LoadResult{}, err
|
|
}
|
|
|
|
userRules := convertRules(raw.Rules)
|
|
freqCfgs := copyDefaults()
|
|
// Add auto-freq entries BEFORE merge so that [sounds.X] overrides for user classes apply.
|
|
addAutoFreqEntries(freqCfgs, userRules)
|
|
merge(freqCfgs, raw.Sounds)
|
|
|
|
return LoadResult{
|
|
FreqCfgs: freqCfgs,
|
|
UserRules: userRules,
|
|
ConfigPath: path,
|
|
}, nil
|
|
}
|
|
|
|
// resolvePath resolves the config path from an explicit flag value or auto-discovery.
|
|
// Returns (path, explicit, error) where explicit=true means the user specified a path.
|
|
func resolvePath(configPath string) (string, bool, error) {
|
|
if configPath != "" {
|
|
return configPath, true, nil
|
|
}
|
|
return discoverPath(), false, nil
|
|
}
|
|
|
|
// discoverPath probes the standard discovery locations in precedence order.
|
|
// Returns the first existing config path, or "" if none found.
|
|
// Discovery order: ./netsynth.toml > ~/.config/netsynth/config.toml
|
|
func discoverPath() string {
|
|
// 1. Working directory
|
|
if _, err := os.Stat("netsynth.toml"); err == nil {
|
|
return "netsynth.toml"
|
|
}
|
|
// 2. XDG config dir (~/.config/netsynth/config.toml or $XDG_CONFIG_HOME/netsynth/config.toml)
|
|
dir, err := os.UserConfigDir()
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
p := filepath.Join(dir, "netsynth", "config.toml")
|
|
if _, err := os.Stat(p); err == nil {
|
|
return p
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// parseFile decodes the TOML file at path and checks for unknown keys via Undecoded().
|
|
// Returns fs.ErrNotExist-wrapped error when the file does not exist.
|
|
func parseFile(path string) (rawConfig, error) {
|
|
var raw rawConfig
|
|
md, err := toml.DecodeFile(path, &raw)
|
|
if err != nil {
|
|
// Preserve the fs.ErrNotExist sentinel so Load can distinguish explicit vs discovered.
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return raw, err
|
|
}
|
|
return raw, fmt.Errorf("config parse error: %w", err)
|
|
}
|
|
// Detect field-level typos within [sounds.<class>] blocks (CFG-05).
|
|
// Note: class-name typos in [sounds.<name>] are NOT caught here because all
|
|
// map keys are valid decode targets. Class validation happens in merge (D-09).
|
|
if undecoded := md.Undecoded(); len(undecoded) > 0 {
|
|
keyPath := strings.Join(undecoded[0], ".")
|
|
return raw, fmt.Errorf("config: unknown key %q — check spelling", keyPath)
|
|
}
|
|
return raw, nil
|
|
}
|
|
|
|
// validate checks waveform strings and rules before merge so we fail fast at startup (D-11).
|
|
func validate(raw rawConfig) error {
|
|
for _, override := range raw.Sounds {
|
|
if override.Waveform != nil {
|
|
if _, err := parseWaveform(*override.Waveform); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return validateRules(raw.Rules)
|
|
}
|
|
|
|
// validateRules checks that each rule has a valid protocol and a non-empty class.
|
|
func validateRules(rules []RawRule) error {
|
|
validProtocols := map[string]bool{"tcp": true, "udp": true, "icmp": true}
|
|
for i, r := range rules {
|
|
if r.Protocol == "" {
|
|
return fmt.Errorf("config: rules[%d]: protocol is required", i)
|
|
}
|
|
if !validProtocols[r.Protocol] {
|
|
return fmt.Errorf("config: rules[%d]: invalid protocol %q -- valid: tcp, udp, icmp", i, r.Protocol)
|
|
}
|
|
if r.Class == "" {
|
|
return fmt.Errorf("config: rules[%d]: class is required", i)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// convertRules converts a slice of RawRule (from TOML) into classify.Rule slice.
|
|
func convertRules(raw []RawRule) []classify.Rule {
|
|
result := make([]classify.Rule, len(raw))
|
|
for i, r := range raw {
|
|
var port uint16
|
|
if r.Port != nil {
|
|
port = *r.Port
|
|
}
|
|
result[i] = classify.Rule{
|
|
Protocol: r.Protocol,
|
|
DstPort: port,
|
|
Class: classify.TrafficClass(r.Class),
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// autoAssignFreq computes a deterministic frequency in [1200, 2350] Hz for a class name
|
|
// using FNV-32a hashing. Same input always produces the same output.
|
|
func autoAssignFreq(className string) float64 {
|
|
h := fnv.New32a()
|
|
h.Write([]byte(className))
|
|
const (
|
|
baseHz = 1200.0
|
|
stepHz = 50.0
|
|
numSteps = uint32(24)
|
|
)
|
|
return baseHz + float64(h.Sum32()%numSteps)*stepHz
|
|
}
|
|
|
|
// addAutoFreqEntries adds a FreqConfig entry for each user-defined class that doesn't
|
|
// already have one in the map. Built-in classes that appear in user rules are skipped.
|
|
// Must be called AFTER merge() so that [sounds.X] overrides are already applied.
|
|
func addAutoFreqEntries(cfgs map[classify.TrafficClass]synth.FreqConfig, userRules []classify.Rule) {
|
|
for _, rule := range userRules {
|
|
if _, exists := cfgs[rule.Class]; !exists {
|
|
baseHz := autoAssignFreq(string(rule.Class))
|
|
cfgs[rule.Class] = synth.FreqConfig{
|
|
BaseHz: baseHz,
|
|
WaveformType: synth.WaveformSine,
|
|
Harmonics: synth.WaveformPresetHarmonics(synth.WaveformSine, baseHz, synth.SampleRate),
|
|
Pan: 0.0,
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// parseWaveform converts a TOML waveform string to a WaveformType.
|
|
func parseWaveform(s string) (synth.WaveformType, error) {
|
|
if wt, ok := validWaveforms[s]; ok {
|
|
return wt, nil
|
|
}
|
|
valid := []string{"sine", "square", "sawtooth", "triangle"}
|
|
return 0, fmt.Errorf("config: invalid waveform %q — valid values: %s", s, strings.Join(valid, ", "))
|
|
}
|
|
|
|
// copyDefaults returns a shallow copy of synth.ClassFreqConfigs.
|
|
// Shallow copy is safe because merge assigns fresh Harmonics slices from
|
|
// WaveformPresetHarmonics, never mutating the original default slice.
|
|
func copyDefaults() map[classify.TrafficClass]synth.FreqConfig {
|
|
result := make(map[classify.TrafficClass]synth.FreqConfig, len(synth.ClassFreqConfigs))
|
|
for k, v := range synth.ClassFreqConfigs {
|
|
result[k] = v
|
|
}
|
|
return result
|
|
}
|
|
|
|
// merge overlays per-class overrides onto the defaults map in-place.
|
|
// Only non-nil pointer fields in each SoundOverride are applied.
|
|
func merge(
|
|
defaults map[classify.TrafficClass]synth.FreqConfig,
|
|
overrides map[string]SoundOverride,
|
|
) map[classify.TrafficClass]synth.FreqConfig {
|
|
for className, override := range overrides {
|
|
class := classify.TrafficClass(className)
|
|
cfg, known := defaults[class]
|
|
if !known {
|
|
// D-09: unknown class name = warning (not error), in case Phase 7 defines it
|
|
fmt.Fprintf(os.Stderr, "Warning: config: unknown class %q (ignored)\n", className)
|
|
continue
|
|
}
|
|
if override.Frequency != nil {
|
|
cfg.BaseHz = *override.Frequency
|
|
// Regenerate harmonics when a waveform preset is active (Pitfall 3)
|
|
if cfg.WaveformType != synth.WaveformCustom {
|
|
cfg.Harmonics = synth.WaveformPresetHarmonics(cfg.WaveformType, cfg.BaseHz, synth.SampleRate)
|
|
}
|
|
}
|
|
if override.Waveform != nil {
|
|
wt, _ := parseWaveform(*override.Waveform) // already validated above
|
|
cfg.WaveformType = wt
|
|
cfg.Harmonics = synth.WaveformPresetHarmonics(wt, cfg.BaseHz, synth.SampleRate)
|
|
}
|
|
defaults[class] = cfg
|
|
}
|
|
return defaults
|
|
}
|