glacier-web 0.4.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//! PDFs from HTML, printed by headless Chrome, as Rails apps do with
//! Grover or a Puppeteer service: render a template to HTML, then print
//! it.
//!
//! ```ignore
//! let pdf = glacier::pdf::render_template(views::orders::Receipt { order }, &PdfOptions::a4()).await?;
//! Ok(Response::download(pdf, "receipt.pdf"))
//! ```
//!
//! [`Chrome`] runs the Chrome or Chromium on the machine (`CHROME_PATH`,
//! or the usual places), one process per PDF, with JavaScript off and
//! every request the page makes refused except `data:` URLs and the
//! prefixes [`PdfOptions::allow`] names, so HTML built from user input
//! can't reach the network (or the machine's own services). Put images
//! and fonts inline with [`data_url`]. Printing waits for the page's load
//! event, so inline images are decoded first.
//!
//! In a `#[glacier::test]`, nothing is printed: [`render`] records the HTML
//! (see `glacier::testing::rendered_pdfs`) and answers with a small
//! placeholder PDF, so tests need no Chrome.

use std::future::Future;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use bytes::Bytes;
use serde_json::{Value as Json, json};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;

use crate::error::{Error, Result};

/// Paper, margins, header and footer, as Puppeteer's `page.pdf` takes
/// them.
#[derive(Debug, Clone, PartialEq)]
pub struct PdfOptions {
    /// Width and height in millimetres.
    pub paper_mm: (f64, f64),
    pub landscape: bool,
    /// Print backgrounds and colours (CSS `background`), as the screen
    /// shows them.
    pub print_background: bool,
    /// Top, right, bottom and left margins in millimetres.
    pub margin_mm: [f64; 4],
    /// HTML for the top and bottom of each page. Chrome fills elements
    /// with the classes `pageNumber`, `totalPages`, `date` and `title`.
    /// Leave room for them with the margins.
    pub header: Option<String>,
    pub footer: Option<String>,
    /// URL prefixes the page may load from, besides `data:` URLs.
    pub allow: Vec<String>,
    /// How long printing may take.
    pub timeout: Duration,
}

impl PdfOptions {
    /// A4 portrait, backgrounds printed, 10 mm margins.
    pub fn a4() -> Self {
        Self {
            paper_mm: (210.0, 297.0),
            landscape: false,
            print_background: true,
            margin_mm: [10.0; 4],
            header: None,
            footer: None,
            allow: Vec::new(),
            timeout: Duration::from_secs(30),
        }
    }

    /// US Letter portrait, otherwise as [`a4`](Self::a4).
    pub fn letter() -> Self {
        Self {
            paper_mm: (215.9, 279.4),
            ..Self::a4()
        }
    }

    pub fn landscape(mut self) -> Self {
        self.landscape = true;
        self
    }

    /// Top, right, bottom and left margins, in millimetres.
    pub fn margins(mut self, top: f64, right: f64, bottom: f64, left: f64) -> Self {
        self.margin_mm = [top, right, bottom, left];
        self
    }

    pub fn header(mut self, html: impl Into<String>) -> Self {
        self.header = Some(html.into());
        self
    }

    pub fn footer(mut self, html: impl Into<String>) -> Self {
        self.footer = Some(html.into());
        self
    }

    /// Lets the page load from URLs starting with `prefix`, such as the
    /// app's own asset host.
    pub fn allow(mut self, prefix: impl Into<String>) -> Self {
        self.allow.push(prefix.into());
        self
    }
}

impl Default for PdfOptions {
    fn default() -> Self {
        Self::a4()
    }
}

type Pending<'a> = Pin<Box<dyn Future<Output = Result<Bytes>> + Send + 'a>>;

/// Something that prints HTML to PDF.
pub trait PdfRenderer: Send + Sync {
    fn render<'a>(&'a self, html: &'a str, options: &'a PdfOptions) -> Pending<'a>;
}

/// Prints `html` with the Chrome on this machine ([`Chrome::find`]), or,
/// in a test, records it and answers with a placeholder.
///
/// # Errors
///
/// If no Chrome is found, it fails to start, or printing fails or takes
/// longer than `options.timeout`.
pub async fn render(html: &str, options: &PdfOptions) -> Result<Bytes> {
    if let Some(rendered) = record_in_test(html, options) {
        return Ok(rendered);
    }
    let chrome = Chrome::find().ok_or_else(|| {
        Error::internal(
            "no Chrome to print PDFs with: install Chrome or Chromium, or set CHROME_PATH",
        )
    })?;
    chrome.render(html, options).await
}

