oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package render
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "image/png"
10 "io"
11 "math"
12 "net/url"
13 "os"
14 "strings"
15 "sync"
16 "sync/atomic"
17 "time"
18)
19
20// callTimeout and memoryLimit are CallTimeout and MemoryLimit; tests
21// lower them. launch is Launch (a seam for the tests).
22var (
23 callTimeout = CallTimeout
24 memoryLimit int64 = MemoryLimit
25 launch = Launch
26)
27
28var (
29 errCallTimeout = errors.New("the call ran out of time")
30 errOverMemory = errors.New("the sandbox used more than its memory")
31)
32
33// Render renders pages of the site in cfg in one sandbox: for each, the
34// viewport, the navigation, the wait for load and then network idle, the
35// capture, the title, console errors, failed loads, same-site links that
36// answer 404 and the accessibility outline. It writes each capture
37// (page-N.png) and report.json to out and returns the report.
38//
39// out is the runner's own directory, never in the sandbox: captures
40// arrive over the browser's pipe and the runner writes them. It must be
41// an empty directory, mode 0700, owned by this user and reached through
42// no symlink; anything else is refused before the sandbox starts.
43//
44// The call has CallTimeout and MemoryLimit: past either the sandbox is
45// killed and the error is an *Error, CodeTimeout or CodeCrashed, as it
46// is for a renderer or browser that dies. The report then holds the
47// pages finished before. A tree that does not verify is the launch's
48// *release.RendererError, and nothing runs.
49func Render(ctx context.Context, cfg LaunchConfig, out string, pages []Page) (*Report, error) {
50 if err := checkPages(pages); err != nil {
51 return nil, err
52 }
53 root, err := openOut(out)
54 if err != nil {
55 return nil, err
56 }
57 defer root.Close()
58 began := time.Now()
59 ctx, cancel := context.WithTimeoutCause(ctx, callTimeout, errCallTimeout)
60 defer cancel()
61 s, err := launch(ctx, cfg)
62 if err != nil {
63 if errors.Is(context.Cause(ctx), errCallTimeout) {
64 // The timeout's code first, with the launch's own error
65 // kept: a sandbox that did not end is still ErrNotEnded
66 // (Health.Ended stops every later render on it).
67 return nil, errors.Join(&Error{Code: CodeTimeout, Detail: errCallTimeout.Error()}, err)
68 }
69 return nil, err
70 }
71 defer s.Close()
72 var over atomic.Bool
73 stopWatch := watchMemory(s, memoryLimit, func() {
74 over.Store(true)
75 cancel()
76 s.stop()
77 })
78 report, err := drive(ctx, s.FromBrowser, s.ToBrowser, s.Site, root, pages)
79 stopWatch()
80 switch {
81 case err == nil:
82 case over.Load():
83 err = &Error{Code: CodeCrashed, Detail: errOverMemory.Error()}
84 case errors.Is(context.Cause(ctx), errCallTimeout):
85 err = &Error{Code: CodeTimeout, Detail: errCallTimeout.Error()}
86 case ctx.Err() != nil:
87 err = ctx.Err()
88 }
89 if code := ErrorCode(err); code != "" {
90 report.Error = code
91 }
92 closeErr := s.Close()
93 report.ElapsedMS = time.Since(began).Milliseconds()
94 if werr := writeReport(root, report); werr != nil && err == nil {
95 err = werr
96 }
97 return report, withClose(err, closeErr)
98}
99
100// withClose is a call's error with its sandbox's Close error: both when
101// both happened, so a failed render whose sandbox did not end still
102// shows ErrNotEnded (Health.Ended stops every later render on it) beside
103// its code.
104func withClose(err, closeErr error) error {
105 switch {
106 case closeErr == nil:
107 return err
108 case err == nil:
109 return closeErr
110 }
111 return errors.Join(err, closeErr)
112}
113
114// checkPages refuses what no render may ask for.
115func checkPages(pages []Page) error {
116 if len(pages) == 0 || len(pages) > MaxPages {
117 return fmt.Errorf("render: %d pages (1 to %d)", len(pages), MaxPages)
118 }
119 for _, p := range pages {
120 if _, _, ok := p.Viewport.Size(); !ok {
121 return fmt.Errorf("render: viewport %q", p.Viewport)
122 }
123 if !sitePath(p.Path) {
124 return fmt.Errorf("render: page path %q", p.Path)
125 }
126 }
127 return nil
128}
129
130// sitePath is a path on the site: absolute, no scheme or host, no
131// fragment, printable ASCII, at most 1024 bytes.
132func sitePath(p string) bool {
133 if len(p) == 0 || len(p) > 1024 || p[0] != '/' || strings.HasPrefix(p, "//") || strings.ContainsAny(p, "#\\") {
134 return false
135 }
136 for i := 0; i < len(p); i++ {
137 if p[i] <= ' ' || p[i] >= 0x7f {
138 return false
139 }
140 }
141 return true
142}
143
144func writeReport(out *os.Root, r *Report) error {
145 raw, err := json.MarshalIndent(r, "", " ")
146 if err != nil {
147 return err
148 }
149 f, err := out.OpenFile(ReportName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
150 if err != nil {
151 return err
152 }
153 if _, err = f.Write(append(raw, '\n')); err != nil {
154 f.Close()
155 return err
156 }
157 return f.Close()
158}
159
160// driver drives one browser over CDP for one call.
161type driver struct {
162 conn *cdpConn
163 site *url.URL
164 out *os.Root
165
166 mu sync.Mutex
167 page *pageState
168}
169
170// drive renders pages over the browser's pipe (from, to), with the site
171// served at site and captures written to out. The report is never nil.
172func drive(ctx context.Context, from io.Reader, to deadlineWriter, site string, out *os.Root, pages []Page) (*Report, error) {
173 report := &Report{Schema: ReportSchema, Pages: []PageReport{}}
174 u, err := url.Parse(site)
175 if err != nil || u.Scheme != "http" || u.Host == "" {
176 return report, fmt.Errorf("render: site %q", site)
177 }
178 d := &driver{site: u, out: out}
179 d.conn = newConn(from, to, maxFrame, d.event)
180 // Downloads go nowhere.
181 d.conn.call(ctx, "", "Browser.setDownloadBehavior", map[string]any{"behavior": "deny"}, nil)
182 for i, p := range pages {
183 pr, err := d.render(ctx, i+1, p)
184 if err != nil {
185 return report, d.ended(ctx, err)
186 }
187 report.Pages = append(report.Pages, pr)
188 }
189 return report, nil
190}
191
192// ended is the error a page's failure ends the call with: a crashed
193// renderer, or a browser whose pipe ended or broke the protocol, is
194// CodeCrashed; the call's own deadline is reported by Render.
195func (d *driver) ended(ctx context.Context, err error) error {
196 if ctx.Err() != nil {
197 return err
198 }
199 if errors.Is(err, errRendererCrashed) {
200 return &Error{Code: CodeCrashed, Detail: errRendererCrashed.Error()}
201 }
202 if cerr := d.conn.Err(); cerr != nil {
203 return &Error{Code: CodeCrashed, Detail: cerr.Error()}
204 }
205 return err
206}
207
208// event routes the browser's events: the current page's session gets its
209// own; a page session that detaches is a page gone.
210func (d *driver) event(session, method string, params json.RawMessage) {
211 d.mu.Lock()
212 p := d.page
213 d.mu.Unlock()
214 if p == nil {
215 return
216 }
217 switch {
218 case session == p.session:
219 p.event(method, params)
220 case session == "" && method == "Target.detachedFromTarget":
221 var e struct {
222 SessionID string `json:"sessionId"`
223 }
224 if json.Unmarshal(params, &e) == nil && e.SessionID == p.session {
225 p.event("Inspector.targetCrashed", nil)
226 }
227 }
228}
229
230// render renders one page in a fresh target; n numbers its capture.
231func (d *driver) render(ctx context.Context, n int, p Page) (PageReport, error) {
232 w, h, _ := p.Viewport.Size()
233 r := PageReport{Path: p.Path, Viewport: p.Viewport, Width: w, Height: h, FullPage: p.FullPage}
234 var target struct {
235 TargetID string `json:"targetId"`
236 }
237 if err := d.conn.call(ctx, "", "Target.createTarget", map[string]any{"url": "about:blank"}, &target); err != nil {
238 return r, err
239 }
240 defer func() {
241 closeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
242 defer cancel()
243 if ctx.Err() == nil {
244 d.conn.call(closeCtx, "", "Target.closeTarget", map[string]any{"targetId": target.TargetID}, nil)
245 }
246 d.mu.Lock()
247 d.page = nil
248 d.mu.Unlock()
249 }()
250 var attached struct {
251 SessionID string `json:"sessionId"`
252 }
253 if err := d.conn.call(ctx, "", "Target.attachToTarget", map[string]any{"targetId": target.TargetID, "flatten": true}, &attached); err != nil {
254 return r, err
255 }
256 pctx, cancel := context.WithCancelCause(ctx)
257 defer cancel(nil)
258 // A browser that ends, or breaks the protocol, ends every wait.
259 go func() {
260 select {
261 case <-d.conn.done:
262 cancel(d.conn.Err())
263 case <-pctx.Done():
264 }
265 }()
266 ps := newPageState(d.site, attached.SessionID, cancel)
267 d.mu.Lock()
268 d.page = ps
269 d.mu.Unlock()
270 call := func(method string, params, result any) error {
271 return d.conn.call(pctx, ps.session, method, params, result)
272 }
273 var tree struct {
274 FrameTree struct {
275 Frame struct {
276 ID string `json:"id"`
277 } `json:"frame"`
278 } `json:"frameTree"`
279 }
280 if err := call("Page.getFrameTree", nil, &tree); err != nil {
281 return r, err
282 }
283 ps.setMain(tree.FrameTree.Frame.ID)
284 steps := []struct {
285 method string
286 params any
287 }{
288 {"Inspector.enable", nil},
289 {"Page.enable", nil},
290 {"Page.setLifecycleEventsEnabled", map[string]any{"enabled": true}},
291 {"Runtime.enable", nil},
292 {"Network.enable", nil},
293 {"Emulation.setDeviceMetricsOverride", map[string]any{"width": w, "height": h, "deviceScaleFactor": 1, "mobile": p.Viewport.mobile()}},
294 }
295 for _, s := range steps {
296 if err := call(s.method, s.params, nil); err != nil {
297 return r, err
298 }
299 }
300 page := *d.site
301 page.Path, page.RawQuery = "", ""
302 addr := strings.TrimSuffix(page.String(), "/") + p.Path
303 if err := call("Page.navigate", map[string]any{"url": addr}, nil); err != nil {
304 return r, err
305 }
306 if err := ps.waitLoaded(pctx); err != nil {
307 return r, err
308 }
309 if err := d.capture(pctx, call, n, p, &r); err != nil {
310 return r, err
311 }
312 ps.finish(&r)
313 if err := d.inspect(pctx, call, tree.FrameTree.Frame.ID, &r); err != nil {
314 return r, err
315 }
316 var ax struct {
317 Nodes []axNode `json:"nodes"`
318 }
319 if err := call("Accessibility.getFullAXTree", nil, &ax); err != nil {
320 return r, err
321 }
322 r.Outline, r.OutlineCut = outline(ax.Nodes, maxOutline)
323 if context.Cause(pctx) != nil {
324 return r, context.Cause(pctx)
325 }
326 return r, nil
327}
328
329// capture takes the page's PNG and writes it to the out directory: the
330// viewport, or the full page clipped at MaxCaptureHeight.
331func (d *driver) capture(ctx context.Context, call func(string, any, any) error, n int, p Page, r *PageReport) error {
332 params := map[string]any{"format": "png", "fromSurface": true}
333 if p.FullPage {
334 var m struct {
335 CSSContentSize struct {
336 Height float64 `json:"height"`
337 } `json:"cssContentSize"`
338 }
339 if err := call("Page.getLayoutMetrics", nil, &m); err != nil {
340 return err
341 }
342 h := float64(r.Height)
343 if c := m.CSSContentSize.Height; !math.IsNaN(c) && c > h {
344 h = math.Min(math.Ceil(c), MaxCaptureHeight)
345 }
346 params["captureBeyondViewport"] = true
347 params["clip"] = map[string]any{"x": 0, "y": 0, "width": r.Width, "height": h, "scale": 1}
348 }
349 var shot struct {
350 Data []byte `json:"data"`
351 }
352 if err := call("Page.captureScreenshot", params, &shot); err != nil {
353 return err
354 }
355 cfg, err := png.DecodeConfig(bytes.NewReader(shot.Data))
356 if err != nil {
357 return &Error{Code: CodeCrashed, Detail: "the capture is not a PNG"}
358 }
359 if cfg.Width > r.Width || cfg.Height > max(r.Height, MaxCaptureHeight) {
360 return &Error{Code: CodeCrashed, Detail: fmt.Sprintf("the capture is %dx%d", cfg.Width, cfg.Height)}
361 }
362 name := fmt.Sprintf("page-%d.png", n)
363 f, err := d.out.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
364 if err != nil {
365 return err
366 }
367 if _, err = f.Write(shot.Data); err != nil {
368 f.Close()
369 return err
370 }
371 if err = f.Close(); err != nil {
372 return err
373 }
374 r.Capture, r.CaptureWidth, r.CaptureHeight = name, cfg.Width, cfg.Height
375 return nil
376}
377
378// linkCheck runs in an isolated world, where the page's own scripts
379// cannot change what it calls: the title, and each distinct same-site
380// anchor (at most maxLinks, without its fragment) asked for with HEAD,
381// four at a time, each within 3 seconds. A link that answers 404 is
382// broken.
383const linkCheck = `(async (site, maxLinks) => {
384 const seen = new Set(), links = [];
385 for (const a of document.querySelectorAll("a[href]")) {
386 let u;
387 try { u = new URL(a.getAttribute("href"), document.baseURI); } catch (e) { continue; }
388 if (u.origin !== site) continue;
389 u.hash = "";
390 if (seen.has(u.href)) continue;
391 seen.add(u.href);
392 links.push(u.href);
393 if (links.length >= maxLinks) break;
394 }
395 const broken = [];
396 let next = 0;
397 const work = async () => {
398 while (next < links.length) {
399 const u = links[next++];
400 try {
401 const r = await fetch(u, {method: "HEAD", credentials: "omit", cache: "no-store", signal: AbortSignal.timeout(3000)});
402 if (r.status === 404) broken.push(u);
403 } catch (e) {}
404 }
405 };
406 await Promise.all([work(), work(), work(), work()]);
407 return {title: String(document.title), checked: links.length, broken: broken};
408})(%s, %d)`
409
410// maxLinks bounds the anchors one page's check asks for.
411const maxLinks = 200
412
413// inspect reads the title and checks the page's same-site links.
414func (d *driver) inspect(ctx context.Context, call func(string, any, any) error, frame string, r *PageReport) error {
415 var world struct {
416 ContextID int `json:"executionContextId"`
417 }
418 if err := call("Page.createIsolatedWorld", map[string]any{"frameId": frame, "worldName": "equipo-render"}, &world); err != nil {
419 return err
420 }
421 origin := d.site.Scheme + "://" + d.site.Host
422 quoted, _ := json.Marshal(origin)
423 var res struct {
424 Result struct {
425 Value struct {
426 Title string `json:"title"`
427 Checked int `json:"checked"`
428 Broken []string `json:"broken"`
429 } `json:"value"`
430 } `json:"result"`
431 ExceptionDetails *json.RawMessage `json:"exceptionDetails"`
432 }
433 expr := fmt.Sprintf(linkCheck, quoted, maxLinks)
434 if err := call("Runtime.evaluate", map[string]any{"expression": expr, "contextId": world.ContextID, "awaitPromise": true, "returnByValue": true}, &res); err != nil {
435 return err
436 }
437 v := res.Result.Value
438 r.Title = clean(v.Title, maxTitle)
439 r.LinksChecked = min(max(v.Checked, 0), maxLinks)
440 r.BrokenLinks = []string{}
441 for _, link := range v.Broken {
442 u, err := url.Parse(link)
443 if err != nil || u.Scheme != d.site.Scheme || u.Host != d.site.Host {
444 continue
445 }
446 if len(r.BrokenLinks) < maxBrokenLinks {
447 r.BrokenLinks = append(r.BrokenLinks, clean(link, maxURL))
448 } else {
449 r.BrokenLinksOmitted++
450 }
451 }
452 return nil
453}
454