Files
archie/internal/app/controlplane/registry.go
T
sam d3d6aedffb fix(statestore): read a kind the store does not hold as its seed, and stop validate touching the daemon's log
Four defects from the re-run contract review, all in the recovery path.

A store missing a control-plane kind was refused while a store with no
resources table at all was accepted -- two stances inside validateStore for
states the daemon cannot tell apart. The State Store seeds every kind from
its own config before it serves (RunStateStore -> ImportConfig), so a kind
the file does not hold yet is one archied reads the seed for: an upgrade that
adds a kind, and a validate before the State Store has started again, exited
1 with "read provider-settings: resource not found" for a store the daemon
boots on fine. StoredRuntimeConfig now reads a missing kind as the seed the
State Store would write for it (Definition.seededValue, shared with
ImportConfig so the two cannot drift), and the missing-table branch is the
same stance taken to its extreme.

defaultConfigPath() derived the daemon's config with os.UserConfigDir, which
disagrees with archied's configHome on darwin and rejects a relative
XDG_CONFIG_HOME outright -- leaving validate with an empty path and no
verdict, on a host where archied boots from relative-dir/archie/config.toml.
It is now the daemon's own rule, exported as archied.DefaultConfigPath and
used by the daemon's own -config default too, with a test pinning the
equality.

-h exited 2, the code documented as "the command line was wrong", while the
serve path in the same binary exits 0 and main.go advertises -h for these
subcommands. ErrHelp now returns 0.

validate resolved the boot config through loadConfig -> setupLogging, which
created cfg.Log.File's directory, opened the log, and wrote a line stamped
component="daemon" -- a diagnostic editing the deployment it inspects, and
rotating a log the daemon is writing. boot.stderrLog keeps setupLogging on
the stderr logger for the recovery path: no feed, no task-log registry, no
durable copy.

Tests: TestRecoveryValidateRunsTheGateBootRuns now asserts the unseeded and
the missing-kind stores are accepted (both exited 1 before), while the
bogus-policy case still refuses; TestRecoveryHelpExitsZero,
TestRecoveryValidateLeavesTheDaemonLogAlone and
TestRecoveryDefaultConfigFollowsTheDaemonsConfigHome are new. Each was run
red first, and the seed fallback and stderrLog were mutation-checked.
2026-09-21 22:04:42 +10:00

167 lines
5.4 KiB
Go

package controlplane
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/samcharles93/archie-core/internal/config"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/store"
)
type Definition struct {
Kind string
Title string
Schema string
ApplyMode string
Seed func(config.Config) any
Validate func([]byte) error
Normalize func([]byte) ([]byte, error)
// Defaults is the factory value clients offer as "restore shipped". Only
// resources that ship with content set it.
Defaults func() any
}
func (d Definition) Descriptor() *pb.ResourceDescriptor {
descriptor := &pb.ResourceDescriptor{Kind: d.Kind, Title: d.Title, SchemaJson: d.Schema, Commands: []string{"replace"}, ApplyMode: d.ApplyMode}
if d.Defaults != nil {
if defaults, err := json.Marshal(d.Defaults()); err == nil {
descriptor.DefaultsJson = string(defaults)
}
}
return descriptor
}
func (d Definition) Decode(input []byte) ([]byte, error) {
if !json.Valid(input) {
return nil, fmt.Errorf("%w: invalid JSON", ErrValidation)
}
if err := d.Validate(input); err != nil {
return nil, fmt.Errorf("%w: %w", ErrValidation, err)
}
if d.Normalize != nil {
normalized, err := d.Normalize(input)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrValidation, err)
}
input = normalized
}
var value any
if err := json.Unmarshal(input, &value); err != nil {
return nil, fmt.Errorf("%w: %w", ErrValidation, err)
}
encoded, err := json.Marshal(value)
if err != nil {
return nil, fmt.Errorf("encode %s: %w", d.Kind, err)
}
return encoded, nil
}
func (s *Server) ImportConfig(ctx context.Context, cfg config.Config) (map[string]int64, error) {
versions := make(map[string]int64, len(s.ordered))
for _, definition := range s.ordered {
resource, err := s.store.Resource(ctx, definition.Kind)
if err == nil {
versions[definition.Kind] = resource.Version
continue
}
if !errors.Is(err, store.ErrResourceNotFound) {
return nil, err
}
value, err := definition.seededValue(cfg)
if err != nil {
return nil, err
}
resource, err = s.store.PutResource(ctx, store.ResourceWrite{Kind: definition.Kind, Value: value, Actor: "system:migration", Source: "legacy-config", RequestID: "import:" + definition.Kind, ExpectedVersion: 0, At: time.Now().UTC()})
if err != nil {
return nil, fmt.Errorf("seed %s: %w", definition.Kind, err)
}
versions[definition.Kind] = resource.Version
}
return versions, nil
}
// seededValue is the value the State Store writes for a kind it does not hold
// yet: the definition's seed derived from cfg, run through the same Decode a
// write applies. ImportConfig stores it; the offline config layering reads it
// for the same reason, so "what the daemon sees for a kind that was never
// stored" is one value rather than two.
func (d Definition) seededValue(cfg config.Config) ([]byte, error) {
value, err := json.Marshal(d.Seed(cfg))
if err != nil {
return nil, fmt.Errorf("seed %s: %w", d.Kind, err)
}
value, err = d.Decode(value)
if err != nil {
return nil, fmt.Errorf("seed %s: %w", d.Kind, err)
}
return value, nil
}
// seededValues is what the State Store would write for every kind, keyed by
// kind.
func (s *Server) seededValues(cfg config.Config) (map[string][]byte, error) {
values := make(map[string][]byte, len(s.ordered))
for _, definition := range s.ordered {
value, err := definition.seededValue(cfg)
if err != nil {
return nil, err
}
values[definition.Kind] = value
}
return values, nil
}
// Owns reports whether kind is a resource the control plane owns, so a caller
// acting on a stored value can refuse a kind nobody defines before it reaches
// the store.
func (s *Server) Owns(kind string) bool {
_, ok := s.definitions[kind]
return ok
}
// ValidateStored decodes every stored resource with the definition that owns
// it, using the same Decode the write path applies, and reports how many
// resources it checked. Errors name the kind and the revision it was stored at,
// which is what an operator needs to roll the value back.
//
// It is the write path's own check, not boot's: boot refuses on
// configuration.Validate over the stored values layered onto the file config,
// and the two disagree in both directions (this one rejects unknown fields
// boot's decode ignores, while only boot checks dispatch.trigger and a positive
// poll interval). A caller answering "would the daemon start" therefore needs
// StoredRuntimeConfig and configuration.Validate as well -- see
// validateStore in internal/app/archied/state_store_recovery.go.
func (s *Server) ValidateStored(ctx context.Context) (int, error) {
checked := 0
var failures []error
for _, definition := range s.ordered {
resource, err := s.store.Resource(ctx, definition.Kind)
if errors.Is(err, store.ErrResourceNotFound) {
continue
}
if err != nil {
return checked, fmt.Errorf("read %s: %w", definition.Kind, err)
}
checked++
if _, err := definition.Decode(resource.Value); err != nil {
failures = append(failures, fmt.Errorf("%s at version %d: %w", definition.Kind, resource.Version, err))
}
}
return checked, errors.Join(failures...)
}
func validateAs[T any](input []byte, validate func(T) error) error {
var value T
decoder := json.NewDecoder(bytes.NewReader(input))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&value); err != nil {
return err
}
return validate(value)
}