/// Prints a template (`views::orders::Receipt { order }`), as [`render`]
/// prints its HTML. The template is rendered on its own, without the
/// app's layout: give it its own `<html>`, `<style>` and all.
///
/// # Errors
///
/// As [`render`].
pub async fn render_template(
    template: impl crate::view::Template,
    options: &PdfOptions,
) -> Result<Bytes> {
    render(&template.render().to_html(), options).await
}

/// A `data:` URL holding `bytes`, for an image or font in a PDF's HTML,
/// which can't load anything else: `data_url("image/png", &logo)`.
pub fn data_url(content_type: &str, bytes: &[u8]) -> String {
    format!("data:{content_type};base64,{}", STANDARD.encode(bytes))
}

/// Headless Chrome or Chromium, started for each PDF.
#[derive(Debug, Clone)]
pub struct Chrome {
    executable: PathBuf,
}

impl Chrome {
    pub fn new(executable: impl Into<PathBuf>) -> Self {
        Self {
            executable: executable.into(),
        }
    }

    /// `CHROME_PATH`, else Chrome or Chromium where they're usually
    /// installed, else on the `PATH`.
    pub fn find() -> Option<Self> {
        if let Some(path) = std::env::var_os("CHROME_PATH").filter(|p| !p.is_empty()) {
            return Some(Self::new(path));
        }
        const PLACES: &[&str] = &[
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
            "/Applications/Chromium.app/Contents/MacOS/Chromium",
            "/usr/bin/google-chrome",
            "/usr/bin/google-chrome-stable",
            "/usr/bin/chromium",
            "/usr/bin/chromium-browser",
        ];
        if let Some(place) = PLACES.iter().find(|p| Path::new(p).exists()) {
            return Some(Self::new(place));
        }
        let path = std::env::var_os("PATH")?;
        std::env::split_paths(&path)
            .flat_map(|dir| {
                [
                    "google-chrome",
                    "google-chrome-stable",
                    "chromium",
                    "chromium-browser",
                ]
                .map(|name| dir.join(name))
            })
            .find(|candidate| candidate.is_file())
            .map(Self::new)
    }

    async fn print(&self, html: &str, options: &PdfOptions) -> Result<Bytes> {
        let profile =
            std::env::temp_dir().join(format!("glacier-chrome-{}", &crate::random::token()[..16]));
        let mut child = tokio::process::Command::new(&self.executable)
            .args([
                "--headless=new",
                "--disable-gpu",
                "--no-first-run",
                "--no-default-browser-check",
                "--disable-extensions",
                "--disable-background-networking",
                "--disable-sync",
                "--disable-default-apps",
                "--mute-audio",
                "--hide-scrollbars",
                "--remote-debugging-port=0",
                "--remote-debugging-address=127.0.0.1",
            ])
            .arg(format!("--user-data-dir={}", profile.display()))
            .arg("about:blank")
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .map_err(|err| {
                Error::internal(format!(
                    "couldn't start {}: {err}",
                    self.executable.display()
                ))
            })?;
        // What it was doing, for the error when it takes too long.
        let step = Arc::new(Mutex::new("waiting for Chrome to start".to_owned()));
        let result = async {
            let stderr = child
                .stderr
                .take()
                .ok_or_else(|| Error::internal("Chrome's stderr"))?;
            let url = devtools_url(stderr).await?;
            *step.lock().unwrap() = "connecting to Chrome".into();
            let mut session = Session::connect(&url, step.clone()).await?;
            session.print(html, options).await
        };
        let result = tokio::time::timeout(options.timeout, result)
            .await
            .unwrap_or_else(|_| {
                Err(Error::internal(format!(
                    "printing a PDF took over {:?}, {}",
                    options.timeout,
                    step.lock().unwrap()
                )))
            });
        let _ = child.kill().await;
        let _ = tokio::fs::remove_dir_all(&profile).await;
        result
    }
}

impl PdfRenderer for Chrome {
    fn render<'a>(&'a self, html: &'a str, options: &'a PdfOptions) -> Pending<'a> {
        Box::pin(self.print(html, options))
    }
}

