diff --git a/app/services/capturers/page.rb b/app/services/capturers/page.rb index 31421ec..8ccb661 100644 --- a/app/services/capturers/page.rb +++ b/app/services/capturers/page.rb @@ -1,3 +1,5 @@ +require "base64" + module Capturers # A rendered web page in headless Chromium, through Ferrum: the MHTML of the page as loaded # (original), a full-page PNG (screenshot) and a print PDF (rendition). One browser, one load. @@ -5,26 +7,40 @@ module Capturers # The browser runs with no sandbox inside the container (Docker gives the isolation), with a # fixed viewport, and with JavaScript on, because most pages are empty without it. It never # signs in anywhere and sends no cookies. + # + # Many pages draw themselves as the reader scrolls: sections start at opacity 0 and fade in + # through an IntersectionObserver, images load lazily, animations run for seconds. A capture + # of the page as first loaded is then mostly blank below the fold. So before the files are + # written, the capturer asks for reduced motion, runs animations fast, walks the whole page + # once in viewport steps, returns to the top, and freezes the page. See docs/design.md, + # "Dynamic pages". class Page < Base VIEWPORT = [ 1440, 900 ].freeze LOAD_TIMEOUT = 60 IDLE_TIMEOUT = 10 + # The walk down the page: at most this many steps of one viewport each, this long apart. + SCROLL_STEPS = 60 + SCROLL_PAUSE = 0.25 + # Up to this many quarter seconds for the web fonts. + FONT_WAITS = 20 + # After the walk, time for the last reveals and the images they started. + SETTLE = 1.0 + # The tallest screenshot: Chromium blanks or clips captures past 16384px, and a feed that + # grows on every scroll would otherwise ask for one the size of the walk, or more. + MAX_SCREENSHOT_HEIGHT = 16_384 def call - log("Chromium: loading #{url}") - with_browser do |browser| - page = browser.create_page - page.go_to(url) - begin - page.network.wait_for_idle(timeout: IDLE_TIMEOUT) - rescue Ferrum::TimeoutError - log("the page kept loading for #{IDLE_TIMEOUT} seconds; capturing as is") - end - log("title: #{page.title.to_s.first(200)}") - - page.mhtml(path: path("page.mhtml")) - page.screenshot(path: path("page.png"), full: true) - page.pdf(path: path("page.pdf"), format: :A4, print_background: true) + @started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + attempts = 0 + begin + attempts += 1 + log("Chromium: loading #{url}#{" (second try)" if attempts > 1}") + with_browser { |browser| capture_in(browser) } + rescue Ferrum::Error => e + # A heavy page can take the browser or its renderer down once. One more try, in a new + # browser, when there is time for it. + retry if crashed?(e) && attempts < 2 && elapsed < Capturers.timeout / 2 + raise end [ @@ -38,18 +54,163 @@ def call private + def capture_in(browser) + page = browser.create_page + calm(page) + page.go_to(url) + wait_for_idle(page, "the page kept loading") + log("title: #{page.title.to_s.first(200)} (#{elapsed}s)") + + height = reveal(page) + wait_for_idle(page, "images kept loading after the scroll") + self.class.sleep_for(SETTLE) + freeze(page) + + log("saving the MHTML (#{elapsed}s)") + page.mhtml(path: path("page.mhtml")) + log("saving the screenshot (#{elapsed}s)") + screenshot(page, height) + log("saving the PDF (#{elapsed}s)") + page.pdf(path: path("page.pdf"), format: :A4, print_background: true) + log("done (#{elapsed}s)") + end + + def elapsed + (Process.clock_gettime(Process::CLOCK_MONOTONIC) - @started).round(1) + end + + # The browser process died, or the page's renderer crashed and Ferrum lost the target. + def crashed?(error) + return true if error.is_a?(Ferrum::DeadBrowserError) || error.is_a?(Ferrum::NoSuchPageError) + + error.message.to_s.match?(/crashed|Inspected target navigated or closed/i) + end + + # Before the page loads: ask for reduced motion, so pages that honor it skip their + # entrance animations, and run the ones that remain at 50x so they are over in time. + def calm(page) + page.command("Emulation.setEmulatedMedia", features: [ { name: "prefers-reduced-motion", value: "reduce" } ]) + page.command("Animation.enable") + page.command("Animation.setPlaybackRate", playbackRate: 50) + rescue Ferrum::Error => e + raise if crashed?(e) + + log("could not set reduced motion: #{e.message.to_s.first(120)}") + end + + # Walks down the page one viewport at a time, so observers fire and lazy images load, + # then returns to the top. Waits for fonts first, so text does not reflow in the capture. + # Returns the height of the page after the walk. + def reveal(page) + wait_for_fonts(page) + height = page.evaluate("document.documentElement.scrollHeight").to_i + step = VIEWPORT.last + steps = [ (height.to_f / step).ceil, SCROLL_STEPS ].min + log("scrolling #{height}px in #{steps} steps") + steps.times do |i| + page.execute("window.scrollTo({ top: #{(i + 1) * step}, left: 0, behavior: \"instant\" })") + self.class.sleep_for(SCROLL_PAUSE) + if i.zero? && steps > 1 && page.evaluate("window.scrollY").to_i.zero? + log("the page did not scroll; an inner element scrolls instead, so the walk reveals nothing") + break + end + end + page.execute("window.scrollTo({ top: 0, left: 0, behavior: \"instant\" })") + self.class.sleep_for(SCROLL_PAUSE) + final = page.evaluate("document.documentElement.scrollHeight").to_i + log("page is #{final}px tall after the scroll") + final + rescue Ferrum::Error => e + raise if crashed?(e) + + log("the scroll stopped early: #{e.message.to_s.first(120)}") + height || VIEWPORT.last + end + + # Stops the page from drawing new frames while the files are written: pauses media, takes + # away requestAnimationFrame in every frame, and pauses the remaining animations, so a + # render loop (a WebGL scene, a carousel) keeps its last frame. Without this, a + # software-rendered WebGL scene made one screenshot take 16 minutes, because every frame + # it kept drawing had to be composited first. + FREEZE = <<~JS.freeze + document.querySelectorAll("video, audio").forEach((media) => { try { media.pause(); } catch (_) {} }); + window.requestAnimationFrame = () => 0; + window.cancelAnimationFrame = () => {}; + JS + + def freeze(page) + page.frames.each do |frame| + frame.execute(FREEZE) + rescue Ferrum::Error => e + raise if crashed?(e) + end + page.command("Animation.setPlaybackRate", playbackRate: 0) + rescue Ferrum::Error => e + raise if crashed?(e) + + log("could not freeze the page: #{e.message.to_s.first(120)}") + end + + # Up to five seconds for the web fonts, so text does not reflow between the files. + def wait_for_fonts(page) + FONT_WAITS.times do + return if page.evaluate("document.fonts.status") == "loaded" + + self.class.sleep_for(SCROLL_PAUSE) + end + log("fonts were still loading after #{FONT_WAITS / 4} seconds; continuing") + rescue Ferrum::Error => e + raise if crashed?(e) + + log("could not wait for fonts: #{e.message.to_s.first(120)}") + end + + # Ferrum answers false when the network is still busy at the deadline; it does not raise. + def wait_for_idle(page, reason) + return if page.network.wait_for_idle(timeout: IDLE_TIMEOUT) + + log("#{reason} for #{IDLE_TIMEOUT} seconds; capturing as is") + end + + # The whole page, as tall as the walk found it, up to the cap. Through the protocol rather + # than Ferrum's `full: true`, which reads the height again and sets no limit. + def screenshot(page, height) + clip_height = [ height, SCROLL_STEPS * VIEWPORT.last, MAX_SCREENSHOT_HEIGHT ].min + clip_height = VIEWPORT.last if clip_height < VIEWPORT.last + log("the screenshot is cut at #{clip_height}px of #{height}px") if clip_height < height + result = page.command("Page.captureScreenshot", format: "png", captureBeyondViewport: true, + clip: { x: 0, y: 0, width: VIEWPORT.first, height: clip_height, scale: 1 }) + ::File.binwrite(path("page.png"), Base64.decode64(result.fetch("data"))) + end + def with_browser - browser = Ferrum::Browser.new( + browser = self.class.new_browser + yield browser + ensure + browser&.quit + log("browser closed (#{elapsed}s)") if @started + end + + # The tests swap this out too, so the walk takes no time there. + def self.sleep_for(seconds) = sleep(seconds) + + # The tests swap this for a fake browser (stub_method), so no test starts Chromium. + def self.new_browser + Ferrum::Browser.new( headless: true, timeout: LOAD_TIMEOUT, process_timeout: 30, window_size: VIEWPORT, browser_path: ENV["BROWSER_PATH"].presence, - browser_options: { "no-sandbox" => nil, "disable-gpu" => nil, "disable-dev-shm-usage" => nil, "hide-scrollbars" => nil } + # SwiftShader draws WebGL in software, so a canvas site renders without a GPU. With + # disable-gpu instead, WebGL is off and such a page captures as a blank gradient. + # enable-unsafe-swiftshader is what turns it on since Chromium 128: the shader compiler + # is not hardened against hostile shaders, and the container is the boundary. + browser_options: { + "no-sandbox" => nil, "disable-dev-shm-usage" => nil, "hide-scrollbars" => nil, + "use-angle" => "swiftshader", "enable-unsafe-swiftshader" => nil + } ) - yield browser - ensure - browser&.quit end end end diff --git a/bin/capture-sample b/bin/capture-sample new file mode 100755 index 0000000..d1f7b97 --- /dev/null +++ b/bin/capture-sample @@ -0,0 +1,105 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Runs the capturers against a list of URLs and writes the outputs where you can look at them. +# No database rows: a fake capture stands in for the model, so this never touches an archive. +# +# bin/capture-sample https://example.com/ https://github.com/rails/rails +# bin/capture-sample --methods page --out tmp/capture-sample urls.txt +# +# Each URL gets a directory under --out (default tmp/capture-sample) with the files the +# capturers wrote, a log.txt, and the run writes index.html at the top with every screenshot +# and log side by side. Open it in a browser. The page capturer needs Chromium: set BROWSER_PATH +# on a Mac (see .env.example). +require "optparse" + +options = { out: "tmp/capture-sample", methods: nil } +OptionParser.new do |parser| + parser.on("--out DIR", "Where to write (default tmp/capture-sample)") { |dir| options[:out] = dir } + parser.on("--methods LIST", "Comma-separated capture methods to run, default: what the router picks") do |list| + options[:methods] = list.split(",").map(&:strip) + end +end.parse! + +urls = ARGV.flat_map { |arg| ::File.file?(arg) ? ::File.readlines(arg, chomp: true) : [ arg ] } + .map(&:strip).reject { |line| line.empty? || line.start_with?("#") } +abort "Usage: bin/capture-sample [--out DIR] [--methods page,git] ..." if urls.empty? + +ENV["RAILS_ENV"] ||= "development" +require_relative "../config/environment" +require "fileutils" +require "erb" +require "digest" + +FakeArchive = Struct.new(:url) +FakeCapture = Struct.new(:archive, :method_name, :log) do + def log!(line) + self.log = "#{log}#{line.to_s.chomp}\n" + $stderr.puts " #{line.to_s.chomp}" + end +end + +out = ::File.expand_path(options[:out], Dir.pwd) +FileUtils.mkdir_p(out) +results = [] + +urls.each do |url| + # The host and path, readable, plus a hash so two URLs never share a directory. + slug = url.sub(%r{\Ahttps?://}, "").gsub(/[^a-z0-9]+/i, "-").squeeze("-").delete_suffix("-").first(72) + + "-" + Digest::SHA256.hexdigest(url).first(8) + methods = options[:methods] || Capturers::Router.methods_for(url) + $stderr.puts "#{url}: #{methods.join(", ")}" + + methods.each do |method_name| + dir = ::File.join(out, slug, method_name) + FileUtils.rm_rf(dir) + FileUtils.mkdir_p(dir) + capture = FakeCapture.new(FakeArchive.new(url), method_name, +"") + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + outputs = [] + error = nil + begin + outputs = Capturers::Router::CAPTURERS.fetch(method_name).constantize.new(capture, dir).call + rescue StandardError => e + error = "#{e.class}: #{e.message}" + $stderr.puts " FAILED #{error}" + end + seconds = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - started).round(1) + ::File.write(::File.join(dir, "log.txt"), capture.log) + files = outputs.map { |o| { role: o.role, path: ::File.join(slug, method_name, ::File.basename(o.path)), bytes: ::File.size(o.path) } } + results << { url: url, method: method_name, seconds: seconds, error: error, files: files, log: capture.log } + end +end + +template = ERB.new(<<~'HTML', trim_mode: "-") + + + Capture sample + +

