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.
184 lines
5.6 KiB
Go
184 lines
5.6 KiB
Go
package configuration
|
|
|
|
import (
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/samcharles93/archie-core/internal/config"
|
|
)
|
|
|
|
// Document is the decoded external configuration together with a record of
|
|
// where it came from.
|
|
type Document struct {
|
|
// Config is the translated settings.
|
|
//
|
|
// TEMPORARY. docs/architecture/configuration.md requires this to become
|
|
// typed per-domain sections that never expose a whole-application model.
|
|
// It stays for now so this package can own loading without every
|
|
// consumer changing at once. Delete when internal/config is dissolved.
|
|
Config config.Config
|
|
|
|
// Provenance lists the files that produced Config, in precedence order.
|
|
Provenance Provenance
|
|
}
|
|
|
|
// Loader reads configuration from files. The zero value is not usable; call
|
|
// [New].
|
|
type Loader struct {
|
|
log *slog.Logger
|
|
|
|
// dataHomeFn resolves the base directory for derived paths. Injected so
|
|
// tests can exercise defaulting without depending on the environment --
|
|
// the previous package-level dataHome() read XDG_DATA_HOME directly and
|
|
// discarded the error from os.UserHomeDir.
|
|
dataHomeFn func() string
|
|
}
|
|
|
|
// New returns a Loader. A nil logger discards output.
|
|
func New(log *slog.Logger) *Loader {
|
|
if log == nil {
|
|
log = slog.New(slog.DiscardHandler)
|
|
}
|
|
return &Loader{log: log, dataHomeFn: xdgDataHome}
|
|
}
|
|
|
|
// dataHome resolves the base directory for derived paths.
|
|
func (l *Loader) dataHome() string {
|
|
if l.dataHomeFn == nil {
|
|
return xdgDataHome()
|
|
}
|
|
return l.dataHomeFn()
|
|
}
|
|
|
|
// xdgDataHome returns $XDG_DATA_HOME, falling back to ~/.local/share, and
|
|
// finally to a relative path when the home directory is unknowable.
|
|
func xdgDataHome() string {
|
|
if dir := os.Getenv("XDG_DATA_HOME"); dir != "" {
|
|
return dir
|
|
}
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
return filepath.Join(".local", "share")
|
|
}
|
|
return filepath.Join(home, ".local", "share")
|
|
}
|
|
|
|
// File loads a single TOML configuration file.
|
|
func (l *Loader) File(path string) (*Document, error) {
|
|
return l.Overlay(path, "")
|
|
}
|
|
|
|
// Overlay loads basePath, then decodes overlayPath into the same value so
|
|
// only the fields the overlay sets are replaced -- every field it omits keeps
|
|
// the base value. This lets a deployment-specific file (config.docker.toml)
|
|
// declare only what differs instead of restating the whole schema. An empty
|
|
// overlayPath is equivalent to [Loader.File].
|
|
func (l *Loader) Overlay(basePath, overlayPath string) (*Document, error) {
|
|
doc := &Document{}
|
|
|
|
if err := decodeTOML(basePath, &doc.Config); err != nil {
|
|
return nil, err
|
|
}
|
|
doc.Provenance.record(Origin{Path: basePath, Role: RoleMain, Layer: LayerBase})
|
|
|
|
if overlayPath != "" {
|
|
if err := decodeTOML(overlayPath, &doc.Config); err != nil {
|
|
return nil, err
|
|
}
|
|
doc.Provenance.record(Origin{Path: overlayPath, Role: RoleMain, Layer: LayerOverlay})
|
|
}
|
|
|
|
return l.finalize(doc)
|
|
}
|
|
|
|
// Dir loads configuration from a directory tree:
|
|
//
|
|
// config.yaml daemon-level settings
|
|
// config.gateway.yaml chat channels and platforms
|
|
// config.tools.yaml MCP servers and tool policy
|
|
// config.memory.yaml memory provider settings
|
|
// config.models.yaml LLM providers and models
|
|
// config.identities.yaml identity settings
|
|
// conf.d/*.yaml additional feature files
|
|
//
|
|
// A missing feature file means the feature is absent, not an error. Legacy
|
|
// config.toml is the fallback when config.yaml is absent; YAML wins when
|
|
// both exist.
|
|
//
|
|
// When overlayDir is non-empty its files are applied on top of baseDir, with
|
|
// the same field-level precedence as [Loader.Overlay]. The overlay directory
|
|
// need not contain a main config.
|
|
func (l *Loader) Dir(baseDir, overlayDir string) (*Document, error) {
|
|
doc := &Document{}
|
|
|
|
if err := l.loadDir(doc, baseDir, LayerBase); err != nil {
|
|
return nil, err
|
|
}
|
|
if overlayDir != "" {
|
|
if err := l.loadDir(doc, overlayDir, LayerOverlay); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
return l.finalize(doc)
|
|
}
|
|
|
|
// loadDir discovers and decodes one directory into doc. The base layer must
|
|
// supply a main config; an overlay may contribute feature files alone.
|
|
func (l *Loader) loadDir(doc *Document, dir string, layer Layer) error {
|
|
files, err := discover(dir)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
switch path, isYAMLFile, ok := files.main(); {
|
|
case ok:
|
|
if err := l.decodeMain(&doc.Config, path, isYAMLFile); err != nil {
|
|
return err
|
|
}
|
|
doc.Provenance.record(Origin{Path: path, Role: RoleMain, Layer: layer})
|
|
case layer == LayerBase:
|
|
return fmt.Errorf("%w: no config.yaml or config.toml in %s", ErrNoConfigFile, dir)
|
|
}
|
|
|
|
for _, feature := range files.sortedFeatures() {
|
|
path := files.features[feature]
|
|
if err := decodeFeature(&doc.Config, feature, path); err != nil {
|
|
return err
|
|
}
|
|
doc.Provenance.record(Origin{Path: path, Role: RoleFeature, Layer: layer, Feature: feature})
|
|
}
|
|
|
|
for _, name := range files.sortedExtras() {
|
|
path := files.extras[name]
|
|
if err := decodeExtra(&doc.Config, name, path); err != nil {
|
|
return err
|
|
}
|
|
doc.Provenance.record(Origin{Path: path, Role: RoleExtra, Layer: layer, Feature: Feature(name)})
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// decodeMain decodes the daemon-level file in whichever format it uses.
|
|
func (l *Loader) decodeMain(cfg *config.Config, path string, isYAMLFile bool) error {
|
|
if isYAMLFile {
|
|
return decodeYAML(path, cfg)
|
|
}
|
|
return decodeTOML(path, cfg)
|
|
}
|
|
|
|
// finalize applies defaults, then validates. The order matters: validation
|
|
// judges the effective configuration, including values the operator never
|
|
// wrote.
|
|
func (l *Loader) finalize(doc *Document) (*Document, error) {
|
|
l.applyDefaults(&doc.Config)
|
|
if err := validate(&doc.Config); err != nil {
|
|
return nil, err
|
|
}
|
|
l.log.Debug("configuration loaded", "sources", doc.Provenance.String())
|
|
return doc, nil
|
|
}
|