Files
archie/internal/app/controlplane/registry.go
T
sam 014868eda8 feat(statestore): offline backup, restore, validate and rollback
archie-state-store gains the offline recovery commands
docs/prds/runtime-control-plane.md ("Bootstrap, migration, and recovery")
asks for. They work on the task database file directly -- <db_path>-tasks.sqlite,
not db_path -- and need neither archied nor the Web UI, which matters because
the failure they exist for is the one that stops archied starting:

  backup   -db F -out F     consistent snapshot (VACUUM INTO), verified as a
                            usable store before it is published; safe against
                            a serving store
  restore  -db F -from F    replace the database with a snapshot, dropping the
                            replaced file's -wal/-shm
  validate -db F            readable, not corrupt, schema no newer than this
                            binary, every stored resource decoding under the
                            definition that owns it
  rollback -db F -kind K    replay an earlier revision of a stored resource
           [-revision N]    through the ordinary replace, recorded as a new
                            revision

No rollback RPC is added and none is needed: a revision carries its own value,
so restoring one is the same replace the dashboard and the channels already
use, by hand, with the store stopped.

"The State Store is stopped" is checked rather than assumed. The serving
process now takes an exclusive flock on <db>.lock for its whole life
(store.AcquireOwnership), and restore/rollback refuse with
`task database is owned by another process` while it holds it. backup is the
deliberate exception: the update installer runs inside the process it is
replacing and cannot stop the State Store.

scripts/archie-update-install takes its pre-flight snapshot through
`go run ./cmd/archie-state-store backup` from the release being installed
instead of its own sqlite3 shell, so the installer and an operator run one
implementation. The watchdog's refusal semantics are unchanged: an update that
cannot back up still must not start.

Docs: safe-change-and-recovery.md's "Recovery: not yet built" now describes
what exists.
2026-09-21 22:04:41 +10:00

137 lines
4.3 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 := json.Marshal(definition.Seed(cfg))
if err != nil {
return nil, fmt.Errorf("seed %s: %w", definition.Kind, err)
}
value, err = definition.Decode(value)
if err != nil {
return nil, fmt.Errorf("seed %s: %w", definition.Kind, 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
}
// 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.
//
// This is how an offline validate reproduces the refusal that stops archied
// starting: the check is the writer's own, so it cannot drift from what a
// replace would accept, and a value can only be stored unvalidated by bypassing
// the write path entirely.
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)
}