Skip to main content

latexml_post/
pack.rs

1//! Output bundling — port of `LaTeXML::Post::Pack`.
2//!
3//! Separates final-bundle concerns from the post-processing pipeline.
4//! Both `latexml_oxide` and `cortex_worker` previously inlined their own
5//! `pack_output_zip` / `pack_output_zip_with_resources` + `add_dir_to_zip`
6//! copies; this module is the single source of truth so the two binaries
7//! produce byte-identical bundle layouts.
8//!
9//! Bundle layout (zip):
10//! ```text
11//! <html_filename>            — post-processed HTML
12//! <resource_dir>/...         — every non-`.html` file under the staging
13//!                               dir (Graphics-converted PNG/SVG, CSS, …),
14//!                               preserving subdirectories.
15//! <log_filename>             — log text, if `log_filename` is set and
16//!                               `log` is non-empty.
17//! status                     — single-line status string.
18//! telemetry.json             — single-line JSON per-job telemetry, only
19//!                               written when `telemetry_json` is set
20//!                               (cortex_worker canvas runs).
21//! ```
22
23use std::{
24  fs::File,
25  io::{self, BufWriter, Write},
26  path::Path,
27};
28
29use zip::{CompressionMethod, ZipWriter, write::SimpleFileOptions};
30
31/// Write-buffer size for the zip output. 64 KiB matches the typical
32/// compressed-block size from miniz_oxide/flate2 on HTML+image
33/// content; smaller buffers (8 KiB) cause one syscall per block,
34/// larger (1 MiB) waste RSS without improving throughput. Measured on
35/// 1910.01256 (3 PNG + 2 SVG + 2 CSS + HTML = 1.2 MB zip): unbuffered
36/// → ~70 write() syscalls; 64 KiB buffer → ~12.
37const ZIP_WRITE_BUF: usize = 64 * 1024;
38
39/// Options for [`pack_archive`].
40pub struct PackOptions<'a> {
41  /// Destination zip path.
42  pub zip_path:          &'a str,
43  /// Name to use for the HTML entry inside the zip (e.g. `paper.html`).
44  /// Conventionally `<stem>.html` where `stem` is the source TeX name.
45  pub html_filename:     &'a str,
46  /// Post-processed HTML content.
47  pub html:              &'a str,
48  /// Name for the log entry; pass `None` to skip writing a log entry.
49  pub log_filename:      Option<&'a str>,
50  /// Log content. Skipped if empty even when `log_filename` is set.
51  pub log:               &'a str,
52  /// Single-line status string. Always written as `status`.
53  pub status:            &'a str,
54  /// Resource staging directory (typically a `TempDir`). Every
55  /// non-`.html` file under it is bundled, preserving subdirectories.
56  /// Pass `None` to skip resource bundling.
57  pub resource_dir:      Option<&'a Path>,
58  /// Optional per-job telemetry JSON line. When `Some`, written as
59  /// `telemetry.json` inside the zip. Used by `cortex_worker` canvas
60  /// runs; `benchmark_canvas.sh` extracts this member and appends to
61  /// `<output_dir>/telemetry.jsonl`. See `docs/performance/TELEMETRY.md`.
62  pub telemetry_json:    Option<&'a str>,
63  /// `SOURCE_DATE_EPOCH` (Unix seconds, UTC). When `Some`, every zip
64  /// member's last-modified time is pinned to it for reproducible
65  /// archives — Perl `Pack/Zip.pm` L113-115
66  /// (`setLastModFileDateTimeFromUnix`). `None` lets the zip crate use
67  /// its default write timestamp.
68  pub source_date_epoch: Option<u64>,
69}
70
71/// Pack the post-processing outputs into a zip archive.
72///
73/// Returns an `io::Result` rather than `crate::processor::PostError`
74/// because callers (binary mains) are already `Box<dyn Error>`-typed.
75///
76/// **IO performance:** the underlying file is wrapped in a 64 KiB
77/// `BufWriter` before handing it to `ZipWriter`. The zip crate's
78/// internal deflate output is small chunks (per-block from miniz);
79/// without buffering each chunk would be its own `write()` syscall.
80/// Measured ~6× fewer syscalls on 1910.01256 (7 resource files + HTML).
81pub fn pack_archive(opts: &PackOptions) -> io::Result<()> {
82  let file = File::create(opts.zip_path)?;
83  let buf_file = BufWriter::with_capacity(ZIP_WRITE_BUF, file);
84  let mut zip = ZipWriter::new(buf_file);
85  let mut zip_options =
86    SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
87  // Reproducible archives: pin every member's mod-time to SOURCE_DATE_EPOCH
88  // when provided (Perl Pack/Zip.pm L113-115). DOS/zip timestamps only
89  // span 1980-2107, so out-of-range epochs are silently left at the
90  // crate default — matching the spirit of `setLastModFileDateTimeFromUnix`
91  // (which would clamp) without failing the whole archive.
92  if let Some(epoch) = opts.source_date_epoch {
93    if let Some(dt) = epoch_to_zip_datetime(epoch) {
94      zip_options = zip_options.last_modified_time(dt);
95    }
96  }
97
98  // HTML first, so `unzip -l` shows the main artifact at the top.
99  zip
100    .start_file(opts.html_filename, zip_options)
101    .map_err(io_err)?;
102  zip.write_all(opts.html.as_bytes())?;
103
104  // Resource files (Graphics-converted PNG/SVG, injected CSS, etc.).
105  if let Some(dir) = opts.resource_dir {
106    if dir.exists() {
107      add_dir_to_zip(&mut zip, dir, dir, &zip_options)?;
108    }
109  }
110
111  // Log entry.
112  if let Some(log_name) = opts.log_filename {
113    if !opts.log.is_empty() {
114      zip.start_file(log_name, zip_options).map_err(io_err)?;
115      zip.write_all(opts.log.as_bytes())?;
116    }
117  }
118
119  // Status.
120  zip.start_file("status", zip_options).map_err(io_err)?;
121  zip.write_all(opts.status.as_bytes())?;
122
123  // Telemetry (cortex_worker only).
124  if let Some(tjson) = opts.telemetry_json {
125    zip
126      .start_file("telemetry.json", zip_options)
127      .map_err(io_err)?;
128    zip.write_all(tjson.as_bytes())?;
129  }
130
131  zip.finish().map_err(io_err)?;
132  Ok(())
133}
134
135/// Zip a whole site directory into `zip_path` — port of Perl `Pack/Zip.pm` `get_archive`: the top-level files in
136/// name order with `mimetype` first and STORED (EPUB OCF wants it at byte 38), then each subdirectory's tree, deflated.
137pub fn pack_directory(
138  dir: &Path,
139  zip_path: &str,
140  source_date_epoch: Option<u64>,
141) -> io::Result<()> {
142  let file = File::create(zip_path)?;
143  let mut zip = ZipWriter::new(BufWriter::with_capacity(ZIP_WRITE_BUF, file));
144  let mut deflated = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
145  if let Some(dt) = source_date_epoch.and_then(epoch_to_zip_datetime) {
146    deflated = deflated.last_modified_time(dt);
147  }
148  let stored = deflated.compression_method(CompressionMethod::Stored);
149  let mut files = Vec::new();
150  let mut subdirs = Vec::new();
151  for entry in std::fs::read_dir(dir)? {
152    let entry = entry?;
153    let name = entry.file_name().to_string_lossy().into_owned();
154    if name.starts_with('.') {
155      continue;
156    }
157    if entry.path().is_dir() {
158      subdirs.push(name);
159    } else if entry.path().is_file() && !is_excluded_archive_entry(&name) {
160      files.push(name);
161    }
162  }
163  files.sort_by_key(|name| (name != "mimetype", name.clone()));
164  subdirs.sort();
165  for name in &files {
166    let options = if name == "mimetype" { stored } else { deflated };
167    zip.start_file(name.as_str(), options).map_err(io_err)?;
168    io::copy(&mut File::open(dir.join(name))?, &mut zip)?;
169  }
170  for name in &subdirs {
171    add_tree_to_zip(&mut zip, &dir.join(name), name, &deflated)?;
172  }
173  zip.finish().map_err(io_err)?;
174  Ok(())
175}
176
177/// Archive::Zip `addTree` for [`pack_directory`]: a directory entry, then its members in name order.
178fn add_tree_to_zip<W: Write + io::Seek>(
179  zip: &mut ZipWriter<W>,
180  dir: &Path,
181  name: &str,
182  options: &SimpleFileOptions,
183) -> io::Result<()> {
184  zip.add_directory(name, *options).map_err(io_err)?;
185  let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<io::Result<_>>()?;
186  entries.sort_by_key(|entry| entry.file_name());
187  for entry in entries {
188    let basename = entry.file_name().to_string_lossy().into_owned();
189    if is_excluded_archive_entry(&basename) {
190      continue;
191    }
192    let member = format!("{name}/{basename}");
193    if entry.path().is_dir() {
194      add_tree_to_zip(zip, &entry.path(), &member, options)?;
195    } else {
196      zip.start_file(member.as_str(), *options).map_err(io_err)?;
197      io::copy(&mut File::open(entry.path())?, zip)?;
198    }
199  }
200  Ok(())
201}
202
203/// Recursively add files from `dir` to a ZIP archive, preserving the
204/// directory structure relative to `base`.
205///
206/// Two skip rules apply:
207///  * `.html` files — the post-processed HTML is added separately by [`pack_archive`] (and the
208///    staging dir may hold a stray copy written there for the Graphics processor's relative paths).
209///  * [`is_excluded_archive_entry`] — Perl `Pack/Zip.pm`'s `ARCHIVE_EXT_EXCLUDE` (source
210///    `.tex`/`.bib`, nested archives, dotfiles, editor backups). Applied per-basename, matching
211///    Perl's `addTree` filter `sub { !/$ext_exclude/ }`.
212///
213/// Each source file is wrapped in a 64 KiB `BufReader` to amortise
214/// `read()` syscalls on the input side (the `io::copy` 8 KiB default
215/// chunk would otherwise issue ~ceil(filesize/8K) reads per resource).
216fn add_dir_to_zip<W: Write + io::Seek>(
217  zip: &mut ZipWriter<W>,
218  dir: &Path,
219  base: &Path,
220  options: &SimpleFileOptions,
221) -> io::Result<()> {
222  for entry in std::fs::read_dir(dir)? {
223    let entry = entry?;
224    let path = entry.path();
225    let rel = path.strip_prefix(base).unwrap_or(&path);
226    // Zip entry names use '/' by spec (APPNOTE 4.4.17.1); Path on Windows
227    // yields '\'. Replace only the platform separator: on Unix that's a
228    // no-op ('/'→'/') that leaves a literal '\' — a legal Unix filename
229    // byte — untouched; on Windows it rewrites '\'→'/'.
230    let name = rel
231      .to_string_lossy()
232      .replace(std::path::MAIN_SEPARATOR, "/");
233    let basename = entry.file_name().to_string_lossy().to_string();
234
235    if path.is_dir() {
236      // Perl's `addTree` filter excludes whole subtrees whose *directory*
237      // name matches (e.g. a nested `.git`); honour the same per-basename
238      // rule before recursing.
239      if !is_excluded_archive_entry(&basename) {
240        add_dir_to_zip(zip, &path, base, options)?;
241      }
242    } else if !name.ends_with(".html") && !is_excluded_archive_entry(&basename) {
243      zip.start_file(&name, *options).map_err(io_err)?;
244      let f = File::open(&path)?;
245      let mut buf_reader = io::BufReader::with_capacity(ZIP_WRITE_BUF, f);
246      io::copy(&mut buf_reader, zip)?;
247    }
248  }
249  Ok(())
250}
251
252/// Whether a bundle entry should be excluded from the archive — port of
253/// Perl `Pack/Zip.pm` `$ARCHIVE_EXT_EXCLUDE`
254/// (`qr/(?:^\.)|(?:\.(?:zip|gz|epub|tex|bib|mobi|cache)$)|(?:~$)/`),
255/// applied to the file's basename:
256///  * hidden dotfiles (`^\.`),
257///  * editor backups (`~$`),
258///  * nested archives / source / cache files (`.zip`, `.gz`, `.epub`, `.tex`, `.bib`, `.mobi`,
259///    `.cache`).
260fn is_excluded_archive_entry(basename: &str) -> bool {
261  if basename.starts_with('.') || basename.ends_with('~') {
262    return true;
263  }
264  // Our cache (`LaTeXML-oxide.cache`) and its SQLite side files, which a killed process leaves.
265  if crate::document::is_cache_file(basename) {
266    return true;
267  }
268  // Suffix test on the lowercase extension (Perl anchors `$`, i.e. the
269  // final extension). `rsplit('.')` yields the extension before any dot.
270  match basename.rsplit_once('.') {
271    Some((_, ext)) => matches!(
272      ext.to_ascii_lowercase().as_str(),
273      "zip" | "gz" | "epub" | "tex" | "bib" | "mobi" | "cache"
274    ),
275    None => false,
276  }
277}
278
279/// Convert a Unix epoch (seconds, UTC) into a zip [`zip::DateTime`].
280///
281/// DOS/zip timestamps only represent 1980-01-01..=2107; epochs outside
282/// that window return `None` (caller falls back to the crate default).
283/// Pure civil-date arithmetic (Howard Hinnant's `civil_from_days`) so we
284/// don't pull in a date-time crate just for `SOURCE_DATE_EPOCH`.
285fn epoch_to_zip_datetime(epoch: u64) -> Option<zip::DateTime> {
286  let days = (epoch / 86_400) as i64;
287  let secs_of_day = (epoch % 86_400) as u32;
288  let (hour, minute, second) = (
289    (secs_of_day / 3600) as u8,
290    ((secs_of_day % 3600) / 60) as u8,
291    (secs_of_day % 60) as u8,
292  );
293  // civil_from_days: days since 1970-01-01 → (year, month, day).
294  let z = days + 719_468;
295  let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
296  let doe = z - era * 146_097; // [0, 146096]
297  let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; // [0, 399]
298  let year = yoe + era * 400;
299  let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
300  let mp = (5 * doy + 2) / 153; // [0, 11]
301  let day = (doy - (153 * mp + 2) / 5 + 1) as u8; // [1, 31]
302  let month = (if mp < 10 { mp + 3 } else { mp - 9 }) as u8; // [1, 12]
303  let year = year + i64::from(month <= 2);
304  if !(1980..=2107).contains(&year) {
305    return None;
306  }
307  zip::DateTime::from_date_and_time(year as u16, month, day, hour, minute, second).ok()
308}
309
310/// Convert a `zip::result::ZipError` into an `io::Error` so the caller
311/// signature can stay `io::Result`. The zip crate wraps `io::Error`
312/// already; we just re-wrap unrecognized kinds as `Other`.
313fn io_err(e: zip::result::ZipError) -> io::Error {
314  match e {
315    zip::result::ZipError::Io(inner) => inner,
316    other => io::Error::other(other.to_string()),
317  }
318}
319
320#[cfg(test)]
321mod tests {
322  use std::io::Read;
323
324  use super::*;
325
326  /// Read back the set of entry names from a zip on disk.
327  fn zip_entry_names(zip_path: &Path) -> Vec<String> {
328    let f = File::open(zip_path).expect("open zip");
329    let mut archive = zip::ZipArchive::new(f).expect("parse zip");
330    (0..archive.len())
331      .map(|i| {
332        archive
333          .by_index(i)
334          .expect("entry")
335          .name()
336          .expect("entry name")
337          .to_string()
338      })
339      .collect()
340  }
341
342  #[test]
343  fn excludes_perl_archive_ext_set() {
344    // Perl Zip.pm ARCHIVE_EXT_EXCLUDE = qr/(?:^\.)|(?:\.(?:zip|gz|epub|
345    // tex|bib|mobi|cache)$)|(?:~$)/ — applied to the basename.
346    assert!(is_excluded_archive_entry("paper.tex"));
347    assert!(is_excluded_archive_entry("refs.bib"));
348    assert!(is_excluded_archive_entry("bundle.zip"));
349    assert!(is_excluded_archive_entry("page.gz"));
350    assert!(is_excluded_archive_entry("book.epub"));
351    assert!(is_excluded_archive_entry("book.mobi"));
352    assert!(is_excluded_archive_entry("LaTeXML.cache"));
353    assert!(is_excluded_archive_entry(".hidden"));
354    assert!(is_excluded_archive_entry("backup~"));
355    // Kept: real bundle resources.
356    assert!(!is_excluded_archive_entry("fig1.png"));
357    assert!(!is_excluded_archive_entry("diagram.svg"));
358    assert!(!is_excluded_archive_entry("LaTeXML.css"));
359    assert!(!is_excluded_archive_entry("logo.jpg"));
360  }
361
362  #[test]
363  fn pack_archive_bundles_resources_minus_excluded() {
364    let staging = tempfile::tempdir().expect("tempdir");
365    let p = staging.path();
366    // Resources that SHOULD be bundled.
367    std::fs::write(p.join("fig1.png"), b"PNGDATA").unwrap();
368    std::fs::write(p.join("LaTeXML.css"), b"body{}").unwrap();
369    std::fs::create_dir(p.join("sub")).unwrap();
370    std::fs::write(p.join("sub").join("img.svg"), b"<svg/>").unwrap();
371    // Resources that must be EXCLUDED.
372    std::fs::write(p.join("paper.tex"), b"\\documentclass{article}").unwrap();
373    std::fs::write(p.join("refs.bib"), b"@book{x}").unwrap();
374    std::fs::write(p.join("LaTeXML.cache"), b"cache").unwrap();
375    std::fs::write(p.join("LaTeXML-oxide.cache"), b"cache").unwrap();
376    std::fs::write(p.join("LaTeXML-oxide.cache-wal"), b"wal").unwrap();
377    std::fs::write(p.join("LaTeXML-oxide.cache-shm"), b"shm").unwrap();
378    std::fs::write(p.join("LaTeXML-oxide.cache-journal"), b"journal").unwrap();
379    std::fs::write(p.join(".hidden"), b"secret").unwrap();
380    std::fs::write(p.join("backup~"), b"old").unwrap();
381    // The HTML is added separately by pack_archive; a stray copy in
382    // the staging dir must not be double-added.
383    std::fs::write(p.join("doc.html"), b"<html>staging copy</html>").unwrap();
384
385    let out = tempfile::tempdir().expect("out dir");
386    let zip_path = out.path().join("bundle.zip");
387    let zip_path_str = zip_path.to_string_lossy().to_string();
388
389    pack_archive(&PackOptions {
390      zip_path:          &zip_path_str,
391      html_filename:     "doc.html",
392      html:              "<html>real document</html>",
393      log_filename:      Some("doc.log"),
394      log:               "log line",
395      status:            "Status:conversion:0",
396      resource_dir:      Some(p),
397      telemetry_json:    None,
398      source_date_epoch: None,
399    })
400    .expect("pack archive");
401
402    let names = zip_entry_names(&zip_path);
403    // Bundled resources present.
404    assert!(names.iter().any(|n| n == "fig1.png"), "names: {names:?}");
405    assert!(names.iter().any(|n| n == "LaTeXML.css"), "names: {names:?}");
406    assert!(
407      names.iter().any(|n| n == "sub/img.svg"),
408      "subdir resource missing; names: {names:?}"
409    );
410    // Core entries present.
411    assert!(names.iter().any(|n| n == "doc.html"));
412    assert!(names.iter().any(|n| n == "doc.log"));
413    assert!(names.iter().any(|n| n == "status"));
414    // Excluded resources absent.
415    for forbidden in [
416      "paper.tex",
417      "refs.bib",
418      "LaTeXML.cache",
419      "LaTeXML-oxide.cache",
420      "LaTeXML-oxide.cache-wal",
421      "LaTeXML-oxide.cache-shm",
422      "LaTeXML-oxide.cache-journal",
423      ".hidden",
424      "backup~",
425    ] {
426      assert!(
427        !names.iter().any(|n| n == forbidden),
428        "{forbidden} must be excluded; names: {names:?}"
429      );
430    }
431    // Exactly one doc.html (the real one), not the staging copy too.
432    assert_eq!(
433      names.iter().filter(|n| n.as_str() == "doc.html").count(),
434      1,
435      "doc.html must not be double-added; names: {names:?}"
436    );
437    // And the real HTML, not the staging copy, is what got stored.
438    let f = File::open(&zip_path).unwrap();
439    let mut archive = zip::ZipArchive::new(f).unwrap();
440    let mut html_entry = archive.by_name("doc.html").unwrap();
441    let mut body = String::new();
442    html_entry.read_to_string(&mut body).unwrap();
443    assert_eq!(body, "<html>real document</html>");
444  }
445
446  #[test]
447  fn source_date_epoch_sets_member_timestamp() {
448    // Perl Zip.pm L113-115: when SOURCE_DATE_EPOCH is set, every member
449    // gets that fixed mod-time for reproducible archives. 2021-01-01
450    // 00:00:00 UTC = 1609459200.
451    let staging = tempfile::tempdir().expect("tempdir");
452    std::fs::write(staging.path().join("fig.png"), b"x").unwrap();
453    let out = tempfile::tempdir().expect("out");
454    let zip_path = out.path().join("ts.zip");
455    let zip_path_str = zip_path.to_string_lossy().to_string();
456    pack_archive(&PackOptions {
457      zip_path:          &zip_path_str,
458      html_filename:     "d.html",
459      html:              "<html/>",
460      log_filename:      None,
461      log:               "",
462      status:            "ok",
463      resource_dir:      Some(staging.path()),
464      telemetry_json:    None,
465      source_date_epoch: Some(1_609_459_200),
466    })
467    .expect("pack");
468
469    let f = File::open(&zip_path).unwrap();
470    let mut archive = zip::ZipArchive::new(f).unwrap();
471    let entry = archive.by_name("fig.png").unwrap();
472    let dt = entry.last_modified().expect("has mod time");
473    assert_eq!(dt.year(), 2021, "year");
474    assert_eq!(dt.month(), 1, "month");
475    assert_eq!(dt.day(), 1, "day");
476  }
477}