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

+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)
}
})
}
}