Files
archie/internal/infrastructure/configuration/discovery.go
T
sam c66c0a2a38 refactor(config): move loading into infrastructure/configuration
internal/config both defined the types every package imports and performed
the file I/O to produce them. Importing a settings struct therefore pulled
in a TOML decoder and a YAML decoder, and the shared model owned discovery,
decoding, overlays, defaulting and validation all at once. See
docs/architecture/configuration.md, which requires loading to move out and
internal/config to be dissolved.

internal/config is now types only -- no os, no filepath, no toml. The new
package owns loading, one concern per file:

  features.go    the closed set of recognised feature files
  discovery.go   directory scan and classification
  decode.go      TOML/YAML decoding, format dispatch
  defaults.go    filling absent values, no errors
  validate.go    judging supplied values, no mutation
  provenance.go  which file contributed what
  loader.go      Loader wiring the above; File/Overlay/Dir

Beyond relocating, this fixes what the old code conflated:

  - Defaulting and validation were interleaved. applyAgentDefaults and
    applyDispatchDefaults returned validation errors; validateContainers and
    validateSingleIdentity quietly mutated the config. There was no point at
    which you could see what the operator actually supplied. They are now
    separate passes: applyDefaults never fails, validate never writes.
  - Errors were fmt.Errorf strings prefixed "config: ", so a caller could not
    distinguish operator-fixable input from an unreadable file without
    matching message text. Five sentinels now carry that distinction.
  - dataHome() read XDG_DATA_HOME directly and discarded the error from
    os.UserHomeDir, so defaulting could not be tested without the
    environment. It is injectable on Loader and no longer swallows the error.
  - Nothing recorded where a value came from. With overlays, feature files
    and conf.d/ all able to set the same field, "which file set this?" was
    answerable only by re-deriving precedence by hand. Provenance records it.
  - Feature files were applied in map iteration order, making load order and
    any resulting error arbitrary. Discovery now returns them sorted.
  - loadMainConfig reported "no config.yaml or config.toml found in %s" with
    an empty string: the directory was lost when it was extracted from
    loadDirInto, so the error named no directory.
  - Unreadable or malformed conf.d/ extras were skipped silently, which
    presents as a setting the operator wrote simply not taking effect.
  - Decode errors from the main config were returned bare, without naming
    the file that failed to parse.

The 40 loader tests moved with the code and their assertions are unchanged,
so the defaulting and validation rewrite is behaviour-preserving.

Document.Config is the temporary seam: still internal/config.Config, named
as a field so the compromise is visible at each use site, with its deletion
condition recorded in doc.go. Building typed per-domain sections now, while
every consumer still reads config.Config, would mean two shapes kept in sync
by hand with no consumer for the new one; that belongs with the dissolution
work, not ahead of it.

No consumer outside cmd/archied changed.

Verified: go build, go vet, gofmt clean; go test ./internal/config/... and
./internal/infrastructure/configuration/... pass. Pre-existing gateway and
telegram failures are unchanged.
2026-07-29 11:07:41 +10:00

157 lines
4.2 KiB
Go

package configuration
import (
"fmt"
"os"
"path/filepath"
"sort"
)
// confDirName is the subdirectory holding additional feature files.
const confDirName = "conf.d"
// fileSet is the outcome of scanning one configuration directory: which file
// carries the daemon-level settings, which files carry recognised features,
// and which carry opaque extras.
//
// Scanning previously returned four bare values (two paths and two maps),
// which left the caller to remember that YAML wins over TOML and that extras
// are keyed by feature name.
type fileSet struct {
mainYAML string
mainTOML string
features map[Feature]string
extras map[string]string
}
// main returns the daemon-level config file and its format. YAML wins when
// both are present; legacy config.toml is the fallback.
func (fs fileSet) main() (path string, yaml bool, ok bool) {
if fs.mainYAML != "" {
return fs.mainYAML, true, true
}
if fs.mainTOML != "" {
return fs.mainTOML, false, true
}
return "", false, false
}
// sortedFeatures returns recognised features in a stable order, so loading
// is deterministic and provenance reads the same across runs. Map iteration
// order previously made the applied order arbitrary.
func (fs fileSet) sortedFeatures() []Feature {
names := make([]Feature, 0, len(fs.features))
for f := range fs.features {
names = append(names, f)
}
sort.Slice(names, func(i, j int) bool { return names[i] < names[j] })
return names
}
// sortedExtras returns extra names in a stable order.
func (fs fileSet) sortedExtras() []string {
names := make([]string, 0, len(fs.extras))
for n := range fs.extras {
names = append(names, n)
}
sort.Strings(names)
return names
}
// discover scans dir and classifies its entries.
func discover(dir string) (fileSet, error) {
entries, err := os.ReadDir(dir)
if err != nil {
return fileSet{}, fmt.Errorf("%w: config dir %s: %w", ErrUnreadable, dir, err)
}
fs := fileSet{
features: map[Feature]string{},
extras: map[string]string{},
}
var unknown []string
for _, e := range entries {
name := e.Name()
if e.IsDir() {
if name == confDirName {
if err := fs.scanConfDir(dir); err != nil {
return fileSet{}, err
}
}
continue
}
switch {
case name == "config.yaml" || name == "config.yml":
fs.mainYAML = filepath.Join(dir, name)
case name == "config.toml":
fs.mainTOML = filepath.Join(dir, name)
case isYAML(name) || isTOML(name):
if err := fs.classify(dir, name, &unknown); err != nil {
return fileSet{}, err
}
}
}
if len(unknown) > 0 {
sort.Strings(unknown)
return fileSet{}, fmt.Errorf("%w: %q (known features: %s)", ErrUnknownFeature, unknown[0], featureList())
}
return fs, nil
}
// classify records a config.<feature>.yaml file, collecting unrecognised
// names into unknown so every one can be reported rather than just the first
// encountered.
func (fs fileSet) classify(dir, name string, unknown *[]string) error {
feature := featureFromFilename(name)
if feature == "" {
return nil
}
if !feature.known() {
*unknown = append(*unknown, name)
return nil
}
return fs.addFeature(feature, filepath.Join(dir, name))
}
// scanConfDir reads dir/conf.d/, routing recognised names to features and
// the rest to extras.
func (fs fileSet) scanConfDir(dir string) error {
confDir := filepath.Join(dir, confDirName)
entries, err := os.ReadDir(confDir)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("%w: %s: %w", ErrUnreadable, confDir, err)
}
for _, e := range entries {
name := e.Name()
if e.IsDir() || !isYAML(name) {
continue
}
path := filepath.Join(confDir, name)
feature := Feature(trimYAMLSuffix(name))
if !feature.known() {
fs.extras[string(feature)] = path
continue
}
if err := fs.addFeature(feature, path); err != nil {
return err
}
}
return nil
}
// addFeature records a feature file, rejecting a second file claiming the
// same feature. Preferring either silently would apply settings the operator
// cannot predict from the filenames.
func (fs fileSet) addFeature(feature Feature, path string) error {
if existing, ok := fs.features[feature]; ok {
return fmt.Errorf("%w: %q defined by both %s and %s", ErrDuplicateFeature, feature, existing, path)
}
fs.features[feature] = path
return nil
}