package provision
import (
"context"
"database/sql"
"embed"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"time"
"amadan.net/oficina/home/handoff/seal"
"amadan.net/rastrillo/rastrillo/migrate"
_ "modernc.org/sqlite"
)
//go:embed migrations/*.sql
var migrationFS embed.FS
// Schema is Alta's own migration set.
var Schema = migrate.MustFromFS(migrationFS, "alta")
// ErrBusy is the run lock already held.
var ErrBusy = errors.New("provision: another run is advancing")
// Store is Alta's sealed SQLite state.
type Store struct {
db *sql.DB
sealer *seal.Sealer
now func() time.Time
}
// OpenDB opens path with the pragmas Alta's privacy rule needs:
// secure_delete, so a deleted address is overwritten, not left in a free
// page. One writer connection, as SQLite allows one.
func OpenDB(path string) (*sql.DB, error) {
dsn := "file:" + path + "?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)&_pragma=secure_delete(1)&_time_format=sqlite&_timezone=UTC"
db, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(1)
if err := db.Ping(); err != nil {
db.Close()
return nil, err
}
return db, nil
}
// NewStore applies extra (sessions, handoff) and Alta's schema and seals
// with dek (ALTA_DEK, 32 bytes).
func NewStore(ctx context.Context, db *sql.DB, dek []byte, now func() time.Time, extra ...*migrate.Set) (*Store, error) {
if len(dek) != 32 {
return nil, errors.New("provision: ALTA_DEK must be 32 bytes")
}
s, err := seal.New(dek, "oficina/alta")
if err != nil {
return nil, err
}
sets := append([]*migrate.Set{Schema}, extra...)
if _, err := migrate.Apply(ctx, migrate.Pool(db), migrate.Merge(sets...)); err != nil {
return nil, fmt.Errorf("provision: migrate: %w", err)
}
if now == nil {
now = time.Now
}
return &Store{db: db, sealer: s, now: now}, nil
}
func (s *Store) DB() *sql.DB { return s.db }
func (s *Store) seal(purpose string, b []byte) ([]byte, error) { return s.sealer.Seal(purpose, b) }
func (s *Store) open(purpose string, b []byte) ([]byte, error) { return s.sealer.Open(purpose, b) }
// adoptionPurpose admits only alta/adopt/
/: the adoption
// journal seals under ALTA_DEK, and can never open Alta's own rows (the
// owner's address, plans, requests).
func adoptionPurpose(purpose string) error {
rest, ok := strings.CutPrefix(purpose, "alta/adopt/")
table, key, two := strings.Cut(rest, "/")
if !ok || !two || table == "" || key == "" {
return errors.New("provision: not an adoption purpose")
}
return nil
}
// SealAdoption seals an adoption journal payload under purpose, which
// must be alta/adopt/
/.
func (s *Store) SealAdoption(purpose string, b []byte) ([]byte, error) {
if err := adoptionPurpose(purpose); err != nil {
return nil, err
}
return s.seal(purpose, b)
}
// OpenAdoption opens what SealAdoption sealed under the same purpose.
func (s *Store) OpenAdoption(purpose string, b []byte) ([]byte, error) {
if err := adoptionPurpose(purpose); err != nil {
return nil, err
}
return s.open(purpose, b)
}
// ---- teams ----
// Team is one team as Alta holds it. No address.
type Team struct {
Label, Name, Environment string
Forked bool
TeamID int64
TeamSQID string
Epoch int64
Generation string
OwnerRef string
CreatedAt time.Time
Apps map[string]string // app -> active|retired
}
func namePurpose(label string) string { return "alta/team-name/" + label }
func ownerPurpose(label string) string { return "alta/owner/" + label }
// LabelUsed reports whether label was ever used.
func (s *Store) LabelUsed(ctx context.Context, label string) (bool, error) {
var n int
err := s.db.QueryRowContext(ctx, "SELECT count(*) FROM teams WHERE label=?", label).Scan(&n)
return n > 0, err
}
// CreateTeam records a new label, its sealed name, its environment and
// the owner's sealed address, in one transaction.
func (s *Store) CreateTeam(ctx context.Context, label, name, env string, forked bool, owner string, apps []string) error {
sealed, err := s.seal(namePurpose(label), []byte(name))
if err != nil {
return err
}
addr, err := s.seal(ownerPurpose(label), []byte(owner))
if err != nil {
return err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
f := 0
if forked {
f = 1
}
if _, err := tx.ExecContext(ctx, "INSERT INTO teams(label,sealed_name,environment,forked,created_at) VALUES(?,?,?,?,?)", label, sealed, env, f, s.now().Unix()); err != nil {
return fmt.Errorf("provision: label taken: %w", err)
}
if _, err := tx.ExecContext(ctx, "INSERT INTO owner_inputs(label,sealed_address) VALUES(?,?)", label, addr); err != nil {
return err
}
for _, app := range apps {
if _, err := tx.ExecContext(ctx, "INSERT INTO environments(app,environment,label) VALUES(?,?,?)", app, env, label); err != nil {
return fmt.Errorf("provision: environment %s already Alta's for %s: %w", env, app, err)
}
if _, err := tx.ExecContext(ctx, "INSERT INTO team_apps(label,app,state) VALUES(?,?,'active')", label, app); err != nil {
return err
}
}
return tx.Commit()
}
// adoptionApps refuses an empty, unknown or repeated app list.
func adoptionApps(apps []string) error {
if len(apps) == 0 {
return errors.New("provision: an adoption names at least one app")
}
seen := map[string]bool{}
for _, a := range apps {
if _, ok := AppBySlug(a); !ok || seen[a] {
return errors.New("provision: an adoption names an unknown or repeated app")
}
seen[a] = true
}
return nil
}
// CreateAdoption records the existing suite's team, label AdoptionLabel:
// its sealed name, the owner's sealed address and its apps, in one
// transaction. It records no environment, and so no environments row:
// the six instances keep the environments they run in, which Alta never
// created, and the §8 guard admits none of them.
func (s *Store) CreateAdoption(ctx context.Context, name, owner string, apps []string) error {
if err := adoptionApps(apps); err != nil {
return err
}
sealed, err := s.seal(namePurpose(AdoptionLabel), []byte(name))
if err != nil {
return err
}
addr, err := s.seal(ownerPurpose(AdoptionLabel), []byte(owner))
if err != nil {
return err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, "INSERT INTO teams(label,sealed_name,environment,forked,created_at) VALUES(?,?,'',0,?)", AdoptionLabel, sealed, s.now().Unix()); err != nil {
return fmt.Errorf("provision: label taken: %w", err)
}
if _, err := tx.ExecContext(ctx, "INSERT INTO owner_inputs(label,sealed_address) VALUES(?,?)", AdoptionLabel, addr); err != nil {
return err
}
for _, app := range apps {
if _, err := tx.ExecContext(ctx, "INSERT INTO team_apps(label,app,state) VALUES(?,?,'active')", AdoptionLabel, app); err != nil {
return err
}
}
return tx.Commit()
}
// AddAdoptionApps records newly supported canonical apps in the existing
// team. Adoption owns no environments and must never reserve one here.
func (s *Store) AddAdoptionApps(ctx context.Context, apps []string) error {
if err := adoptionApps(apps); err != nil {
return err
}
t, err := s.Team(ctx, AdoptionLabel)
if err != nil {
return err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
for _, app := range apps {
switch t.Apps[app] {
case "retired":
return errors.New("provision: retired adoption app")
case "active":
continue
}
if _, err := tx.ExecContext(ctx, "INSERT INTO team_apps(label,app,state) VALUES(?,?,'active')", AdoptionLabel, app); err != nil {
return err
}
}
return tx.Commit()
}
// AddApps records apps joining a team (an add-apps run). A retired app is
// refused: its hostnames are dead for good.
func (s *Store) AddApps(ctx context.Context, label string, apps []string) error {
t, err := s.Team(ctx, label)
if err != nil {
return err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
for _, app := range apps {
switch t.Apps[app] {
case "retired":
return fmt.Errorf("provision: %s was retired from this team and is never re-added", app)
case "active":
continue
}
if _, err := tx.ExecContext(ctx, "INSERT INTO environments(app,environment,label) VALUES(?,?,?)", app, t.Environment, label); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, "INSERT INTO team_apps(label,app,state) VALUES(?,?,'active')", label, app); err != nil {
return err
}
}
return tx.Commit()
}
// RetireApp marks an app retired.
func (s *Store) RetireApp(ctx context.Context, label, app string) error {
_, err := s.db.ExecContext(ctx, "UPDATE team_apps SET state='retired' WHERE label=? AND app=?", label, app)
return err
}
// Team reads one team.
func (s *Store) Team(ctx context.Context, label string) (Team, error) {
var t Team
var sealed []byte
var forked int
var id, epoch sql.NullInt64
var sqid, gen, owner sql.NullString
var created int64
err := s.db.QueryRowContext(ctx, "SELECT label,sealed_name,environment,forked,team_id,team_sqid,epoch,generation,owner_ref,created_at FROM teams WHERE label=?", label).Scan(&t.Label, &sealed, &t.Environment, &forked, &id, &sqid, &epoch, &gen, &owner, &created)
if err != nil {
return Team{}, err
}
name, err := s.open(namePurpose(label), sealed)
if err != nil {
return Team{}, err
}
t.Name, t.Forked, t.TeamID, t.TeamSQID, t.Epoch, t.Generation, t.OwnerRef = string(name), forked == 1, id.Int64, sqid.String, epoch.Int64, gen.String, owner.String
t.CreatedAt = time.Unix(created, 0)
t.Apps = map[string]string{}
rows, err := s.db.QueryContext(ctx, "SELECT app,state FROM team_apps WHERE label=?", label)
if err != nil {
return Team{}, err
}
defer rows.Close()
for rows.Next() {
var app, state string
if err := rows.Scan(&app, &state); err != nil {
return Team{}, err
}
t.Apps[app] = state
}
return t, rows.Err()
}
// Teams lists every label, newest first.
func (s *Store) Teams(ctx context.Context) ([]Team, error) {
rows, err := s.db.QueryContext(ctx, "SELECT label FROM teams ORDER BY created_at DESC, label")
if err != nil {
return nil, err
}
var labels []string
for rows.Next() {
var l string
if err := rows.Scan(&l); err != nil {
rows.Close()
return nil, err
}
labels = append(labels, l)
}
rows.Close()
var out []Team
for _, l := range labels {
t, err := s.Team(ctx, l)
if err != nil {
return nil, err
}
out = append(out, t)
}
return out, nil
}
// SetSeeded records what seed-team committed.
// SetSeeded records what seed-team committed and marks the team step
// done, in one transaction: a crash between the two would leave a team
// sqid with its step undone, a state the owner-forgetting guard would
// otherwise never see as seeded.
func (s *Store) SetSeeded(ctx context.Context, label string, id int64, sqid string, epoch int64, generation, ownerRef string, step map[string]any) error {
data, err := json.Marshal(step)
if err != nil {
return err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, "UPDATE teams SET team_id=?,team_sqid=?,epoch=?,generation=?,owner_ref=? WHERE label=?", id, sqid, epoch, generation, ownerRef, label); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, "INSERT INTO steps(label,app,step,state,code,data,updated_at) VALUES(?,'',?,'done','',?,?) ON CONFLICT(label,app,step) DO UPDATE SET state='done',code='',data=excluded.data,updated_at=excluded.updated_at", label, StepTeam, string(data), s.now().Unix()); err != nil {
return err
}
return tx.Commit()
}
// ---- owner input ----
// Owner returns the sealed owner address, if Alta still holds it.
func (s *Store) Owner(ctx context.Context, label string) (string, bool, error) {
var sealed []byte
err := s.db.QueryRowContext(ctx, "SELECT sealed_address FROM owner_inputs WHERE label=?", label).Scan(&sealed)
if errors.Is(err, sql.ErrNoRows) {
return "", false, nil
}
if err != nil {
return "", false, err
}
b, err := s.open(ownerPurpose(label), sealed)
if err != nil {
return "", false, err
}
return string(b), true, nil
}
// SetOwner stores a retyped owner address (§4: the stopgap allowlist edit
// after step 13 has Paul retype it, and Alta deletes it again once
// written).
func (s *Store) SetOwner(ctx context.Context, label, addr string) error {
sealed, err := s.seal(ownerPurpose(label), []byte(addr))
if err != nil {
return err
}
_, err = s.db.ExecContext(ctx, "INSERT INTO owner_inputs(label,sealed_address) VALUES(?,?) ON CONFLICT(label) DO UPDATE SET sealed_address=excluded.sealed_address", label, sealed)
return err
}
// ForgetOwner deletes every row that carries the owner's address: the
// owner input, the credential role's plan bytes and every owner-seed
// request (§4, step 13). secure_delete overwrites them.
func (s *Store) ForgetOwner(ctx context.Context, label string) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, "DELETE FROM owner_inputs WHERE label=?", label); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, "DELETE FROM operator_requests WHERE label=? AND action='credential.owner-seed'", label); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, "UPDATE plan_submissions SET sealed_plan=NULL WHERE role='credential' AND plan_id IN (SELECT plan_id FROM runs WHERE label=? AND plan_id IS NOT NULL)", label); err != nil {
return err
}
return tx.Commit()
}
// ---- runs ----
// Run is one (team, plan) run.
type Run struct {
ID int64
Label string
Kind string
Apps []string
PlanID string
PlanExpires int64
State, Code string
Created, Upd time.Time
// Options is the profile and samples choice the run writes recipes
// with (create-team and add-apps; the others record outside).
Options RunOptions
// Adoption marks a run for the existing suite's team (label
// AdoptionLabel), whose instances Alta never created.
Adoption bool
}
// NewRun starts a run. Any unfinished run for the same label is
// superseded: one live plan per team.
func (s *Store) NewRun(ctx context.Context, kind, label string, apps []string, opt RunOptions) (int64, error) {
opt, ok := opt.Normal()
if !ok {
return 0, errors.New("provision: unknown profile")
}
return s.newRun(ctx, kind, label, apps, opt, false)
}
// NewAdoptionRun starts a create-team or add-apps run for the existing
// suite's team, label AdoptionLabel, marked as an adoption. It writes no
// recipe, so it records the default options. Like NewRun, it supersedes
// any unfinished run for the label.
func (s *Store) NewAdoptionRun(ctx context.Context, kind string, apps []string) (int64, error) {
if kind != "create-team" && kind != "add-apps" {
return 0, errors.New("provision: an adoption run is create-team or add-apps")
}
if err := adoptionApps(apps); err != nil {
return 0, err
}
return s.newRun(ctx, kind, AdoptionLabel, apps, RunOptions{Profile: ProfileOutside}, true)
}
func (s *Store) newRun(ctx context.Context, kind, label string, apps []string, opt RunOptions, adoption bool) (int64, error) {
now := s.now().Unix()
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, "UPDATE runs SET state='superseded',updated_at=? WHERE label=? AND kind<>'initialize' AND state IN ('planned','running','parked')", now, label); err != nil {
return 0, err
}
if kind == "initialize" {
if _, err := tx.ExecContext(ctx, "UPDATE runs SET state='superseded',updated_at=? WHERE kind='initialize' AND state IN ('planned','running','parked')", now); err != nil {
return 0, err
}
}
res, err := tx.ExecContext(ctx, "INSERT INTO runs(label,kind,apps,state,created_at,updated_at,profile,samples,adoption) VALUES(?,?,?,'planned',?,?,?,?,?)", label, kind, strings.Join(apps, ","), now, now, string(opt.Profile), opt.Samples, adoption)
if err != nil {
return 0, err
}
id, err := res.LastInsertId()
if err != nil {
return 0, err
}
return id, tx.Commit()
}
func scanRun(sc interface{ Scan(...any) error }) (Run, error) {
var r Run
var apps string
var plan sql.NullString
var exp sql.NullInt64
var c, u int64
var profile string
if err := sc.Scan(&r.ID, &r.Label, &r.Kind, &apps, &plan, &exp, &r.State, &r.Code, &c, &u, &profile, &r.Options.Samples, &r.Adoption); err != nil {
return Run{}, err
}
r.Options.Profile = Profile(profile)
if apps != "" {
r.Apps = strings.Split(apps, ",")
}
r.PlanID, r.PlanExpires, r.Created, r.Upd = plan.String, exp.Int64, time.Unix(c, 0), time.Unix(u, 0)
return r, nil
}
const runCols = "id,label,kind,apps,plan_id,plan_expires_at,state,code,created_at,updated_at,profile,samples,adoption"
func (s *Store) Run(ctx context.Context, id int64) (Run, error) {
return scanRun(s.db.QueryRowContext(ctx, "SELECT "+runCols+" FROM runs WHERE id=?", id))
}
// Runs lists a label's runs, newest first ("" lists initialize runs).
func (s *Store) Runs(ctx context.Context, label string) ([]Run, error) {
rows, err := s.db.QueryContext(ctx, "SELECT "+runCols+" FROM runs WHERE label=? ORDER BY id DESC LIMIT 50", label)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Run
for rows.Next() {
r, err := scanRun(rows)
if err != nil {
return nil, err
}
out = append(out, r)
}
return out, rows.Err()
}
// LastOptions is the options of label's newest create-team or add-apps
// run: what a run continued without a fresh choice writes with. A label
// with none has the default (outside, no samples).
func (s *Store) LastOptions(ctx context.Context, label string) (RunOptions, error) {
r, err := scanRun(s.db.QueryRowContext(ctx, "SELECT "+runCols+" FROM runs WHERE label=? AND kind IN ('create-team','add-apps') ORDER BY id DESC LIMIT 1", label))
if errors.Is(err, sql.ErrNoRows) {
return RunOptions{Profile: ProfileOutside}, nil
}
if err != nil {
return RunOptions{}, err
}
return r.Options, nil
}
// WrittenOptions is the run options app's environment was written with,
// as step 7 recorded them when it finished. ok is false while step 7 is
// not done. A step recorded before options existed reads as outside.
func (s *Store) WrittenOptions(ctx context.Context, label, app string) (RunOptions, bool, error) {
d, ok, err := s.Done(ctx, label, app, StepEnv)
if err != nil || !ok {
return RunOptions{}, false, err
}
opt := RunOptions{Profile: ProfileOutside}
if p, _ := d["profile"].(string); p != "" {
opt.Profile = Profile(p)
}
opt.Samples, _ = d["samples"].(bool)
if opt, ok = opt.Normal(); !ok {
return RunOptions{}, false, errors.New("provision: unknown profile recorded")
}
return opt, true, nil
}
// AppOptions is the choice app runs under when Paul makes none: the one
// its environment was written with (step 7 done), else that of the newest
// create-team or add-apps run naming it, else the default.
func (s *Store) AppOptions(ctx context.Context, label, app string) (RunOptions, error) {
if opt, ok, err := s.WrittenOptions(ctx, label, app); err != nil || ok {
return opt, err
}
rows, err := s.db.QueryContext(ctx, "SELECT "+runCols+" FROM runs WHERE label=? AND kind IN ('create-team','add-apps') ORDER BY id DESC", label)
if err != nil {
return RunOptions{}, err
}
defer rows.Close()
for rows.Next() {
r, err := scanRun(rows)
if err != nil {
return RunOptions{}, err
}
if slices.Contains(r.Apps, app) {
return r.Options, nil
}
}
if err := rows.Err(); err != nil {
return RunOptions{}, err
}
return RunOptions{Profile: ProfileOutside}, nil
}
// LiveRuns lists every run not finished.
func (s *Store) LiveRuns(ctx context.Context) ([]Run, error) {
rows, err := s.db.QueryContext(ctx, "SELECT "+runCols+" FROM runs WHERE state IN ('planned','running','parked') ORDER BY id")
if err != nil {
return nil, err
}
defer rows.Close()
var out []Run
for rows.Next() {
r, err := scanRun(rows)
if err != nil {
return nil, err
}
out = append(out, r)
}
return out, rows.Err()
}
func (s *Store) SetRunState(ctx context.Context, id int64, state, code string) error {
_, err := s.db.ExecContext(ctx, "UPDATE runs SET state=?,code=?,updated_at=? WHERE id=?", state, code, s.now().Unix(), id)
return err
}
func (s *Store) SetRunPlan(ctx context.Context, id int64, planID string, expires int64) error {
_, err := s.db.ExecContext(ctx, "UPDATE runs SET plan_id=?,plan_expires_at=?,state='planned',code='',updated_at=? WHERE id=?", planID, expires, s.now().Unix(), id)
return err
}
// ---- plans ----
// PlanSubmission is one role's copy of a plan.
type PlanSubmission struct {
PlanID, Role, State string
Expires, Window int64
Signed []byte
}
func planPurpose(id, role string) string { return "alta/plan/" + id + "/" + role }
func (s *Store) SavePlan(ctx context.Context, id, role string, signed []byte, expires int64) error {
sealed, err := s.seal(planPurpose(id, role), signed)
if err != nil {
return err
}
_, err = s.db.ExecContext(ctx, "INSERT INTO plan_submissions(plan_id,role,sealed_plan,state,expires_at) VALUES(?,?,?,'signed',?)", id, role, sealed, expires)
return err
}
func (s *Store) Plans(ctx context.Context, id string) (map[string]PlanSubmission, error) {
rows, err := s.db.QueryContext(ctx, "SELECT plan_id,role,sealed_plan,state,expires_at,window_expires_at FROM plan_submissions WHERE plan_id=?", id)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]PlanSubmission{}
for rows.Next() {
var p PlanSubmission
var sealed []byte
var w sql.NullInt64
if err := rows.Scan(&p.PlanID, &p.Role, &sealed, &p.State, &p.Expires, &w); err != nil {
return nil, err
}
p.Window = w.Int64
if sealed != nil {
if p.Signed, err = s.open(planPurpose(p.PlanID, p.Role), sealed); err != nil {
return nil, err
}
}
out[p.Role] = p
}
return out, rows.Err()
}
func (s *Store) MarkPlan(ctx context.Context, id, role, state string, window int64) error {
var w any
if window > 0 {
w = window
}
_, err := s.db.ExecContext(ctx, "UPDATE plan_submissions SET state=?,window_expires_at=coalesce(?,window_expires_at) WHERE plan_id=? AND role=?", state, w, id, role)
return err
}
// DropExpiredPlans deletes the signed bytes of every plan past its expiry
// and window: they are kept only to retry a busy role.
func (s *Store) DropExpiredPlans(ctx context.Context) error {
now := s.now().Unix()
_, err := s.db.ExecContext(ctx, "UPDATE plan_submissions SET sealed_plan=NULL WHERE expires_at<=? AND (window_expires_at IS NULL OR window_expires_at<=?)", now, now)
return err
}
// ---- steps ----
// Step is one recorded step. Data is non-secret JSON.
type Step struct {
Label, App, Name, State, Code string
Data map[string]any
Updated time.Time
}
func (s *Store) Step(ctx context.Context, label, app, name string) (Step, bool, error) {
st := Step{Label: label, App: app, Name: name}
var data string
var u int64
err := s.db.QueryRowContext(ctx, "SELECT state,code,data,updated_at FROM steps WHERE label=? AND app=? AND step=?", label, app, name).Scan(&st.State, &st.Code, &data, &u)
if errors.Is(err, sql.ErrNoRows) {
return st, false, nil
}
if err != nil {
return st, false, err
}
st.Updated = time.Unix(u, 0)
if err := json.Unmarshal([]byte(data), &st.Data); err != nil {
return st, false, err
}
return st, true, nil
}
// Done reports whether a step is done, and its data.
func (s *Store) Done(ctx context.Context, label, app, name string) (map[string]any, bool, error) {
st, ok, err := s.Step(ctx, label, app, name)
if err != nil || !ok || st.State != "done" {
return nil, false, err
}
return st.Data, true, nil
}
func (s *Store) SetStep(ctx context.Context, label, app, name, state, code string, data map[string]any) error {
if data == nil {
data = map[string]any{}
}
b, err := json.Marshal(data)
if err != nil {
return err
}
_, err = s.db.ExecContext(ctx, "INSERT INTO steps(label,app,step,state,code,data,updated_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(label,app,step) DO UPDATE SET state=excluded.state,code=excluded.code,data=excluded.data,updated_at=excluded.updated_at", label, app, name, state, code, string(b), s.now().Unix())
return err
}
// Steps lists a team's steps.
func (s *Store) Steps(ctx context.Context, label string) ([]Step, error) {
rows, err := s.db.QueryContext(ctx, "SELECT app,step,state,code,data,updated_at FROM steps WHERE label=? ORDER BY app,step", label)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Step
for rows.Next() {
st := Step{Label: label}
var data string
var u int64
if err := rows.Scan(&st.App, &st.Name, &st.State, &st.Code, &data, &u); err != nil {
return nil, err
}
_ = json.Unmarshal([]byte(data), &st.Data)
st.Updated = time.Unix(u, 0)
out = append(out, st)
}
return out, rows.Err()
}
// ---- operator requests and streams ----
// OpRequest is one signed operation Alta holds.
type OpRequest struct {
ID int64
Role, OperationID, Action string
Label, App, Purpose, Head string
Sequence, Expires int64
State string
Bytes []byte
}
func requestPurpose(opID string) string { return "alta/request/" + opID }
// NextJournal reserves a journal sequence for a request about to be
// signed (Home requires journal_sequence > 0; it is Alta's own counter).
func (s *Store) NextJournal(ctx context.Context) (int64, error) {
var n sql.NullInt64
err := s.db.QueryRowContext(ctx, "SELECT max(id) FROM operator_requests").Scan(&n)
return n.Int64 + 1, err
}
// SaveRequest stores a signed request, sealed, before it is sent.
func (s *Store) SaveRequest(ctx context.Context, r OpRequest) error {
sealed, err := s.seal(requestPurpose(r.OperationID), r.Bytes)
if err != nil {
return err
}
_, err = s.db.ExecContext(ctx, "INSERT INTO operator_requests(id,role,sequence,operation_id,action,label,app,purpose,head,sealed_request,state,expires_at,created_at) VALUES(?,?,?,?,?,?,?,?,?,?,'signed',?,?)", r.ID, r.Role, r.Sequence, r.OperationID, r.Action, r.Label, r.App, r.Purpose, r.Head, sealed, r.Expires, s.now().Unix())
return err
}
func (s *Store) scanRequest(sc interface{ Scan(...any) error }) (OpRequest, error) {
var r OpRequest
var sealed []byte
if err := sc.Scan(&r.ID, &r.Role, &r.Sequence, &r.OperationID, &r.Action, &r.Label, &r.App, &r.Purpose, &r.Head, &sealed, &r.State, &r.Expires); err != nil {
return OpRequest{}, err
}
b, err := s.open(requestPurpose(r.OperationID), sealed)
if err != nil {
return OpRequest{}, err
}
r.Bytes = b
return r, nil
}
const reqCols = "id,role,sequence,operation_id,action,label,app,purpose,head,sealed_request,state,expires_at"
// LastRequest is the newest request for (label, app, purpose) that is
// not refused: the one to replay.
func (s *Store) LastRequest(ctx context.Context, label, app, purpose string) (OpRequest, bool, error) {
r, err := s.scanRequest(s.db.QueryRowContext(ctx, "SELECT "+reqCols+" FROM operator_requests WHERE label=? AND app=? AND purpose=? AND state<>'refused' ORDER BY id DESC LIMIT 1", label, app, purpose))
if errors.Is(err, sql.ErrNoRows) {
return OpRequest{}, false, nil
}
return r, err == nil, err
}
// RequestByHead finds the request Alta signed whose authorization hashes
// to head on role, if it holds one.
func (s *Store) RequestByHead(ctx context.Context, role, head string) (OpRequest, bool, error) {
r, err := s.scanRequest(s.db.QueryRowContext(ctx, "SELECT "+reqCols+" FROM operator_requests WHERE role=? AND head=?", role, head))
if errors.Is(err, sql.ErrNoRows) {
return OpRequest{}, false, nil
}
return r, err == nil, err
}
func (s *Store) MarkRequest(ctx context.Context, id int64, state string) error {
_, err := s.db.ExecContext(ctx, "UPDATE operator_requests SET state=? WHERE id=?", state, id)
return err
}
// Commit records a committed request and advances the role's stream in
// one transaction.
func (s *Store) Commit(ctx context.Context, r OpRequest) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, "UPDATE operator_requests SET state='committed' WHERE id=?", r.ID); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, "INSERT INTO operator_streams(role,sequence,head,updated_at) VALUES(?,?,?,?) ON CONFLICT(role) DO UPDATE SET sequence=excluded.sequence,head=excluded.head,updated_at=excluded.updated_at WHERE excluded.sequence>operator_streams.sequence", r.Role, r.Sequence, r.Head, s.now().Unix()); err != nil {
return err
}
return tx.Commit()
}
// Stream is a role's position: the last committed sequence and head.
func (s *Store) Stream(ctx context.Context, role string) (int64, string, bool, error) {
var seq int64
var head string
err := s.db.QueryRowContext(ctx, "SELECT sequence,head FROM operator_streams WHERE role=?", role).Scan(&seq, &head)
if errors.Is(err, sql.ErrNoRows) {
return 0, "", false, nil
}
return seq, head, err == nil, err
}
// SetStream adopts Home's position (resync through inspect).
func (s *Store) SetStream(ctx context.Context, role string, seq int64, head string) error {
_, err := s.db.ExecContext(ctx, "INSERT INTO operator_streams(role,sequence,head,updated_at) VALUES(?,?,?,?) ON CONFLICT(role) DO UPDATE SET sequence=excluded.sequence,head=excluded.head,updated_at=excluded.updated_at", role, seq, head, s.now().Unix())
return err
}
// ---- audit ----
// AuditEntry is one audit row.
type AuditEntry struct {
At time.Time
RunID int64
Label, App, Event, Detail string
}
func (s *Store) Audit(ctx context.Context, runID int64, label, app, event, detail string) {
_, _ = s.db.ExecContext(ctx, "INSERT INTO audit(at,run_id,label,app,event,detail) VALUES(?,?,?,?,?,?)", s.now().Unix(), runID, label, app, event, detail)
}
func (s *Store) AuditLog(ctx context.Context, label string, limit int) ([]AuditEntry, error) {
rows, err := s.db.QueryContext(ctx, "SELECT at,run_id,label,app,event,detail FROM audit WHERE label=? ORDER BY id DESC LIMIT ?", label, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []AuditEntry
for rows.Next() {
var e AuditEntry
var at int64
if err := rows.Scan(&at, &e.RunID, &e.Label, &e.App, &e.Event, &e.Detail); err != nil {
return nil, err
}
e.At = time.Unix(at, 0)
out = append(out, e)
}
return out, rows.Err()
}
// ---- lock ----
// Lock takes the one-run-at-a-time lock. A lock older than stale is
// taken over: its holder crashed (a run resumes by probing, so taking
// over a dead holder's run is safe).
func (s *Store) Lock(ctx context.Context, runID int64, stale time.Duration) error {
now := s.now().Unix()
res, err := s.db.ExecContext(ctx, "INSERT INTO run_lock(singleton,run_id,acquired_at) VALUES(1,?,?) ON CONFLICT(singleton) DO UPDATE SET run_id=excluded.run_id,acquired_at=excluded.acquired_at WHERE run_lock.acquired_at", runID, now, now-int64(stale.Seconds()))
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrBusy
}
return nil
}
func (s *Store) Unlock(ctx context.Context, runID int64) {
_, _ = s.db.ExecContext(context.WithoutCancel(ctx), "DELETE FROM run_lock WHERE run_id=?", runID)
}
// ---- the §8 guard ----
type deprovisionKey struct{}
type proposalKey struct{}
// WithDeprovision marks ctx as inside retire-apps run id: the only
// context in which the console client may send a DELETE.
func WithDeprovision(ctx context.Context, runID int64) context.Context {
return context.WithValue(ctx, deprovisionKey{}, runID)
}
// proposal is a team not yet recorded, whose hosts and environment a
// preflight may READ (never write): checking a label must not burn it.
type proposal struct {
label, env string
apps []string
}
func withProposal(ctx context.Context, label, env string, apps []string) context.Context {
return context.WithValue(ctx, proposalKey{}, proposal{label, env, apps})
}
// Guard implements console.Guard from Alta's records.
type Guard struct {
Store *Store
Account string
}
func (g Guard) proposed(ctx context.Context, app string) (proposal, bool) {
p, ok := ctx.Value(proposalKey{}).(proposal)
if !ok {
return proposal{}, false
}
for _, a := range p.apps {
if a == app {
return p, true
}
}
return proposal{}, false
}
// Environment admits env for app only if Alta's records own it (or, for
// a read, a preflight proposes it).
func (g Guard) Environment(ctx context.Context, app, env string, write bool) error {
if env == "" {
return errors.New("empty environment")
}
if p, ok := g.proposed(ctx, app); ok && !write && p.env == env {
return nil
}
var n int
if err := g.Store.db.QueryRowContext(ctx, "SELECT count(*) FROM environments WHERE app=? AND environment=?", app, env).Scan(&n); err != nil {
return err
}
if n == 0 {
return errors.New("environment not Alta's")
}
return nil
}
// Host admits only