package renderpage import ( "context" "encoding/json" "errors" "fmt" "image" "os" "path/filepath" "slices" "strconv" "sync" "time" "amadan.net/oficina/equipo/internal/release" "amadan.net/oficina/equipo/internal/runner/render" "amadan.net/oficina/equipo/internal/wire" ) // The fixed error codes: the spec's seven and the plan's two (a site // whose files hold a secret, a scanner that could not run). Each is a // *render.Error with that Code. const ( CodeRendererMissing = "renderer_missing" CodeRendererMismatch = "renderer_mismatch" CodeNoSite = "no_site" CodeTooMany = "too_many" CodeBusy = "busy" CodeTimeout = render.CodeTimeout CodeCrashed = render.CodeCrashed CodeSecrets = "secrets" CodeScanner = "scanner" ) // Codes are every code, in the spec's order then the plan's. var Codes = []string{CodeRendererMissing, CodeRendererMismatch, CodeNoSite, CodeTooMany, CodeBusy, CodeTimeout, CodeCrashed, CodeSecrets, CodeScanner} // Per-step limits (spec section 3, "Sandbox"), counted by the Step in // the step's own persisted state. const ( MaxCalls = 20 MaxCaptures = 60 ) // callTimeout bounds one accepted call, every phase of it (spec section // 3, "Limits per call: 60 seconds"): render.CallTimeout; tests lower it. var callTimeout = render.CallTimeout // errCallTimeout is the cause of an accepted call's own deadline. var errCallTimeout = errors.New("render_page: the call ran past its bound") // Refuse is a refusal with one of the fixed codes; detail is for the // runner's log, never the reply. func Refuse(code, detail string) error { return &render.Error{Code: code, Detail: detail} } // Usage is a step's render use so far, this call included. type Usage struct{ Calls, Captures int } // Step is the running step a call is for. type Step interface { // Accept counts one call of captures captures in the step's // persisted state, unless the step would pass MaxCalls or // MaxCaptures: then it is Refuse(CodeTooMany). Accept(ctx context.Context, captures int) (Usage, error) // Site writes tree's site into stage (made fresh and private) and // scans it: its digest, or a refusal (no_site, busy, secrets, // scanner). Site(ctx context.Context, tree, stage string) (digest string, err error) // Dir is the step's render directory, which the model reads as // /render/ (the runner makes it private), and Scratch a directory // of the runner's for a call's work, outside it. Dir() string Scratch() string // Audit keeps one accepted call's record on the step, with the // step's attempt set (spec section 4, "Audit"); a record it cannot // keep is the step's to log, never the call's failure. Audit(ctx context.Context, rec wire.RenderAudit) } // Renderer is the page renderer's health (render.Health). type Renderer interface { // Ready verifies the tree before a render: the tree to launch, or // its health and why not. Ready(ctx context.Context) (tree, health string, err error) // Ended hears how each render ended. Ended(err error) } // Capture is one PNG a call wrote to the step's render directory. type Capture struct { // File is its name in the directory (/render/ to the model). File string // Tree is the tree rendered and Digest its export's; a diff has // Diff set, Tree "diff" and work's Digest. Tree, Digest string Page render.Page // Width and Height are the PNG's, as written; Bytes its size. Width, Height int Bytes int64 Diff bool // Changed is a diff's share of changed pixels, 0 to 1. Changed float64 } // Tool is render_page on one runner. Its zero value with Renderer and // Config set is ready; one call runs at a time across the runner. type Tool struct { Renderer Renderer // Config is the launch configuration but Tree and Site, which each // render sets (Ready's tree, the call's export). Config render.LaunchConfig // Render is render.Render (nil); tests replace it. Render func(ctx context.Context, cfg render.LaunchConfig, out string, pages []render.Page) (*render.Report, error) busy sync.Mutex } // rendered is one tree's render. type rendered struct { tree, digest, out string report *render.Report captures []Capture pngs [][]byte } // Call is one render_page call for step with raw, its input. The text is // the reply for the model, always set. err is nil for a call that // rendered; a refusal with a fixed code (render.ErrorCode), the // context's error, or an invalid input (no code: the tool call is wrong, // and it was not counted). Only a call that rendered writes captures. // // In order: the input is checked; one call at a time per runner (else // busy); the call is counted (too_many); every tree's site is exported // and scanned before any render; each tree is rendered after Ready // verifies the renderer; each capture is decoded and re-encoded; with // compare, each page's pair is diffed; then the PNGs are written. // // From its acceptance the call has one deadline, callTimeout, across // every phase: both trees' exports and scans, both renders of a compare // (each render's own bound sits inside it) and the captures' processing. // Past it the call ends timeout, writes nothing, and its error still // carries what ended it (a sandbox not shown to have ended stays // render.ErrNotEnded). func (t *Tool) Call(ctx context.Context, step Step, raw json.RawMessage) (string, []Capture, error) { req, err := Parse(raw) if err != nil { return err.Error(), nil, err } if !t.busy.TryLock() { return refused(ctx, Refuse(CodeBusy, "another render is running on this runner")) } defer t.busy.Unlock() usage, err := step.Accept(ctx, len(req.Pages)*len(req.trees())) if err != nil { return refused(ctx, err) } began := time.Now() call, cancel := context.WithTimeoutCause(ctx, callTimeout, errCallTimeout) defer cancel() text, caps, err := t.accepted(call, step, req, usage) if err != nil { text, caps, err = ended(ctx, call, err) } step.Audit(context.WithoutCancel(ctx), audit(ctx, req, usage, began, caps, err)) return text, caps, err } // audit is an accepted call's record: its tree, pages and counted // captures, the files it wrote, how long it took and how it ended // (rendered, its code, or cancelled when ctx, the caller's, ended). func audit(ctx context.Context, req Request, usage Usage, began time.Time, caps []Capture, err error) wire.RenderAudit { rec := wire.RenderAudit{Call: usage.Calls, Tree: req.Tree, Pages: len(req.Pages), Captures: len(req.Pages) * len(req.trees()), Files: len(caps), DurationMS: time.Since(began).Milliseconds(), Outcome: wire.RenderRendered} if req.Compare { rec.Tree = wire.RenderTreeCompare } switch { case err == nil: case ctx.Err() != nil: rec.Outcome = wire.RenderCancelled default: rec.Outcome = render.ErrorCode(err) } return rec } // accepted is an accepted call's work under its deadline (ctx): the // reply and captures, or the error that ended it, unmapped. func (t *Tool) accepted(ctx context.Context, step Step, req Request, usage Usage) (string, []Capture, error) { work := filepath.Join(step.Scratch(), strconv.Itoa(usage.Calls)) if err := freshDir(work); err != nil { return "", nil, err } defer os.RemoveAll(work) // Every site first: a secret in one tree refuses before any render. var done []*rendered for _, tree := range req.trees() { if err := ctx.Err(); err != nil { return "", nil, err } digest, err := step.Site(ctx, tree, filepath.Join(work, "site-"+tree)) if err != nil { return "", nil, err } done = append(done, &rendered{tree: tree, digest: digest, out: filepath.Join(work, "out-"+tree)}) } for _, r := range done { if err := t.renderTree(ctx, work, usage.Calls, req, r); err != nil { return "", nil, err } } var diffs []Capture var diffPNGs [][]byte if req.Compare { for i, p := range req.Pages { if err := ctx.Err(); err != nil { return "", nil, err } c, png, err := diffPage(done[0], done[1], i, p, usage.Calls) if err != nil { return "", nil, err } diffs, diffPNGs = append(diffs, c), append(diffPNGs, png) } } var caps []Capture var pngs [][]byte for _, r := range done { caps, pngs = append(caps, r.captures...), append(pngs, r.pngs...) } caps, pngs = append(caps, diffs...), append(pngs, diffPNGs...) // Nothing past the deadline is written, or kept (writeCaptures). if err := writeCaptures(ctx, step.Dir(), caps, pngs); err != nil { return "", nil, err } return reply(req, usage, done, diffs), caps, nil } // renderTree renders r's site and takes in its captures. func (t *Tool) renderTree(ctx context.Context, work string, call int, req Request, r *rendered) error { tree, health, err := t.Renderer.Ready(ctx) if err != nil || health != wire.ToolHealthy { if ctx.Err() != nil { return ctx.Err() } return errors.Join(Refuse(healthCode(health), "not ready"), err) } if err := freshDir(r.out); err != nil { return err } cfg := t.Config cfg.Tree, cfg.Site = tree, filepath.Join(work, "site-"+r.tree) run := t.Render if run == nil { run = render.Render } report, err := run(ctx, cfg, r.out, req.Pages) t.Renderer.Ended(err) if err != nil { return err } if report == nil || len(report.Pages) != len(req.Pages) || report.Error != "" { return Refuse(CodeCrashed, "the report does not hold every page") } r.report = report for i, p := range req.Pages { // A render that came back past the call's deadline is not taken // in, nor processed past it. if err := ctx.Err(); err != nil { return err } img, err := readCapture(r.out, report.Pages[i], p) if err != nil { return err } png, w, h, err := encodeCapture(img) if err != nil { return Refuse(CodeCrashed, err.Error()) } r.pngs = append(r.pngs, png) r.captures = append(r.captures, Capture{File: fmt.Sprintf("%d-%s-%d.png", call, r.tree, i+1), Tree: r.tree, Digest: r.digest, Page: p, Width: w, Height: h, Bytes: int64(len(png))}) } return nil } // readCapture decodes the capture rep names in out, checked against the // page asked for: the report is of that page, and the capture is the // size the report says and within its viewport (a full page within // MaxHeight). func readCapture(out string, rep render.PageReport, p render.Page) (*image.NRGBA, error) { vw, vh, _ := p.Viewport.Size() if rep.Path != p.Path || rep.Viewport != p.Viewport || rep.FullPage != p.FullPage || rep.Capture == "" || filepath.Base(rep.Capture) != rep.Capture || rep.Capture == "." || rep.Capture == ".." { return nil, Refuse(CodeCrashed, "the report is not of the page asked for") } root, err := os.OpenRoot(out) if err != nil { return nil, Refuse(CodeCrashed, err.Error()) } defer root.Close() f, err := root.Open(rep.Capture) if err != nil { return nil, Refuse(CodeCrashed, err.Error()) } defer f.Close() img, err := decodeCapture(f) if err != nil { return nil, Refuse(CodeCrashed, err.Error()) } w, h := img.Bounds().Dx(), img.Bounds().Dy() limit := vh if p.FullPage { limit = MaxHeight } if w != rep.CaptureWidth || h != rep.CaptureHeight || w > vw || h > limit { return nil, Refuse(CodeCrashed, fmt.Sprintf("the capture is %dx%d", w, h)) } return img, nil } // diffPage diffs page i of base and work, from the browser's files // (decoded again, at full size). func diffPage(base, work *rendered, i int, p render.Page, call int) (Capture, []byte, error) { a, err := readCapture(base.out, base.report.Pages[i], p) if err != nil { return Capture{}, nil, err } b, err := readCapture(work.out, work.report.Pages[i], p) if err != nil { return Capture{}, nil, err } ratio, diff := compare(a, b) png, w, h, err := encodeCapture(diff) if err != nil { return Capture{}, nil, Refuse(CodeCrashed, err.Error()) } return Capture{File: fmt.Sprintf("%d-diff-%d.png", call, i+1), Tree: "diff", Digest: work.digest, Page: p, Width: w, Height: h, Bytes: int64(len(png)), Diff: true, Changed: ratio}, png, nil } // captureWritten runs after each capture is in place (a seam for the // tests: a slow write). var captureWritten = func(name string) {} // writeCaptures writes each PNG to dir (made private) under its name, // each through a temporary file renamed into place, never over another, // within ctx (the call's deadline): nothing is written once it has // ended, and a write that ends past it is not kept. On any failure, the // deadline's included, the ones written are removed. func writeCaptures(ctx context.Context, dir string, caps []Capture, pngs [][]byte) (err error) { if err := privateDir(dir); err != nil { return err } root, err := os.OpenRoot(dir) if err != nil { return err } defer root.Close() var written []string defer func() { if err != nil { for _, name := range written { root.Remove(name) } } }() for i, c := range caps { if err := ctx.Err(); err != nil { return err } tmp := "." + c.File + ".tmp" root.Remove(tmp) f, err := root.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if err != nil { return err } _, werr := f.Write(pngs[i]) if cerr := f.Close(); werr != nil || cerr != nil { root.Remove(tmp) return errors.Join(werr, cerr) } if _, err := root.Lstat(c.File); err == nil { root.Remove(tmp) return fmt.Errorf("render_page: %s exists", c.File) } if err := root.Rename(tmp, c.File); err != nil { root.Remove(tmp) return err } written = append(written, c.File) captureWritten(c.File) } // Written, but only kept within the deadline. return ctx.Err() } // privateDir makes dir (and its parents) if need be and checks it is a // directory reached through no link at its last part, mode 0700. func privateDir(dir string) error { if err := os.MkdirAll(dir, 0o700); err != nil { return err } info, err := os.Lstat(dir) if err != nil { return err } if !info.IsDir() { return fmt.Errorf("render_page: %s is not a directory", dir) } if info.Mode().Perm() != 0o700 { return os.Chmod(dir, 0o700) } return nil } // freshDir is dir emptied and made again, private. func freshDir(dir string) error { if err := os.RemoveAll(dir); err != nil { return err } return privateDir(dir) } // healthCode is a renderer health's code: mismatch, or missing (which // covers unpinned and a tree that cannot render). func healthCode(health string) string { if health == wire.ToolMismatch { return CodeRendererMismatch } return CodeRendererMissing } // code is err's fixed code: a sandbox that did not end is the renderer // missing (the runner needs attention, and every later render refuses // so), a launch's refusal its health's, a code of the set itself, and // anything else crashed. func code(err error) string { if errors.Is(err, render.ErrNotEnded) { return CodeRendererMissing } var re *release.RendererError if errors.As(err, &re) { return healthCode(release.RendererHealth(err)) } if c := render.ErrorCode(err); slices.Contains(Codes, c) { return c } return CodeCrashed } // ended is an accepted call that ended with err: cancelled when ctx, the // caller's, ended; timeout, with err kept, when the call's own deadline // passed; otherwise refused's code. func ended(ctx, call context.Context, err error) (string, []Capture, error) { if ctx.Err() == nil && errors.Is(context.Cause(call), errCallTimeout) { return refusal(CodeTimeout), nil, errors.Join(Refuse(CodeTimeout, errCallTimeout.Error()), err) } return refused(ctx, err) } // refused is a call that ends with err: its code's reply, and the error // carrying the code first. A cancelled call is the context's error. func refused(ctx context.Context, err error) (string, []Capture, error) { if ctx.Err() != nil { return "render_page: the call was cancelled.", nil, ctx.Err() } c := code(err) if render.ErrorCode(err) != c { err = errors.Join(Refuse(c, ""), err) } return refusal(c), nil, err } // refusal is the reply for a code: model-facing, one line. func refusal(code string) string { why := map[string]string{ CodeRendererMissing: "This runner's page renderer is not ready; the runner needs updating, not another try.", CodeRendererMismatch: "This runner's page renderer does not match its pin; the runner needs updating, not another try.", CodeNoSite: "The tree has no site to render: release/preview.json is missing or refused, or the site breaks the export's rules or caps.", CodeTooMany: "This step has used its renders: at most 20 calls and 60 captures a step.", CodeBusy: "Another render is running on this runner, or the workspace could not be paused for its snapshot. Try again shortly.", CodeTimeout: "The render ran past its 60 seconds.", CodeCrashed: "The browser or the renderer failed during the render.", CodeSecrets: "The site's files hold what looks like a secret, so it was not rendered.", CodeScanner: "The secret scanner could not run, so the site was not rendered.", }[code] return "render_page refused: " + code + ". " + why }