use std::collections::BTreeSet;
use std::path::Path;
use anyhow::{Context, Result};
use super::stored_gzip::{gzip_best, is_stored_gzip_candidate};
pub const MAX_STAGE_ENTRY_BYTES: u64 = 256 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntryFile {
pub path: String,
pub raw_bytes: u64,
pub wire_bytes: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntryReport {
pub files: Vec<EntryFile>,
pub wire_bytes: u64,
pub deferred_wire_bytes: u64,
}
fn string_list(ui: &serde_json::Value, key: &str) -> Vec<String> {
ui.get(key)
.and_then(|value| value.as_array())
.map(|items| {
items
.iter()
.filter_map(|item| item.as_str().map(str::to_string))
.collect()
})
.unwrap_or_default()
}
fn wire_size(app_dir: &Path, relative: &str) -> Result<(u64, u64)> {
let full = app_dir.join(relative);
let bytes = std::fs::read(&full)
.with_context(|| format!("read ui.integrity file {relative} ({})", full.display()))?;
let raw = bytes.len() as u64;
let wire = if is_stored_gzip_candidate(Path::new(relative), raw) {
gzip_best(&bytes)
.with_context(|| format!("gzip ui.integrity file {relative}"))?
.len() as u64
} else {
raw
};
Ok((raw, wire))
}
pub fn entry_report(app_dir: &Path, ui: &serde_json::Value) -> Result<EntryReport> {
let deferred: BTreeSet<String> = string_list(ui, "deferred").into_iter().collect();
let icon = ui.get("icon").and_then(|value| value.as_str());
let integrity = ui
.get("integrity")
.and_then(|value| value.as_object())
.cloned()
.unwrap_or_default();
let mut files = Vec::new();
let mut wire_bytes = 0_u64;
let mut deferred_wire_bytes = 0_u64;
for path in integrity.keys() {
if Some(path.as_str()) == icon {
continue;
}
let (raw_bytes, wire) = wire_size(app_dir, path)?;
if deferred.contains(path) {
deferred_wire_bytes += wire;
} else {
wire_bytes += wire;
files.push(EntryFile {
path: path.clone(),
raw_bytes,
wire_bytes: wire,
});
}
}
files.sort_by(|a, b| b.wire_bytes.cmp(&a.wire_bytes).then(a.path.cmp(&b.path)));
Ok(EntryReport {
files,
wire_bytes,
deferred_wire_bytes,
})
}
fn kib(bytes: u64) -> String {
format!("{:.1} KiB", bytes as f64 / 1024.0)
}
pub fn format_entry_report(report: &EntryReport, ceiling: Option<u64>) -> String {
let mut out = String::from("stage entry set (fetched before mount):\n");
for file in &report.files {
out.push_str(&format!(" {:>10} {}\n", kib(file.wire_bytes), file.path));
}
out.push_str(&format!(
" total {} before mount, {} deferred\n",
kib(report.wire_bytes),
kib(report.deferred_wire_bytes)
));
if report.deferred_wire_bytes == 0 {
out.push_str(
" the whole bundle is fetched before mount; list files in `ui.deferred` to defer them\n",
);
}
if let Some(ceiling) = ceiling {
out.push_str(&format!(" ceiling {}\n", kib(ceiling)));
}
out
}
pub fn print_entry_report(report: &EntryReport, ceiling: Option<u64>) {
print!("{}", format_entry_report(report, ceiling));
}
pub fn entry_budget_warning(report: &EntryReport) -> Option<String> {
if report.wire_bytes <= MAX_STAGE_ENTRY_BYTES {
return None;
}
let largest = report
.files
.iter()
.take(3)
.map(|file| format!("{} ({})", file.path, kib(file.wire_bytes)))
.collect::<Vec<_>>()
.join(", ");
Some(format!(
"the stage entry set is {} before mount, over the {} ceiling; largest entry files: {}; \
list files the stage can mount without in `ui.deferred` to move them out of the before-mount set",
kib(report.wire_bytes),
kib(MAX_STAGE_ENTRY_BYTES),
largest
))
}
pub fn report_or_warn(app_dir: &Path, ui: &serde_json::Value) {
match entry_report(app_dir, ui) {
Ok(report) => {
print_entry_report(&report, Some(MAX_STAGE_ENTRY_BYTES));
if let Some(warning) = entry_budget_warning(&report) {
eprintln!("warning: {warning}");
}
}
Err(error) => eprintln!("warning: could not measure the stage entry set: {error:#}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn write(dir: &Path, rel: &str, bytes: &[u8]) {
let path = dir.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, bytes).unwrap();
}
fn js(len: usize) -> Vec<u8> {
"const a = 1;\n".repeat(len / 13).into_bytes()
}
fn ui(integrity: &[&str], deferred: &[&str], icon: Option<&str>) -> serde_json::Value {
let map: serde_json::Map<String, serde_json::Value> = integrity
.iter()
.map(|p| (p.to_string(), json!("hash")))
.collect();
let mut ui = json!({ "integrity": map, "deferred": deferred });
if let Some(icon) = icon {
ui["icon"] = json!(icon);
}
ui
}
#[test]
fn entry_set_is_integrity_minus_deferred_minus_icon() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "ui/main.js", &js(4000));
write(dir.path(), "ui/chunk.js", &js(4000));
write(dir.path(), "ui/icon.svg", &js(4000));
let ui = ui(
&["ui/main.js", "ui/chunk.js", "ui/icon.svg"],
&["ui/chunk.js"],
Some("ui/icon.svg"),
);
let report = entry_report(dir.path(), &ui).unwrap();
let paths: Vec<_> = report.files.iter().map(|f| f.path.as_str()).collect();
assert_eq!(paths, ["ui/main.js"]);
}
#[test]
fn compressible_files_count_their_gzip_size_and_images_their_raw_size() {
let dir = tempfile::tempdir().unwrap();
let source = js(8000);
write(dir.path(), "ui/main.js", &source);
write(dir.path(), "ui/photo.png", &source);
let ui = ui(&["ui/main.js", "ui/photo.png"], &[], None);
let report = entry_report(dir.path(), &ui).unwrap();
let by = |p: &str| report.files.iter().find(|f| f.path == p).unwrap().clone();
let main = by("ui/main.js");
assert_eq!(main.raw_bytes, source.len() as u64);
assert_eq!(main.wire_bytes, gzip_best(&source).unwrap().len() as u64);
assert!(main.wire_bytes < main.raw_bytes);
assert_eq!(by("ui/photo.png").wire_bytes, source.len() as u64);
assert_eq!(report.wire_bytes, main.wire_bytes + source.len() as u64);
}
#[test]
fn files_are_listed_largest_first() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "ui/a.png", &[1; 10]);
write(dir.path(), "ui/b.png", &[1; 300]);
write(dir.path(), "ui/c.png", &[1; 50]);
let ui = ui(&["ui/a.png", "ui/b.png", "ui/c.png"], &[], None);
let report = entry_report(dir.path(), &ui).unwrap();
let paths: Vec<_> = report.files.iter().map(|f| f.path.as_str()).collect();
assert_eq!(paths, ["ui/b.png", "ui/c.png", "ui/a.png"]);
}
#[test]
fn a_stage_with_no_deferred_files_counts_everything_but_the_icon() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "ui/main.js", &js(4000));
write(dir.path(), "ui/main.css", &js(4000));
write(dir.path(), "ui/icon.png", &[1; 500]);
let ui = ui(
&["ui/main.js", "ui/main.css", "ui/icon.png"],
&[],
Some("ui/icon.png"),
);
let report = entry_report(dir.path(), &ui).unwrap();
assert_eq!(report.files.len(), 2);
assert_eq!(report.deferred_wire_bytes, 0);
let text = format_entry_report(&report, None);
assert!(text.contains("whole bundle is fetched before mount"));
assert!(text.contains("ui.deferred"));
}
fn report_of(sizes: &[(&str, u64)]) -> EntryReport {
let files: Vec<EntryFile> = sizes
.iter()
.map(|(path, bytes)| EntryFile {
path: path.to_string(),
raw_bytes: *bytes,
wire_bytes: *bytes,
})
.collect();
EntryReport {
wire_bytes: files.iter().map(|f| f.wire_bytes).sum(),
files,
deferred_wire_bytes: 0,
}
}
#[test]
fn at_or_under_the_ceiling_there_is_no_warning() {
let at = report_of(&[("ui/main.js", MAX_STAGE_ENTRY_BYTES)]);
assert_eq!(entry_budget_warning(&at), None);
let under = report_of(&[("ui/main.js", 10)]);
assert_eq!(entry_budget_warning(&under), None);
}
#[test]
fn over_the_ceiling_the_warning_states_both_numbers() {
let over = report_of(&[("ui/main.js", MAX_STAGE_ENTRY_BYTES + 1024)]);
let text = entry_budget_warning(&over).unwrap();
assert!(text.contains("257.0 KiB"), "{text}");
assert!(text.contains("256.0 KiB"), "{text}");
}
#[test]
fn the_warning_lists_the_three_largest_entry_files() {
let over = report_of(&[
("ui/a.js", 200 * 1024),
("ui/b.js", 90 * 1024),
("ui/c.js", 30 * 1024),
("ui/d.js", 1024),
]);
let text = entry_budget_warning(&over).unwrap();
for kept in [
"ui/a.js (200.0 KiB)",
"ui/b.js (90.0 KiB)",
"ui/c.js (30.0 KiB)",
] {
assert!(text.contains(kept), "{text}");
}
assert!(!text.contains("ui/d.js"), "{text}");
}
#[test]
fn the_warning_names_ui_deferred_as_the_fix() {
let over = report_of(&[("ui/main.js", MAX_STAGE_ENTRY_BYTES + 1)]);
assert!(entry_budget_warning(&over).unwrap().contains("ui.deferred"));
}
#[test]
fn a_missing_integrity_file_is_an_error_naming_the_path() {
let dir = tempfile::tempdir().unwrap();
let ui = ui(&["ui/gone.js"], &[], None);
let error = entry_report(dir.path(), &ui).unwrap_err();
assert!(format!("{error:#}").contains("ui/gone.js"), "{error:#}");
}
#[test]
fn deferred_bytes_are_totalled_separately() {
let dir = tempfile::tempdir().unwrap();
write(dir.path(), "ui/main.png", &[1; 100]);
write(dir.path(), "ui/late.png", &[1; 700]);
let ui = ui(&["ui/main.png", "ui/late.png"], &["ui/late.png"], None);
let report = entry_report(dir.path(), &ui).unwrap();
assert_eq!(report.wire_bytes, 100);
assert_eq!(report.deferred_wire_bytes, 700);
let text = format_entry_report(&report, None);
assert!(
text.contains("total 0.1 KiB before mount, 0.7 KiB deferred"),
"{text}"
);
assert!(!text.contains("whole bundle"));
}
}