package render import ( "context" "errors" "fmt" "log/slog" "os" "path/filepath" "sync" "time" "amadan.net/oficina/equipo/internal/release" "amadan.net/oficina/equipo/internal/wire" ) // Platform reports whether a runner on goos/goarch has the page // renderer: Linux amd64 only. A Mac runner and a Linux arm64 one neither // install, check nor report one. func Platform(goos, goarch string) bool { return goos == "linux" && goarch == "amd64" } // Installed is the launch configuration of the renderer installed beside // the runner's executable, for pin: the tree release.RendererTree(, pin), bubblewrap bwrap and the runner itself as the // sandbox's first process; and the scratch directory a fixture render // uses, /renderer, which the installer made private. func Installed(bwrap, executable, pin string) (LaunchConfig, string) { dir := filepath.Dir(executable) return LaunchConfig{Bwrap: bwrap, Binary: executable, Tree: release.RendererTree(dir, pin), Pin: pin}, filepath.Join(dir, "renderer") } // ErrNotChecked is a tree that verifies but has not rendered the fixture // page since this runner started: the check is still running, or the // render failed. Such a tree is not used. var ErrNotChecked = errors.New("render: the renderer has not rendered its check page") // FixtureRetry is how long a tree whose fixture render failed waits // before a check renders it again. const FixtureRetry = 10 * time.Minute // errTreeMoved is a tree that was replaced while it was checked. var errTreeMoved = &release.RendererError{Health: wire.ToolMismatch, Reason: "the tree was replaced while it was checked"} // Health is the runner's word on its page renderer, ToolHealth.Renderer // (spec section 3, "Pin and provisioning"). It is ok only when the tree // verifies against the linked pin now and this very tree (the same // directory, not only the same path) has rendered the fixture page since // the runner started. Otherwise it is the state VerifyRenderer gives // (missing, mismatch or unpinned), or missing for a tree that verifies // but has not rendered: still being checked, or unable to render, as a // host that cannot nest the browser's sandbox is. // // The fixture is rendered once per tree: a failure is not tried again // for FixtureRetry, since another try soon after does not help a // renderer that cannot render (the runner needs updating); past that, // the next check (Ready's or a report's) renders it once more, so a // failure on a loaded box does not stick until the runner restarts. A // fixture whose sandbox could not be shown to // have ended (ErrNotEnded) stops every later render of this process: the // runner needs attention. // // A nil Health is a runner without a renderer: it reports nothing and is // never ready. type Health struct { // Config is Installed's launch configuration and Scratch its scratch // directory. Config LaunchConfig Scratch string // Verify and Fixture are release.VerifyRenderer and CheckFixture // (nil for those); tests replace them. Verify func(tree, pin string) error Fixture func(ctx context.Context, cfg LaunchConfig, scratch string) error // Changed hears that the reported state changed, so the next hello // says it; it is never called with Health's lock held. Changed func() // Logger hears why a check was not ok, for the operator. Logger *slog.Logger // Now is the clock (nil: time.Now); tests replace it. Now func() time.Time mu sync.Mutex base context.Context state string passed os.FileInfo tried []tried stuck error running chan struct{} } // Start checks the renderer in the background (it does not hold up the // runner's connect): the tree is verified and the fixture page rendered. // Background checks run with ctx, the runner's. func (h *Health) Start(ctx context.Context) { if h == nil { return } h.mu.Lock() h.base = ctx h.mu.Unlock() h.kick() } // Report is the state for ToolHealth.Renderer ("" without a renderer): // the last check's, missing before the first has ended. It never waits // on the disk; it starts another check in the background, when none is // running, so the files are verified again for the next report, and a // change of state is told to Changed. func (h *Health) Report(context.Context) string { if h == nil { return "" } h.mu.Lock() state := reported(h.state) h.mu.Unlock() h.kick() return state } // Ready is the render path's check before each render: it waits for a // running check, then verifies the tree again now. It returns the tree // to launch with when the health is ok; otherwise "", the health and why. // Launch verifies the tree once more as it mounts it. func (h *Health) Ready(ctx context.Context) (tree, health string, err error) { if h == nil { return "", wire.ToolMissing, errors.New("render: this runner has no page renderer") } if health, err = h.run(ctx); err != nil { return "", health, err } return h.Config.Tree, health, nil } // Ended is told how each render with the tree ended (its error, or // nil). A sandbox that could not be shown to have ended (ErrNotEnded) // stops every later render of this process, as a fixture's does: the // runner needs attention, never another try. func (h *Health) Ended(err error) { if h == nil || !errors.Is(err, ErrNotEnded) { return } h.mu.Lock() before := reported(h.state) if h.stuck == nil { h.stuck = err } h.state = wire.ToolMissing h.mu.Unlock() if before != wire.ToolMissing && h.Changed != nil { h.Changed() } } // tried is a tree whose fixture was rendered and failed (at failed; zero // while it renders). type tried struct { tree os.FileInfo failed time.Time } func (h *Health) now() time.Time { if h.Now != nil { return h.Now() } return time.Now() } // reported is a state as reported: missing before the first check. func reported(state string) string { if state == "" { return wire.ToolMissing } return state } // kick runs a check in the background unless one is running or Start // was not called. func (h *Health) kick() { h.mu.Lock() ctx := h.base if ctx == nil || h.running != nil || ctx.Err() != nil { h.mu.Unlock() return } done := make(chan struct{}) h.running = done h.mu.Unlock() go h.finish(ctx, done) } // wait waits for a running check to end. func (h *Health) wait(ctx context.Context) { for { h.mu.Lock() ch := h.running h.mu.Unlock() if ch == nil { return } select { case <-ch: case <-ctx.Done(): return } } } // run is one check, one at a time: it waits for a running one first. func (h *Health) run(ctx context.Context) (string, error) { h.mu.Lock() for h.running != nil { ch := h.running h.mu.Unlock() select { case <-ch: case <-ctx.Done(): return wire.ToolMissing, ctx.Err() } h.mu.Lock() } done := make(chan struct{}) h.running = done h.mu.Unlock() return h.finish(ctx, done) } // finish runs the check that holds done (h.running), records its state, // lets the next check start and tells Changed of a change. func (h *Health) finish(ctx context.Context, done chan struct{}) (string, error) { state, err := h.check(ctx) if err != nil && h.Logger != nil { h.Logger.Warn("page renderer not ready", "health", state, "err", err) } h.mu.Lock() before := reported(h.state) h.state, h.running = state, nil h.mu.Unlock() close(done) if before != state && h.Changed != nil { h.Changed() } return state, err } // check verifies the tree and, for a tree that has not been tried, // renders the fixture page with it. func (h *Health) check(ctx context.Context) (string, error) { cfg := h.Config verify, fixture := h.Verify, h.Fixture if verify == nil { verify = release.VerifyRenderer } if fixture == nil { fixture = CheckFixture } before, _ := os.Lstat(cfg.Tree) if err := verify(cfg.Tree, cfg.Pin); err != nil { return release.RendererHealth(err), err } tree, err := os.Lstat(cfg.Tree) if err != nil || before == nil || !os.SameFile(before, tree) { return wire.ToolMismatch, errTreeMoved } h.mu.Lock() stuck, passed, wasTried := h.stuck, h.passed != nil && os.SameFile(h.passed, tree), false for i, t := range h.tried { if !os.SameFile(t.tree, tree) { continue } // A failure more than FixtureRetry old gets one more try now. if stuck == nil && !passed && !t.failed.IsZero() && h.now().Sub(t.failed) > FixtureRetry { h.tried = append(h.tried[:i], h.tried[i+1:]...) } else { wasTried = true } break } if stuck == nil && !passed && !wasTried { h.tried = append(h.tried, tried{tree: tree}) } h.mu.Unlock() switch { case stuck != nil: return wire.ToolMissing, stuck case passed: return wire.ToolHealthy, nil case wasTried: return wire.ToolMissing, ErrNotChecked } err = fixture(ctx, cfg, h.Scratch) if after, serr := os.Lstat(cfg.Tree); err == nil && (serr != nil || !os.SameFile(tree, after)) { err = errTreeMoved } switch { case errors.Is(err, ErrNotEnded): h.mu.Lock() h.stuck = err h.mu.Unlock() return wire.ToolMissing, err case err != nil && ctx.Err() != nil: // Cut short (the runner stopping, a render call cancelled): the // tree was not given its try. h.mu.Lock() h.tried = h.tried[:len(h.tried)-1] h.mu.Unlock() return wire.ToolMissing, fmt.Errorf("%w: %w", ErrNotChecked, err) case err != nil: h.mu.Lock() h.tried[len(h.tried)-1].failed = h.now() h.mu.Unlock() var re *release.RendererError if errors.As(err, &re) { return release.RendererHealth(err), fmt.Errorf("%w: %w", ErrNotChecked, err) } return wire.ToolMissing, fmt.Errorf("%w: %w", ErrNotChecked, err) } h.mu.Lock() h.passed = tree h.mu.Unlock() return wire.ToolHealthy, nil }