package render import ( "context" "errors" "fmt" "os" "path/filepath" "sync" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/release" "amadan.net/oficina/equipo/internal/wire" ) // healthRig is a Health over a real tree directory, with VerifyRenderer // and the fixture render faked: verify returns verifyErr, the fixture // fixtureErr (after waiting on gate when it is set). type healthRig struct { h *Health tree string mu sync.Mutex verifyErr error fixtureErr error gate chan struct{} verifies atomic.Int32 fixtures atomic.Int32 changed atomic.Int32 configs []LaunchConfig } const healthPin = "8f27c7adf358cd4c9f31fb16a06449ecf67696864f35b54005574b0a9ce8dae8" func newHealthRig(t *testing.T) *healthRig { t.Helper() exe := filepath.Join(t.TempDir(), "equipo-runner") cfg, scratch := Installed("/usr/bin/bwrap", exe, healthPin) r := &healthRig{tree: cfg.Tree} if err := os.MkdirAll(cfg.Tree, 0o755); err != nil { t.Fatal(err) } r.h = &Health{Config: cfg, Scratch: scratch, Verify: func(tree, pin string) error { r.verifies.Add(1) if tree != cfg.Tree || pin != healthPin { return fmt.Errorf("verified %s against %s", tree, pin) } r.mu.Lock() defer r.mu.Unlock() return r.verifyErr }, Fixture: func(ctx context.Context, c LaunchConfig, s string) error { r.fixtures.Add(1) r.mu.Lock() r.configs = append(r.configs, c) gate, err := r.gate, r.fixtureErr r.mu.Unlock() if s != scratch { return fmt.Errorf("scratch %s", s) } if gate != nil { select { case <-gate: case <-ctx.Done(): return ctx.Err() } } return err }, Changed: func() { r.changed.Add(1) }, } return r } func (r *healthRig) set(verify, fixture error) { r.mu.Lock() r.verifyErr, r.fixtureErr = verify, fixture r.mu.Unlock() } // settle starts the check and waits for its end (Ready waits on a // running check before its own). func (r *healthRig) settle(t *testing.T) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() r.h.Start(ctx) r.h.wait(ctx) } // TestHealthReportsEachState (task 8): the renderer's health is ok only // when the tree verifies and has rendered the fixture page; otherwise // the state VerifyRenderer's error gives (anything unexpected is a // mismatch), never ok. func TestHealthReportsEachState(t *testing.T) { for _, c := range []struct { name string verify error want string }{ {"ok", nil, wire.ToolHealthy}, {"missing", &release.RendererError{Health: wire.ToolMissing, Reason: "absent"}, wire.ToolMissing}, {"mismatch", &release.RendererError{Health: wire.ToolMismatch, Path: "usr/lib/x", Reason: "hash"}, wire.ToolMismatch}, {"unpinned", &release.RendererError{Health: wire.ToolUnpinned, Reason: "no pin"}, wire.ToolUnpinned}, {"unexpected", errors.New("disk on fire"), wire.ToolMismatch}, } { t.Run(c.name, func(t *testing.T) { r := newHealthRig(t) r.set(c.verify, nil) r.settle(t) if got := r.h.Report(context.Background()); got != c.want { t.Fatalf("reported %q, want %q", got, c.want) } tree, health, err := r.h.Ready(context.Background()) if health != c.want || (c.want == wire.ToolHealthy) != (err == nil) || (c.want == wire.ToolHealthy) != (tree == r.tree) { t.Fatalf("ready: %q %q %v", tree, health, err) } if c.verify != nil && r.fixtures.Load() != 0 { t.Fatalf("a tree that does not verify was rendered") } if c.want == wire.ToolHealthy && (len(r.configs) != 1 || r.configs[0] != r.h.Config) { t.Fatalf("fixture rendered with %+v", r.configs) } }) } } // TestHealthVerifiedButNotRenderedIsNotOK: a tree that verifies but // cannot render the fixture page reports missing (as a host that cannot // nest the browser's sandbox does) and Ready refuses it. The render is // not tried again for the same tree: the runner needs updating. func TestHealthVerifiedButNotRenderedIsNotOK(t *testing.T) { r := newHealthRig(t) r.set(nil, errors.New("the browser's sandbox did not start")) r.settle(t) if got := r.h.Report(context.Background()); got != wire.ToolMissing { t.Fatalf("reported %q", got) } r.h.wait(context.Background()) tree, health, err := r.h.Ready(context.Background()) if tree != "" || health != wire.ToolMissing || !errors.Is(err, ErrNotChecked) { t.Fatalf("ready: %q %q %v", tree, health, err) } // Even once it would render, the same tree is not tried again. r.set(nil, nil) if _, health, _ := r.h.Ready(context.Background()); health != wire.ToolMissing || r.fixtures.Load() != 1 { t.Fatalf("tried again: %q after %d renders", health, r.fixtures.Load()) } } // TestHealthNotEndedNeedsAttention: a fixture whose sandbox could not be // shown to have ended is never ok and never tried again, not even with // another tree. func TestHealthNotEndedNeedsAttention(t *testing.T) { r := newHealthRig(t) r.set(nil, fmt.Errorf("closing: %w", ErrNotEnded)) r.settle(t) replaceTree(t, r.tree) r.set(nil, nil) tree, health, err := r.h.Ready(context.Background()) if tree != "" || health != wire.ToolMissing || !errors.Is(err, ErrNotEnded) || r.fixtures.Load() != 1 { t.Fatalf("ready: %q %q %v after %d renders", tree, health, err, r.fixtures.Load()) } } // TestHealthRenderNotEndedNeedsAttention: a render after the fixture // whose sandbox could not be shown to have ended stops every later one; // another render's error does not. func TestHealthRenderNotEndedNeedsAttention(t *testing.T) { r := newHealthRig(t) r.settle(t) r.h.Ended(nil) r.h.Ended(&Error{Code: CodeTimeout}) if _, health, err := r.h.Ready(context.Background()); health != wire.ToolHealthy || err != nil { t.Fatalf("after a timeout: %q %v", health, err) } r.h.Ended(fmt.Errorf("render: %w", ErrNotEnded)) if got := r.h.Report(context.Background()); got != wire.ToolMissing || r.changed.Load() != 2 { t.Fatalf("reported %q, changed %d", got, r.changed.Load()) } r.h.wait(context.Background()) if tree, health, err := r.h.Ready(context.Background()); tree != "" || health != wire.ToolMissing || !errors.Is(err, ErrNotEnded) { t.Fatalf("after a render that did not end: %q %q %v", tree, health, err) } } // TestHealthStartsInTheBackground: Start does not wait for the check; // until the fixture has rendered the report is not ok, and once it has, // Changed hears it (the next hello says ok). func TestHealthStartsInTheBackground(t *testing.T) { r := newHealthRig(t) r.gate = make(chan struct{}) done := make(chan struct{}) go func() { r.h.Start(context.Background()) close(done) }() select { case <-done: case <-time.After(5 * time.Second): t.Fatal("Start waited for the fixture render") } if got := r.h.Report(context.Background()); got != wire.ToolMissing { t.Fatalf("reported %q before the fixture rendered", got) } close(r.gate) r.h.wait(context.Background()) if r.changed.Load() != 1 { t.Fatalf("changed %d times", r.changed.Load()) } if got := r.h.Report(context.Background()); got != wire.ToolHealthy { t.Fatalf("reported %q", got) } // Report checks again in the background; the same state says nothing. r.h.wait(context.Background()) if r.changed.Load() != 1 || r.verifies.Load() < 2 { t.Fatalf("changed %d times, verified %d", r.changed.Load(), r.verifies.Load()) } } // TestHealthRechecksTheFilesBeforeEachRender: Ready verifies the tree // every time; once it no longer verifies it is not ok, and the report // changes with it. func TestHealthRechecksTheFilesBeforeEachRender(t *testing.T) { r := newHealthRig(t) r.settle(t) for range 3 { if _, health, err := r.h.Ready(context.Background()); health != wire.ToolHealthy || err != nil { t.Fatalf("ready %q %v", health, err) } } if r.verifies.Load() != 4 || r.fixtures.Load() != 1 { t.Fatalf("verified %d times, rendered %d", r.verifies.Load(), r.fixtures.Load()) } r.set(&release.RendererError{Health: wire.ToolMismatch, Path: "MANIFEST", Reason: "tampered"}, nil) tree, health, err := r.h.Ready(context.Background()) if tree != "" || health != wire.ToolMismatch || !errors.Is(err, release.ErrRendererMismatch) { t.Fatalf("ready: %q %q %v", tree, health, err) } if got := r.h.Report(context.Background()); got != wire.ToolMismatch || r.changed.Load() != 2 { t.Fatalf("reported %q, changed %d", got, r.changed.Load()) } } // TestHealthIsPerTree: the fixture rendered with one tree says nothing // about another at the same path (an update put it there): that one is // not ok until it has rendered too. func TestHealthIsPerTree(t *testing.T) { r := newHealthRig(t) r.settle(t) replaceTree(t, r.tree) r.set(nil, errors.New("crashed")) if _, health, _ := r.h.Ready(context.Background()); health != wire.ToolMissing || r.fixtures.Load() != 2 { t.Fatalf("another tree: %q after %d renders", health, r.fixtures.Load()) } // A tree replaced while the fixture renders is not the one rendered. r = newHealthRig(t) var once sync.Once r.h.Fixture = func(context.Context, LaunchConfig, string) error { once.Do(func() { replaceTree(t, r.tree) }) return nil } r.settle(t) if got := r.h.Report(context.Background()); got == wire.ToolHealthy { t.Fatal("a tree replaced during its fixture render is ok") } // The tree now there renders once on its own, and then it is ok. r.h.wait(context.Background()) if _, health, _ := r.h.Ready(context.Background()); health != wire.ToolHealthy { t.Fatalf("the new tree: %q", health) } } // TestHealthTreeReplacedWhileVerified: a tree replaced while it is // verified is not the one verified: a mismatch, never rendered. func TestHealthTreeReplacedWhileVerified(t *testing.T) { r := newHealthRig(t) r.h.Verify = func(string, string) error { replaceTree(t, r.tree) return nil } if _, health, err := r.h.Ready(context.Background()); health != wire.ToolMismatch || err == nil || r.fixtures.Load() != 0 { t.Fatalf("ready %q %v after %d renders", health, err, r.fixtures.Load()) } } // TestHealthLaunchRefusalKeepsItsState: a fixture render that Launch // refuses because the tree no longer verifies says that state. func TestHealthLaunchRefusalKeepsItsState(t *testing.T) { r := newHealthRig(t) r.set(nil, &release.RendererError{Health: wire.ToolMismatch, Path: "usr/bin/x", Reason: "hash"}) if _, health, err := r.h.Ready(context.Background()); health != wire.ToolMismatch || !errors.Is(err, ErrNotChecked) { t.Fatalf("ready %q %v", health, err) } } // TestHealthCancelledRenderIsTriedAgain: a fixture render cut short (the // runner stopping, a render call cancelled) was not the tree's try. func TestHealthCancelledRenderIsTriedAgain(t *testing.T) { r := newHealthRig(t) r.gate = make(chan struct{}) ctx, cancel := context.WithCancel(context.Background()) cancel() if health, _ := r.h.run(ctx); health != wire.ToolMissing { t.Fatalf("cancelled: %q", health) } close(r.gate) if _, health, err := r.h.Ready(context.Background()); health != wire.ToolHealthy || err != nil || r.fixtures.Load() != 2 { t.Fatalf("after a cancelled render: %q %v, %d renders", health, err, r.fixtures.Load()) } } // TestHealthOnlyOnLinuxAmd64: the renderer is Linux amd64's; a nil // Health (a Mac or arm64 runner has none) reports nothing and is never // ready. func TestHealthOnlyOnLinuxAmd64(t *testing.T) { for _, p := range [][2]string{{"darwin", "arm64"}, {"linux", "arm64"}, {"darwin", "amd64"}} { if Platform(p[0], p[1]) { t.Fatalf("%s/%s has a renderer", p[0], p[1]) } } if !Platform("linux", "amd64") { t.Fatal("linux/amd64 has no renderer") } var h *Health h.Start(context.Background()) if got := h.Report(context.Background()); got != "" { t.Fatalf("no renderer reported %q", got) } if tree, health, err := h.Ready(context.Background()); tree != "" || health != wire.ToolMissing || err == nil { t.Fatalf("no renderer ready: %q %q %v", tree, health, err) } } // replaceTree puts another directory at tree, as an install's rename // does. func replaceTree(t *testing.T, tree string) { t.Helper() next := tree + ".next" if err := os.Mkdir(next, 0o755); err != nil { t.Fatal(err) } if err := os.Rename(tree, tree+".old"); err != nil { t.Fatal(err) } if err := os.Rename(next, tree); err != nil { t.Fatal(err) } } // TestHealthTriesAFailedFixtureAgainAfterTenMinutes (task 10): a failed // fixture render (a loaded box timing it out, say) does not stick until // the runner restarts. Once the failure is more than FixtureRetry old, // the next check, Ready's or a report's, renders it once more; within // that it is not tried again. A sandbox that did not end still never is. func TestHealthTriesAFailedFixtureAgainAfterTenMinutes(t *testing.T) { r := newHealthRig(t) var mu sync.Mutex clock := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC) r.h.Now = func() time.Time { mu.Lock(); defer mu.Unlock(); return clock } advance := func(d time.Duration) { mu.Lock(); clock = clock.Add(d); mu.Unlock() } r.set(nil, errors.New("the render ran out of time")) r.settle(t) ready := func() (string, error) { t.Helper() _, health, err := r.h.Ready(context.Background()) return health, err } advance(FixtureRetry - time.Second) if health, err := ready(); health != wire.ToolMissing || !errors.Is(err, ErrNotChecked) || r.fixtures.Load() != 1 { t.Fatalf("within ten minutes: %q %v after %d renders", health, err, r.fixtures.Load()) } advance(2 * time.Second) if health, _ := ready(); health != wire.ToolMissing || r.fixtures.Load() != 2 { t.Fatalf("past ten minutes: %q after %d renders", health, r.fixtures.Load()) } // The failure just now starts the wait again. if health, _ := ready(); health != wire.ToolMissing || r.fixtures.Load() != 2 { t.Fatalf("right after the second try: %q after %d renders", health, r.fixtures.Load()) } // A report's background check tries too, once the wait is over. r.set(nil, nil) advance(FixtureRetry + time.Second) r.h.Start(context.Background()) // settle's context has ended r.h.wait(context.Background()) if got := r.h.Report(context.Background()); got != wire.ToolHealthy || r.fixtures.Load() != 3 { t.Fatalf("a report's check past ten minutes: %q after %d renders", got, r.fixtures.Load()) } // A sandbox that did not end is never tried again, however long ago. r2 := newHealthRig(t) r2.h.Now = r.h.Now r2.set(nil, fmt.Errorf("closing: %w", ErrNotEnded)) r2.settle(t) r2.set(nil, nil) advance(10 * FixtureRetry) if _, health, err := r2.h.Ready(context.Background()); health != wire.ToolMissing || !errors.Is(err, ErrNotEnded) || r2.fixtures.Load() != 1 { t.Fatalf("not ended, much later: %q %v after %d renders", health, err, r2.fixtures.Load()) } }