Files
felhom-controller/controller/internal/stacks/after_setup.go
T
admin 5b8656974b R-717: after_setup open_command — the family window reopens an app's DB-held sign-up switch
The command form ran only when the lock was SET, so a database switch closed by
`command` stayed closed through the household's 15-minute window. New twin
fields `open_command` + `open_success` (same service/user/args_env and the same
argv-safe expansion and success-marker rules as `command`/`success`).

- liftNativeLock (the window, via OpenSignupWindow → goNativeLock(false)): marks
  the gate record native_lock "opening" BEFORE anything opens, lifts the env,
  runs open_command; only full success records "lifted". A failed open closes
  the switch again at once and records after_setup {ok: false, step: open}; the
  app page shows its own line (app_info.signup_native_open_failed).
- The close: reconcileSignupBlocks (every 20 s and at controller start) runs
  `command` for any non-"applied" state once no window runs. A failed close
  after a window is logged ERROR ("may still be OPEN past the household's
  window") and retried every nativeLockOpenRetry (2 min) instead of 30.
- After a successful app update, verifyAndConclude → markNativeLockForReapply
  sets native_lock "" so the loop closes the switch again.
- A template with `command` but no `open_command` keeps today's window (env
  only) and logs once per app that its own switch cannot be reopened.

Tests: internal/stacks/after_setup_r717_test.go (7), web render + parity case.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-10-06 15:15:33 +02:00

411 lines
18 KiB
Go

