Files
archie/internal/infrastructure/configuration/validate.go
T
sam f544dd0978 feat(config): SIGHUP-triggered reload with requires-restart warnings
The daemon can now re-read its configuration on SIGHUP (or on a
future in-process trigger) and republish it through the Holder,
closing the first half of issue #348: 'config can change at runtime,
safely, and can't brick the daemon.'

Reload path:
- cmd/archied/reload.go: ReloadController re-runs loader.Resolve on
  the same paths main.go passed at startup (Resolve is pure -- no
  reload state added to the loader). apply is called only with a
  Document that passed validation; a failed reload records the error
  and its timestamp and leaves the running config untouched. That
  Set-not-called-on-error property is the safety core and is pinned
  by TestReloadValidationFailureDoesNotApply.
- SIGHUP listener in main.go runs reloadLoop(ctx, ch, controller, log);
  the loop is extracted as a testable seam (syscall.SIGHUP is Unix-only,
  fine given the Linux target).

PollInterval is genuinely reloadable now, not just re-read:
the three ticker sites (Run, per-identity goroutine, shared
maintenance loop) re-read the interval each tick and Reset the ticker
on change. A reloaded poll_interval takes effect on the next cycle.

Diff-and-warn so an operator never has to read the source to know
whether an edit took effect: changedNonReloadableFields compares the
old and new snapshots against an allowlist of re-read fields
(PollInterval, Repos, DiffCapLines, Budgets, Dispatch, and the
Containers sub-fields VolumeTTL + MaxConcurrency). Anything else that
changed logs Warn 'requires a restart'; a fully-applied reload logs
Info. The allowlist is deliberate: a field added to Config later
defaults to requires-restart, the safe direction.

NATS split-brain closed: containerEnv now hands containers the
endpoint the daemon's own client connected with at startup
(Daemon.ConnectedNATS, captured at construction) instead of the live
config, so a reloaded nats.url cannot point new containers at a
server the daemon is not publishing on. A nats change is therefore
classified requires-restart, and CLAUDE.md's 'hands its own nats.url
verbatim' note is updated to the meaning it now has (same today,
deliberately different after a reload).

Validation guard: poll_interval <= 0 is rejected in validate.go
beside the VolumeTTL guard. applyDefaults fills zero with 60s, so
this fires on an explicit negative -- which would panic
time.NewTicker/Reset at boot and, after the per-iteration reset,
on a SIGHUP mid-run.

Observability: config.ReloadStatus (last_error, last_error_at,
last_reload_at) is recorded by the controller and surfaced in
/api/config via Server.LastReload, so a stale running config is
visible in the dashboard, not just the logs. Rendering waits for the
UI step.