/// The browser's DevTools address, from the line Chrome writes to stderr.
async fn devtools_url(stderr: tokio::process::ChildStderr) -> Result<String> {
    let mut lines = BufReader::new(stderr).lines();
    let mut seen = Vec::new();
    while let Some(line) = lines
        .next_line()
        .await
        .map_err(|err| Error::internal(format!("reading Chrome's output: {err}")))?
    {
        if let Some(url) = line.strip_prefix("DevTools listening on ") {
            // Keep draining stderr, so Chrome never blocks writing to it.
            tokio::spawn(async move { while let Ok(Some(_)) = lines.next_line().await {} });
            return Ok(url.trim().to_owned());
        }
        seen.push(line);
    }
    Err(Error::internal(format!(
        "Chrome exited before it was ready: {}",
        seen.join("\n")
    )))
}

/// One page of a browser, driven over the DevTools protocol.
struct Session {
    socket: WebSocket,
    next_id: u64,
    session_id: Option<String>,
    allow: Vec<String>,
    /// The page's load event has fired.
    loaded: bool,
    /// What it's waiting for, for the timeout's error.
    step: Arc<Mutex<String>>,
}

impl Session {
    async fn connect(url: &str, step: Arc<Mutex<String>>) -> Result<Self> {
        Ok(Self {
            step,
            socket: WebSocket::connect(url).await?,
            next_id: 0,
            session_id: None,
            allow: Vec::new(),
            loaded: false,
        })
    }

    async fn print(&mut self, html: &str, options: &PdfOptions) -> Result<Bytes> {
        self.allow = options.allow.clone();
        let target = self
            .call("Target.createTarget", json!({"url": "about:blank"}))
            .await?;
        let target_id = target["targetId"].as_str().unwrap_or_default().to_owned();
        let attached = self
            .call(
                "Target.attachToTarget",
                json!({"targetId": target_id, "flatten": true}),
            )
            .await?;
        self.session_id = attached["sessionId"].as_str().map(str::to_owned);
        self.call("Page.enable", json!({})).await?;
        self.call(
            "Emulation.setScriptExecutionDisabled",
            json!({"value": true}),
        )
        .await?;
        // Every request comes here first: data: URLs and allowed prefixes
        // go on, anything else fails.
        self.call("Fetch.enable", json!({"patterns": [{"urlPattern": "*"}]}))
            .await?;
        let tree = self.call("Page.getFrameTree", json!({})).await?;
        let frame_id = tree["frameTree"]["frame"]["id"]
            .as_str()
            .unwrap_or_default()
            .to_owned();
        self.loaded = false;
        self.call(
            "Page.setDocumentContent",
            json!({"frameId": frame_id, "html": html}),
        )
        .await?;
        // As Puppeteer's waitUntil: images (data: URLs included) decoded
        // before printing. A page whose load never fires prints anyway.
        *self.step.lock().unwrap() = "waiting for the page to load".into();
        let _ = tokio::time::timeout(Duration::from_secs(5), self.until_loaded()).await;
        let inch = |mm: f64| mm / 25.4;
        let (width, height) = options.paper_mm;
        let [top, right, bottom, left] = options.margin_mm;
        let headed = options.header.is_some() || options.footer.is_some();
        let printed = self
            .call(
                "Page.printToPDF",
                json!({
                    "landscape": options.landscape,
                    "printBackground": options.print_background,
                    "paperWidth": inch(width),
                    "paperHeight": inch(height),
                    "marginTop": inch(top),
                    "marginRight": inch(right),
                    "marginBottom": inch(bottom),
                    "marginLeft": inch(left),
                    "displayHeaderFooter": headed,
                    // Chrome prints its own date and URL when these are empty.
                    "headerTemplate": options.header.clone().unwrap_or_else(|| "<span></span>".into()),
                    "footerTemplate": options.footer.clone().unwrap_or_else(|| "<span></span>".into()),
                    "preferCSSPageSize": false,
                }),
            )
            .await?;
        let data = printed["data"].as_str().unwrap_or_default();
        let bytes = STANDARD
            .decode(data)
            .map_err(|err| Error::internal(format!("Chrome's PDF wasn't base64: {err}")))?;
        let _ = self.send("Browser.close", json!({}), false).await;
        Ok(bytes.into())
    }

    /// Reads events until the page's load event.
    async fn until_loaded(&mut self) -> Result<()> {
        while !self.loaded {
            let message = self.next_message().await?;
            self.handle_event(&message).await?;
        }
        Ok(())
    }

    async fn next_message(&mut self) -> Result<Json> {
        serde_json::from_str(&self.socket.read().await?)
            .map_err(|err| Error::internal(format!("Chrome sent bad JSON: {err}")))
    }

