Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
199 changes: 180 additions & 19 deletions app/services/capturers/page.rb
Original file line number Diff line number Diff line change
@@ -1,30 +1,46 @@
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.
#
# 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

[
Expand All @@ -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
105 changes: 105 additions & 0 deletions bin/capture-sample
Original file line number Diff line number Diff line change
@@ -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] <url or file>..." 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: "-")
<!doctype html>
<meta charset="utf-8">
<title>Capture sample</title>
<style>
body { font: 14px/1.4 system-ui, sans-serif; margin: 24px; color: #222; }
section { border-top: 1px solid #ccc; padding: 16px 0; }
h2 { font-size: 16px; margin: 0 0 4px; word-break: break-all; }
.meta { color: #666; font-size: 12px; }
.fail { color: #b00; }
img { max-width: 100%; max-height: 900px; border: 1px solid #ccc; display: block; margin: 8px 0; }
pre { background: #f4f4f4; padding: 8px; font-size: 11px; max-height: 240px; overflow: auto; }
.row { display: flex; gap: 16px; align-items: flex-start; }
.row > * { flex: 1; min-width: 0; }
</style>
<h1>Capture sample, <%= Time.now.utc.strftime("%Y-%m-%d %H:%M UTC") %></h1>
<%- results.each do |r| -%>
<section>
<h2><a href="<%= ERB::Util.h(r[:url]) %>"><%= ERB::Util.h(r[:url]) %></a> <span class="meta">(<%= r[:method] %>, <%= r[:seconds] %> s)</span></h2>
<%- if r[:error] -%><p class="fail"><%= ERB::Util.h(r[:error]) %></p><%- end -%>
<p class="meta"><%= r[:files].map { |f| "#{ERB::Util.h(f[:role])}: <a href='#{ERB::Util.h(f[:path])}'>#{ERB::Util.h(::File.basename(f[:path]))}</a> (#{f[:bytes]} bytes)" }.join(" · ") %></p>
<div class="row">
<%- r[:files].select { |f| f[:path].end_with?(".png", ".jpg", ".jpeg", ".webp") }.each do |f| -%>
<a href="<%= ERB::Util.h(f[:path]) %>"><img src="<%= ERB::Util.h(f[:path]) %>" alt="<%= ERB::Util.h(f[:role]) %>" loading="lazy"></a>
<%- end -%>
<pre><%= ERB::Util.html_escape(r[:log]) %></pre>
</div>
</section>
<%- end -%>
HTML
::File.write(::File.join(out, "index.html"), template.result(binding))
$stderr.puts "Wrote #{::File.join(out, "index.html")}"
2 changes: 1 addition & 1 deletion docs/deploy.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
18 changes: 18 additions & 0 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <urls>` 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:
Expand Down
Loading
Loading