Capture sample, <%= Time.now.utc.strftime("%Y-%m-%d %H:%M UTC") %>

+ <%- results.each do |r| -%> +
+

<%= ERB::Util.h(r[:url]) %> (<%= r[:method] %>, <%= r[:seconds] %> s)

+ <%- if r[:error] -%>

<%= ERB::Util.h(r[:error]) %>

<%- end -%> +

<%= r[:files].map { |f| "#{ERB::Util.h(f[:role])}: #{ERB::Util.h(::File.basename(f[:path]))} (#{f[:bytes]} bytes)" }.join(" ยท ") %>

+
+ <%- r[:files].select { |f| f[:path].end_with?(".png", ".jpg", ".jpeg", ".webp") }.each do |f| -%> + <%= ERB::Util.h(f[:role]) %> + <%- end -%> +
<%= ERB::Util.html_escape(r[:log]) %>
+
+
+ <%- end -%> +HTML +::File.write(::File.join(out, "index.html"), template.result(binding)) +$stderr.puts "Wrote #{::File.join(out, "index.html")}" diff --git a/docs/deploy.md b/docs/deploy.md index 421e0f7..f598e36 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -47,7 +47,7 @@ flowchart LR | `CAPTURE_TIMEOUT`, `CAPTURE_MAX_BYTES` | defaults 600 seconds, 2 GB | the same | | `GOOD_JOB_MAX_THREADS` | `2` | `1` | -The worker needs `/tmp` with room for a capture (a video or a repository), and `/dev/shm` of at least 1 GB or Chromium with `--disable-dev-shm-usage` (already set). Give the worker container 2 GB of memory. +The worker needs `/tmp` with room for a capture (a video or a repository), and `/dev/shm` of at least 1 GB or Chromium with `--disable-dev-shm-usage` (already set). Give the worker container 2 GB of memory. Chromium draws WebGL in software (`--use-angle=swiftshader --enable-unsafe-swiftshader`, see `design.md`, "Dynamic pages"): a canvas-heavy page can hold one CPU for the half minute before the capturer freezes it, and the second flag trades shader-compiler hardening for working WebGL, with the container as the boundary. Debian's `chromium` package ships the SwiftShader libraries the flags need. ## What the infra module must provide diff --git a/docs/design.md b/docs/design.md index e73ca0b..8126652 100644 --- a/docs/design.md +++ b/docs/design.md @@ -88,6 +88,24 @@ Each capturer has a timeout (`CAPTURE_TIMEOUT`, default 10 minutes) and a size l Every external tool runs in a subprocess with a clean environment and the URL as an argument, never through a shell string. A capturer never runs code from the archived content. +### Dynamic pages + +Many pages draw themselves as the reader scrolls: sections start at opacity 0 and fade in through an IntersectionObserver, images load lazily, animations run for seconds. A capture of the page as first loaded is mostly blank below the fold. So the `page` capturer, before it writes a file: + +1. Asks for `prefers-reduced-motion: reduce` and sets the animation playback rate to 50x, both through the DevTools protocol, before the page loads. Pages that honor reduced motion skip their entrance animations. The ones that do not are over in a moment. +2. Waits for the network to go idle (10 seconds at most), then up to 5 seconds for `document.fonts.status` to read `loaded`. +3. Walks the page one viewport (900px) at a time with instant scrolls, a quarter second per step, at most 60 steps, then returns to the top. Observers fire and lazy images load on the way. When the window does not move after the first step (an inner element scrolls instead), the walk stops and the log says so. +4. Waits for the network to go idle again, then one second for the last reveals. +5. Freezes the page: pauses every video and audio element and takes away `requestAnimationFrame` in every frame, then sets the animation playback rate to 0, so a render loop keeps its last frame while the files are written. A software-rendered WebGL scene that kept drawing made one screenshot take 16 minutes. + +Then the MHTML, the PNG and the PDF are written from that state. The PNG is as tall as the page was after the walk, capped at 16384px (Chromium blanks taller captures) and at the walked height, so a feed that grows on every scroll does not ask for a screenshot the size of the feed. The MHTML keeps the DOM as revealed, so the archived copy is not blank either. + +Chromium runs with SwiftShader (`--use-angle=swiftshader --enable-unsafe-swiftshader`), so WebGL draws in software and a canvas site renders without a GPU; with the GPU off, such a page captured as a blank gradient. The second flag is what turns WebGL on since Chromium 128: its shader compiler is not hardened against hostile shaders, so an archived page gets that attack surface, with the container as the boundary (the browser already runs with `--no-sandbox` there). A heavy page can take the browser or its renderer down once; the capturer then tries once more in a new browser, when less than half of `CAPTURE_TIMEOUT` is spent. The log notes the elapsed seconds at each step. + +What this does not fix: a page that pins sections to the scroll position (a scroll-driven hero) still looks like a long strip in the screenshot; a reveal library that hides sections again when they leave the viewport un-reveals them on the return to the top; a JavaScript entrance animation that the return to the top starts is frozen where it was. Those pages are captured as they are; the PDF and the MHTML keep the content. + +`bin/capture-sample ` runs the capturers on a list of URLs without the database and writes an `index.html` with every screenshot and log, to check a change like this against real pages before it ships. + ## Who can do what Sign-in is Weave OIDC, as in Quilt. The roles come from the `roles` claim: diff --git a/test/services/capturers/page_test.rb b/test/services/capturers/page_test.rb new file mode 100644 index 0000000..6790676 --- /dev/null +++ b/test/services/capturers/page_test.rb @@ -0,0 +1,220 @@ +require "test_helper" + +# The page capturer against a fake browser: no Chromium runs in the tests. The fake records +# every CDP command, navigation, script and scroll in order, and writes empty files where the +# real browser would. +class Capturers::PageTest < ActiveSupport::TestCase + class FakeNetwork + def initialize(idle) + @idle = idle + end + + # Ferrum answers false at the deadline; it does not raise. + def wait_for_idle(timeout:) = @idle + end + + class FakeFrame + def initialize(page) = @page = page + def execute(script) = @page.execute(script) + end + + class FakePage + attr_reader :events, :files, :network + attr_accessor :scroll_y + + def initialize(height:, idle: true, frames: 1) + @height = height + @events = [] + @files = [] + @network = FakeNetwork.new(idle) + @frames = Array.new(frames) { FakeFrame.new(self) } + @scroll_y = nil + end + + def command(name, **params) + @events << [ :command, name, params ] + name == "Page.captureScreenshot" ? { "data" => Base64.strict_encode64("png") } : {} + end + + def go_to(url) = @events << [ :go_to, url ] + def title = "A page" + def frames = @frames + + def evaluate(script, **) + @events << [ :evaluate, script ] + case script + when /scrollHeight/ then @height + when /fonts.status/ then "loaded" + when /scrollY/ then @scroll_y || scrolls.last + else true + end + end + + def execute(script) + if script.include?("scrollTo") + @events << [ :scroll, script[/top: (\d+)/, 1].to_i ] + else + @events << [ :execute, script ] + end + end + + def mhtml(path:) = write(path) + def pdf(path:, **) = write(path) + + def scrolls = @events.filter_map { |event| event[1] if event[0] == :scroll } + def commands = @events.filter_map { |event| event[1] if event[0] == :command } + def screenshot_clip = @events.find { |event| event[0] == :command && event[1] == "Page.captureScreenshot" }&.dig(2, :clip) + + private + + def write(path) + File.write(path, "x") + @files << File.basename(path) + @events << [ :write, File.basename(path) ] + end + end + + class FakeBrowser + attr_reader :quit_called + + def initialize(page) + @page = page + end + + def create_page = @page + def quit = @quit_called = true + end + + setup do + @archive = create_archive(url: "https://example.org/story") + @capture = @archive.captures.create!(method_name: "page", status: "running", position: 0) + @workdir = Dir.mktmpdir + end + + teardown do + FileUtils.rm_rf(@workdir) + end + + def run_capture(page) + browser = FakeBrowser.new(page) + outputs = nil + stub_method(Capturers::Page, :new_browser, browser) do + stub_method(Capturers::Page, :sleep_for, ->(_seconds) { }) do + outputs = Capturers::Page.new(@capture, @workdir).call + end + end + assert browser.quit_called, "the browser is closed" + outputs + end + + test "asks for reduced motion and fast animations before the page loads" do + page = FakePage.new(height: 900) + run_capture(page) + + first_navigation = page.events.index { |event| event[0] == :go_to } + before = page.events.first(first_navigation) + assert_includes before, [ :command, "Emulation.setEmulatedMedia", { features: [ { name: "prefers-reduced-motion", value: "reduce" } ] } ] + assert_includes before, [ :command, "Animation.setPlaybackRate", { playbackRate: 50 } ] + end + + test "walks the page one viewport at a time, instantly, and returns to the top" do + page = FakePage.new(height: 3000) + run_capture(page) + + assert_equal [ 900, 1800, 2700, 3600, 0 ], page.scrolls + assert_includes @capture.log, "scrolling 3000px in 4 steps" + assert_includes @capture.log, "page is 3000px tall after the scroll" + scroll = page.events.find { |event| event[0] == :scroll } + assert scroll, "scrolls through scrollTo" + end + + test "caps the walk on a very long page, and the screenshot at the Chromium limit" do + page = FakePage.new(height: 900 * 500) + run_capture(page) + + assert_equal Capturers::Page::SCROLL_STEPS + 1, page.scrolls.size + assert_equal 0, page.scrolls.last + assert_equal 16_384, page.screenshot_clip[:height] + assert_includes @capture.log, "the screenshot is cut at 16384px of 450000px" + end + + test "stops the walk when the window does not scroll" do + page = FakePage.new(height: 5000) + page.scroll_y = 0 + run_capture(page) + + assert_equal [ 900, 0 ], page.scrolls + assert_includes @capture.log, "the page did not scroll" + end + + test "pauses media and stops animation frames in every frame after the walk and before the files" do + page = FakePage.new(height: 1800, frames: 2) + run_capture(page) + + freezes = page.events.each_index.select { |i| page.events[i][0] == :execute && page.events[i][1].include?("requestAnimationFrame") } + last_scroll = page.events.rindex { |event| event[0] == :scroll } + first_write = page.events.index { |event| event[0] == :write } + assert_equal 2, freezes.size, "one freeze per frame" + assert_operator last_scroll, :<, freezes.first + assert_operator freezes.last, :<, first_write + assert_includes page.events[freezes.first][1], "media.pause()" + assert_includes page.events, [ :command, "Animation.setPlaybackRate", { playbackRate: 0 } ] + end + + test "writes the three files and returns them in role order" do + outputs = run_capture(FakePage.new(height: 900)) + + assert_equal %w[original screenshot rendition], outputs.map(&:role) + assert_equal %w[page.mhtml page.png page.pdf], outputs.map { |o| File.basename(o.path) } + assert_equal "png", File.read(File.join(@workdir, "page.png")) + assert_equal({ x: 0, y: 0, width: 1440, height: 900, scale: 1 }, FakePage.new(height: 900).then { |p| run_capture(p); p.screenshot_clip }) + end + + test "tries once more in a new browser when the first one dies" do + dead = FakePage.new(height: 900) + dead.define_singleton_method(:go_to) { |_url| raise Ferrum::DeadBrowserError } + browsers = [ FakeBrowser.new(dead), FakeBrowser.new(FakePage.new(height: 900)) ] + outputs = nil + stub_method(Capturers::Page, :new_browser, -> { browsers.shift }) do + stub_method(Capturers::Page, :sleep_for, ->(_seconds) { }) do + outputs = Capturers::Page.new(@capture, @workdir).call + end + end + + assert_equal 3, outputs.size + assert_empty browsers, "both browsers were used" + assert_includes @capture.log, "(second try)" + end + + test "a renderer crash during the walk is not swallowed, and gets the second try" do + crashing = FakePage.new(height: 3000) + crashing.define_singleton_method(:execute) { |_script| raise Ferrum::BrowserError.new({ "message" => "Target crashed" }) } + browsers = [ FakeBrowser.new(crashing), FakeBrowser.new(FakePage.new(height: 900)) ] + outputs = nil + stub_method(Capturers::Page, :new_browser, -> { browsers.shift }) do + stub_method(Capturers::Page, :sleep_for, ->(_seconds) { }) do + outputs = Capturers::Page.new(@capture, @workdir).call + end + end + + assert_equal 3, outputs.size + assert_empty browsers + end + + test "any other browser error fails the capture as a tool failure, once" do + page = FakePage.new(height: 900) + page.define_singleton_method(:mhtml) { |path:| raise Ferrum::BrowserError.new({ "message" => "No MHTML for this scheme" }) } + + error = assert_raises(Capturers::ToolFailed) { run_capture(page) } + assert_includes error.message, "No MHTML for this scheme" + assert_not_includes @capture.log, "(second try)" + end + + test "logs when the network never goes idle, and captures as is" do + outputs = run_capture(FakePage.new(height: 900, idle: false)) + + assert_equal 3, outputs.size + assert_includes @capture.log, "the page kept loading for" + assert_includes @capture.log, "images kept loading after the scroll" + end +end