package render import ( "context" "encoding/json" "errors" "fmt" "net/url" "strings" "sync" "time" ) // pageState is what one page's events told the driver: how far it has // loaded, its console errors and its failed loads. Every list and map in // it is bounded; the browser's data never grows it past those bounds. type pageState struct { site *url.URL session string mu sync.Mutex mainFrame string loader string loaded bool loadedAt time.Time idle bool // collecting is false once the page is captured: later events (the // link check's own requests among them) are not the page's report. collecting bool console []string consoleMore int failed []FailedLoad failedMore int // requests is each request in flight by the browser's id, bounded // by maxTracked: loadingFailed does not carry the URL. requests map[string]request crashed bool notify chan struct{} cancel context.CancelCauseFunc } type request struct { url, kind string } // maxTracked bounds pageState.requests, and maxRequestID the length of // an id kept there. const ( maxTracked = 512 maxRequestID = 64 ) // errRendererCrashed is a page whose renderer ended under it. var errRendererCrashed = errors.New("the renderer crashed") func newPageState(site *url.URL, session string, cancel context.CancelCauseFunc) *pageState { return &pageState{site: site, session: session, collecting: true, requests: map[string]request{}, notify: make(chan struct{}, 1), cancel: cancel} } func (p *pageState) wake() { select { case p.notify <- struct{}{}: default: } } // Event parameters the driver reads. Fields not listed are ignored. type ( frameNavigatedEvent struct { Frame struct { ID string `json:"id"` ParentID string `json:"parentId"` LoaderID string `json:"loaderId"` } `json:"frame"` } lifecycleEvent struct { FrameID string `json:"frameId"` LoaderID string `json:"loaderId"` Name string `json:"name"` } remoteObject struct { Type string `json:"type"` Value json.RawMessage `json:"value"` UnserializableValue string `json:"unserializableValue"` Description string `json:"description"` } consoleEvent struct { Type string `json:"type"` Args []remoteObject `json:"args"` } exceptionEvent struct { ExceptionDetails struct { Text string `json:"text"` Exception *remoteObject `json:"exception"` } `json:"exceptionDetails"` } requestEvent struct { RequestID string `json:"requestId"` Type string `json:"type"` Request struct { URL string `json:"url"` } `json:"request"` } responseEvent struct { RequestID string `json:"requestId"` Type string `json:"type"` Response struct { URL string `json:"url"` Status int `json:"status"` } `json:"response"` } loadingFailedEvent struct { RequestID string `json:"requestId"` Type string `json:"type"` Canceled bool `json:"canceled"` } loadingFinishedEvent struct { RequestID string `json:"requestId"` } ) // event takes one of the page session's events. func (p *pageState) event(method string, params json.RawMessage) { p.mu.Lock() defer p.mu.Unlock() defer p.wake() switch method { case "Inspector.targetCrashed": p.crashed = true p.cancel(errRendererCrashed) case "Page.frameNavigated": var e frameNavigatedEvent if json.Unmarshal(params, &e) == nil && e.Frame.ParentID == "" && e.Frame.ID == p.mainFrame && p.mainFrame != "" { // A new document in the main frame (the navigation, or one // the page made): wait for its load. p.loader, p.loaded, p.idle = e.Frame.LoaderID, false, false } case "Page.lifecycleEvent": var e lifecycleEvent if json.Unmarshal(params, &e) != nil || e.FrameID != p.mainFrame || e.LoaderID != p.loader || p.loader == "" { return } switch e.Name { case "load": if !p.loaded { p.loaded, p.loadedAt = true, time.Now() } case "networkIdle": p.idle = true } case "Runtime.consoleAPICalled": var e consoleEvent if !p.collecting || json.Unmarshal(params, &e) != nil || e.Type != "error" && e.Type != "assert" { return } parts := make([]string, 0, min(len(e.Args), 8)) for _, a := range e.Args[:min(len(e.Args), 8)] { parts = append(parts, a.text()) } p.addConsole(strings.Join(parts, " ")) case "Runtime.exceptionThrown": var e exceptionEvent if !p.collecting || json.Unmarshal(params, &e) != nil { return } msg := e.ExceptionDetails.Text if x := e.ExceptionDetails.Exception; x != nil { if first, _, _ := strings.Cut(x.text(), "\n"); first != "" { msg += " " + first } } p.addConsole(msg) case "Network.requestWillBeSent": var e requestEvent if json.Unmarshal(params, &e) != nil || e.RequestID == "" || len(e.RequestID) > maxRequestID { return } // A redirect keeps the id with the new URL. if _, ok := p.requests[e.RequestID]; ok || len(p.requests) < maxTracked { p.requests[e.RequestID] = request{url: truncate(e.Request.URL, maxURL), kind: e.Type} } case "Network.responseReceived": var e responseEvent if json.Unmarshal(params, &e) != nil { return } if e.Response.Status >= 400 { // Reported here; its loadingFinished only forgets it. delete(p.requests, e.RequestID) p.addFailed(e.Response.URL, e.Type, e.Response.Status, false) } case "Network.loadingFailed": var e loadingFailedEvent if json.Unmarshal(params, &e) != nil { return } r, ok := p.requests[e.RequestID] delete(p.requests, e.RequestID) if ok && !e.Canceled { kind := e.Type if kind == "" { kind = r.kind } p.addFailed(r.url, kind, 0, true) } case "Network.loadingFinished": var e loadingFinishedEvent if json.Unmarshal(params, &e) == nil { delete(p.requests, e.RequestID) } } } func (p *pageState) addConsole(msg string) { msg = clean(msg, maxMessage) if msg == "" { return } if len(p.console) < maxConsoleErrors { p.console = append(p.console, msg) } else { p.consoleMore++ } } func (p *pageState) addFailed(rawURL, resourceType string, status int, netErr bool) { if !p.collecting { return } kind, ok := classifyLoad(p.site, rawURL, resourceType, status, netErr) if !ok { return } f := FailedLoad{Kind: kind, URL: clean(rawURL, maxURL), Status: status} for _, have := range p.failed { if have == f { return } } if len(p.failed) < maxFailedLoads { p.failed = append(p.failed, f) } else { p.failedMore++ } } // classifyLoad names a load that failed: a font (any font that did not // load, from anywhere), a same-site resource that answered an HTTP error // (not found), or a resource elsewhere, which the sandbox cannot reach // (external blocked). Other failures (a same-site request the browser // itself refused, a scheme that is not HTTP) are not reported. func classifyLoad(site *url.URL, rawURL, resourceType string, status int, netErr bool) (string, bool) { u, err := url.Parse(rawURL) if err != nil || u.Scheme != "http" && u.Scheme != "https" || !netErr && status < 400 { return "", false } if resourceType == "Font" { return LoadFont, true } same := u.Scheme == site.Scheme && u.Host == site.Host switch { case same && !netErr: return LoadNotFound, true case !same && netErr: return LoadExternalBlocked, true } return "", false } // text is a console argument as text: a string's value, else what the // browser describes it as. func (o remoteObject) text() string { if o.Type == "string" { var s string if json.Unmarshal(o.Value, &s) == nil { return truncate(s, maxMessage) } } if o.UnserializableValue != "" { return truncate(o.UnserializableValue, maxMessage) } if o.Description != "" { return truncate(o.Description, maxMessage) } if len(o.Value) > 0 && len(o.Value) <= maxMessage { return string(o.Value) } return o.Type } // truncate cuts s to at most max bytes; clean makes it valid later. func truncate(s string, max int) string { if len(s) > max { return s[:max] } return s } // setMain names the page's main frame, before it navigates. func (p *pageState) setMain(frame string) { p.mu.Lock() p.mainFrame = frame p.mu.Unlock() } // waitLoaded waits for the main frame's current document to fire load, // then for the network to be idle, at most IdleWait after the load. func (p *pageState) waitLoaded(ctx context.Context) error { for { p.mu.Lock() loaded, idle, at := p.loaded, p.idle, p.loadedAt p.mu.Unlock() var timer *time.Timer if loaded { left := IdleWait - time.Since(at) if idle || left <= 0 { return nil } timer = time.NewTimer(left) } var fired <-chan time.Time if timer != nil { fired = timer.C } select { case <-p.notify: case <-fired: case <-ctx.Done(): if timer != nil { timer.Stop() } return context.Cause(ctx) } if timer != nil { timer.Stop() } } } // finish stops collecting and returns what was collected. func (p *pageState) finish(r *PageReport) { p.mu.Lock() defer p.mu.Unlock() p.collecting = false r.ConsoleErrors = append([]string{}, p.console...) r.ConsoleErrorsOmitted = p.consoleMore r.FailedLoads = append([]FailedLoad{}, p.failed...) r.FailedLoadsOmitted = p.failedMore } // axNode is one node of Accessibility.getFullAXTree. type axNode struct { NodeID string `json:"nodeId"` Ignored bool `json:"ignored"` Role *axValue `json:"role"` Name *axValue `json:"name"` ChildIDs []string `json:"childIds"` ParentID string `json:"parentId"` } type axValue struct { Value json.RawMessage `json:"value"` } func (v *axValue) text() string { if v == nil { return "" } var s string if json.Unmarshal(v.Value, &s) != nil { return "" } return s } // maxAXNodes bounds the nodes an outline reads, and maxAXDepth its // indentation. const ( maxAXNodes = 20000 maxAXDepth = 24 ) // outline writes the accessibility tree as text: one line a node, // "role" or `role "name"`, indented two spaces a level. Ignored nodes, // and roles that only group (generic, none), are skipped and their // children lifted; text is shown only where its parent has no name of // its own. The result is at most max bytes, whole lines; cut says some // were left out. Each node is visited at most once, whatever the ids // claim. func outline(nodes []axNode, max int) (text string, cut bool) { if len(nodes) > maxAXNodes { nodes, cut = nodes[:maxAXNodes], true } index := make(map[string]int, len(nodes)) for i, n := range nodes { if _, dup := index[n.NodeID]; !dup && n.NodeID != "" { index[n.NodeID] = i } } root := -1 for i, n := range nodes { if _, ok := index[n.ParentID]; n.ParentID == "" || !ok { root = i break } } if root < 0 { return "", cut } type item struct { i, depth int named bool } seen := make([]bool, len(nodes)) stack := []item{{i: root}} var b strings.Builder for len(stack) > 0 { it := stack[len(stack)-1] stack = stack[:len(stack)-1] if seen[it.i] { continue } seen[it.i] = true n := nodes[it.i] role, name := clean(n.Role.text(), 40), clean(n.Name.text(), maxName) depth, named := it.depth, it.named switch { case n.Ignored || role == "" || role == "none" || role == "generic" || role == "InlineTextBox" || role == "LineBreak": case role == "StaticText" && (named || name == ""): default: line := strings.Repeat(" ", min(depth, maxAXDepth)) + role if name != "" { line += fmt.Sprintf(" %q", name) } if b.Len()+len(line)+1 > max { return b.String(), true } b.WriteString(line) b.WriteByte('\n') depth, named = depth+1, name != "" } // Children in order: pushed last first. for k := len(n.ChildIDs) - 1; k >= 0; k-- { if c, ok := index[n.ChildIDs[k]]; ok && !seen[c] { stack = append(stack, item{i: c, depth: depth, named: named}) } } if len(stack) > maxAXNodes { return b.String(), true } } return b.String(), cut }