feat(archie): add container runtime, migrate command, secret files, and proxy egress

This commit is contained in:
sam committed 2026-11-27 20:36:52 +11:00
1 parent 7630a14705
commit 86b89a5957
13 files changed
+803 -61

No files matched your search

+128 -12
View File
@@ -9,6 +9,7 @@ import (
"path/filepath"
"regexp"
"strings"
"time"
"filippo.io/age"
"github.com/BurntSushi/toml"
@@ -16,6 +17,8 @@ import (
"github.com/samcharles93/archie-core/internal/platform/deletions"
)
const defaultShutdownGrace = 30 * time.Second
// Config is the bootstrap configuration: only what the binary needs before it
// can reach its database. Everything else is a setting in the control plane.
type Config struct {
@@ -37,10 +40,14 @@ type Config struct {
// directory, and a relative path is refused: the restore that reads this
// directory runs as another process.
StateDir string `toml:"state_dir"`
// ShutdownGraceRaw sets how long SIGTERM waits for active requests to finish.
ShutdownGraceRaw string `toml:"shutdown_grace"`
ShutdownGrace time.Duration `toml:"-"`
}
// DatabaseConfig holds the two connection URLs. The owner runs migrations at
// boot and nothing else; the runtime URL never holds DDL rights.
// boot (or via `archie migrate`) and nothing else; the runtime URL never holds
// DDL rights.
type DatabaseConfig struct {
URL string `toml:"url"`
OwnerURL string `toml:"owner_url"`
@@ -54,6 +61,9 @@ var adminLine = regexp.MustCompile(`(?m)^\s*admin_token_sha256\s*=.*$`)
// every other line. The hash is the only value written: the old token and the
// old hash are never read back or logged.
func WriteAdminHash(path, hash string) error {
if path == "" {
return errors.New("admin token cannot be rotated in place without a config file path")
}
if !adminHash.MatchString(hash) {
return errors.New("an admin token hash is a hex SHA-256")
}
@@ -145,23 +155,118 @@ func NewAgeIdentity(w io.Writer) error {
return err
}
// LoadConfig reads and validates the bootstrap config at path.
// LoadConfig reads and validates the bootstrap config at path (when non-empty)
// and applies ARCHIE_* and ARCHIE_*_FILE environment overrides.
func LoadConfig(path string) (Config, error) {
cfg := Config{Listen: "127.0.0.1:8080", StateDir: DefaultStateDir()}
if _, err := toml.DecodeFile(path, &cfg); err != nil {
return Config{}, fmt.Errorf("read config %s: %w", path, err)
cfg := Config{
Listen: "127.0.0.1:8080",
StateDir: DefaultStateDir(),
ShutdownGrace: defaultShutdownGrace,
}
if err := decodeConfig(path, &cfg); err != nil {
return Config{}, err
}
if cfg.ShutdownGraceRaw != "" {
d, err := time.ParseDuration(cfg.ShutdownGraceRaw)
if err != nil || d <= 0 {
return Config{}, fmt.Errorf("config %s: shutdown_grace must be a positive duration", configLabel(path))
}
cfg.ShutdownGrace = d
}
dir, err := deletions.Dir(cfg.StateDir)
if err != nil {
return Config{}, fmt.Errorf("config %s: %w", path, err)
return Config{}, fmt.Errorf("config %s: %w", configLabel(path), err)
}
cfg.StateDir = dir
if err := cfg.validate(); err != nil {
return Config{}, fmt.Errorf("config %s: %w", path, err)
return Config{}, fmt.Errorf("config %s: %w", configLabel(path), err)
}
return cfg, nil
}
// LoadMigrateConfig loads only the database configuration required by `archie
// migrate`, so migration jobs never need runtime sealing keys or admin hashes.
func LoadMigrateConfig(path string) (DatabaseConfig, error) {
var cfg Config
if err := decodeConfig(path, &cfg); err != nil {
return DatabaseConfig{}, err
}
if err := cfg.Database.validateMigrate(); err != nil {
return DatabaseConfig{}, fmt.Errorf("config %s: %w", configLabel(path), err)
}
return cfg.Database, nil
}
func decodeConfig(path string, cfg *Config) error {
if path != "" {
if _, err := toml.DecodeFile(path, cfg); err != nil {
return fmt.Errorf("read config %s: %w", path, err)
}
}
if err := applyEnv(cfg); err != nil {
return fmt.Errorf("config %s: %w", configLabel(path), err)
}
return nil
}
func applyEnv(cfg *Config) error {
overrides := []struct {
envKey string
fileKey string
target *string
}{
{envKey: "ARCHIE_LISTEN", target: &cfg.Listen},
{envKey: "ARCHIE_STATE_DIR", target: &cfg.StateDir},
{envKey: "ARCHIE_DATABASE_URL", fileKey: "ARCHIE_DATABASE_URL_FILE", target: &cfg.Database.URL},
{envKey: "ARCHIE_DATABASE_OWNER_URL", fileKey: "ARCHIE_DATABASE_OWNER_URL_FILE", target: &cfg.Database.OwnerURL},
{envKey: "ARCHIE_AGE_IDENTITY", fileKey: "ARCHIE_AGE_IDENTITY_FILE", target: &cfg.AgeIdentity},
{envKey: "ARCHIE_ADMIN_TOKEN_SHA256", fileKey: "ARCHIE_ADMIN_TOKEN_SHA256_FILE", target: &cfg.AdminTokenSHA256},
{envKey: "ARCHIE_SHUTDOWN_GRACE", target: &cfg.ShutdownGraceRaw},
}
for _, o := range overrides {
val, ok, err := envOrFile(o.envKey, o.fileKey)
if err != nil {
return err
}
if ok {
*o.target = val
}
}
return nil
}
func envOrFile(envKey, fileKey string) (string, bool, error) {
val, hasEnv := os.LookupEnv(envKey)
val = strings.TrimSpace(val)
var filePath string
var hasFile bool
if fileKey != "" {
filePath, hasFile = os.LookupEnv(fileKey)
filePath = strings.TrimSpace(filePath)
}
if hasEnv && val != "" && hasFile && filePath != "" {
return "", false, fmt.Errorf("set either %s or %s, not both", envKey, fileKey)
}
if hasFile && filePath != "" {
raw, err := os.ReadFile(filePath) //nolint:gosec // operator-configured *_FILE secret path
if err != nil {
return "", false, fmt.Errorf("read %s (%s): %w", fileKey, filePath, err)
}
return strings.TrimSpace(string(raw)), true, nil
}
if hasEnv && val != "" {
return val, true, nil
}
return "", false, nil
}
func configLabel(path string) string {
if path == "" {
return "env"
}
return path
}
func (c Config) validate() error {
var errs []error
if c.Listen == "" {
@@ -170,10 +275,10 @@ func (c Config) validate() error {
if c.Database.URL == "" {
errs = append(errs, errors.New("database.url is required"))
}
// The owner URL has no fallback to the runtime URL: a runtime connection
// that can run DDL defeats the role split.
if c.Database.OwnerURL == "" {
errs = append(errs, errors.New("database.owner_url is required"))
// OwnerURL is optional in serving mode (migrations run out-of-band via
// `archie migrate`). When set, it must still name a distinct DDL role.
if c.Database.URL != "" && c.Database.OwnerURL != "" && c.Database.URL == c.Database.OwnerURL {
errs = append(errs, errors.New("database.url and database.owner_url must name different roles"))
}
if c.AgeIdentity == "" {
errs = append(errs, errors.New("age_identity is required"))
@@ -181,7 +286,18 @@ func (c Config) validate() error {
if !adminHash.MatchString(c.AdminTokenSHA256) {
errs = append(errs, errors.New("admin_token_sha256 must be a hex SHA-256"))
}
if c.Database.URL != "" && c.Database.URL == c.Database.OwnerURL {
return errors.Join(errs...)
}
func (d DatabaseConfig) validateMigrate() error {
var errs []error
if d.URL == "" {
errs = append(errs, errors.New("database.url is required"))
}
if d.OwnerURL == "" {
errs = append(errs, errors.New("database.owner_url is required"))
}
if d.URL != "" && d.OwnerURL != "" && d.URL == d.OwnerURL {
errs = append(errs, errors.New("database.url and database.owner_url must name different roles"))
}
return errors.Join(errs...)
+72
View File
@@ -5,6 +5,9 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"filippo.io/age"
)
// TestWriteAdminHashReplacesOnlyTheHash guards token rotation: the config keeps
@@ -63,3 +66,72 @@ func TestWriteAdminHashAddsAMissingLine(t *testing.T) {
t.Fatal("the hash was not added")
}
}
// TestLoadConfigRuntimeAndEnvFiles guards containerised secret injection and
// DML-only serving mode where owner_url is omitted from the runtime pod.
func TestLoadConfigRuntimeAndEnvFiles(t *testing.T) {
id, err := age.GenerateX25519Identity()
if err != nil {
t.Fatal(err)
}
const adminSHA = "4444444444444444444444444444444444444444444444444444444444444444"
const wantDBURL = "postgres://archie_app:pass@db:5432/archie?sslmode=verify-full" //nolint:gosec // test fixture DSN without real credentials
dir := t.TempDir()
dbFile := filepath.Join(dir, "db_url")
ageFile := filepath.Join(dir, "age_key")
stateDir := filepath.Join(dir, "state")
if err := os.WriteFile(dbFile, []byte(wantDBURL+"\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(ageFile, []byte(id.String()+"\n"), 0o600); err != nil {
t.Fatal(err)
}
t.Setenv("ARCHIE_LISTEN", "0.0.0.0:8080")
t.Setenv("ARCHIE_STATE_DIR", stateDir)
t.Setenv("ARCHIE_DATABASE_URL_FILE", dbFile)
t.Setenv("ARCHIE_AGE_IDENTITY_FILE", ageFile)
t.Setenv("ARCHIE_ADMIN_TOKEN_SHA256", adminSHA)
t.Setenv("ARCHIE_SHUTDOWN_GRACE", "45s")
cfg, err := LoadConfig("")
if err != nil {
t.Fatalf("LoadConfig from env: %v", err)
}
if cfg.Database.OwnerURL != "" {
t.Fatalf("OwnerURL = %q, want empty in runtime-only mode", cfg.Database.OwnerURL)
}
if cfg.Database.URL != wantDBURL {
t.Fatalf("Database.URL = %q", cfg.Database.URL)
}
if cfg.ShutdownGrace != 45*time.Second {
t.Fatalf("ShutdownGrace = %s, want 45s", cfg.ShutdownGrace)
}
// Setting both ENV and ENV_FILE must fail loudly rather than picking one silently.
t.Setenv("ARCHIE_DATABASE_URL", "postgres://other@db:5432/archie")
if _, err := LoadConfig(""); err == nil || !strings.Contains(err.Error(), "not both") {
t.Fatalf("expected ambiguity error, got %v", err)
}
}
// TestLoadMigrateConfigRequiresOnlyDatabaseRoles guards migration jobs running
// without runtime sealing keys or bootstrap admin hashes.
func TestLoadMigrateConfigRequiresOnlyDatabaseRoles(t *testing.T) {
t.Setenv("ARCHIE_DATABASE_URL", "postgres://archie_app:pass@db:5432/archie")
t.Setenv("ARCHIE_DATABASE_OWNER_URL", "postgres://archie_owner:pass@db:5432/archie")
dbCfg, err := LoadMigrateConfig("")
if err != nil {
t.Fatalf("LoadMigrateConfig: %v", err)
}
if dbCfg.OwnerURL == "" || dbCfg.URL == "" {
t.Fatalf("unexpected empty DB config: %+v", dbCfg)
}
t.Setenv("ARCHIE_DATABASE_OWNER_URL", dbCfg.URL)
if _, err := LoadMigrateConfig(""); err == nil {
t.Fatal("expected error when owner_url matches url")
}
}
+4 -3
View File
@@ -24,9 +24,10 @@ const (
// What stopped operations from starting. Readiness reports the stage; the error
// text stays in the log, since it can name hosts, roles and tables.
const (
stageSetupRead = "cannot read whether owner setup is required"
stageStartup = "starting operations failed"
stageMigrate = "migrating the database failed"
stageSetupRead = "cannot read whether owner setup is required"
stageStartup = "starting operations failed"
stageMigrate = "migrating the database failed"
stageSchemaVerify = "verifying the database schema failed"
)
// How long a failed boot step waits before it runs again. The delay doubles up
+49 -14
View File
@@ -14,6 +14,7 @@ import (
"os"
"path/filepath"
"strconv"
"sync/atomic"
"time"
"github.com/google/uuid"
@@ -42,12 +43,21 @@ import (
"github.com/samcharles93/archie-core/ui"
)
const shutdownGrace = 10 * time.Second
// deletionRecordRetry is how often an incomplete record of a committed deletion
// is retried.
const deletionRecordRetry = 30 * time.Second
// Migrate applies embedded database migrations and grants runtime DML privileges
// using database.owner_url, then exits.
func Migrate(ctx context.Context, configPath string) error {
log := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With("service", "archie", "version", buildinfo.Version)
dbCfg, err := LoadMigrateConfig(configPath)
if err != nil {
return err
}
return pg.Migrate(ctx, log, dbCfg.OwnerURL, dbCfg.URL, schemas)
}
// Run boots the binary from the config at configPath and blocks until ctx ends
// or the server fails.
//
@@ -78,10 +88,17 @@ func Run(ctx context.Context, configPath string) error {
}
defer holdServe()
// Nothing is served yet, so there is no readiness to report while this retries.
migrate := func(ctx context.Context) error {
return pg.Migrate(ctx, log, cfg.Database.OwnerURL, cfg.Database.URL, schemas)
stage := stageMigrate
if cfg.Database.OwnerURL == "" {
stage = stageSchemaVerify
}
if err := retryStartup(ctx, log, func(string) {}, stageMigrate, migrate); err != nil {
migrateOrVerify := func(ctx context.Context) error {
if cfg.Database.OwnerURL != "" {
return pg.Migrate(ctx, log, cfg.Database.OwnerURL, cfg.Database.URL, schemas)
}
return pg.VerifySchema(ctx, db)
}
if err := retryStartup(ctx, log, func(string) {}, stage, migrateOrVerify); err != nil {
_ = db.Close()
return err
}
@@ -104,7 +121,8 @@ func Run(ctx context.Context, configPath string) error {
} else if applied > 0 {
log.WarnContext(ctx, "applied the record of deletions", "notes", applied)
}
b, err := wire(log, configPath, cfg, db) //nolint:contextcheck // the API's guard derives its context from each request
var draining atomic.Bool
b, err := wire(log, configPath, cfg, db, &draining) //nolint:contextcheck // the API's guard derives its context from each request
if err != nil {
_ = db.Close()
return err
@@ -121,7 +139,7 @@ func Run(ctx context.Context, configPath string) error {
close(started)
}()
serveErr := serve(work, log, cfg.Listen, b.served)
serveErr := serve(work, log, cfg.Listen, cfg.ShutdownGrace, &draining, b.served)
stop()
<-started
// Every loop activation began has returned before the caller closes the
@@ -145,9 +163,8 @@ type binary struct {
// wire builds every module and registers its routes. Nothing operational
// starts here: the routes are wired on a mux the gate holds back, and Start
// brings them up once owner setup has committed.
func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary, error) {
checks := health.NewRegistry()
checks.Register("database", db.PingContext)
func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB, draining *atomic.Bool) (*binary, error) {
checks := newHealthChecks(db, draining)
runtime.RegisterBuiltinClasses()
settings := governance.NewModule(db, log.With("module", "governance"), orgID)
@@ -215,12 +232,14 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary
return nil, fmt.Errorf("prepare the deletion record: %w", err)
}
remember := memory.NewModule(db, orgID, log.With("module", "memory"), ledger)
checks.Register("deletion record", func(context.Context) error {
deletionCheck := func(context.Context) error {
if remember.RecordPending() {
return errors.New("a deletion is committed and its record is still being written")
}
return nil
})
}
checks.RegisterStartup("deletion record", deletionCheck)
checks.Register("deletion record", deletionCheck)
proposed := proposals.NewModule(db, log.With("module", "proposals"), orgID, hear, engine, policies, judge)
// A cause that keeps recurring becomes a root-cause proposal.
remember.UseProposals(proposed)
@@ -247,6 +266,19 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary
}, nil
}
func newHealthChecks(db *sqlx.DB, draining *atomic.Bool) *health.Registry {
checks := health.NewRegistry()
checks.RegisterStartup("database", db.PingContext)
checks.Register("database", db.PingContext)
checks.Register("shutdown", func(context.Context) error {
if draining != nil && draining.Load() {
return errors.New("shutting down")
}
return nil
})
return checks
}
// close stops the connectors and then the database.
func (b *binary) close() {
b.conns.Close()
@@ -319,7 +351,7 @@ func owner() string {
return host + ":" + strconv.Itoa(os.Getpid())
}
func serve(ctx context.Context, log *slog.Logger, addr string, handler http.Handler) error {
func serve(ctx context.Context, log *slog.Logger, addr string, grace time.Duration, draining *atomic.Bool, handler http.Handler) error {
var lc net.ListenConfig
listener, err := lc.Listen(ctx, "tcp", addr)
if err != nil {
@@ -339,7 +371,10 @@ func serve(ctx context.Context, log *slog.Logger, addr string, handler http.Hand
return fmt.Errorf("serve: %w", err)
case <-ctx.Done():
}
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownGrace)
if draining != nil {
draining.Store(true)
}
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), grace)
defer cancel()
if err := server.Shutdown(shutdownCtx); err != nil && !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("shut down: %w", err)
+54 -20
View File
@@ -1,5 +1,5 @@
// Package health serves liveness and readiness. Each module registers the
// check that says whether it can do its work.
// Package health serves liveness, startup, and readiness. Each module
// registers the check that says whether it can do its work.
package health
import (
@@ -14,47 +14,74 @@ import (
// Check reports whether one part of the binary is ready.
type Check func(context.Context) error
// Registry holds the named readiness checks.
// Registry holds the named startup and readiness checks.
type Registry struct {
mu sync.RWMutex
checks map[string]Check
mu sync.RWMutex
checks map[string]Check
startup map[string]Check
}
// NewRegistry returns an empty registry.
func NewRegistry() *Registry {
return &Registry{checks: map[string]Check{}}
return &Registry{
checks: map[string]Check{},
startup: map[string]Check{},
}
}
// Register adds or replaces the check for name.
// Register adds or replaces the readiness check for name.
func (r *Registry) Register(name string, check Check) {
r.mu.Lock()
defer r.mu.Unlock()
r.checks[name] = check
}
// Routes adds /healthz and /readyz to mux.
// RegisterStartup adds or replaces the startup check for name. Startup checks
// run on /startupz independently of operational readiness checks such as owner
// setup.
func (r *Registry) RegisterStartup(name string, check Check) {
r.mu.Lock()
defer r.mu.Unlock()
r.startup[name] = check
}
// Routes adds /healthz, /startupz, and /readyz to mux.
func (r *Registry) Routes(mux *http.ServeMux) {
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok\n"))
})
mux.HandleFunc("GET /readyz", r.ready)
mux.HandleFunc("GET /startupz", func(w http.ResponseWriter, req *http.Request) {
writeProbe(w, req, r.StartupResults)
})
mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, req *http.Request) {
writeProbe(w, req, r.Results)
})
}
// Result is the outcome of one readiness check; Error is empty when it passed.
// Result is the outcome of one check; Error is empty when it passed.
type Result struct {
Name string `json:"name"`
Error string `json:"error,omitzero"`
}
// Results runs every check and returns the outcomes in name order. A failing
// check does not stop the others.
// Results runs every readiness check and returns the outcomes in name order. A
// failing check does not stop the others.
func (r *Registry) Results(ctx context.Context) []Result {
names := r.names()
return r.run(ctx, false)
}
// StartupResults runs every startup check and returns the outcomes in name order.
func (r *Registry) StartupResults(ctx context.Context) []Result {
return r.run(ctx, true)
}
func (r *Registry) run(ctx context.Context, startup bool) []Result {
names := r.names(startup)
out := make([]Result, 0, len(names))
for _, name := range names {
res := Result{Name: name}
if err := r.check(name)(ctx); err != nil {
if err := r.check(name, startup)(ctx); err != nil {
res.Error = err.Error()
}
out = append(out, res)
@@ -62,12 +89,12 @@ func (r *Registry) Results(ctx context.Context) []Result {
return out
}
func (r *Registry) ready(w http.ResponseWriter, req *http.Request) {
func writeProbe(w http.ResponseWriter, req *http.Request, run func(context.Context) []Result) {
ctx, cancel := context.WithTimeout(req.Context(), 5*time.Second)
defer cancel()
failures := map[string]string{}
for _, res := range r.Results(ctx) {
for _, res := range run(ctx) {
if res.Error != "" {
failures[res.Name] = res.Error
}
@@ -79,19 +106,26 @@ func (r *Registry) ready(w http.ResponseWriter, req *http.Request) {
_ = json.MarshalWrite(w, map[string]any{"ready": len(failures) == 0, "failures": failures})
}
func (r *Registry) names() []string {
func (r *Registry) names(startup bool) []string {
r.mu.RLock()
defer r.mu.RUnlock()
names := make([]string, 0, len(r.checks))
for name := range r.checks {
src := r.checks
if startup {
src = r.startup
}
names := make([]string, 0, len(src))
for name := range src {
names = append(names, name)
}
sort.Strings(names)
return names
}
func (r *Registry) check(name string) Check {
func (r *Registry) check(name string, startup bool) Check {
r.mu.RLock()
defer r.mu.RUnlock()
if startup {
return r.startup[name]
}
return r.checks[name]
}
+51
View File
@@ -0,0 +1,51 @@
package health
import (
"context"
json "encoding/json/v2"
"errors"
"net/http"
"net/http/httptest"
"testing"
)
// TestProbesSeparateStartupFromReadiness guards /startupz returning 200 once
// core boot checks pass even while /readyz waits on owner setup or drains.
func TestProbesSeparateStartupFromReadiness(t *testing.T) {
reg := NewRegistry()
reg.RegisterStartup("database", func(context.Context) error { return nil })
reg.Register("database", func(context.Context) error { return nil })
reg.Register("setup", func(context.Context) error { return errors.New("owner setup is incomplete") })
mux := http.NewServeMux()
reg.Routes(mux)
for _, tc := range []struct {
path string
status int
ready bool
}{
{path: "/healthz", status: http.StatusOK},
{path: "/startupz", status: http.StatusOK, ready: true},
{path: "/readyz", status: http.StatusServiceUnavailable, ready: false},
} {
req := httptest.NewRequestWithContext(context.Background(), http.MethodGet, tc.path, nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
if rec.Code != tc.status {
t.Fatalf("%s: status = %d, want %d", tc.path, rec.Code, tc.status)
}
if tc.path == "/healthz" {
continue
}
var body struct {
Ready bool `json:"ready"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("%s: decode body: %v", tc.path, err)
}
if body.Ready != tc.ready {
t.Fatalf("%s: ready = %v, want %v", tc.path, body.Ready, tc.ready)
}
}
}
+63
View File
@@ -9,6 +9,9 @@ import (
"fmt"
"io/fs"
"log/slog"
"slices"
"strconv"
"strings"
"github.com/jackc/pgx/v5"
// Registers the "pgx" database/sql driver that sqlx and goose use.
@@ -121,9 +124,69 @@ func grantRuntime(ctx context.Context, db *sqlx.DB, runtimeURL string, schemas [
}
}
}
if _, err := db.ExecContext(ctx, "GRANT SELECT ON TABLE public.goose_db_version TO "+role); err != nil {
return fmt.Errorf("grant runtime role on goose_db_version: %w", err)
}
return nil
}
// VerifySchema checks that every embedded migration has been applied to db.
// Serving processes without DDL credentials call this at boot and refuse to
// serve if migrations are pending.
func VerifySchema(ctx context.Context, db *sqlx.DB) error {
embedded, err := embeddedMigrationVersions()
if err != nil {
return err
}
var applied []int64
if err := db.SelectContext(ctx, &applied, "SELECT version_id FROM public.goose_db_version WHERE is_applied"); err != nil {
return fmt.Errorf("read schema version (has 'archie migrate' run?): %w", err)
}
missing := missingMigrations(embedded, applied)
if len(missing) > 0 {
return fmt.Errorf("database schema is behind by %d migration(s) (next missing: %d); run 'archie migrate'", len(missing), missing[0])
}
return nil
}
func embeddedMigrationVersions() ([]int64, error) {
entries, err := fs.ReadDir(migrationFiles, "migrations")
if err != nil {
return nil, fmt.Errorf("read embedded migrations: %w", err)
}
var versions []int64
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
continue
}
prefix, _, ok := strings.Cut(entry.Name(), "_")
if !ok {
return nil, fmt.Errorf("migration %q has no version prefix", entry.Name())
}
v, err := strconv.ParseInt(prefix, 10, 64)
if err != nil {
return nil, fmt.Errorf("parse migration %q version: %w", entry.Name(), err)
}
versions = append(versions, v)
}
slices.Sort(versions)
return versions, nil
}
func missingMigrations(embedded, applied []int64) []int64 {
seen := make(map[int64]struct{}, len(applied))
for _, v := range applied {
seen[v] = struct{}{}
}
var missing []int64
for _, v := range embedded {
if _, ok := seen[v]; !ok {
missing = append(missing, v)
}
}
return missing
}
// ServeLockKey is the advisory-lock key the serving processes hold in its shared
// form and a restore takes exclusively: several processes may serve at once, and
// none may serve while a restore runs. The other archie binaries lock the same
+43
View File
@@ -0,0 +1,43 @@
package pg
import (
"slices"
"testing"
)
func TestEmbeddedMigrationVersions(t *testing.T) {
versions, err := embeddedMigrationVersions()
if err != nil {
t.Fatalf("embeddedMigrationVersions: %v", err)
}
if len(versions) == 0 {
t.Fatal("expected at least one embedded migration")
}
if !slices.IsSorted(versions) {
t.Fatalf("versions not sorted: %v", versions)
}
}
// TestMissingMigrations guards schema verification for DML-only serving pods.
func TestMissingMigrations(t *testing.T) {
embedded := []int64{1, 2, 3}
tests := []struct {
name string
applied []int64
want []int64
}{
{name: "up to date", applied: []int64{1, 2, 3}, want: nil},
{name: "ahead with extra history", applied: []int64{1, 2, 3, 4}, want: nil},
{name: "pending tail migration", applied: []int64{1, 2}, want: []int64{3}},
{name: "missing middle migration", applied: []int64{1, 3}, want: []int64{2}},
{name: "empty database", applied: nil, want: []int64{1, 2, 3}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := missingMigrations(embedded, tc.applied)
if !slices.Equal(got, tc.want) {
t.Fatalf("missingMigrations(%v, %v) = %v, want %v", embedded, tc.applied, got, tc.want)
}
})
}
}