| 1 | package render |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "net/url" |
| 9 | "strings" |
| 10 | "sync" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | // pageState is what one page's events told the driver: how far it has |
| 15 | // loaded, its console errors and its failed loads. Every list and map in |
| 16 | // it is bounded; the browser's data never grows it past those bounds. |
| 17 | type pageState struct { |
| 18 | site *url.URL |
| 19 | session string |
| 20 | |
| 21 | mu sync.Mutex |
| 22 | mainFrame string |
| 23 | loader string |
| 24 | loaded bool |
| 25 | loadedAt time.Time |
| 26 | idle bool |
| 27 | // collecting is false once the page is captured: later events (the |
| 28 | // link check's own requests among them) are not the page's report. |
| 29 | collecting bool |
| 30 | console []string |
| 31 | consoleMore int |
| 32 | failed []FailedLoad |
| 33 | failedMore int |
| 34 | // requests is each request in flight by the browser's id, bounded |
| 35 | // by maxTracked: loadingFailed does not carry the URL. |
| 36 | requests map[string]request |
| 37 | crashed bool |
| 38 | notify chan struct{} |
| 39 | cancel context.CancelCauseFunc |
| 40 | } |
| 41 | |
| 42 | type request struct { |
| 43 | url, kind string |
| 44 | } |
| 45 | |
| 46 | // maxTracked bounds pageState.requests, and maxRequestID the length of |
| 47 | // an id kept there. |
| 48 | const ( |
| 49 | maxTracked = 512 |
| 50 | maxRequestID = 64 |
| 51 | ) |
| 52 | |
| 53 | // errRendererCrashed is a page whose renderer ended under it. |
| 54 | var errRendererCrashed = errors.New("the renderer crashed") |
| 55 | |
| 56 | func newPageState(site *url.URL, session string, cancel context.CancelCauseFunc) *pageState { |
| 57 | return &pageState{site: site, session: session, collecting: true, requests: map[string]request{}, notify: make(chan struct{}, 1), cancel: cancel} |
| 58 | } |
| 59 | |
| 60 | func (p *pageState) wake() { |
| 61 | select { |
| 62 | case p.notify <- struct{}{}: |
| 63 | default: |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | // Event parameters the driver reads. Fields not listed are ignored. |
| 68 | type ( |
| 69 | frameNavigatedEvent struct { |
| 70 | Frame struct { |
| 71 | ID string `json:"id"` |
| 72 | ParentID string `json:"parentId"` |
| 73 | LoaderID string `json:"loaderId"` |
| 74 | } `json:"frame"` |
| 75 | } |
| 76 | lifecycleEvent struct { |
| 77 | FrameID string `json:"frameId"` |
| 78 | LoaderID string `json:"loaderId"` |
| 79 | Name string `json:"name"` |
| 80 | } |
| 81 | remoteObject struct { |
| 82 | Type string `json:"type"` |
| 83 | Value json.RawMessage `json:"value"` |
| 84 | UnserializableValue string `json:"unserializableValue"` |
| 85 | Description string `json:"description"` |
| 86 | } |
| 87 | consoleEvent struct { |
| 88 | Type string `json:"type"` |
| 89 | Args []remoteObject `json:"args"` |
| 90 | } |
| 91 | exceptionEvent struct { |
| 92 | ExceptionDetails struct { |
| 93 | Text string `json:"text"` |
| 94 | Exception *remoteObject `json:"exception"` |
| 95 | } `json:"exceptionDetails"` |
| 96 | } |
| 97 | requestEvent struct { |
| 98 | RequestID string `json:"requestId"` |
| 99 | Type string `json:"type"` |
| 100 | Request struct { |
| 101 | URL string `json:"url"` |
| 102 | } `json:"request"` |
| 103 | } |
| 104 | responseEvent struct { |
| 105 | RequestID string `json:"requestId"` |
| 106 | Type string `json:"type"` |
| 107 | Response struct { |
| 108 | URL string `json:"url"` |
| 109 | Status int `json:"status"` |
| 110 | } `json:"response"` |
| 111 | } |
| 112 | loadingFailedEvent struct { |
| 113 | RequestID string `json:"requestId"` |
| 114 | Type string `json:"type"` |
| 115 | Canceled bool `json:"canceled"` |
| 116 | } |
| 117 | loadingFinishedEvent struct { |
| 118 | RequestID string `json:"requestId"` |
| 119 | } |
| 120 | ) |
| 121 | |
| 122 | // event takes one of the page session's events. |
| 123 | func (p *pageState) event(method string, params json.RawMessage) { |
| 124 | p.mu.Lock() |
| 125 | defer p.mu.Unlock() |
| 126 | defer p.wake() |
| 127 | switch method { |
| 128 | case "Inspector.targetCrashed": |
| 129 | p.crashed = true |
| 130 | p.cancel(errRendererCrashed) |
| 131 | case "Page.frameNavigated": |
| 132 | var e frameNavigatedEvent |
| 133 | if json.Unmarshal(params, &e) == nil && e.Frame.ParentID == "" && e.Frame.ID == p.mainFrame && p.mainFrame != "" { |
| 134 | // A new document in the main frame (the navigation, or one |
| 135 | // the page made): wait for its load. |
| 136 | p.loader, p.loaded, p.idle = e.Frame.LoaderID, false, false |
| 137 | } |
| 138 | case "Page.lifecycleEvent": |
| 139 | var e lifecycleEvent |
| 140 | if json.Unmarshal(params, &e) != nil || e.FrameID != p.mainFrame || e.LoaderID != p.loader || p.loader == "" { |
| 141 | return |
| 142 | } |
| 143 | switch e.Name { |
| 144 | case "load": |
| 145 | if !p.loaded { |
| 146 | p.loaded, p.loadedAt = true, time.Now() |
| 147 | } |
| 148 | case "networkIdle": |
| 149 | p.idle = true |
| 150 | } |
| 151 | case "Runtime.consoleAPICalled": |
| 152 | var e consoleEvent |
| 153 | if !p.collecting || json.Unmarshal(params, &e) != nil || e.Type != "error" && e.Type != "assert" { |
| 154 | return |
| 155 | } |
| 156 | parts := make([]string, 0, min(len(e.Args), 8)) |
| 157 | for _, a := range e.Args[:min(len(e.Args), 8)] { |
| 158 | parts = append(parts, a.text()) |
| 159 | } |
| 160 | p.addConsole(strings.Join(parts, " ")) |
| 161 | case "Runtime.exceptionThrown": |
| 162 | var e exceptionEvent |
| 163 | if !p.collecting || json.Unmarshal(params, &e) != nil { |
| 164 | return |
| 165 | } |
| 166 | msg := e.ExceptionDetails.Text |
| 167 | if x := e.ExceptionDetails.Exception; x != nil { |
| 168 | if first, _, _ := strings.Cut(x.text(), "\n"); first != "" { |
| 169 | msg += " " + first |
| 170 | } |
| 171 | } |
| 172 | p.addConsole(msg) |
| 173 | case "Network.requestWillBeSent": |
| 174 | var e requestEvent |
| 175 | if json.Unmarshal(params, &e) != nil || e.RequestID == "" || len(e.RequestID) > maxRequestID { |
| 176 | return |
| 177 | } |
| 178 | // A redirect keeps the id with the new URL. |
| 179 | if _, ok := p.requests[e.RequestID]; ok || len(p.requests) < maxTracked { |
| 180 | p.requests[e.RequestID] = request{url: truncate(e.Request.URL, maxURL), kind: e.Type} |
| 181 | } |
| 182 | case "Network.responseReceived": |
| 183 | var e responseEvent |
| 184 | if json.Unmarshal(params, &e) != nil { |
| 185 | return |
| 186 | } |
| 187 | if e.Response.Status >= 400 { |
| 188 | // Reported here; its loadingFinished only forgets it. |
| 189 | delete(p.requests, e.RequestID) |
| 190 | p.addFailed(e.Response.URL, e.Type, e.Response.Status, false) |
| 191 | } |
| 192 | case "Network.loadingFailed": |
| 193 | var e loadingFailedEvent |
| 194 | if json.Unmarshal(params, &e) != nil { |
| 195 | return |
| 196 | } |
| 197 | r, ok := p.requests[e.RequestID] |
| 198 | delete(p.requests, e.RequestID) |
| 199 | if ok && !e.Canceled { |
| 200 | kind := e.Type |
| 201 | if kind == "" { |
| 202 | kind = r.kind |
| 203 | } |
| 204 | p.addFailed(r.url, kind, 0, true) |
| 205 | } |
| 206 | case "Network.loadingFinished": |
| 207 | var e loadingFinishedEvent |
| 208 | if json.Unmarshal(params, &e) == nil { |
| 209 | delete(p.requests, e.RequestID) |
| 210 | } |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | func (p *pageState) addConsole(msg string) { |
| 215 | msg = clean(msg, maxMessage) |
| 216 | if msg == "" { |
| 217 | return |
| 218 | } |
| 219 | if len(p.console) < maxConsoleErrors { |
| 220 | p.console = append(p.console, msg) |
| 221 | } else { |
| 222 | p.consoleMore++ |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | func (p *pageState) addFailed(rawURL, resourceType string, status int, netErr bool) { |
| 227 | if !p.collecting { |
| 228 | return |
| 229 | } |
| 230 | kind, ok := classifyLoad(p.site, rawURL, resourceType, status, netErr) |
| 231 | if !ok { |
| 232 | return |
| 233 | } |
| 234 | f := FailedLoad{Kind: kind, URL: clean(rawURL, maxURL), Status: status} |
| 235 | for _, have := range p.failed { |
| 236 | if have == f { |
| 237 | return |
| 238 | } |
| 239 | } |
| 240 | if len(p.failed) < maxFailedLoads { |
| 241 | p.failed = append(p.failed, f) |
| 242 | } else { |
| 243 | p.failedMore++ |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | // classifyLoad names a load that failed: a font (any font that did not |
| 248 | // load, from anywhere), a same-site resource that answered an HTTP error |
| 249 | // (not found), or a resource elsewhere, which the sandbox cannot reach |
| 250 | // (external blocked). Other failures (a same-site request the browser |
| 251 | // itself refused, a scheme that is not HTTP) are not reported. |
| 252 | func classifyLoad(site *url.URL, rawURL, resourceType string, status int, netErr bool) (string, bool) { |
| 253 | u, err := url.Parse(rawURL) |
| 254 | if err != nil || u.Scheme != "http" && u.Scheme != "https" || !netErr && status < 400 { |
| 255 | return "", false |
| 256 | } |
| 257 | if resourceType == "Font" { |
| 258 | return LoadFont, true |
| 259 | } |
| 260 | same := u.Scheme == site.Scheme && u.Host == site.Host |
| 261 | switch { |
| 262 | case same && !netErr: |
| 263 | return LoadNotFound, true |
| 264 | case !same && netErr: |
| 265 | return LoadExternalBlocked, true |
| 266 | } |
| 267 | return "", false |
| 268 | } |
| 269 | |
| 270 | // text is a console argument as text: a string's value, else what the |
| 271 | // browser describes it as. |
| 272 | func (o remoteObject) text() string { |
| 273 | if o.Type == "string" { |
| 274 | var s string |
| 275 | if json.Unmarshal(o.Value, &s) == nil { |
| 276 | return truncate(s, maxMessage) |
| 277 | } |
| 278 | } |
| 279 | if o.UnserializableValue != "" { |
| 280 | return truncate(o.UnserializableValue, maxMessage) |
| 281 | } |
| 282 | if o.Description != "" { |
| 283 | return truncate(o.Description, maxMessage) |
| 284 | } |
| 285 | if len(o.Value) > 0 && len(o.Value) <= maxMessage { |
| 286 | return string(o.Value) |
| 287 | } |
| 288 | return o.Type |
| 289 | } |
| 290 | |
| 291 | // truncate cuts s to at most max bytes; clean makes it valid later. |
| 292 | func truncate(s string, max int) string { |
| 293 | if len(s) > max { |
| 294 | return s[:max] |
| 295 | } |
| 296 | return s |
| 297 | } |
| 298 | |
| 299 | // setMain names the page's main frame, before it navigates. |
| 300 | func (p *pageState) setMain(frame string) { |
| 301 | p.mu.Lock() |
| 302 | p.mainFrame = frame |
| 303 | p.mu.Unlock() |
| 304 | } |
| 305 | |
| 306 | // waitLoaded waits for the main frame's current document to fire load, |
| 307 | // then for the network to be idle, at most IdleWait after the load. |
| 308 | func (p *pageState) waitLoaded(ctx context.Context) error { |
| 309 | for { |
| 310 | p.mu.Lock() |
| 311 | loaded, idle, at := p.loaded, p.idle, p.loadedAt |
| 312 | p.mu.Unlock() |
| 313 | var timer *time.Timer |
| 314 | if loaded { |
| 315 | left := IdleWait - time.Since(at) |
| 316 | if idle || left <= 0 { |
| 317 | return nil |
| 318 | } |
| 319 | timer = time.NewTimer(left) |
| 320 | } |
| 321 | var fired <-chan time.Time |
| 322 | if timer != nil { |
| 323 | fired = timer.C |
| 324 | } |
| 325 | select { |
| 326 | case <-p.notify: |
| 327 | case <-fired: |
| 328 | case <-ctx.Done(): |
| 329 | if timer != nil { |
| 330 | timer.Stop() |
| 331 | } |
| 332 | return context.Cause(ctx) |
| 333 | } |
| 334 | if timer != nil { |
| 335 | timer.Stop() |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | // finish stops collecting and returns what was collected. |
| 341 | func (p *pageState) finish(r *PageReport) { |
| 342 | p.mu.Lock() |
| 343 | defer p.mu.Unlock() |
| 344 | p.collecting = false |
| 345 | r.ConsoleErrors = append([]string{}, p.console...) |
| 346 | r.ConsoleErrorsOmitted = p.consoleMore |
| 347 | r.FailedLoads = append([]FailedLoad{}, p.failed...) |
| 348 | r.FailedLoadsOmitted = p.failedMore |
| 349 | } |
| 350 | |
| 351 | // axNode is one node of Accessibility.getFullAXTree. |
| 352 | type axNode struct { |
| 353 | NodeID string `json:"nodeId"` |
| 354 | Ignored bool `json:"ignored"` |
| 355 | Role *axValue `json:"role"` |
| 356 | Name *axValue `json:"name"` |
| 357 | ChildIDs []string `json:"childIds"` |
| 358 | ParentID string `json:"parentId"` |
| 359 | } |
| 360 | |
| 361 | type axValue struct { |
| 362 | Value json.RawMessage `json:"value"` |
| 363 | } |
| 364 | |
| 365 | func (v *axValue) text() string { |
| 366 | if v == nil { |
| 367 | return "" |
| 368 | } |
| 369 | var s string |
| 370 | if json.Unmarshal(v.Value, &s) != nil { |
| 371 | return "" |
| 372 | } |
| 373 | return s |
| 374 | } |
| 375 | |
| 376 | // maxAXNodes bounds the nodes an outline reads, and maxAXDepth its |
| 377 | // indentation. |
| 378 | const ( |
| 379 | maxAXNodes = 20000 |
| 380 | maxAXDepth = 24 |
| 381 | ) |
| 382 | |
| 383 | // outline writes the accessibility tree as text: one line a node, |
| 384 | // "role" or `role "name"`, indented two spaces a level. Ignored nodes, |
| 385 | // and roles that only group (generic, none), are skipped and their |
| 386 | // children lifted; text is shown only where its parent has no name of |
| 387 | // its own. The result is at most max bytes, whole lines; cut says some |
| 388 | // were left out. Each node is visited at most once, whatever the ids |
| 389 | // claim. |
| 390 | func outline(nodes []axNode, max int) (text string, cut bool) { |
| 391 | if len(nodes) > maxAXNodes { |
| 392 | nodes, cut = nodes[:maxAXNodes], true |
| 393 | } |
| 394 | index := make(map[string]int, len(nodes)) |
| 395 | for i, n := range nodes { |
| 396 | if _, dup := index[n.NodeID]; !dup && n.NodeID != "" { |
| 397 | index[n.NodeID] = i |
| 398 | } |
| 399 | } |
| 400 | root := -1 |
| 401 | for i, n := range nodes { |
| 402 | if _, ok := index[n.ParentID]; n.ParentID == "" || !ok { |
| 403 | root = i |
| 404 | break |
| 405 | } |
| 406 | } |
| 407 | if root < 0 { |
| 408 | return "", cut |
| 409 | } |
| 410 | type item struct { |
| 411 | i, depth int |
| 412 | named bool |
| 413 | } |
| 414 | seen := make([]bool, len(nodes)) |
| 415 | stack := []item{{i: root}} |
| 416 | var b strings.Builder |
| 417 | for len(stack) > 0 { |
| 418 | it := stack[len(stack)-1] |
| 419 | stack = stack[:len(stack)-1] |
| 420 | if seen[it.i] { |
| 421 | continue |
| 422 | } |
| 423 | seen[it.i] = true |
| 424 | n := nodes[it.i] |
| 425 | role, name := clean(n.Role.text(), 40), clean(n.Name.text(), maxName) |
| 426 | depth, named := it.depth, it.named |
| 427 | switch { |
| 428 | case n.Ignored || role == "" || role == "none" || role == "generic" || role == "InlineTextBox" || role == "LineBreak": |
| 429 | case role == "StaticText" && (named || name == ""): |
| 430 | default: |
| 431 | line := strings.Repeat(" ", min(depth, maxAXDepth)) + role |
| 432 | if name != "" { |
| 433 | line += fmt.Sprintf(" %q", name) |
| 434 | } |
| 435 | if b.Len()+len(line)+1 > max { |
| 436 | return b.String(), true |
| 437 | } |
| 438 | b.WriteString(line) |
| 439 | b.WriteByte('\n') |
| 440 | depth, named = depth+1, name != "" |
| 441 | } |
| 442 | // Children in order: pushed last first. |
| 443 | for k := len(n.ChildIDs) - 1; k >= 0; k-- { |
| 444 | if c, ok := index[n.ChildIDs[k]]; ok && !seen[c] { |
| 445 | stack = append(stack, item{i: c, depth: depth, named: named}) |
| 446 | } |
| 447 | } |
| 448 | if len(stack) > maxAXNodes { |
| 449 | return b.String(), true |
| 450 | } |
| 451 | } |
| 452 | return b.String(), cut |
| 453 | } |
| 454 | |