    /// An event: a request to decide on, or the page having loaded.
    async fn handle_event(&mut self, message: &Json) -> Result<()> {
        match message["method"].as_str() {
            Some("Fetch.requestPaused") => self.decide(&message["params"]).await,
            Some("Page.loadEventFired") => {
                self.loaded = true;
                Ok(())
            }
            _ => Ok(()),
        }
    }

    /// Sends a command and waits for its answer, handling the page's
    /// requests in the meantime.
    async fn call(&mut self, method: &str, params: Json) -> Result<Json> {
        let id = self.send(method, params, true).await?;
        *self.step.lock().unwrap() = format!("waiting for Chrome's answer to {method}");
        loop {
            let message = self.next_message().await?;
            if message["id"].as_u64() == Some(id) {
                if let Some(error) = message.get("error") {
                    return Err(Error::internal(format!("Chrome: {method}: {error}")));
                }
                return Ok(message["result"].clone());
            }
            self.handle_event(&message).await?;
        }
    }

    async fn send(&mut self, method: &str, params: Json, in_page: bool) -> Result<u64> {
        self.next_id += 1;
        let mut message = json!({"id": self.next_id, "method": method, "params": params});
        if in_page && let Some(session) = &self.session_id {
            message["sessionId"] = session.clone().into();
        }
        self.socket.send(&message.to_string()).await?;
        Ok(self.next_id)
    }

    /// Lets a request through or fails it.
    async fn decide(&mut self, request: &Json) -> Result<()> {
        let id = request["requestId"].clone();
        let url = request["request"]["url"].as_str().unwrap_or_default();
        let allowed = url.starts_with("data:") || self.allow.iter().any(|p| url.starts_with(p));
        if allowed {
            self.send("Fetch.continueRequest", json!({"requestId": id}), true)
                .await?;
        } else {
            tracing::debug!(target: "glacier", "PDF: refused a request for {url}");
            self.send(
                "Fetch.failRequest",
                json!({"requestId": id, "errorReason": "BlockedByClient"}),
                true,
            )
            .await?;
        }
        Ok(())
    }
}

/// Just enough of a WebSocket client (RFC 6455) for Chrome's DevTools on
/// localhost: text messages, pings, and close.
struct WebSocket {
    stream: BufReader<TcpStream>,
}

impl WebSocket {
    async fn connect(url: &str) -> Result<Self> {
        let rest = url
            .strip_prefix("ws://")
            .ok_or_else(|| Error::internal(format!("not a ws:// address: {url}")))?;
        let (host, path) = rest.split_once('/').unwrap_or((rest, ""));
        let stream = TcpStream::connect(host)
            .await
            .map_err(|err| Error::internal(format!("connecting to Chrome: {err}")))?;
        let mut stream = BufReader::new(stream);
        let key = STANDARD.encode(random::<16>());
        let request = format!(
            "GET /{path} HTTP/1.1\r\nHost: {host}\r\nUpgrade: websocket\r\n\
             Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n\
             Sec-WebSocket-Version: 13\r\n\r\n"
        );
        stream
            .get_mut()
            .write_all(request.as_bytes())
            .await
            .map_err(io)?;
        let mut status = String::new();
        stream.read_line(&mut status).await.map_err(io)?;
        if !status.contains(" 101 ") {
            return Err(Error::internal(format!(
                "Chrome refused the DevTools connection: {}",
                status.trim()
            )));
        }
        loop {
            let mut line = String::new();
            if stream.read_line(&mut line).await.map_err(io)? == 0 || line == "\r\n" {
                break;
            }
        }
        Ok(Self { stream })
    }

    async fn send(&mut self, text: &str) -> Result<()> {
        self.frame(0x1, text.as_bytes()).await
    }

    /// A client's frame: final, masked.
    async fn frame(&mut self, opcode: u8, payload: &[u8]) -> Result<()> {
        let mut frame = vec![0x80 | opcode];
        let len = payload.len();
        if len < 126 {
            frame.push(0x80 | len as u8);
        } else if let Ok(len) = u16::try_from(len) {
            frame.push(0x80 | 126);
            frame.extend_from_slice(&len.to_be_bytes());
        } else {
            frame.push(0x80 | 127);
            frame.extend_from_slice(&(len as u64).to_be_bytes());
        }
        let mask = random::<4>();
        frame.extend_from_slice(&mask);
        frame.extend(payload.iter().enumerate().map(|(i, b)| b ^ mask[i % 4]));
        self.stream.get_mut().write_all(&frame).await.map_err(io)
    }

