node-app-build 7.7.65

Mini app developer CLI: scaffold, validate, package node-app-* Debian packages
//! Stored gzip siblings for staged stage-UI files (#5111).
//!
//! `node-app package` writes `<file>.gz` beside each compressible staged UI
//! file so the node can stream the stored copy instead of compressing on every
//! request. Siblings are never part of `ui.integrity`.

use std::io::Write;
use std::path::Path;

use flate2::write::GzEncoder;
use flate2::Compression;

/// Files smaller than this are not worth a sibling (the node's
/// `MIN_COMPRESSED_BYTES`).
const MIN_STORED_GZIP_BYTES: u64 = 1024;

/// Extensions that compress well enough to store a sibling for.
const CANDIDATE_EXTENSIONS: &[&str] = &["js", "mjs", "css", "html", "svg", "json", "wasm", "map"];

/// Totals for one run of [`write_stored_gzip_siblings`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct StoredGzipReport {
    pub written: usize,
    pub raw_bytes: u64,
    pub stored_bytes: u64,
}

/// Gzip `bytes` at the best compression level.
pub fn gzip_best(bytes: &[u8]) -> std::io::Result<Vec<u8>> {
    let mut encoder = GzEncoder::new(Vec::new(), Compression::best());
    encoder.write_all(bytes)?;
    encoder.finish()
}

/// True when a file of `len` bytes at `path` should get a stored sibling.
pub fn is_stored_gzip_candidate(path: &Path, len: u64) -> bool {
    if len < MIN_STORED_GZIP_BYTES {
        return false;
    }
    path.extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| {
            CANDIDATE_EXTENSIONS
                .iter()
                .any(|candidate| ext.eq_ignore_ascii_case(candidate))
        })
        .unwrap_or(false)
}

/// True when `path` is a `<file>.gz` whose `<file>` is a regular file beside it.
/// A `.gz` with no base file is a real stage file, not a sibling.
pub fn is_stored_gzip_sibling(path: &Path) -> bool {
    let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
        return false;
    };
    let Some(base_name) = name.strip_suffix(".gz") else {
        return false;
    };
    if base_name.is_empty() {
        return false;
    }
    std::fs::symlink_metadata(path.with_file_name(base_name))
        .map(|meta| meta.file_type().is_file())
        .unwrap_or(false)
}

/// Walk `ui_root` (a directory, or a single file) and write a `<file>.gz`
/// sibling for each candidate that the sibling makes smaller. Symlinks are
/// never followed and existing siblings are never compressed again.
pub fn write_stored_gzip_siblings(ui_root: &Path) -> std::io::Result<StoredGzipReport> {
    let mut report = StoredGzipReport::default();
    visit(ui_root, &mut report)?;
    Ok(report)
}

fn visit(path: &Path, report: &mut StoredGzipReport) -> std::io::Result<()> {
    let meta = std::fs::symlink_metadata(path)?;
    let file_type = meta.file_type();
    if file_type.is_symlink() {
        return Ok(());
    }
    if file_type.is_dir() {
        // Collect first: writing siblings while iterating would revisit them.
        let mut children = Vec::new();
        for entry in std::fs::read_dir(path)? {
            children.push(entry?.path());
        }
        children.sort();
        for child in children {
            visit(&child, report)?;
        }
        return Ok(());
    }
    if !file_type.is_file() || is_stored_gzip_sibling(path) {
        return Ok(());
    }
    if !is_stored_gzip_candidate(path, meta.len()) {
        return Ok(());
    }
    let raw = std::fs::read(path)?;
    let gz = gzip_best(&raw)?;
    if (gz.len() as u64) >= meta.len() {
        return Ok(());
    }
    let mut sibling = path.as_os_str().to_owned();
    sibling.push(".gz");
    std::fs::write(&sibling, &gz)?;
    report.written += 1;
    report.raw_bytes += meta.len();
    report.stored_bytes += gz.len() as u64;
    Ok(())
}

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

    fn text(len: usize) -> Vec<u8> {
        "export const value = 'stage file';\n"
            .bytes()
            .cycle()
            .take(len)
            .collect()
    }

    fn pseudo_random(len: usize) -> Vec<u8> {
        let mut state: u64 = 0x9E37_79B9_7F4A_7C15;
        (0..len)
            .map(|_| {
                state ^= state << 13;
                state ^= state >> 7;
                state ^= state << 17;
                (state >> 24) as u8
            })
            .collect()
    }

    #[test]
    fn a_large_js_file_gets_a_smaller_sibling_that_decodes_to_it() {
        let dir = tempfile::tempdir().unwrap();
        let raw = text(4096);
        std::fs::write(dir.path().join("app.js"), &raw).unwrap();

        let report = write_stored_gzip_siblings(dir.path()).unwrap();

        let gz = std::fs::read(dir.path().join("app.js.gz")).unwrap();
        assert!(gz.len() < raw.len());
        let mut decoded = Vec::new();
        flate2::read::GzDecoder::new(gz.as_slice())
            .read_to_end(&mut decoded)
            .unwrap();
        assert_eq!(decoded, raw);
        assert_eq!(report.written, 1);
        assert_eq!(report.raw_bytes, 4096);
        assert_eq!(report.stored_bytes, gz.len() as u64);
    }

    #[test]
    fn a_file_under_1024_bytes_gets_no_sibling() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("small.js"), text(1023)).unwrap();

        let report = write_stored_gzip_siblings(dir.path()).unwrap();

        assert!(!dir.path().join("small.js.gz").exists());
        assert_eq!(report.written, 0);
    }

    #[test]
    fn an_incompressible_file_gets_no_sibling() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("x.js"), pseudo_random(4096)).unwrap();

        write_stored_gzip_siblings(dir.path()).unwrap();

        assert!(!dir.path().join("x.js.gz").exists());
    }

    #[test]
    fn a_png_gets_no_sibling() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("logo.png"), text(4096)).unwrap();

        write_stored_gzip_siblings(dir.path()).unwrap();

        assert!(!dir.path().join("logo.png.gz").exists());
    }

    #[test]
    fn a_gz_file_with_no_base_file_is_not_a_sibling() {
        let dir = tempfile::tempdir().unwrap();
        let alone = dir.path().join("data.json.gz");
        std::fs::write(&alone, b"gz").unwrap();
        assert!(!is_stored_gzip_sibling(&alone));

        std::fs::write(dir.path().join("data.json"), b"{}").unwrap();
        assert!(is_stored_gzip_sibling(&alone));
    }

    #[test]
    fn running_twice_does_not_compress_the_siblings() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("app.js"), text(4096)).unwrap();

        write_stored_gzip_siblings(dir.path()).unwrap();
        let first = std::fs::read(dir.path().join("app.js.gz")).unwrap();
        write_stored_gzip_siblings(dir.path()).unwrap();

        assert!(!dir.path().join("app.js.gz.gz").exists());
        assert_eq!(first, std::fs::read(dir.path().join("app.js.gz")).unwrap());
    }
}