package stacks
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
)
// ── after_setup: the app's OWN sign-up switch, set once the first admin exists (v0.282.0, `09` §3 decisions 47, 49) ──
//
// Decision 47 closes open sign-up once an app's first admin exists. v0.281.0 did it with an address block only
// (signup_block.go). Measured 2026-09-29 evening: 9 of the 11 apps with a block also have their own switch, and every
// one is read from the environment at start (gitea through its env-to-ini; the others directly). So the template
// wires that switch to SIGNUP_CLOSED / SIGNUP_OPEN, whose compose default is OPEN — an installed app is unchanged by
// the catalog — and declares:
//
// after_setup:
// env: {SIGNUP_CLOSED: "true"} # merged into the app's env, then ONE `compose up -d`
//
// It runs when the setup gate opens (probe or the household's press) and on the household's "close sign-up now"
// (decision 49), AFTER the address block is up. The block stays either way: two locks. A failed step is recorded
// (`after_setup:` in app.yaml) and shown on the app page; the block still holds.
//
// The household's 15-minute window lifts BOTH: the env keys are removed (the compose default is open again) and the
// app is started once more; when the window ends the loop puts them back (one more start). The page says the app
// restarts.
//
// A command form (`service`, `command`, `success`, `env` names) follows after_install's argv-safe rules (R-713).
//
// R-717: an app whose switch lives in its own database (opengist, wishlist) is closed by `command` and reopened for
// the household's window by its twin:
//
// after_setup:
// service: app # shared by both commands, as is `user` and `args_env`
// command: [...] # CLOSES the switch; `success` must appear in its output
// success: "closed"
// open_command: [...] # OPENS it for the 15-minute window; `open_success` must appear in its output
// open_success: "opened"
//
// Where each runs: the window (OpenSignupWindow → liftNativeLock) runs `open_command` after the env lift; the loop
// (reconcileSignupBlocks, every 20 s and once at controller start) runs `command` again for every app whose state is
// not "applied" once no window runs — after the window, after a box restart, and after an app update
// (markNativeLockForReapply in verifyAndConclude). Fail closed: the state is marked "opening" BEFORE anything opens,
// so a crash mid-open leaves a state the loop closes; an `open_command` that fails closes the switch again at once and
// records `after_setup: {ok: false, step: open}` (the app page says the switch could not be opened); a close that fails
// keeps the state not-"applied", logs ERROR and is retried by the loop every nativeLockOpenRetry. A template with
// `command` but no `open_command` keeps today's window (env lift only) and logs once that the app's own switch cannot
// be reopened.
// Pinned by internal/stacks/after_setup_test.go.
// AfterSetupSpec is `.felhom.yml`'s `after_setup:`.
type AfterSetupSpec struct {
Env map[string]string `yaml:"env,omitempty" json:"env,omitempty"`
Service string `yaml:"service,omitempty" json:"service,omitempty"`
User string `yaml:"user,omitempty" json:"user,omitempty"`
Args []string `yaml:"args_env,omitempty" json:"args_env,omitempty"` // deploy values a command may use
Command []string `yaml:"command,omitempty" json:"command,omitempty"`
Success string `yaml:"success,omitempty" json:"success,omitempty"`
// OpenCommand / OpenSuccess (R-717): the twin that opens the switch `command` closes, for the household's window.
OpenCommand []string `yaml:"open_command,omitempty" json:"open_command,omitempty"`
OpenSuccess string `yaml:"open_success,omitempty" json:"open_success,omitempty"`
}
// Native-lock states in SetupGateRecord.NativeLock.
const (
NativeLockApplied = "applied" // the app's own switch says closed
NativeLockLifted = "lifted" // the household's window: the switch is open again
// NativeLockOpening (R-717) is written BEFORE the window opens anything: a crash between the opening and its
// record leaves a state that is not "applied", so the loop closes it once the window has passed.
NativeLockOpening = "opening"
)
// afterSetupStepOpen marks an AfterInstallRecord written by a failed OPEN (the window), not a failed close.
const afterSetupStepOpen = "open"
// afterSetupUp starts the app from its stored app.yaml (a seam: tests never reach Docker).
func (m *Manager) afterSetupUp(name string) error {
if m.afterSetupUpFn != nil {
return m.afterSetupUpFn(name)
}
return m.upFromAppConfig(name)
}
// setNativeEnv merges (lock) or removes (lift) the after_setup env keys in app.yaml.
func (m *Manager) setNativeEnv(name, dir string, spec *AfterSetupSpec, lock bool) bool {
changed := false
m.mutateAppConfig(name, dir, "after_setup_env", func(cfg *AppConfig) bool {
if cfg.Env == nil {
cfg.Env = map[string]string{}
}
for k, v := range spec.Env {
if lock {
if cfg.Env[k] != v {
cfg.Env[k] = v
changed = true
}
} else if _, ok := cfg.Env[k]; ok {
delete(cfg.Env, k)
changed = true
}
}
return changed
})
return changed
}
// applyNativeLock sets (lock=true) or lifts the app's own switch, then starts the app once when anything changed.
// Records the outcome. Safe to call again: an unchanged env starts nothing. A lift goes to liftNativeLock (R-717).
func (m *Manager) applyNativeLock(name string, lock bool, why string) error {
st, ok := m.GetStack(name)
if !ok || st.Meta.AfterSetup == nil {
return nil
}
if !lock {
return m.liftNativeLock(name, st, why)
}
spec := st.Meta.AfterSetup
dir := filepath.Dir(st.ComposePath)
priorState := ""
if st.AppConfig != nil && st.AppConfig.SetupGate != nil {
priorState = st.AppConfig.SetupGate.NativeLock
}
var err error
// The switch works only if the app's INSTALLED compose reads the variable. An app installed before the template
// wired it (decision 49's apps) carries the old compose until its next update: say so, never report a lock that
// is not there. The address block still holds.
if len(spec.Env) > 0 {
if miss := composeMissingVars(st.ComposePath, spec.Env); len(miss) > 0 {
err = fmt.Errorf("the installed version of the app does not read %v yet — its own switch applies after its next update", miss)
m.logger.Printf("[WARN] [stacks] %s: %v", name, err)
m.recordNativeLock(name, dir, false, err.Error(), "", "")
return err
}
}
if len(spec.Env) > 0 {
if m.setNativeEnv(name, dir, spec, true) {
err = m.afterSetupUp(name)
}
}
if err == nil && len(spec.Command) > 0 {
err = m.runAfterSetupCommand(name, dir, spec, spec.Command, spec.Success, "command")
}
if err != nil {
if priorState == NativeLockLifted || priorState == NativeLockOpening {
// R-717: the household's window was (or may have been) opened — the app's own sign-up may still be OPEN.
m.logger.Printf("[ERROR] [stacks] %s: the app's own sign-up switch could NOT be closed again (%s): %v — sign-up inside the app may still be OPEN past the household's window; the address block holds and the loop retries every %s", name, why, err, nativeLockOpenRetry)
} else {
m.logger.Printf("[ERROR] [stacks] %s: the app's own sign-up switch could not be closed (%s): %v — the address block still holds", name, why, err)
}
m.recordNativeLock(name, dir, false, err.Error(), "", "")
return err
}
m.logger.Printf("[INFO] [stacks] %s: the app's own sign-up switch CLOSED (%s; env %v, command %v)", name, why, sortedEnvKeys(spec.Env), len(spec.Command) > 0)
m.recordNativeLock(name, dir, true, "", "", NativeLockApplied)
return nil
}
// liftNativeLock is the household's window (R-717): the env keys go (one start) and the template's open_command runs.
// Fail closed: the state says "opening" before anything opens; an open that fails closes the switch again at once and
// records the failure with step "open" (the app page says it could not be opened). Only a full success records
// "lifted", which the loop closes again once the window has passed.
func (m *Manager) liftNativeLock(name string, st *Stack, why string) error {
spec := st.Meta.AfterSetup
dir := filepath.Dir(st.ComposePath)
if len(spec.Command) > 0 && len(spec.OpenCommand) == 0 {
if _, seen := m.nativeOpenMissingLogged.LoadOrStore(name, true); !seen {
m.logger.Printf("[WARN] [stacks] %s: the template closes the app's own sign-up switch with a command but has no open_command — the household's window cannot reopen it (only the address block opens)", name)
}
}
if len(spec.Env) == 0 && len(spec.OpenCommand) == 0 {
return nil // nothing of the app's own to open
}
m.mutateAppConfig(name, dir, "after_setup_opening", func(cfg *AppConfig) bool {
if cfg.SetupGate == nil {
return false
}
cfg.SetupGate.NativeLock = NativeLockOpening
return true
})
if c := LoadAppConfig(dir); c == nil || c.SetupGate == nil || c.SetupGate.NativeLock != NativeLockOpening {
err := fmt.Errorf("the record could not be marked before opening — the app's own switch stays closed")
m.logger.Printf("[ERROR] [stacks] %s: the app's own sign-up switch was NOT opened (%s): %v", name, why, err)
m.recordNativeLock(name, dir, false, err.Error(), afterSetupStepOpen, "")
return err
}
var err error
if len(spec.Env) > 0 && m.setNativeEnv(name, dir, spec, false) {
err = m.afterSetupUp(name)
}
if err == nil && len(spec.OpenCommand) > 0 {
err = m.runAfterSetupCommand(name, dir, spec, spec.OpenCommand, spec.OpenSuccess, "open_command")
}
if err != nil {
m.logger.Printf("[ERROR] [stacks] %s: the app's own sign-up switch could NOT be opened (%s): %v — closing it again; a new family member cannot sign up in the app itself", name, why, err)
detail := "could not be opened for the household's window: " + err.Error()
if cerr := m.applyNativeLock(name, true, "an opening that failed"); cerr != nil {
detail += "; closing it again failed too (the loop retries): " + cerr.Error()
}
m.recordNativeLock(name, dir, false, detail, afterSetupStepOpen, "")
return err
}
m.logger.Printf("[INFO] [stacks] %s: the app's own sign-up switch opened for the household's window (%s; env %v, open_command %v)", name, why, sortedEnvKeys(spec.Env), len(spec.OpenCommand) > 0)
m.recordNativeLock(name, dir, true, "", "", NativeLockLifted)
return nil
}
// recordNativeLock writes the after_setup record; state != "" also moves SetupGate.NativeLock.
func (m *Manager) recordNativeLock(name, dir string, ok bool, detail, step, state string) {
rec := &AfterInstallRecord{At: m.now().UTC().Format(time.RFC3339), OK: ok, Detail: truncateStr(detail, 300), Step: step}
m.mutateAppConfig(name, dir, "after_setup", func(cfg *AppConfig) bool {
cfg.AfterSetup = rec
if state != "" && cfg.SetupGate != nil {
cfg.SetupGate.NativeLock = state
}
return true
})
}
// markNativeLockForReapply (R-717) makes the loop run the close again after an app update: an update may bring a
// database whose switch is not the one the box set. NativeLock "" = "run once the app is up" (as after a restore).
func (m *Manager) markNativeLockForReapply(name, dir string) {
st, ok := m.GetStack(name)
if !ok || st.Meta.AfterSetup == nil {
return
}
marked := false
m.mutateAppConfig(name, dir, "after_setup_reapply", func(cfg *AppConfig) bool {
if cfg.SetupGate == nil || cfg.SetupGate.State != SetupGateOpen || cfg.SetupGate.NativeLock != NativeLockApplied {
return false // never set, or not applied: the loop already runs it
}
cfg.SetupGate.NativeLock = ""
marked = true
return true
})
if marked {
m.logger.Printf("[INFO] [stacks] %s: after the update the app's own sign-up switch is closed again by the loop", name)
}
}
func sortedEnvKeys(mp map[string]string) []string {
keys := make([]string, 0, len(mp))
for k := range mp {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// runAfterSetupCommand runs one command of the command form (`command` or `open_command`) once, with after_install's
// argv-safe expansion and its success marker.
func (m *Manager) runAfterSetupCommand(name, dir string, spec *AfterSetupSpec, command []string, success, field string) error {
if spec.Service == "" || success == "" {
return fmt.Errorf("after_setup %s needs a service and a success marker", field)
}
cfg := LoadAppConfigDecrypted(dir, m.encKey)
if cfg == nil {
return fmt.Errorf("app.yaml unreadable")
}
cmd, err := expandAfterInstall(command, spec.Args, cfg.Env)
if err != nil {
return err
}
args := []string{"exec", "-T"}
if spec.User != "" {
args = append(args, "-u", spec.User)
}
args = append(args, spec.Service)
args = append(args, cmd...)
out, err := m.runInService(dir, args...)
if err != nil || !strings.Contains(out, success) {
return fmt.Errorf("after_setup %s did not report %q (err %v)", field, success, err)
}
return nil
}
// runInService is the compose exec seam shared with after_install (afterLoadFn in tests).
func (m *Manager) runInService(dir string, args ...string) (string, error) {
if m.afterLoadFn != nil {
return m.afterLoadFn(dir, args...)
}
return m.composeExecCustomEnv(dir, m.stackEnv(dir), args...)
}
// ── "Close sign-up now" (decision 49) ─────────────────────────────────────────────────────────────────
// ErrCloseSignupNotOffered: the app is not installed, has no gate-free install, or its template has no lock.
var ErrCloseSignupNotOffered = fmt.Errorf("close sign-up is not offered for this app")
// CloseSignupOffered: an installed app whose template has a sign-up lock and whose install has none — an app
// installed before decision 47 (demo-hp's adventurelog, opengist). Offered once: the press records a lock.
func (m *Manager) CloseSignupOffered(name string) bool {
st, ok := m.GetStack(name)
if !ok || !st.Deployed || st.AppConfig == nil || st.AppConfig.SetupGate != nil {
return false
}
return strings.TrimSpace(st.Meta.SignupBlock) != "" || st.Meta.AfterSetup != nil
}
// CloseSignupNow applies to an installed app exactly what a fresh install gets after its setup: a lock record
// (never a closed gate), the address block, then the app's own switch. It never gates the app and never touches
// its data.
func (m *Manager) CloseSignupNow(name string) error {
if !m.CloseSignupOffered(name) {
return ErrCloseSignupNotOffered
}
st, _ := m.GetStack(name)
dir := filepath.Dir(st.ComposePath)
cfg := LoadAppConfigDecrypted(dir, m.encKey)
if cfg == nil {
return fmt.Errorf("%s: app.yaml unreadable", name)
}
rs, err := gateRoutersFromCompose(st.ComposePath, cfg.Env)
if err != nil {
return fmt.Errorf("%s: the app's addresses could not be read: %w", name, err)
}
hosts := gateHosts(rs)
if b := strings.TrimSpace(st.Meta.SignupBlock); b != "" {
if err := m.writeSignupBlock(name, hosts, b); err != nil {
return fmt.Errorf("%s: the sign-up block could not be written: %w", name, err)
}
}
now := m.now().UTC().Format(time.RFC3339)
done := false
m.mutateAppConfig(name, dir, "setup_gate", func(c *AppConfig) bool {
if c.SetupGate != nil {
return false
}
c.SetupGate = &SetupGateRecord{State: SetupGateOpen, Since: now, Hosts: hosts, OpenedAt: now, OpenedBy: SetupGateByCloseSignup}
done = true
return true
})
if !done {
_ = m.removeSignupBlockFile(name)
return fmt.Errorf("%s: the lock could not be recorded", name)
}
m.logger.Printf("[INFO] [stacks] %s: the household closed sign-up on an app installed before decision 47 (hosts %v)", name, hosts)
if st.Meta.AfterSetup != nil {
m.goNativeLock(name, true, "close sign-up now")
}
return nil
}
// restoreSignupLock is R-773's half of PersistUnitRedeployConfig: for an app whose template locks sign-up, the lock
// record (opened_by "restore", never a closed gate) and — best effort — its block file. nil, nil when the template has
// no lock. A block that cannot be written now is logged and left to the loop (the record says it is wanted); hosts that
// cannot be read refuse the restore before anything starts (fail closed, as the gate's own install does).
// The app's own switch (`after_setup`) is the loop's: NativeLock is "" so it runs once the app is up.
func (m *Manager) restoreSignupLock(name, composePath string, env map[string]string, meta *Metadata) (*SetupGateRecord, error) {
block := strings.TrimSpace(meta.SignupBlock)
if block == "" && meta.AfterSetup == nil {
return nil, nil
}
rs, err := gateRoutersFromCompose(composePath, env)
if err != nil {
return nil, fmt.Errorf("%s: the app's addresses could not be read: %w", name, err)
}
hosts := gateHosts(rs)
if block != "" {
if err := m.writeSignupBlock(name, hosts, block); err != nil {
m.logger.Printf("[ERROR] [stacks] %s: the restore's sign-up block could not be written: %v — the loop retries; sign-up is OPEN until it is", name, err)
}
}
now := m.now().UTC().Format(time.RFC3339)
m.logger.Printf("[INFO] [stacks] %s: restored after a removal — sign-up closed again as after its setup (hosts %v)", name, hosts)
return &SetupGateRecord{State: SetupGateOpen, Since: now, Hosts: hosts, OpenedAt: now, OpenedBy: SetupGateByRestore}, nil
}
// goNativeLock runs applyNativeLock in the background, one at a time per app (a press, the window and the loop
// can meet). The seam afterSetupSync makes it synchronous for tests.
func (m *Manager) goNativeLock(name string, lock bool, why string) {
if _, busy := m.nativeLockBusy.LoadOrStore(name, true); busy {
return
}
run := func() {
defer m.nativeLockBusy.Delete(name)
_ = m.applyNativeLock(name, lock, why)
}
if m.afterSetupSync {
run()
return
}
go run()
}
// SetupGateByCloseSignup marks a lock record written by "close sign-up now" (the app was never gated).
const SetupGateByCloseSignup = "close-signup"
// composeMissingVars lists the after_setup env keys the compose file never reads as ${KEY...}.
func composeMissingVars(composePath string, env map[string]string) []string {
b, err := os.ReadFile(composePath)
if err != nil {
keys := make([]string, 0, len(env))
for k := range env {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
var miss []string
for k := range env {
if !strings.Contains(string(b), "${"+k+"}") && !strings.Contains(string(b), "${"+k+":") {
miss = append(miss, k)
}
}
sort.Strings(miss)
return miss
}