    /// The next text message, answering pings on the way.
    async fn read(&mut self) -> Result<String> {
        let mut message = Vec::new();
        loop {
            let mut head = [0u8; 2];
            self.stream.read_exact(&mut head).await.map_err(io)?;
            let fin = head[0] & 0x80 != 0;
            let opcode = head[0] & 0x0f;
            let masked = head[1] & 0x80 != 0;
            let len = match head[1] & 0x7f {
                126 => {
                    let mut n = [0u8; 2];
                    self.stream.read_exact(&mut n).await.map_err(io)?;
                    u64::from(u16::from_be_bytes(n))
                }
                127 => {
                    let mut n = [0u8; 8];
                    self.stream.read_exact(&mut n).await.map_err(io)?;
                    u64::from_be_bytes(n)
                }
                n => u64::from(n),
            };
            let mut mask = [0u8; 4];
            if masked {
                self.stream.read_exact(&mut mask).await.map_err(io)?;
            }
            let len = usize::try_from(len)
                .map_err(|_| Error::internal("a DevTools message too large to read"))?;
            let mut payload = vec![0u8; len];
            self.stream.read_exact(&mut payload).await.map_err(io)?;
            if masked {
                for (i, b) in payload.iter_mut().enumerate() {
                    *b ^= mask[i % 4];
                }
            }
            match opcode {
                0x0 | 0x1 => {
                    message.extend_from_slice(&payload);
                    if fin {
                        return String::from_utf8(message).map_err(|_| {
                            Error::internal("Chrome sent a message that wasn't UTF-8")
                        });
                    }
                }
                0x8 => return Err(Error::internal("Chrome closed the DevTools connection")),
                0x9 => self.frame(0xA, &payload).await?,
                _ => {}
            }
        }
    }
}

fn random<const N: usize>() -> [u8; N] {
    let mut bytes = [0u8; N];
    getrandom::fill(&mut bytes).expect("the OS random number generator failed");
    bytes
}

fn io(err: std::io::Error) -> Error {
    Error::internal(format!("talking to Chrome: {err}"))
}

/// A tiny valid PDF, what [`render`] answers with in a test.
pub const PLACEHOLDER: &[u8] = b"%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n\
2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n\
3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 595 842]>>endobj\n\
trailer<</Root 1 0 R>>\n%%EOF\n";

/// The HTML (and options) a test printed.
#[derive(Debug, Clone)]
pub struct Rendered {
    pub html: String,
    pub options: PdfOptions,
}

tokio::task_local! {
    static RENDERED: Arc<Mutex<Vec<Rendered>>>;
}

/// In a test, records the render and answers with [`PLACEHOLDER`].
fn record_in_test(html: &str, options: &PdfOptions) -> Option<Bytes> {
    RENDERED
        .try_with(|rendered| {
            rendered
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .push(Rendered {
                    html: html.to_owned(),
                    options: options.clone(),
                });
            Bytes::from_static(PLACEHOLDER)
        })
        .ok()
}

/// Runs `fut` with PDFs recorded, not printed. `#[glacier::test]` does
/// this.
#[doc(hidden)]
pub async fn with_test_recorder<F: Future>(fut: F) -> F::Output {
    RENDERED.scope(Arc::default(), fut).await
}

/// The PDFs this test rendered, oldest first.
pub(crate) fn rendered() -> Vec<Rendered> {
    RENDERED
        .try_with(|rendered| rendered.lock().unwrap_or_else(|e| e.into_inner()).clone())
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn a_test_records_what_it_prints() {
        with_test_recorder(async {
            let pdf = render("<h1>Receipt</h1>", &PdfOptions::a4().landscape())
                .await
                .unwrap();
            assert!(pdf.starts_with(b"%PDF-"));
            let rendered = rendered();
            assert_eq!(rendered.len(), 1);
            assert_eq!(rendered[0].html, "<h1>Receipt</h1>");
            assert!(rendered[0].options.landscape);
        })
        .await;
    }

    #[test]
    fn data_urls_inline_bytes() {
        assert_eq!(
            data_url("image/gif", b"GIF8"),
            "data:image/gif;base64,R0lGOA=="
        );
    }

    #[test]
    fn options_read_like_puppeteer_s() {
        let options = PdfOptions::letter()
            .margins(20.0, 10.0, 20.0, 10.0)
            .footer("<span class=\"pageNumber\"></span>")
            .allow("https://assets.example.com/");
        assert_eq!(options.paper_mm, (215.9, 279.4));
        assert_eq!(options.margin_mm, [20.0, 10.0, 20.0, 10.0]);
        assert!(options.print_background);
        assert_eq!(options.allow, ["https://assets.example.com/"]);
    }
}