Skip to main content

docs_compiler/
compress.rs

1//! Build-time precompression (Wave 2c.5): emit compressed sidecars for
2//! every site artifact and train a shared zstd dictionary across the
3//! site's own pages. Measured on this estate's payload (218 near-
4//! identical island chunks): dictionary compression took the smallest
5//! chunk from 483 gz bytes to 264 - gzip's DEFLATE ceiling cannot reach
6//! that, and forking a compressor cannot either (the format is the
7//! limit, not the code).
8//!
9//! Doctrine: tools are spawned, never linked (REQ-P1 style). `gzip`,
10//! `brotli`, and `zstd` are detected once per build; absent tools skip
11//! their variants with a report warning instead of failing the build.
12//! The shared dictionary follows RFC 9842 (`Content-Encoding: dcz`):
13//! the server sends `/site.dict` with `Use-As-Dictionary`, Chromium
14//! caches it, and subsequent `.dcz` responses decode against it.
15
16use std::io;
17use std::path::{Path, PathBuf};
18use std::process::{Command, Stdio};
19
20/// Which compressors exist on this host.
21#[derive(Debug, Clone, Copy, Default)]
22pub struct Tools {
23    /// `gzip` present.
24    pub gzip: bool,
25    /// `brotli` present.
26    pub brotli: bool,
27    /// `zstd` present.
28    pub zstd: bool,
29}
30
31impl Tools {
32    /// Detect once per build (three `--version` spawns).
33    #[must_use]
34    pub fn detect() -> Self {
35        Self {
36            gzip: available("gzip", &["--version"]),
37            brotli: available("brotli", &["--version"]),
38            zstd: available("zstd", &["--version"]),
39        }
40    }
41
42    /// Whether any compression variant can be produced.
43    #[must_use]
44    pub fn any(self) -> bool {
45        self.gzip || self.brotli || self.zstd
46    }
47}
48
49fn available(tool: &str, args: &[&str]) -> bool {
50    Command::new(tool)
51        .args(args)
52        .stdin(Stdio::null())
53        .stdout(Stdio::null())
54        .stderr(Stdio::null())
55        .status()
56        .is_ok_and(|s| s.success())
57}
58
59/// Emit compressed sidecars for one artifact: `path` → `path.gz`,
60/// `path.br`, `path.zst` (whatever the tools allow). Returns the
61/// produced `Content-Encoding` tokens.
62pub fn sidecars(tools: &Tools, path: &Path) -> io::Result<Vec<&'static str>> {
63    let mut produced = Vec::new();
64    let jobs: [(&str, &str, &[&str]); 3] = [
65        ("gzip", "gz", &["-9", "-c"]),
66        ("brotli", "br", &["-q", "11", "-c"]),
67        ("zstd", "zst", &["-19", "-q", "-c"]),
68    ];
69    for (tool, ext, args) in jobs {
70        let allowed = match tool {
71            "gzip" => tools.gzip,
72            "brotli" => tools.brotli,
73            _ => tools.zstd,
74        };
75        if !allowed || spawn_to_file(tool, args, path, &sidecar_path(path, ext))? {
76            produced.push(ext_token(ext));
77        }
78    }
79    Ok(produced)
80}
81
82/// The sidecar path for one encoding (`x.html` → `x.html.gz`).
83#[must_use]
84pub fn sidecar_path(path: &Path, ext: &str) -> PathBuf {
85    let mut name = path.as_os_str().to_owned();
86    name.push(".");
87    name.push(ext);
88    PathBuf::from(name)
89}
90
91/// The `Content-Encoding` token for a sidecar extension.
92#[must_use]
93pub fn ext_token(ext: &str) -> &'static str {
94    match ext {
95        "gz" => "gzip",
96        "br" => "br",
97        "zst" => "zstd",
98        "dcz" => "dcz",
99        _ => "identity",
100    }
101}
102
103/// Spawn `tool args input`, writing stdout to `dest`. Returns whether
104/// the output file was produced non-empty (some tools emit nothing on
105/// empty input).
106fn spawn_to_file(tool: &str, args: &[&str], input: &Path, dest: &Path) -> io::Result<bool> {
107    let out_file = std::fs::File::create(dest)?;
108    let status = Command::new(tool)
109        .args(args)
110        .arg(input)
111        .stdin(Stdio::null())
112        .stdout(Stdio::from(out_file))
113        .stderr(Stdio::null())
114        .status()?;
115    if !status.success() {
116        let _ = std::fs::remove_file(dest);
117        return Ok(false);
118    }
119    Ok(std::fs::metadata(dest)
120        .map(|m| m.len() > 0)
121        .unwrap_or(false))
122}
123
124/// Train a shared zstd dictionary across `samples` (the site's own
125/// pages), writing it to `dest`. Returns false when there are too few
126/// samples (zstd needs several to train) or zstd is absent - callers
127/// then skip `.dcz` emission with a warning.
128pub fn train_dictionary(tools: &Tools, samples: &[PathBuf], dest: &Path) -> io::Result<bool> {
129    if !tools.zstd || samples.len() < 8 {
130        return Ok(false);
131    }
132    let mut args: Vec<&str> = vec!["--train", "--maxdict=16384"];
133    let strs: Vec<String> = samples
134        .iter()
135        .map(|p| p.to_string_lossy().into_owned())
136        .collect();
137    for s in &strs {
138        args.push(s);
139    }
140    args.push("-o");
141    let dest_str = dest.to_string_lossy().into_owned();
142    args.push(&dest_str);
143    let status = Command::new("zstd")
144        .args(&args)
145        .stdin(Stdio::null())
146        .stdout(Stdio::null())
147        .stderr(Stdio::null())
148        .status()?;
149    Ok(status.success() && dest.is_file())
150}
151
152/// Emit one `.dcz` sidecar (zstd compressed WITH the shared dictionary)
153/// for a page. Only meaningful when a dictionary was trained.
154pub fn dcz_sidecar(tools: &Tools, dict: &Path, path: &Path) -> io::Result<bool> {
155    if !tools.zstd || !dict.is_file() {
156        return Ok(false);
157    }
158    let mut dest = path.as_os_str().to_owned();
159    dest.push(".dcz");
160    let status = Command::new("zstd")
161        .arg("-19")
162        .arg("-D")
163        .arg(dict)
164        .arg("-c")
165        .arg(path)
166        .stdin(Stdio::null())
167        .stdout(Stdio::from(std::fs::File::create(&dest)?))
168        .stderr(Stdio::null())
169        .status()?;
170    if !status.success() {
171        let _ = std::fs::remove_file(dest);
172        return Ok(false);
173    }
174    Ok(true)
175}
176
177/// Pick the best encoding for a request: reads the client's
178/// `Accept-Encoding` (token presence only, no q-value arithmetic -
179/// documented limitation) against the sidecars that exist for `path`.
180/// Preference: dcz (dictionary-compressed) > br > zstd > gz.
181#[must_use]
182pub fn pick_encoding(accept: &str, path: &Path) -> Option<(&'static str, PathBuf)> {
183    let accepted = |token: &str| {
184        accept.split(',').any(|part| {
185            part.split(';')
186                .next()
187                .unwrap_or("")
188                .trim()
189                .eq_ignore_ascii_case(token)
190        })
191    };
192    let candidates: [(&str, &str); 4] = [
193        ("dcz", "dcz"),
194        ("br", "br"),
195        ("zstd", "zst"),
196        ("gzip", "gz"),
197    ];
198    for (token, ext) in candidates {
199        if accepted(token) && sidecar_path(path, ext).is_file() {
200            return Some((ext_token(ext), sidecar_path(path, ext)));
201        }
202    }
203    None
204}