feat(config): key services by name through a registry

Services was a struct with one field per service, so each service's name was
stated three times: the field, the loader's defaulting branch, and every
consumer's field access. Adding one meant editing all three, and nothing
stopped them disagreeing. The drift was already there: stateStoreResolvedToken
and gatewayResolvedToken were identical apart from the env var each hard-coded.

Services becomes map[string]ServiceConnection, and RegisterService declares a
service once with the five fields it has. Everything that differs between
services is now an argument rather than a branch elsewhere: an empty registered
target means the operator must supply one, which is how services.state.target
stays required while the gateway's is defaulted, and the registered token env
var replaces the two copied resolvers with Services.ResolvedToken.

Defaulting iterates the registry, so a new service needs no loader edit.
Consumers read Services.Get(name).

Keeping a typo'd section reported took explicit work. [services.gatway] used to
land in toml.MetaData.Undecoded() because the struct had no such field; a map
decodes any section, so it would have loaded silently and left the daemon
dialing the default. unregisteredServiceKeys asks the registry which names are
real, and the test for it fails with an empty UnknownKeys when that check is
removed.

The TOML shape is unchanged, so no deployment profile, config.example.toml or
install.sh edit is needed.

Refs: archie-core-u23g
This commit is contained in:
sam committed 2026-09-18 23:32:36 +10:00
1 parent a4fc93dc62
commit 6bdbd5e31e
21 files changed
+478 -115

No files matched your search

