oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package renderpage
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "image"
9 "os"
10 "path/filepath"
11 "slices"
12 "strconv"
13 "sync"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/release"
17 "amadan.net/oficina/equipo/internal/runner/render"
18 "amadan.net/oficina/equipo/internal/wire"
19)
20
21// The fixed error codes: the spec's seven and the plan's two (a site
22// whose files hold a secret, a scanner that could not run). Each is a
23// *render.Error with that Code.
24const (
25 CodeRendererMissing = "renderer_missing"
26 CodeRendererMismatch = "renderer_mismatch"
27 CodeNoSite = "no_site"
28 CodeTooMany = "too_many"
29 CodeBusy = "busy"
30 CodeTimeout = render.CodeTimeout
31 CodeCrashed = render.CodeCrashed
32 CodeSecrets = "secrets"
33 CodeScanner = "scanner"
34)
35
36// Codes are every code, in the spec's order then the plan's.
37var Codes = []string{CodeRendererMissing, CodeRendererMismatch, CodeNoSite, CodeTooMany, CodeBusy, CodeTimeout, CodeCrashed, CodeSecrets, CodeScanner}
38
39// Per-step limits (spec section 3, "Sandbox"), counted by the Step in
40// the step's own persisted state.
41const (
42 MaxCalls = 20
43 MaxCaptures = 60
44)
45
46// callTimeout bounds one accepted call, every phase of it (spec section
47// 3, "Limits per call: 60 seconds"): render.CallTimeout; tests lower it.
48var callTimeout = render.CallTimeout
49
50// errCallTimeout is the cause of an accepted call's own deadline.
51var errCallTimeout = errors.New("render_page: the call ran past its bound")
52
53// Refuse is a refusal with one of the fixed codes; detail is for the
54// runner's log, never the reply.
55func Refuse(code, detail string) error { return &render.Error{Code: code, Detail: detail} }
56
57// Usage is a step's render use so far, this call included.
58type Usage struct{ Calls, Captures int }
59
60// Step is the running step a call is for.
61type Step interface {
62 // Accept counts one call of captures captures in the step's
63 // persisted state, unless the step would pass MaxCalls or
64 // MaxCaptures: then it is Refuse(CodeTooMany).
65 Accept(ctx context.Context, captures int) (Usage, error)
66 // Site writes tree's site into stage (made fresh and private) and
67 // scans it: its digest, or a refusal (no_site, busy, secrets,
68 // scanner).
69 Site(ctx context.Context, tree, stage string) (digest string, err error)
70 // Dir is the step's render directory, which the model reads as
71 // /render/ (the runner makes it private), and Scratch a directory
72 // of the runner's for a call's work, outside it.
73 Dir() string
74 Scratch() string
75 // Audit keeps one accepted call's record on the step, with the
76 // step's attempt set (spec section 4, "Audit"); a record it cannot
77 // keep is the step's to log, never the call's failure.
78 Audit(ctx context.Context, rec wire.RenderAudit)
79}
80
81// Renderer is the page renderer's health (render.Health).
82type Renderer interface {
83 // Ready verifies the tree before a render: the tree to launch, or
84 // its health and why not.
85 Ready(ctx context.Context) (tree, health string, err error)
86 // Ended hears how each render ended.
87 Ended(err error)
88}
89
90// Capture is one PNG a call wrote to the step's render directory.
91type Capture struct {
92 // File is its name in the directory (/render/<File> to the model).
93 File string
94 // Tree is the tree rendered and Digest its export's; a diff has
95 // Diff set, Tree "diff" and work's Digest.
96 Tree, Digest string
97 Page render.Page
98 // Width and Height are the PNG's, as written; Bytes its size.
99 Width, Height int
100 Bytes int64
101 Diff bool
102 // Changed is a diff's share of changed pixels, 0 to 1.
103 Changed float64
104}
105
106// Tool is render_page on one runner. Its zero value with Renderer and
107// Config set is ready; one call runs at a time across the runner.
108type Tool struct {
109 Renderer Renderer
110 // Config is the launch configuration but Tree and Site, which each
111 // render sets (Ready's tree, the call's export).
112 Config render.LaunchConfig
113 // Render is render.Render (nil); tests replace it.
114 Render func(ctx context.Context, cfg render.LaunchConfig, out string, pages []render.Page) (*render.Report, error)
115
116 busy sync.Mutex
117}
118
119// rendered is one tree's render.
120type rendered struct {
121 tree, digest, out string
122 report *render.Report
123 captures []Capture
124 pngs [][]byte
125}
126
127// Call is one render_page call for step with raw, its input. The text is
128// the reply for the model, always set. err is nil for a call that
129// rendered; a refusal with a fixed code (render.ErrorCode), the
130// context's error, or an invalid input (no code: the tool call is wrong,
131// and it was not counted). Only a call that rendered writes captures.
132//
133// In order: the input is checked; one call at a time per runner (else
134// busy); the call is counted (too_many); every tree's site is exported
135// and scanned before any render; each tree is rendered after Ready
136// verifies the renderer; each capture is decoded and re-encoded; with
137// compare, each page's pair is diffed; then the PNGs are written.
138//
139// From its acceptance the call has one deadline, callTimeout, across
140// every phase: both trees' exports and scans, both renders of a compare
141// (each render's own bound sits inside it) and the captures' processing.
142// Past it the call ends timeout, writes nothing, and its error still
143// carries what ended it (a sandbox not shown to have ended stays
144// render.ErrNotEnded).
145func (t *Tool) Call(ctx context.Context, step Step, raw json.RawMessage) (string, []Capture, error) {
146 req, err := Parse(raw)
147 if err != nil {
148 return err.Error(), nil, err
149 }
150 if !t.busy.TryLock() {
151 return refused(ctx, Refuse(CodeBusy, "another render is running on this runner"))
152 }
153 defer t.busy.Unlock()
154 usage, err := step.Accept(ctx, len(req.Pages)*len(req.trees()))
155 if err != nil {
156 return refused(ctx, err)
157 }
158 began := time.Now()
159 call, cancel := context.WithTimeoutCause(ctx, callTimeout, errCallTimeout)
160 defer cancel()
161 text, caps, err := t.accepted(call, step, req, usage)
162 if err != nil {
163 text, caps, err = ended(ctx, call, err)
164 }
165 step.Audit(context.WithoutCancel(ctx), audit(ctx, req, usage, began, caps, err))
166 return text, caps, err
167}
168
169// audit is an accepted call's record: its tree, pages and counted
170// captures, the files it wrote, how long it took and how it ended
171// (rendered, its code, or cancelled when ctx, the caller's, ended).
172func audit(ctx context.Context, req Request, usage Usage, began time.Time, caps []Capture, err error) wire.RenderAudit {
173 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}
174 if req.Compare {
175 rec.Tree = wire.RenderTreeCompare
176 }
177 switch {
178 case err == nil:
179 case ctx.Err() != nil:
180 rec.Outcome = wire.RenderCancelled
181 default:
182 rec.Outcome = render.ErrorCode(err)
183 }
184 return rec
185}
186
187// accepted is an accepted call's work under its deadline (ctx): the
188// reply and captures, or the error that ended it, unmapped.
189func (t *Tool) accepted(ctx context.Context, step Step, req Request, usage Usage) (string, []Capture, error) {
190 work := filepath.Join(step.Scratch(), strconv.Itoa(usage.Calls))
191 if err := freshDir(work); err != nil {
192 return "", nil, err
193 }
194 defer os.RemoveAll(work)
195 // Every site first: a secret in one tree refuses before any render.
196 var done []*rendered
197 for _, tree := range req.trees() {
198 if err := ctx.Err(); err != nil {
199 return "", nil, err
200 }
201 digest, err := step.Site(ctx, tree, filepath.Join(work, "site-"+tree))
202 if err != nil {
203 return "", nil, err
204 }
205 done = append(done, &rendered{tree: tree, digest: digest, out: filepath.Join(work, "out-"+tree)})
206 }
207 for _, r := range done {
208 if err := t.renderTree(ctx, work, usage.Calls, req, r); err != nil {
209 return "", nil, err
210 }
211 }
212 var diffs []Capture
213 var diffPNGs [][]byte
214 if req.Compare {
215 for i, p := range req.Pages {
216 if err := ctx.Err(); err != nil {
217 return "", nil, err
218 }
219 c, png, err := diffPage(done[0], done[1], i, p, usage.Calls)
220 if err != nil {
221 return "", nil, err
222 }
223 diffs, diffPNGs = append(diffs, c), append(diffPNGs, png)
224 }
225 }
226 var caps []Capture
227 var pngs [][]byte
228 for _, r := range done {
229 caps, pngs = append(caps, r.captures...), append(pngs, r.pngs...)
230 }
231 caps, pngs = append(caps, diffs...), append(pngs, diffPNGs...)
232 // Nothing past the deadline is written, or kept (writeCaptures).
233 if err := writeCaptures(ctx, step.Dir(), caps, pngs); err != nil {
234 return "", nil, err
235 }
236 return reply(req, usage, done, diffs), caps, nil
237}
238
239// renderTree renders r's site and takes in its captures.
240func (t *Tool) renderTree(ctx context.Context, work string, call int, req Request, r *rendered) error {
241 tree, health, err := t.Renderer.Ready(ctx)
242 if err != nil || health != wire.ToolHealthy {
243 if ctx.Err() != nil {
244 return ctx.Err()
245 }
246 return errors.Join(Refuse(healthCode(health), "not ready"), err)
247 }
248 if err := freshDir(r.out); err != nil {
249 return err
250 }
251 cfg := t.Config
252 cfg.Tree, cfg.Site = tree, filepath.Join(work, "site-"+r.tree)
253 run := t.Render
254 if run == nil {
255 run = render.Render
256 }
257 report, err := run(ctx, cfg, r.out, req.Pages)
258 t.Renderer.Ended(err)
259 if err != nil {
260 return err
261 }
262 if report == nil || len(report.Pages) != len(req.Pages) || report.Error != "" {
263 return Refuse(CodeCrashed, "the report does not hold every page")
264 }
265 r.report = report
266 for i, p := range req.Pages {
267 // A render that came back past the call's deadline is not taken
268 // in, nor processed past it.
269 if err := ctx.Err(); err != nil {
270 return err
271 }
272 img, err := readCapture(r.out, report.Pages[i], p)
273 if err != nil {
274 return err
275 }
276 png, w, h, err := encodeCapture(img)
277 if err != nil {
278 return Refuse(CodeCrashed, err.Error())
279 }
280 r.pngs = append(r.pngs, png)
281 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))})
282 }
283 return nil
284}
285
286// readCapture decodes the capture rep names in out, checked against the
287// page asked for: the report is of that page, and the capture is the
288// size the report says and within its viewport (a full page within
289// MaxHeight).
290func readCapture(out string, rep render.PageReport, p render.Page) (*image.NRGBA, error) {
291 vw, vh, _ := p.Viewport.Size()
292 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 == ".." {
293 return nil, Refuse(CodeCrashed, "the report is not of the page asked for")
294 }
295 root, err := os.OpenRoot(out)
296 if err != nil {
297 return nil, Refuse(CodeCrashed, err.Error())
298 }
299 defer root.Close()
300 f, err := root.Open(rep.Capture)
301 if err != nil {
302 return nil, Refuse(CodeCrashed, err.Error())
303 }
304 defer f.Close()
305 img, err := decodeCapture(f)
306 if err != nil {
307 return nil, Refuse(CodeCrashed, err.Error())
308 }
309 w, h := img.Bounds().Dx(), img.Bounds().Dy()
310 limit := vh
311 if p.FullPage {
312 limit = MaxHeight
313 }
314 if w != rep.CaptureWidth || h != rep.CaptureHeight || w > vw || h > limit {
315 return nil, Refuse(CodeCrashed, fmt.Sprintf("the capture is %dx%d", w, h))
316 }
317 return img, nil
318}
319
320// diffPage diffs page i of base and work, from the browser's files
321// (decoded again, at full size).
322func diffPage(base, work *rendered, i int, p render.Page, call int) (Capture, []byte, error) {
323 a, err := readCapture(base.out, base.report.Pages[i], p)
324 if err != nil {
325 return Capture{}, nil, err
326 }
327 b, err := readCapture(work.out, work.report.Pages[i], p)
328 if err != nil {
329 return Capture{}, nil, err
330 }
331 ratio, diff := compare(a, b)
332 png, w, h, err := encodeCapture(diff)
333 if err != nil {
334 return Capture{}, nil, Refuse(CodeCrashed, err.Error())
335 }
336 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
337}
338
339// captureWritten runs after each capture is in place (a seam for the
340// tests: a slow write).
341var captureWritten = func(name string) {}
342
343// writeCaptures writes each PNG to dir (made private) under its name,
344// each through a temporary file renamed into place, never over another,
345// within ctx (the call's deadline): nothing is written once it has
346// ended, and a write that ends past it is not kept. On any failure, the
347// deadline's included, the ones written are removed.
348func writeCaptures(ctx context.Context, dir string, caps []Capture, pngs [][]byte) (err error) {
349 if err := privateDir(dir); err != nil {
350 return err
351 }
352 root, err := os.OpenRoot(dir)
353 if err != nil {
354 return err
355 }
356 defer root.Close()
357 var written []string
358 defer func() {
359 if err != nil {
360 for _, name := range written {
361 root.Remove(name)
362 }
363 }
364 }()
365 for i, c := range caps {
366 if err := ctx.Err(); err != nil {
367 return err
368 }
369 tmp := "." + c.File + ".tmp"
370 root.Remove(tmp)
371 f, err := root.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
372 if err != nil {
373 return err
374 }
375 _, werr := f.Write(pngs[i])
376 if cerr := f.Close(); werr != nil || cerr != nil {
377 root.Remove(tmp)
378 return errors.Join(werr, cerr)
379 }
380 if _, err := root.Lstat(c.File); err == nil {
381 root.Remove(tmp)
382 return fmt.Errorf("render_page: %s exists", c.File)
383 }
384 if err := root.Rename(tmp, c.File); err != nil {
385 root.Remove(tmp)
386 return err
387 }
388 written = append(written, c.File)
389 captureWritten(c.File)
390 }
391 // Written, but only kept within the deadline.
392 return ctx.Err()
393}
394
395// privateDir makes dir (and its parents) if need be and checks it is a
396// directory reached through no link at its last part, mode 0700.
397func privateDir(dir string) error {
398 if err := os.MkdirAll(dir, 0o700); err != nil {
399 return err
400 }
401 info, err := os.Lstat(dir)
402 if err != nil {
403 return err
404 }
405 if !info.IsDir() {
406 return fmt.Errorf("render_page: %s is not a directory", dir)
407 }
408 if info.Mode().Perm() != 0o700 {
409 return os.Chmod(dir, 0o700)
410 }
411 return nil
412}
413
414// freshDir is dir emptied and made again, private.
415func freshDir(dir string) error {
416 if err := os.RemoveAll(dir); err != nil {
417 return err
418 }
419 return privateDir(dir)
420}
421
422// healthCode is a renderer health's code: mismatch, or missing (which
423// covers unpinned and a tree that cannot render).
424func healthCode(health string) string {
425 if health == wire.ToolMismatch {
426 return CodeRendererMismatch
427 }
428 return CodeRendererMissing
429}
430
431// code is err's fixed code: a sandbox that did not end is the renderer
432// missing (the runner needs attention, and every later render refuses
433// so), a launch's refusal its health's, a code of the set itself, and
434// anything else crashed.
435func code(err error) string {
436 if errors.Is(err, render.ErrNotEnded) {
437 return CodeRendererMissing
438 }
439 var re *release.RendererError
440 if errors.As(err, &re) {
441 return healthCode(release.RendererHealth(err))
442 }
443 if c := render.ErrorCode(err); slices.Contains(Codes, c) {
444 return c
445 }
446 return CodeCrashed
447}
448
449// ended is an accepted call that ended with err: cancelled when ctx, the
450// caller's, ended; timeout, with err kept, when the call's own deadline
451// passed; otherwise refused's code.
452func ended(ctx, call context.Context, err error) (string, []Capture, error) {
453 if ctx.Err() == nil && errors.Is(context.Cause(call), errCallTimeout) {
454 return refusal(CodeTimeout), nil, errors.Join(Refuse(CodeTimeout, errCallTimeout.Error()), err)
455 }
456 return refused(ctx, err)
457}
458
459// refused is a call that ends with err: its code's reply, and the error
460// carrying the code first. A cancelled call is the context's error.
461func refused(ctx context.Context, err error) (string, []Capture, error) {
462 if ctx.Err() != nil {
463 return "render_page: the call was cancelled.", nil, ctx.Err()
464 }
465 c := code(err)
466 if render.ErrorCode(err) != c {
467 err = errors.Join(Refuse(c, ""), err)
468 }
469 return refusal(c), nil, err
470}
471
472// refusal is the reply for a code: model-facing, one line.
473func refusal(code string) string {
474 why := map[string]string{
475 CodeRendererMissing: "This runner's page renderer is not ready; the runner needs updating, not another try.",
476 CodeRendererMismatch: "This runner's page renderer does not match its pin; the runner needs updating, not another try.",
477 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.",
478 CodeTooMany: "This step has used its renders: at most 20 calls and 60 captures a step.",
479 CodeBusy: "Another render is running on this runner, or the workspace could not be paused for its snapshot. Try again shortly.",
480 CodeTimeout: "The render ran past its 60 seconds.",
481 CodeCrashed: "The browser or the renderer failed during the render.",
482 CodeSecrets: "The site's files hold what looks like a secret, so it was not rendered.",
483 CodeScanner: "The secret scanner could not run, so the site was not rendered.",
484 }[code]
485 return "render_page refused: " + code + ". " + why
486}
487