feat(config): runtime config overlay store and PATCH /api/config
The second half of #348's storage layer: dashboard-edited overrides live in their own SQLite file, separate from the task and conversation stores so each file owns its user_version and migrator with no contention (configDBPath -> cfg.DBPath + "-config.sqlite", matching the taskDBPath / conversationDBPath convention). Store (internal/infrastructure/configuration/overlay): - config_overlay(key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at, updated_by), own migration, WAL. - Set refuses DeniedKeys (db_path, work_dir) at write time as well as at the API layer; the map is exported so the dashboard can show the reason instead of silently omitting the edit affordance. - Snapshot JSON-decodes each value and nests dotted keys ("budgets.max_steps" -> map[b][m]) ready to decode into Config. Loader (ApplyOverlay / ApplyOverlayValues): - Decodes a nested overlay map with the same field-level precedence as a file overlay, records the runtime-overlay origin, then applies defaults and validates. Used at boot, on SIGHUP reload (ReloadController gained an optional WithOverlay source) and by the PATCH path. Boot and reload: - A broken overlay (unopenable store, unreadable snapshot, values that fail validation) degrades to file config alone -- it must never brick the daemon. --no-config-overlay / ARCHIE_SKIP_CONFIG_OVERLAY=1 skips the store entirely; the flag is now a real gate, not a log-only stub. PATCH /api/config (webui): - handleConfigUpdate decodes {"updates": {dotted.key: value}}, calls the composition-wired UpdateConfig seam, and classifies errors via webui sentinels: ErrConfigUpdateInvalid -> 400 (denylisted key, failed validation, unparseable value), ErrConfigUpdateUnavailable -> 503 (overlay skipped by recovery flag), anything else -> 500. - The seam (main.go) applies updates to a COPY of the published config, validates the materialised result, persists to the overlay, then publishes through the same path as reload -- it never calls Set directly from the handler, since web.Cfg is the daemon's own Holder. - ConfigView gains Locked (dotted key -> reason) so the UI disables denylisted rows explicitly. Verified: task check clean; new tests cover the store round-trip, denied keys, loader overlay layering/validation/provenance, reload with and without overlay, and the PATCH handler's 200/400/503 paths.
This commit is contained in:
1 parent
31fdbddd61
commit
da2d93a830
11 files changed
+796
-14
No files matched your search
+102
-14
@@ -43,6 +43,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/forgerpc"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
@@ -293,6 +294,15 @@ func taskDBPath(configuredPath string) string {
|
||||
return configuredPath + "-tasks.sqlite"
|
||||
}
|
||||
|
||||
// configDBPath resolves the runtime config overlay file. It is a sibling
|
||||
// of the task and conversation stores (same configured path, own suffix)
|
||||
// so each file owns its user_version and its migrator with no
|
||||
// contention; recovery from a broken overlay is rm this file plus the
|
||||
// --no-config-overlay boot flag.
|
||||
func configDBPath(configuredPath string) string {
|
||||
return configuredPath + "-config.sqlite"
|
||||
}
|
||||
|
||||
func manualRequeueTask(ctx context.Context, st store.TaskStore, taskID int64) error {
|
||||
task, err := st.TaskByID(ctx, taskID)
|
||||
if err != nil {
|
||||
@@ -323,7 +333,8 @@ func run() int {
|
||||
log := slog.New(slog.NewJSONHandler(os.Stderr, nil))
|
||||
|
||||
loader := configuration.New(log)
|
||||
if *noConfigOverlay || configuration.SkipOverlay() {
|
||||
skipOverlay := *noConfigOverlay || configuration.SkipOverlay()
|
||||
if skipOverlay {
|
||||
log.Info("runtime config overlay disabled (recovery hatch); booting on file config alone")
|
||||
}
|
||||
doc, err := loader.Resolve(*cfgPath, *overlayPath)
|
||||
@@ -331,6 +342,32 @@ func run() int {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
return 1
|
||||
}
|
||||
// Runtime config overlay: dashboard-edited overrides layered over the
|
||||
// file config from their own SQLite file (own user_version and
|
||||
// migrator, no contention with the task store). Skipped under
|
||||
// --no-config-overlay / ARCHIE_SKIP_CONFIG_OVERLAY=1, or when the
|
||||
// store cannot be opened or its values fail validation -- a broken
|
||||
// overlay must not brick the daemon.
|
||||
var overlayStore *overlay.Store
|
||||
if !skipOverlay {
|
||||
overlayStore, err = overlay.Open(ctx, configDBPath(doc.Config.DBPath))
|
||||
if err != nil {
|
||||
log.Error("config overlay unavailable; booting on file config alone", "path", configDBPath(doc.Config.DBPath), "err", err)
|
||||
} else {
|
||||
defer overlayStore.Close()
|
||||
if overrides, err := overlayStore.Snapshot(ctx); err != nil {
|
||||
log.Error("config overlay unreadable; booting on file config alone", "err", err)
|
||||
} else if len(overrides) > 0 {
|
||||
next := *doc
|
||||
applied, err := loader.ApplyOverlay(&next, overrides)
|
||||
if err != nil {
|
||||
log.Error("config overlay rejected by validation; booting on file config alone", "err", err)
|
||||
} else {
|
||||
doc = applied
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cfg := doc.Config
|
||||
|
||||
// Re-create the logger now the config is known. Everything above this
|
||||
@@ -986,11 +1023,28 @@ func run() int {
|
||||
// published config.
|
||||
web.Cfg = d.Cfg
|
||||
|
||||
// SIGHUP re-loads the config from disk and republishes it. The apply
|
||||
// closure swaps the daemon's Holder and the dashboard's provenance;
|
||||
// the reload log warns about changed fields that require a restart, so
|
||||
// an operator never has to read the source to find out whether their
|
||||
// edit took effect. web.LastReload exposes the outcome to /api/config.
|
||||
// publishConfig publishes a config snapshot and its provenance to
|
||||
// both the daemon and the dashboard (they share one Holder). Reload
|
||||
// and the PATCH path both go through it, so the two can never
|
||||
// diverge. currentProvenance is the last published provenance chain;
|
||||
// the PATCH path appends the runtime-overlay origin to it.
|
||||
currentProvenance := doc.Provenance
|
||||
publishConfig := func(cfg config.Config, provenance configuration.Provenance) {
|
||||
d.Cfg.Set(cfg)
|
||||
origins := make([]webui.ConfigOrigin, 0, len(provenance.Origins))
|
||||
for _, origin := range provenance.Origins {
|
||||
origins = append(origins, webui.ConfigOrigin{
|
||||
Path: origin.Path, Role: string(origin.Role), Layer: string(origin.Layer), Feature: string(origin.Feature),
|
||||
})
|
||||
}
|
||||
web.SetProvenance(origins)
|
||||
}
|
||||
|
||||
// SIGHUP re-loads the config from disk, layers the runtime overlay,
|
||||
// and republishes it. The reload log warns about changed fields that
|
||||
// require a restart, so an operator never has to read the source to
|
||||
// find out whether their edit took effect. web.LastReload exposes
|
||||
// the outcome to /api/config.
|
||||
reloadController := newReloadController(loader, *cfgPath, *overlayPath, func(doc *configuration.Document) {
|
||||
// Boot merges catalog-discovered providers into cfg before the
|
||||
// Holders are seeded; publishing the raw reloaded document would
|
||||
@@ -999,14 +1053,8 @@ func run() int {
|
||||
// failed to load merges to identity).
|
||||
applyModelCatalog(&doc.Config, catalog)
|
||||
old := d.Cfg.Get()
|
||||
d.Cfg.Set(doc.Config)
|
||||
provenance := make([]webui.ConfigOrigin, 0, len(doc.Provenance.Origins))
|
||||
for _, origin := range doc.Provenance.Origins {
|
||||
provenance = append(provenance, webui.ConfigOrigin{
|
||||
Path: origin.Path, Role: string(origin.Role), Layer: string(origin.Layer), Feature: string(origin.Feature),
|
||||
})
|
||||
}
|
||||
web.SetProvenance(provenance)
|
||||
currentProvenance = doc.Provenance
|
||||
publishConfig(doc.Config, doc.Provenance)
|
||||
if fields := changedNonReloadableFields(old, doc.Config); len(fields) > 0 {
|
||||
log.Warn("config reloaded; some changes require a restart",
|
||||
"fields", fields, "paths", doc.Provenance.Paths())
|
||||
@@ -1014,8 +1062,48 @@ func run() int {
|
||||
log.Info("config reloaded", "paths", doc.Provenance.Paths())
|
||||
}
|
||||
})
|
||||
if overlayStore != nil {
|
||||
reloadController.WithOverlay(func() (map[string]any, error) { return overlayStore.Snapshot(ctx) })
|
||||
}
|
||||
web.LastReload = reloadController.Status
|
||||
|
||||
// PATCH /api/config goes through the same publish path as reload:
|
||||
// apply to a copy of the published config, validate the materialised
|
||||
// result, persist to the overlay, then publish. It must never call
|
||||
// Set directly from the handler -- web.Cfg is the daemon's own Holder.
|
||||
web.UpdateConfig = func(ctx context.Context, updates map[string]any) error {
|
||||
if overlayStore == nil {
|
||||
return fmt.Errorf("%w: config overlay is disabled (--no-config-overlay or ARCHIE_SKIP_CONFIG_OVERLAY=1)", webui.ErrConfigUpdateUnavailable)
|
||||
}
|
||||
for key := range updates {
|
||||
if reason, denied := overlay.DeniedKeys[key]; denied {
|
||||
return fmt.Errorf("%w: config key %s is not runtime-tunable: %s", webui.ErrConfigUpdateInvalid, key, reason)
|
||||
}
|
||||
}
|
||||
next := d.Cfg.Get()
|
||||
if err := configuration.ApplyOverlayValues(&next, updates); err != nil {
|
||||
return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err)
|
||||
}
|
||||
if err := configuration.Validate(&next); err != nil {
|
||||
return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err)
|
||||
}
|
||||
for key, value := range updates {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %v", webui.ErrConfigUpdateInvalid, err)
|
||||
}
|
||||
if err := overlayStore.Set(ctx, key, string(data), "dashboard"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
prov := configuration.Provenance{Origins: append(append([]configuration.Origin{}, currentProvenance.Origins...),
|
||||
configuration.Origin{Path: "config_overlay (runtime)", Role: configuration.RoleMain, Layer: configuration.LayerOverlay})}
|
||||
currentProvenance = prov
|
||||
publishConfig(next, prov)
|
||||
log.Info("config updated from dashboard", "keys", len(updates))
|
||||
return nil
|
||||
}
|
||||
|
||||
reloadCh := make(chan os.Signal, 1)
|
||||
signal.Notify(reloadCh, syscall.SIGHUP)
|
||||
defer signal.Stop(reloadCh)
|
||||
|
||||
@@ -29,6 +29,12 @@ type ReloadController struct {
|
||||
// non-nil; newReloadController requires it.
|
||||
apply func(*configuration.Document)
|
||||
|
||||
// overlayValues, when non-nil, returns the runtime config overlay
|
||||
// (dotted keys -> typed values) to layer over the file config before
|
||||
// publishing. A failed overlay read or validation aborts the reload
|
||||
// exactly like a bad file.
|
||||
overlayValues func() (map[string]any, error)
|
||||
|
||||
status atomic.Pointer[config.ReloadStatus]
|
||||
}
|
||||
|
||||
@@ -51,6 +57,26 @@ func (c *ReloadController) Reload() error {
|
||||
})
|
||||
return err
|
||||
}
|
||||
if c.overlayValues != nil {
|
||||
values, err := c.overlayValues()
|
||||
if err != nil {
|
||||
c.status.Store(&config.ReloadStatus{
|
||||
LastError: err.Error(),
|
||||
LastErrorAt: time.Now().UTC().Format(time.RFC3339),
|
||||
})
|
||||
return err
|
||||
}
|
||||
if len(values) > 0 {
|
||||
next := *doc
|
||||
if doc, err = c.loader.ApplyOverlay(&next, values); err != nil {
|
||||
c.status.Store(&config.ReloadStatus{
|
||||
LastError: err.Error(),
|
||||
LastErrorAt: time.Now().UTC().Format(time.RFC3339),
|
||||
})
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
c.apply(doc)
|
||||
c.status.Store(&config.ReloadStatus{
|
||||
LastReloadAt: time.Now().UTC().Format(time.RFC3339),
|
||||
@@ -58,6 +84,13 @@ func (c *ReloadController) Reload() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// WithOverlay attaches the runtime config overlay source. Optional: a
|
||||
// controller without it publishes the file config alone.
|
||||
func (c *ReloadController) WithOverlay(fn func() (map[string]any, error)) *ReloadController {
|
||||
c.overlayValues = fn
|
||||
return c
|
||||
}
|
||||
|
||||
// Status returns the most recent reload outcome.
|
||||
func (c *ReloadController) Status() config.ReloadStatus {
|
||||
if p := c.status.Load(); p != nil {
|
||||
|
||||
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -105,6 +106,53 @@ func TestReloadValidationFailureDoesNotApply(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReloadAppliesOverlayBeforePublish(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.toml")
|
||||
writeConfig(t, path, minimalConfigTOML("widget"))
|
||||
|
||||
loader := configuration.New(slog.New(slog.DiscardHandler))
|
||||
var published config.Config
|
||||
controller := newReloadController(loader, path, "", func(doc *configuration.Document) {
|
||||
published = doc.Config
|
||||
}).WithOverlay(func() (map[string]any, error) {
|
||||
return map[string]any{"poll_interval": "90s"}, nil
|
||||
})
|
||||
|
||||
if err := controller.Reload(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if published.PollInterval != config.Duration(90*time.Second) {
|
||||
t.Errorf("PollInterval = %v, want 90s (overlay applied before publish)", published.PollInterval)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReloadOverlayFailureAborts pins that a failed overlay read or
|
||||
// validation aborts the reload exactly like a bad file: apply is not
|
||||
// called and the error is recorded.
|
||||
func TestReloadOverlayFailureAborts(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.toml")
|
||||
writeConfig(t, path, minimalConfigTOML("widget"))
|
||||
|
||||
loader := configuration.New(slog.New(slog.DiscardHandler))
|
||||
applied := 0
|
||||
controller := newReloadController(loader, path, "", func(*configuration.Document) { applied++ }).
|
||||
WithOverlay(func() (map[string]any, error) {
|
||||
return nil, errors.New("overlay unreadable")
|
||||
})
|
||||
|
||||
if err := controller.Reload(); err == nil {
|
||||
t.Fatal("expected an error from the failed overlay")
|
||||
}
|
||||
if applied != 0 {
|
||||
t.Fatalf("apply called %d times after overlay failure, want 0", applied)
|
||||
}
|
||||
if st := controller.Status(); st.LastError == "" {
|
||||
t.Fatal("expected LastError recorded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReloadLoopAppliesOnSignalAndStopsOnCancel(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.toml")
|
||||
|
||||
Reference in new issue
Block a user