@@ -12,18 +12,9 @@ import (
// Defaults applied to absent input. Named so a reader can find the value
// without reading the code that applies it.
const (
defaultPollInterval = 60 * time.Second
defaultDiffCapLines = 400
defaultWebListen = "127.0.0.1:8484" // "off" disables
// defaultGatewayAddr is where archie-gateway binds and, by default, where
// clients look for it. One constant for both so a default deployment's
// client and server cannot drift onto different ports.
defaultGatewayAddr = "127.0.0.1:8585"
// defaultStateListen is the state store's bind address. There is
// deliberately no default for [services.state].target: an empty target is
// a startup error in the daemon and the gateway, which no longer serve a
// local store (docs/prds/state-store-contract.md).
defaultStateListen = "127.0.0.1:9090"
defaultPollInterval = 60 * time.Second
defaultDiffCapLines = 400
defaultWebListen = "127.0.0.1:8484" // "off" disables
defaultMaxRetries = 3
defaultForgeType = "github"
defaultForgeHost = "https://github.com"
@@ -71,15 +62,7 @@ const (
// input was to not call them. Splitting them means defaults can be applied,
// inspected, and reasoned about independently of whether the result is valid.
func (l *Loader) applyDefaults(cfg *config.Config) {
if cfg.Services.Gateway.Target == "" {
cfg.Services.Gateway.Target = defaultGatewayAddr
}
if cfg.Services.Gateway.Listen == "" {
cfg.Services.Gateway.Listen = defaultGatewayAddr
}
if cfg.Services.State.Listen == "" {
cfg.Services.State.Listen = defaultStateListen
}
applyServiceDefaults(cfg)
if cfg.Health.Listen == "" {
cfg.Health.Listen = defaultHealthListen
}
@@ -94,6 +77,31 @@ func (l *Loader) applyDefaults(cfg *config.Config) {
applyMemoryDefaults(cfg)
}
// applyServiceDefaults fills each registered service's absent addresses from
// its registration. It iterates the registry rather than naming services, so a
// new service needs no branch here -- only its RegisterService call.
//
// A registered service always ends with an entry, so later code can read
// cfg.Services.Get(name) without distinguishing "absent section" from
// "section with every field defaulted". An empty registered Target is a
// service whose target the operator must supply, and stays empty for
// validation to reject rather than being defaulted to something dialable.
func applyServiceDefaults(cfg *config.Config) {
if cfg.Services == nil {
cfg.Services = config.Services{}
}
for _, spec := range config.RegisteredServices() {
conn := cfg.Services[spec.Name]
if conn.Target == "" {
conn.Target = spec.Target
}
if conn.Listen == "" {
conn.Listen = spec.Listen
}
cfg.Services[spec.Name] = conn
}
}
// applyMemoryDefaults fills an absent engine choice with the builtin
// engine, so "nothing configured" and "explicitly builtin" are the same
// resolved state everywhere after this point -- validateMemory and every
@@ -210,6 +210,23 @@ func unknownKeys(a, b []string) []string {
return out
}
// unregisteredServiceKeys reports [services.<name>] sections naming a service
// nobody registered.
//
// Undecoded() cannot see these. Services is a map, so TOML decodes any section
// under [services] into it successfully, and a typo'd [services.gatway] would
// load clean where the previous struct form reported it. The registry is the
// authority on which names exist, so ask it.
func unregisteredServiceKeys(services config.Services) []string {
var out []string
for name := range services {
if _, ok := config.LookupService(name); !ok {
out = append(out, "services."+name)
}
}
return out
}
// sortedUnique returns keys sorted and de-duplicated, so Document.UnknownKeys
// is deterministic across a base+overlay load that happens to name the same
// stray key in both files.
@@ -322,7 +339,7 @@ func (l *Loader) decodeMain(doc *Document, path string, isYAMLFile bool) error {
// judges the effective configuration, including values the operator never
// wrote.
func (l *Loader) finalize(doc *Document) (*Document, error) {
doc.UnknownKeys = sortedUnique(doc.UnknownKeys)
doc.UnknownKeys = sortedUnique(append(doc.UnknownKeys, unregisteredServiceKeys(doc.Config.Services)...))
l.applyDefaults(&doc.Config)
if err := Validate(&doc.Config); err != nil {
return nil, err
@@ -3,7 +3,11 @@ package configuration
import (
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/config"
)
func TestLoadGatewayServiceTarget(t *testing.T) {
@@ -22,8 +26,8 @@ func TestLoadGatewayServiceTarget(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if cfg.Services.Gateway.Target != tt.wantTarget {
t.Fatalf("target = %q, want %q", cfg.Services.Gateway.Target, tt.wantTarget)
if cfg.Services.Get(config.ServiceNameGateway).Target != tt.wantTarget {
t.Fatalf("target = %q, want %q", cfg.Services.Get(config.ServiceNameGateway).Target, tt.wantTarget)
}
})
}
@@ -61,11 +65,11 @@ func TestLoadServiceListens(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if cfg.Services.State.Listen != tt.wantState {
t.Fatalf("state listen = %q, want %q", cfg.Services.State.Listen, tt.wantState)
if cfg.Services.Get(config.ServiceNameState).Listen != tt.wantState {
t.Fatalf("state listen = %q, want %q", cfg.Services.Get(config.ServiceNameState).Listen, tt.wantState)
}
if cfg.Services.Gateway.Listen != tt.wantGateway {
t.Fatalf("gateway listen = %q, want %q", cfg.Services.Gateway.Listen, tt.wantGateway)
if cfg.Services.Get(config.ServiceNameGateway).Listen != tt.wantGateway {
t.Fatalf("gateway listen = %q, want %q", cfg.Services.Get(config.ServiceNameGateway).Listen, tt.wantGateway)
}
})
}
@@ -98,3 +102,85 @@ func TestLoadHealthListen(t *testing.T) {
})
}
}
// TestRegisteredServiceDefaultsNeedNoLoaderEdit pins criterion 4 of
// docs/prds/service-registry.md. A service registered anywhere gets its
// defaults applied here without this package naming it, which is the whole
// point of iterating the registry instead of writing one branch per service.
func TestRegisteredServiceDefaultsNeedNoLoaderEdit(t *testing.T) {
config.RegisterService(config.ServiceBoth, "loadertest", "127.0.0.1:7101", "127.0.0.1:7102", "LOADERTEST_TOKEN")
path := filepath.Join(t.TempDir(), "config.toml")
if err := os.WriteFile(path, []byte("bot_user = 'widget'\n"), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := loadFile(path)
if err != nil {
t.Fatal(err)
}
got := cfg.Services.Get("loadertest")
if got.Target != "127.0.0.1:7101" {
t.Errorf("target = %q, want the registered default", got.Target)
}
if got.Listen != "127.0.0.1:7102" {
t.Errorf("listen = %q, want the registered default", got.Listen)
}
}
// TestStateTargetIsNotDefaulted keeps the asymmetry the registry now carries as
// data: the gateway's target is defaulted, the State Store's is operator
// input, and defaulting it to something dialable would turn a missing
// required value into a connection attempt against the wrong host.
func TestStateTargetIsNotDefaulted(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml")
if err := os.WriteFile(path, []byte("bot_user = 'widget'\n"), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := loadFile(path)
if err != nil {
t.Fatal(err)
}
if got := cfg.Services.Get(config.ServiceNameState).Target; got != "" {
t.Errorf("state target = %q, want empty", got)
}
}
// TestUnregisteredServiceSectionIsReported is the regression this change had to
// avoid introducing. Services was a struct, so [services.gatway] landed in
// Undecoded() and was reported. As a map it decodes cleanly, so without the
// registry check a typo'd service section would load silently and the daemon
// would dial the default instead.
func TestUnregisteredServiceSectionIsReported(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml")
src := minimalValidConfigTOML + "[services.gatway]\ntarget = '127.0.0.1:1'\n"
if err := os.WriteFile(path, []byte(src), 0o600); err != nil {
t.Fatal(err)
}
doc, err := New(nil).File(path)
if err != nil {
t.Fatalf("File: %v (an unknown key must not fail the load)", err)
}
if !slices.Contains(doc.UnknownKeys, "services.gatway") {
t.Errorf("UnknownKeys = %v, want it to contain %q", doc.UnknownKeys, "services.gatway")
}
}
// TestRegisteredServiceSectionIsNotReported is the other half: a real service
// section must not be flagged just because the map would accept anything.
func TestRegisteredServiceSectionIsNotReported(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml")
src := minimalValidConfigTOML + "[services.state]\ntarget = '127.0.0.1:9090'\n"
if err := os.WriteFile(path, []byte(src), 0o600); err != nil {
t.Fatal(err)
}
doc, err := New(nil).File(path)
if err != nil {
t.Fatal(err)
}
for _, k := range doc.UnknownKeys {
if strings.HasPrefix(k, "services.") {
t.Errorf("UnknownKeys = %v, want no services.* entry for a registered service", doc.UnknownKeys)
break
}
}
}
@@ -27,7 +27,7 @@ func minimalValidConfig() config.Config {
Image: "ghcr.io/samcharles93/archie-agent:latest",
},
Services: config.Services{
Gateway: config.ServiceConnection{Target: "127.0.0.1:8585"},
config.ServiceNameGateway: {Target: "127.0.0.1:8585"},
},
}
}