Recovery hatch: --no-config-overlay flag plus ARCHIE_SKIP_CONFIG_OVERLAY=1
(configuration.SkipOverlay), logged at startup. No overlay source
exists yet; the flag is the documented escape hatch the DB overlay
(step 3 of #348) will consult.

webui.Server.ConfigProvenance becomes atomic.Pointer so a reload can
swap it via SetProvenance independently of Cfg; the accepted skew
(new config alongside old provenance) is documented on the field.

Verified: task check clean; -race on daemon, webui, cmd/archied,
config, infrastructure/configuration.
2026-08-10 00:19:46 +10:00

218 lines
7.6 KiB
Go

package configuration
import (
"fmt"
"net/url"
"path/filepath"
"slices"
"strings"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/secret"
)
// Recognised enum values, named so validation and its error message cannot
// disagree about what is allowed.
const (
agentModeInProcess = "inprocess"
agentModeSubprocess = "subprocess"
agentModeNATS = "nats"
forgeTypeGitHub = "github"
forgeTypeGitea = "gitea"
forgeTypeNone = "none"
forgeTypeOff = "off"
forgeTypeDisabled = "disabled"
dispatchTriggerAssignee = "assignee"
dispatchTriggerLabel = "label"
dispatchTriggerEither = "either"
)
var (
agentModes = []string{agentModeInProcess, agentModeSubprocess, agentModeNATS}
forgeTypes = []string{forgeTypeGitHub, forgeTypeGitea, forgeTypeNone, forgeTypeOff, forgeTypeDisabled}
dispatchTriggers = []string{dispatchTriggerAssignee, dispatchTriggerLabel, dispatchTriggerEither}
)
// Validate runs the same checks Loader applies before accepting a config,
// against a config.Config value already built in memory -- e.g. by archied
// setup, before it has written anything to disk.
//
// Like validate, it does not apply defaults. Several checks (agent.mode,
// dispatch.trigger, forge.type) only pass once a default has been filled
// in, and defaulting is currently unexported ((*Loader).applyDefaults). A
// cfg built by hand, with those fields left zero-valued, will fail
// validation that a config loaded through [Loader.File] would pass. Callers
// that build a config directly (rather than decoding one through a Loader)
// must fill in the same defaults themselves, or -- the safer option, since
// it can't drift from what the real load path does -- render the config to
// TOML and load it back through a Loader instead of calling Validate on the
// in-memory value directly.
func Validate(cfg *config.Config) error {
return validate(cfg)
}
// validate reports the first problem that would stop the daemon running.
// It does not modify cfg -- run applyDefaults first.
func validate(cfg *config.Config) error {
if err := validateAgent(cfg); err != nil {
return err
}
if err := validateDispatch(cfg); err != nil {
return err
}
if err := validateProviders(cfg.Providers); err != nil {
return err
}
if len(cfg.Identities) > 0 {
if err := validateIdentities(cfg.Identities); err != nil {
return err
}
} else if err := validateSingleIdentity(cfg); err != nil {
return err
}
if err := validatePollInterval(cfg); err != nil {
return err
}
return validateContainers(cfg)
}
// validatePollInterval rejects a non-positive poll interval.
// applyDefaults fills PollInterval == 0 with the default, so this only
// fires on an explicit negative value -- which would panic
// time.NewTicker/Reset in the daemon's poll loops, at boot and (worse)
// on a SIGHUP reload mid-run, when the edit that broke it is no longer
// fresh in the operator's mind.
func validatePollInterval(cfg *config.Config) error {
if cfg.PollInterval <= 0 {
return fmt.Errorf("%w: poll_interval must be positive", ErrInvalidInput)
}
return nil
}
func validateAgent(cfg *config.Config) error {
if !oneOf(cfg.Agent.Mode, agentModes) {
return fmt.Errorf("%w: agent.mode %q (want %s)", ErrInvalidInput, cfg.Agent.Mode, list(agentModes))
}
if cfg.Agent.Mode == agentModeSubprocess && strings.TrimSpace(cfg.Agent.Command) == "" {
return fmt.Errorf("%w: agent.command is required in subprocess mode", ErrInvalidInput)
}
for i, name := range cfg.Agent.Env {
if strings.TrimSpace(name) == "" || strings.Contains(name, "=") {
return fmt.Errorf("%w: agent.env[%d] %q is not an environment variable name", ErrInvalidInput, i, name)
}
}
return nil
}
func validateDispatch(cfg *config.Config) error {
if !oneOf(cfg.Dispatch.Trigger, dispatchTriggers) {
return fmt.Errorf("%w: dispatch.trigger %q (want %s)", ErrInvalidInput, cfg.Dispatch.Trigger, list(dispatchTriggers))
}
return nil
}
// validateProviders rejects base URLs carrying credentials or query state.
// A provider URL is used to build API requests, so userinfo or a stray query
// string would be silently attached to every call.
func validateProviders(providers map[string]config.Provider) error {
for name, provider := range providers {
if provider.BaseURL == "" {
continue
}
u, err := url.Parse(provider.BaseURL)
if err != nil {
return fmt.Errorf("%w: providers.%s.base_url: %w", ErrInvalidInput, name, err)
}
if u.User != nil || u.RawQuery != "" || u.Fragment != "" {
return fmt.Errorf("%w: providers.%s.base_url must not contain userinfo, query parameters, or a fragment", ErrInvalidInput, name)
}
}
return nil
}
func validateIdentities(identities []config.IdentityConfig) error {
for i, id := range identities {
if id.Name == "" {
return fmt.Errorf("%w: identities[%d].name is required", ErrInvalidInput, i)
}
if id.BotUser == "" {
return fmt.Errorf("%w: identities[%d].bot_user is required", ErrInvalidInput, i)
}
if len(id.Repos) == 0 {
return fmt.Errorf("%w: identities[%d] has no [[identities.repos]] entries -- at least one is required", ErrInvalidInput, i)
}
if !oneOf(id.Forge.Type, forgeTypes) {
return fmt.Errorf("%w: identities[%d].forge.type %q (want %s)", ErrInvalidInput, i, id.Forge.Type, list(forgeTypes))
}
if !isForgeDisabled(id.Forge.Type) && id.Forge.Token == (secret.SecretRef{}) {
return fmt.Errorf("%w: identities[%d].forge.token is required (each identity needs its own secret reference; unlike the top-level [forge], there is no default)", ErrInvalidInput, i)
}
if err := validateRepos(id.Repos); err != nil {
return fmt.Errorf("identities[%d]: %w", i, err)
}
}
return nil
}
func isForgeDisabled(t string) bool {
return t == forgeTypeNone || t == forgeTypeOff || t == forgeTypeDisabled
}
func validateSingleIdentity(cfg *config.Config) error {
if cfg.BotUser == "" {
return fmt.Errorf("%w: bot_user is required (or define [[identities]])", ErrInvalidInput)
}
if !oneOf(cfg.Forge.Type, forgeTypes) {
return fmt.Errorf("%w: forge.type %q (want %s)", ErrInvalidInput, cfg.Forge.Type, list(forgeTypes))
}
return validateRepos(cfg.Repos)
}
func validateRepos(repos []config.Repo) error {
for i, r := range repos {
if r.Owner == "" || r.Name == "" {
return fmt.Errorf("%w: repos[%d] needs owner and name", ErrInvalidInput, i)
}
if glob := r.ResolvedTestGlob(); glob != "" {
if _, err := filepath.Match(glob, ""); err != nil {
return fmt.Errorf("%w: repos[%d] test_glob %q: %w", ErrInvalidInput, i, glob, err)
}
}
}
return nil
}
// validateContainers checks the combination that container execution
// requires: a NATS transport and somewhere to reach it.
func validateContainers(cfg *config.Config) error {
if !cfg.Containers.Enabled {
return nil
}
if cfg.Containers.Image == "" {
return fmt.Errorf("%w: containers.image is required when containers.enabled is true", ErrInvalidInput)
}
if cfg.Agent.Mode != agentModeNATS {
return fmt.Errorf("%w: agent.mode must be %q when containers.enabled is true", ErrInvalidInput, agentModeNATS)
}
if cfg.NATS.URL == "" {
return fmt.Errorf("%w: [nats] url is required when containers.enabled is true", ErrInvalidInput)
}
if cfg.Containers.VolumeTTL < 0 {
return fmt.Errorf("%w: containers.volume_ttl must not be negative", ErrInvalidInput)
}
return nil
}
// oneOf reports whether value is in allowed.
func oneOf(value string, allowed []string) bool {
return slices.Contains(allowed, value)
}
// list renders allowed values for an error message.
func list(values []string) string { return strings.Join(values, ", ") }
// isOff reports the documented "disable this" spelling.
func isOff(value string) bool { return strings.EqualFold(value, "off") }