v0.282.0: after_setup (the app's own sign-up switch), close sign-up now (decision 49), probes read lists + done_status (R-715)
gates / gates (push) Successful in 27s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
This commit is contained in:
2026-09-29 16:19:12 +02:00
parent 6fc3059167
commit 4110da50e9
25 changed files with 1864 additions and 36 deletions
+271
View File
@@ -0,0 +1,271 @@
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).
// 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"`
}
// 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
)
// 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.
func (m *Manager) applyNativeLock(name string, lock bool, why string) error {
st, ok := m.GetStack(name)
if !ok || st.Meta.AfterSetup == nil {
return nil
}
spec := st.Meta.AfterSetup
dir := filepath.Dir(st.ComposePath)
record := func(ok bool, detail string) {
rec := &AfterInstallRecord{At: m.now().UTC().Format(time.RFC3339), OK: ok, Detail: truncateStr(detail, 300)}
state := NativeLockApplied
if !lock {
state = NativeLockLifted
}
m.mutateAppConfig(name, dir, "after_setup", func(cfg *AppConfig) bool {
cfg.AfterSetup = rec
if ok && cfg.SetupGate != nil {
cfg.SetupGate.NativeLock = state
}
return true
})
}
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 && lock {
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)
record(false, err.Error())
return err
}
}
if len(spec.Env) > 0 {
if m.setNativeEnv(name, dir, spec, lock) {
err = m.afterSetupUp(name)
}
}
if err == nil && lock && len(spec.Command) > 0 {
err = m.runAfterSetupCommand(name, dir, spec)
}
if err != nil {
m.logger.Printf("[ERROR] [stacks] %s: the app's own sign-up switch could not be %s (%s): %v — the address block still holds", name, map[bool]string{true: "closed", false: "opened"}[lock], why, err)
record(false, err.Error())
return err
}
keys := make([]string, 0, len(spec.Env))
for k := range spec.Env {
keys = append(keys, k)
}
sort.Strings(keys)
m.logger.Printf("[INFO] [stacks] %s: the app's own sign-up switch %s (%s; env %v)", name, map[bool]string{true: "CLOSED", false: "opened for the household's window"}[lock], why, keys)
record(true, "")
return nil
}
// runAfterSetupCommand runs the command form once, with after_install's argv-safe expansion and success marker.
func (m *Manager) runAfterSetupCommand(name, dir string, spec *AfterSetupSpec) error {
if spec.Service == "" || spec.Success == "" {
return fmt.Errorf("after_setup command needs a service and a success marker")
}
cfg := LoadAppConfigDecrypted(dir, m.encKey)
if cfg == nil {
return fmt.Errorf("app.yaml unreadable")
}
cmd, err := expandAfterInstall(spec.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, spec.Success) {
return fmt.Errorf("after_setup command did not report %q (err %v)", spec.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
}
// 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
}
@@ -0,0 +1,180 @@
package stacks
import (
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
// v0.282.0 — the app's own sign-up switch (after_setup), "close sign-up now" (decision 49), richer probes (R-715).
const nativeCompose = "services:\n" +
" gapp:\n image: busybox\n environment:\n - DISABLE_REGISTRATION=${SIGNUP_CLOSED:-false}\n labels:\n" +
" - \"traefik.enable=true\"\n" +
" - \"traefik.http.routers.gapp.rule=Host(`${SUBDOMAIN}.${DOMAIN}`)\"\n" +
" - \"traefik.http.services.gapp.loadbalancer.server.port=80\"\n"
const nativeYml = "display_name: Gated App\nsetup_gate: true\nsignup_block: \"PathPrefix(`/signup`)\"\n" +
"after_setup:\n env:\n SIGNUP_CLOSED: \"true\"\n" +
"deploy_fields:\n - env_var: DOMAIN\n type: domain\n - env_var: SUBDOMAIN\n type: subdomain\n default: gapp\n"
type upRecorder struct {
mu sync.Mutex
n int
env []string
m *Manager
}
func (u *upRecorder) up(name string) error {
u.mu.Lock()
defer u.mu.Unlock()
u.n++
c := LoadAppConfig(filepath.Join(u.m.cfg.Paths.StacksDir, name))
u.env = append(u.env, c.Env["SIGNUP_CLOSED"])
return nil
}
func nativeManager(t *testing.T, compose string) (*Manager, *upRecorder) {
t.Helper()
m := gateManager(t, nativeYml)
must(t, os.WriteFile(filepath.Join(m.cfg.Paths.StacksDir, "gapp", "docker-compose.yml"), []byte(compose), 0o644))
must(t, m.ScanStacks())
m.afterSetupSync = true
u := &upRecorder{m: m}
m.afterSetupUpFn = u.up
return m, u
}
// When the gate opens the box sets the app's own switch (then starts it once), after the block is up.
// COMPANION RED-PROOF: drop the goNativeLock call in OpenSetupGate → "the app's own switch was not set" fails.
func TestAfterSetup_TheGateOpeningSetsTheAppsOwnSwitch(t *testing.T) {
m, u := nativeManager(t, nativeCompose)
dir := closedGate(t, m)
must(t, m.OpenSetupGate("gapp", SetupGateByHousehold))
c := LoadAppConfig(dir)
if c.Env["SIGNUP_CLOSED"] != "true" || u.n != 1 {
t.Fatalf("the app's own switch was not set: env=%q starts=%d", c.Env["SIGNUP_CLOSED"], u.n)
}
if c.AfterSetup == nil || !c.AfterSetup.OK || c.SetupGate.NativeLock != NativeLockApplied {
t.Fatalf("record %+v / native %q", c.AfterSetup, c.SetupGate.NativeLock)
}
if _, err := os.Stat(m.signupBlockPath("gapp")); err != nil {
t.Fatal("the address block is not up — two locks, not one")
}
m.SetupGateTick() // an applied lock is not re-applied (no restart per tick)
if u.n != 1 {
t.Fatalf("the loop restarted the app again (%d starts)", u.n)
}
}
// The household's window lifts the app's own switch too, and the loop closes it again after.
// COMPANION RED-PROOF: drop the goNativeLock(true, …) in reconcileSignupBlocks → "the switch stayed open" fails.
func TestAfterSetup_TheWindowLiftsItAndTheLoopClosesItAgain(t *testing.T) {
m, u := nativeManager(t, nativeCompose)
dir := closedGate(t, m)
must(t, m.OpenSetupGate("gapp", SetupGateByHousehold))
_, err := m.OpenSignupWindow("gapp")
must(t, err)
if c := LoadAppConfig(dir); c.Env["SIGNUP_CLOSED"] != "" || c.SetupGate.NativeLock != NativeLockLifted || u.n != 2 {
t.Fatalf("window: env=%q native=%q starts=%d", c.Env["SIGNUP_CLOSED"], c.SetupGate.NativeLock, u.n)
}
later := time.Now().Add(signupWindow + time.Minute)
m.updateNowFn = func() time.Time { return later }
m.SetupGateTick()
if c := LoadAppConfig(dir); c.Env["SIGNUP_CLOSED"] != "true" || c.SetupGate.NativeLock != NativeLockApplied || u.n != 3 {
t.Fatalf("the switch stayed open after the window: env=%q native=%q starts=%d", c.Env["SIGNUP_CLOSED"], c.SetupGate.NativeLock, u.n)
}
}
// An installed version whose compose does not read the variable is reported, never recorded as locked.
// COMPANION RED-PROOF: drop the composeMissingVars check → the record says ok and this fails.
func TestAfterSetup_AnOldComposeIsReportedNotFaked(t *testing.T) {
m, u := nativeManager(t, strings.Replace(nativeCompose, " - DISABLE_REGISTRATION=${SIGNUP_CLOSED:-false}\n", " - TZ=x\n", 1))
dir := closedGate(t, m)
must(t, m.OpenSetupGate("gapp", SetupGateByHousehold))
c := LoadAppConfig(dir)
if c.AfterSetup == nil || c.AfterSetup.OK || !strings.Contains(c.AfterSetup.Detail, "SIGNUP_CLOSED") || u.n != 0 || c.SetupGate.NativeLock == NativeLockApplied {
t.Fatalf("an unread switch was recorded as set: %+v native=%q starts=%d", c.AfterSetup, c.SetupGate.NativeLock, u.n)
}
if _, err := os.Stat(m.signupBlockPath("gapp")); err != nil {
t.Fatal("the block must hold anyway")
}
}
// Decision 49: offered only for an installed app with a template lock and no lock record; the press writes the
// block and sets the switch, never a gate; offered once.
// COMPANION RED-PROOF: return true from CloseSignupOffered when SetupGate != nil → the second press succeeds.
func TestCloseSignup_OnceOnAnAppInstalledBeforeTheRule(t *testing.T) {
m, u := nativeManager(t, nativeCompose)
dir := filepath.Join(m.cfg.Paths.StacksDir, "gapp")
cfg := &AppConfig{Deployed: true, Env: map[string]string{"DOMAIN": "example.hu", "SUBDOMAIN": "gapp"}}
must(t, SaveAppConfig(dir, cfg, m.encKey, nil))
m.mu.Lock()
m.stacks["gapp"].Deployed, m.stacks["gapp"].State, m.stacks["gapp"].AppConfig = true, StateRunning, cfg
m.mu.Unlock()
if !m.CloseSignupOffered("gapp") {
t.Fatal("not offered on an installed app without a lock")
}
must(t, m.CloseSignupNow("gapp"))
c := LoadAppConfig(dir)
if c.SetupGate == nil || c.SetupGate.State != SetupGateOpen || c.SetupGate.OpenedBy != SetupGateByCloseSignup || strings.Join(c.SetupGate.Hosts, ",") != "gapp.example.hu" {
t.Fatalf("lock record %+v", c.SetupGate)
}
if _, err := os.Stat(m.setupGatePath("gapp")); !os.IsNotExist(err) {
t.Fatal("close sign-up GATED the app")
}
if _, err := os.Stat(m.signupBlockPath("gapp")); err != nil {
t.Fatal("no address block")
}
if c.Env["SIGNUP_CLOSED"] != "true" || u.n != 1 {
t.Fatalf("the app's own switch: env=%q starts=%d", c.Env["SIGNUP_CLOSED"], u.n)
}
m.mu.Lock()
m.stacks["gapp"].AppConfig = c
m.mu.Unlock()
if m.CloseSignupOffered("gapp") {
t.Fatal("offered twice")
}
if err := m.CloseSignupNow("gapp"); err != ErrCloseSignupNotOffered {
t.Fatalf("second press: %v", err)
}
}
// R-715: list indexes and a "done" HTTP status.
// COMPANION RED-PROOF: drop the []interface{} case in probeSaysDone → the ghost/home-assistant rows fail.
func TestProbe_ListIndexesAndADoneStatus(t *testing.T) {
for _, c := range []struct {
body, field, done string
want bool
}{
{`{"setup":[{"status":true}]}`, "setup.0.status", "true", true},
{`{"setup":[{"status":false}]}`, "setup.0.status", "true", false},
{`[{"step":"user","done":true},{"step":"core_config","done":false}]`, "0.done", "true", true},
{`[{"step":"user","done":false}]`, "0.done", "true", false},
{`[]`, "0.done", "true", false},
{`{"setup":[]}`, "setup.3.status", "true", false},
} {
if got, _ := probeSaysDone([]byte(c.body), c.field, c.done); got != c.want {
t.Errorf("%s @ %s: %v, want %v", c.body, c.field, got, c.want)
}
}
old := setupGateProbeFetch
t.Cleanup(func() { setupGateProbeFetch = old })
status := 200
setupGateProbeFetch = func(string) (int, []byte, error) { return status, []byte(`{"access_token":"x"}`), nil }
p := &SetupDoneProbe{URL: "u", Field: "error.code", Done: "405", DoneStatus: 405}
if done, _, _ := probeOnce(p); done {
t.Fatal("gramps-web before its setup (200 + a token) read as done")
}
status = 405
if done, _, err := probeOnce(p); !done || err != nil {
t.Fatalf("gramps-web after its setup (405) not read as done: %v", err)
}
status = 500
if done, _, err := probeOnce(p); done || err == nil {
t.Fatal("another status read as done (must fail closed)")
}
}
+2
View File
@@ -187,6 +187,8 @@ type AppConfig struct {
// DefaultLogin (v0.280.0, R-710) is the household's own word that it changed the template's known default
// login by hand. The page stops naming the default. See internal/web/known_login.go.
DefaultLogin *DefaultLoginRecord `yaml:"default_login,omitempty" json:"default_login,omitempty"`
// AfterSetup (v0.282.0) is what the template's after_setup (the app's own sign-up switch) last did.
AfterSetup *AfterInstallRecord `yaml:"after_setup,omitempty" json:"after_setup,omitempty"`
}
// DefaultLoginRecord is app.yaml's `default_login:`.
@@ -37,6 +37,7 @@ func carryLifeRecords(logger *log.Logger, name string, prior, cfg *AppConfig) {
// No prior record (a removed app, kept data, a rebuilt guest) = no gate: the data comes back with its admin.
cfg.SetupGate = prior.SetupGate
cfg.DefaultLogin = prior.DefaultLogin
cfg.AfterSetup = prior.AfterSetup
if n := len(prior.EarlierConversionCopies); prior.ConversionCopy != nil || n > 0 {
cur := ""
if prior.ConversionCopy != nil {
+5
View File
@@ -270,6 +270,11 @@ type Manager struct {
execFn func(name string, args ...string) (string, error)
// composeExecFn replaces the initial deploy's compose call (composeExecWithEnv) in tests; nil in production.
composeExecFn func(dir string, env map[string]string, args ...string) (string, error)
// afterSetupUpFn replaces after_setup's `compose up -d` in tests; nil in production.
afterSetupUpFn func(name string) error
// nativeLockBusy: one after_setup run per app at a time (the loop, the window and a press can meet).
nativeLockBusy sync.Map
afterSetupSync bool // tests: run after_setup in the caller
// --- guarded update (slice 4, update.go) ---
updateGuards UpdateGuards // init-only, SetUpdateGuards; nil ⇒ every update is REFUSED
+3 -1
View File
@@ -63,7 +63,9 @@ type Metadata struct {
SetupDoneProbe *SetupDoneProbe `yaml:"setup_done_probe,omitempty" json:"setup_done_probe,omitempty"`
// SignupBlock (v0.281.0, `09` §3 decision 47): a traefik matcher for the app's own sign-up address, closed once the
// setup gate opens. See signup_block.go.
SignupBlock string `yaml:"signup_block,omitempty" json:"signup_block,omitempty"`
SignupBlock string `yaml:"signup_block,omitempty" json:"signup_block,omitempty"`
// AfterSetup (v0.282.0, decisions 47/49): the app's OWN sign-up switch, set when the gate opens. See after_setup.go.
AfterSetup *AfterSetupSpec `yaml:"after_setup,omitempty" json:"after_setup,omitempty"`
Integrations []IntegrationDef `yaml:"integrations,omitempty" json:"integrations,omitempty"`
// InitialCreds: for apps that auto-generate a first-login credential into a file inside the
// container (e.g. Crafty's default-creds.txt). The controller reads + parses that file live and
+53 -16
View File
@@ -10,6 +10,7 @@ import (
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
@@ -47,6 +48,8 @@ type SetupDoneProbe struct {
URL string `yaml:"url" json:"url"`
Field string `yaml:"field" json:"field"`
Done string `yaml:"done" json:"done"`
// DoneStatus (v0.282.0, R-715): a non-200 HTTP status that itself means "set up" (gramps-web answers 405).
DoneStatus int `yaml:"done_status,omitempty" json:"done_status,omitempty"`
}
// Setup gate states.
@@ -67,6 +70,8 @@ type SetupGateRecord struct {
OpenedBy string `yaml:"opened_by,omitempty" json:"opened_by,omitempty"`
// SignupOpenUntil (v0.281.0, decision 47): the household opened sign-up until this time (signup_block.go).
SignupOpenUntil string `yaml:"signup_open_until,omitempty" json:"signup_open_until,omitempty"`
// NativeLock (v0.282.0): the app's own sign-up switch — "applied", "lifted" (the window), or "" (never set).
NativeLock string `yaml:"native_lock,omitempty" json:"native_lock,omitempty"`
}
// Closed reports whether the gate stands.
@@ -325,6 +330,10 @@ func (m *Manager) OpenSetupGate(name, by string) error {
m.logger.Printf("[ERROR] [stacks] %s: setup gate opened but its traefik file could not be removed (%v) — the reconcile retries", name, err)
}
m.logger.Printf("[INFO] [stacks] %s: setup gate OPENED by %s — the app is reached as without a gate", name, by)
// v0.282.0 (decision 47): the app's own sign-up switch, after the block is up and the gate is down. One restart.
if st.Meta.AfterSetup != nil {
m.goNativeLock(name, true, "the gate opened ("+by+")")
}
return nil
}
@@ -347,33 +356,62 @@ func (m *Manager) SetupGateHost(host string) (name string, closed bool, found bo
return "", false, false
}
// setupGateProbeGet reads a probe URL (a seam: tests never reach a network).
var setupGateProbeGet = func(url string) ([]byte, error) {
// setupGateProbeFetch reads a probe URL: the HTTP status and the body (a seam: tests never reach a network).
var setupGateProbeFetch = func(url string) (int, []byte, error) {
c := &http.Client{Timeout: 5 * time.Second}
resp, err := c.Get(url)
if err != nil {
return nil, err
return 0, nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
}
return io.ReadAll(io.LimitReader(resp.Body, 1<<20))
b, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
return resp.StatusCode, b, err
}
// probeSaysDone reads the field at the dotted path and compares its text form with done. Anything it cannot
// read is "not done" — the gate stays closed (fail closed).
// probeOnce asks the app's own status once. v0.282.0 (R-715): `done_status:` — an app that answers a fixed non-200
// status once it is set up (gramps-web: 405 "Users already exist") — counts as done on that status alone; any other
// non-200 is "cannot read" (fail closed). A 200 is read as JSON: `field` is a dotted path whose parts may be list
// indexes (`setup.0.status` — ghost; `0.done` — home-assistant), compared as text with `done`.
func probeOnce(p *SetupDoneProbe) (done bool, got string, err error) {
status, body, err := setupGateProbeFetch(p.URL)
if err != nil {
return false, "", err
}
if p.DoneStatus != 0 && status == p.DoneStatus {
return true, fmt.Sprintf("HTTP %d", status), nil
}
if status != http.StatusOK {
return false, fmt.Sprintf("HTTP %d", status), fmt.Errorf("HTTP %d", status)
}
if p.Field == "" {
return false, "no field", fmt.Errorf("the probe names no field")
}
done, got = probeSaysDone(body, p.Field, p.Done)
return done, got, nil
}
// probeSaysDone reads the field at the dotted path (a numeric part indexes a list) and compares its text form with
// done. Anything it cannot read is "not done" — the gate stays closed (fail closed).
func probeSaysDone(body []byte, field, done string) (bool, string) {
var v interface{}
if err := json.Unmarshal(body, &v); err != nil {
return false, "not JSON"
}
for _, k := range strings.Split(field, ".") {
obj, ok := v.(map[string]interface{})
if !ok {
return false, "no field " + field
}
if v, ok = obj[k]; !ok {
switch cur := v.(type) {
case map[string]interface{}:
nv, ok := cur[k]
if !ok {
return false, "no field " + field
}
v = nv
case []interface{}:
n, err := strconv.Atoi(k)
if err != nil || n < 0 || n >= len(cur) {
return false, "no field " + field
}
v = cur[n]
default:
return false, "no field " + field
}
}
@@ -431,14 +469,13 @@ func (m *Manager) SetupGateTick() {
if it.probe == nil || it.probe.URL == "" || !it.running {
continue
}
body, err := setupGateProbeGet(it.probe.URL)
done, got, err := probeOnce(it.probe)
if err != nil {
if m.isDebug() {
m.logger.Printf("[DEBUG] [stacks] %s: setup probe unreadable (%v) — gate stays closed", it.name, err)
}
continue
}
done, got := probeSaysDone(body, it.probe.Field, it.probe.Done)
if m.isDebug() {
m.logger.Printf("[DEBUG] [stacks] %s: setup probe %s = %q (done when %q)", it.name, it.probe.Field, got, it.probe.Done)
}
@@ -162,14 +162,12 @@ func TestSetupGate_TheProbeOpensItOnlyWhenTheAppSaysSetUp(t *testing.T) {
dir := closedGate(t, m)
answer := `{"data":{"initialized":false}}`
var probeErr error
old := setupGateProbeGet
setupGateProbeGet = func(url string) ([]byte, error) {
t.Cleanup(SetSetupGateProbeGetForTest(func(url string) ([]byte, error) {
if url != "http://gapp:80/api/status" {
t.Errorf("probed %q", url)
}
return []byte(answer), probeErr
}
t.Cleanup(func() { setupGateProbeGet = old })
}))
m.SetupGateTick()
if c := LoadAppConfig(dir); !c.SetupGate.Closed() {
+33 -9
View File
@@ -134,6 +134,9 @@ func (m *Manager) OpenSignupWindow(name string) (string, error) {
if err := m.removeSignupBlockFile(name); err != nil {
return "", err
}
if st.Meta.AfterSetup != nil && len(st.Meta.AfterSetup.Env) > 0 { // v0.282.0: the app's own switch opens too (a restart)
m.goNativeLock(name, false, "the household's window")
}
m.logger.Printf("[INFO] [stacks] %s: the household opened sign-up until %s — the loop closes it again", name, until)
return until, nil
}
@@ -178,9 +181,27 @@ func (m *Manager) reconcileSignupBlocks() {
if err := m.writeSignupBlock(n, w.hosts, w.fragment); err != nil {
m.logger.Printf("[ERROR] [stacks] %s: the sign-up block could not be written: %v — sign-up is OPEN until it is", n, err)
}
// v0.282.0: the app's own switch back on (after the household's window), or a retry of a failed attempt —
// at most every nativeLockRetry, so a switch that cannot be set does not restart the app every tick.
if st, ok := m.GetStack(n); ok && st.Meta.AfterSetup != nil && st.AppConfig != nil && st.AppConfig.SetupGate != nil &&
st.AppConfig.SetupGate.NativeLock != NativeLockApplied {
last := st.AppConfig.AfterSetup
due := last == nil || last.OK
if !due {
if t, err := time.Parse(time.RFC3339, last.At); err != nil || m.now().Sub(t) > nativeLockRetry {
due = true
}
}
if due {
m.goNativeLock(n, true, "the loop (window ended or retry)")
}
}
}
}
// nativeLockRetry: how often the loop retries an app's own switch that could not be set.
var nativeLockRetry = 30 * time.Minute
// SetupGateProbe asks the app's own "setup done" status once (the household's button asks it first, Part A of the
// 2026-09-29 afternoon brief). has=false: the template declares no probe.
func (m *Manager) SetupGateProbe(name string) (has bool, done bool, got string, err error) {
@@ -192,17 +213,20 @@ func (m *Manager) SetupGateProbe(name string) (has bool, done bool, got string,
if p == nil || p.URL == "" {
return false, false, "", nil
}
body, err := setupGateProbeGet(p.URL)
if err != nil {
return true, false, "", err
}
done, got = probeSaysDone(body, p.Field, p.Done)
return true, done, got, nil
done, got, err = probeOnce(p)
return true, done, got, err
}
// SetSetupGateProbeGetForTest swaps the probe's HTTP read (a test seam for other packages); returns the restore.
// f's error means "unreadable"; a nil error is a 200 with that body.
func SetSetupGateProbeGetForTest(f func(url string) ([]byte, error)) func() {
old := setupGateProbeGet
setupGateProbeGet = f
return func() { setupGateProbeGet = old }
old := setupGateProbeFetch
setupGateProbeFetch = func(url string) (int, []byte, error) {
b, err := f(url)
if err != nil {
return 0, nil, err
}
return 200, b, nil
}
return func() { setupGateProbeFetch = old }
}