Skip to main content

latexml_post/
writer.rs

1//! XML/HTML output sink — port of `LaTeXML::Post::Writer`.
2//!
3//! Two related concerns live here:
4//!
5//! 1. The [`Writer`] post-processor (last in the chain) that serializes a `PostDocument` to its
6//!    `destination`, handling DOCTYPE removal, TEMPORARY_DOCUMENT_ID cleanup, and HTML vs XML
7//!    serialization.
8//! 2. Free-standing helpers ([`write_output`], [`ensure_parent_dir`]) used by binary main()s that
9//!    already have the serialized string in hand (post-processing returns a `String`) and need to
10//!    route it to a destination path or stdout. Replaces the duplicated `File::create + write! +
11//!    ensure_parent_dir` boilerplate that used to live in `latexml_oxide.rs` (and the now-retired
12//!    `latexmlpost_oxide.rs`).
13//!
14//! Companion module: [`crate::pack`] (the `LaTeXML::Post::Pack` analog)
15//! handles archive bundling when the destination is a zip.
16
17use std::{
18  fs,
19  io::{self, Write},
20  path::{Path, PathBuf},
21  sync::atomic::{AtomicU64, Ordering},
22};
23
24use libxml::tree::{Node, SaveOptions};
25
26use crate::{
27  document::{PostDocument, get_xml_id},
28  processor::{PostError, ProcessResult, Processor},
29};
30
31/// Write the serialized output `content` to `dest` if `Some`, else to
32/// stdout. Creates parent directories as needed.
33///
34/// Used by `latexml_oxide.rs`'s main() (XML-input mode included) for
35/// the "write a single HTML/XML file" exit path. For the zip-archive
36/// exit path, use [`crate::pack::pack_archive`].
37pub fn write_output(content: &str, dest: Option<&str>) -> io::Result<()> {
38  match dest {
39    Some(path) => {
40      ensure_parent_dir(path)?;
41      fs::write(path, content)?;
42      Info!(
43        "writer",
44        "wrote",
45        "Wrote '{}' ({} bytes)",
46        path,
47        content.len()
48      );
49      Ok(())
50    },
51    None => io::stdout().write_all(content.as_bytes()),
52  }
53}
54
55/// Like [`write_output`] but writes several segments back-to-back without
56/// concatenating them into one buffer first. Used for the conversion log,
57/// where the core and post-phase segments are each already-allocated and
58/// large for real articles — a `format!("{core}{post}")` would allocate a
59/// third copy of their combined size on the conversion hot path. Segments are
60/// written verbatim and in order through a single `BufWriter` (one file
61/// open/truncate); insert any separators (e.g. `"\n"`) as their own segments.
62pub fn write_output_segments(segments: &[&str], dest: Option<&str>) -> io::Result<()> {
63  match dest {
64    Some(path) => {
65      ensure_parent_dir(path)?;
66      let mut writer = io::BufWriter::new(fs::File::create(path)?);
67      let mut total = 0usize;
68      for seg in segments {
69        writer.write_all(seg.as_bytes())?;
70        total += seg.len();
71      }
72      writer.flush()?;
73      Info!("writer", "wrote", "Wrote '{}' ({} bytes)", path, total);
74      Ok(())
75    },
76    None => {
77      let stdout = io::stdout();
78      let mut handle = stdout.lock();
79      for seg in segments {
80        handle.write_all(seg.as_bytes())?;
81      }
82      Ok(())
83    },
84  }
85}
86
87/// Ensure the parent directory of `path` exists, creating it (and any
88/// missing ancestors) as needed. No-op when `path` has no parent or
89/// the parent is the current directory.
90pub fn ensure_parent_dir(path: &str) -> io::Result<()> {
91  if let Some(parent) = Path::new(path).parent() {
92    if !parent.as_os_str().is_empty() {
93      fs::create_dir_all(parent)?;
94    }
95  }
96  Ok(())
97}
98
99/// The directories a page render already made: a split run writes thousands of pages into a handful of
100/// directories, and each `create_dir_all` is a `mkdir` and a `statx` (Nasser's 71,476-page document,
101/// #777 FAQ).
102#[derive(Debug, Default)]
103pub struct MadeDirs(std::collections::HashSet<PathBuf>);
104
105std::thread_local! {
106  static DIRS_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
107}
108
109/// How many directories [`MadeDirs::ensure_parent`] asked the OS for on this thread (a test seam).
110pub fn made_dir_count() -> usize { DIRS_MADE.get() }
111
112impl MadeDirs {
113  /// [`ensure_parent_dir`], once per directory; an error leaves the directory to be retried.
114  pub fn ensure_parent(&mut self, path: &str) -> io::Result<()> {
115    let Some(parent) = Path::new(path).parent() else {
116      return Ok(());
117    };
118    if parent.as_os_str().is_empty() || self.0.contains(parent) {
119      return Ok(());
120    }
121    DIRS_MADE.set(DIRS_MADE.get() + 1);
122    fs::create_dir_all(parent)?;
123    self.0.insert(parent.to_path_buf());
124    Ok(())
125  }
126}
127
128/// Monotonic per-process counter for unique sibling temp files ([`Staged::beside`]).
129static ATOMIC_TMP_SEQ: AtomicU64 = AtomicU64::new(0);
130
131/// A private file beside a destination that parallel render workers may share (the CSS, a figure
132/// every page uses): written or converted there, then [installed](Staged::install) by one rename,
133/// so no reader sees a partial file and no writer touches another's. Named
134/// `.<stem>.tmp.<pid>.<seq>.<ext>` (the stem [bounded](bounded_name)), its extension kept last
135/// for converters that read the format from it; registered with the watchdog's exit sweep, and
136/// removed when dropped — after an install too, since a rename onto a hard link of the same file
137/// succeeds and leaves both names (POSIX `rename(2)`; a destination an older binary hard-linked to
138/// a graphics-cache entry). A name some file already holds — a killed run's leftover, perhaps a
139/// link to a cache entry, or a process with the same pid in another PID namespace sharing the
140/// cache — is skipped, never written through.
141pub struct Staged {
142  path:     PathBuf,
143  _on_exit: latexml_core::watchdog::RemoveOnExit,
144}
145
146impl Staged {
147  /// A fresh private path beside `dest` that no file holds, for a converter to write (nothing
148  /// is created).
149  pub fn beside(dest: &Path) -> Self { Self::at(free_path(dest)) }
150
151  /// [`Self::beside`], created empty by `create_new`: the name is this caller's alone.
152  fn create(dest: &Path) -> io::Result<(Self, fs::File)> { Self::create_at(|| free_path(dest)) }
153
154  /// The first of the `next` names that `create_new` makes, created empty.
155  fn create_at(next: impl Fn() -> PathBuf) -> io::Result<(Self, fs::File)> {
156    loop {
157      let path = next();
158      match fs::OpenOptions::new()
159        .write(true)
160        .create_new(true)
161        .open(&path)
162      {
163        Ok(file) => return Ok((Self::at(path), file)),
164        Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
165        Err(e) => return Err(e),
166      }
167    }
168  }
169
170  /// The first of the `next` names made a hard link to `src`; `None` where the filesystem can't link it there.
171  fn link_at(src: &Path, next: impl Fn() -> PathBuf) -> io::Result<Option<Self>> {
172    loop {
173      let path = next();
174      match fs::hard_link(src, &path) {
175        Ok(()) => return Ok(Some(Self::at(path))),
176        Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
177        // Another filesystem, or one without (more) hard links: the caller copies.
178        Err(e)
179          if matches!(
180            e.kind(),
181            io::ErrorKind::CrossesDevices
182              | io::ErrorKind::PermissionDenied
183              | io::ErrorKind::TooManyLinks
184              | io::ErrorKind::Unsupported
185          ) =>
186        {
187          return Ok(None);
188        },
189        Err(e) => return Err(e),
190      }
191    }
192  }
193
194  /// A hard link to `src`, or a copy, under a short name in the temporary directory, `lx.<pid>.<seq>.<ext>` (the
195  /// extension kept for converters that read the format from it): `src`'s bytes where its own path is out of reach.
196  pub fn alias(src: &Path) -> io::Result<Self> {
197    let ext = src.extension().and_then(|e| e.to_str());
198    let next = || free_alias_path(ext);
199    if let Ok(Some(alias)) = Self::link_at(src, next) {
200      return Ok(alias);
201    }
202    let (alias, file) = Self::create_at(next)?;
203    drop(file);
204    fs::copy(src, alias.path())?;
205    Ok(alias)
206  }
207
208  fn at(path: PathBuf) -> Self {
209    let _on_exit = latexml_core::watchdog::remove_on_exit(&path);
210    Staged { path, _on_exit }
211  }
212
213  pub fn path(&self) -> &Path { &self.path }
214
215  /// Install the staged file as `dest` by rename. When the rename fails (Windows'
216  /// `MoveFileExW` refuses a file another worker holds open) but `dest` already holds these very
217  /// bytes, a sibling installed the same output and the install stands; the bytes are compared
218  /// before the temp is removed, so a stale file of the same length is never taken for it.
219  pub fn install(self, dest: &Path) -> io::Result<()> {
220    match fs::rename(&self.path, dest) {
221      Ok(()) => Ok(()),
222      Err(_) if same_bytes(&self.path, dest) => Ok(()),
223      Err(e) => Err(e),
224    }
225  }
226}
227
228/// Bytes of a file name [`bounded_name`] keeps.
229const NAME_KEPT: usize = 64;
230
231/// `name`, or for a longer one its first 64 bytes and a hash of the whole: every name derived from a
232/// destination (its staged file, a stage of that, a converter's temp) then stays under the 255-byte
233/// NAME_MAX, which a figure name of 220 characters or more took them past.
234pub fn bounded_name(name: &str) -> std::borrow::Cow<'_, str> {
235  use std::hash::{Hash, Hasher};
236  if name.len() <= NAME_KEPT {
237    return name.into();
238  }
239  let mut cut = NAME_KEPT;
240  while !name.is_char_boundary(cut) {
241    cut -= 1;
242  }
243  let mut hasher = std::hash::DefaultHasher::new();
244  name.hash(&mut hasher);
245  format!("{}~{:016x}", &name[..cut], hasher.finish()).into()
246}
247
248/// The staged name for `dest` with counter `seq`: `.<stem>.tmp.<pid>.<seq>.<ext>`, the stem
249/// [bounded](bounded_name).
250fn staged_path(dest: &Path, seq: u64) -> PathBuf {
251  let pid = std::process::id();
252  let stem = bounded_name(
253    dest
254      .file_stem()
255      .and_then(|n| n.to_str())
256      .unwrap_or("resource"),
257  );
258  let name = match dest.extension().and_then(|e| e.to_str()) {
259    Some(ext) => format!(".{stem}.tmp.{pid}.{seq}.{ext}"),
260    None => format!(".{stem}.tmp.{pid}.{seq}"),
261  };
262  match dest.parent() {
263    Some(p) if !p.as_os_str().is_empty() => p.join(name),
264    _ => PathBuf::from(name),
265  }
266}
267
268/// The next [`staged_path`] for `dest` that names no file (a failing `lstat` other than "not
269/// found" is left to the write that follows).
270fn free_path(dest: &Path) -> PathBuf {
271  loop {
272    let path = staged_path(dest, ATOMIC_TMP_SEQ.fetch_add(1, Ordering::Relaxed));
273    if fs::symlink_metadata(&path).is_err() {
274      return path;
275    }
276  }
277}
278
279/// The next [`Staged::alias`] name that names no file.
280fn free_alias_path(ext: Option<&str>) -> PathBuf {
281  let (dir, pid) = (std::env::temp_dir(), std::process::id());
282  loop {
283    let seq = ATOMIC_TMP_SEQ.fetch_add(1, Ordering::Relaxed);
284    let path = dir.join(match ext {
285      Some(ext) => format!("lx.{pid}.{seq}.{ext}"),
286      None => format!("lx.{pid}.{seq}"),
287    });
288    if fs::symlink_metadata(&path).is_err() {
289      return path;
290    }
291  }
292}
293
294impl Drop for Staged {
295  fn drop(&mut self) { let _ = fs::remove_file(&self.path); }
296}
297
298/// Whether `a` and `b` are regular files holding the same bytes.
299pub fn same_bytes(a: &Path, b: &Path) -> bool {
300  match (fs::metadata(a), fs::metadata(b)) {
301    (Ok(ma), Ok(mb)) if ma.is_file() && mb.is_file() && ma.len() == mb.len() => {
302      matches!((fs::read(a), fs::read(b)), (Ok(x), Ok(y)) if x == y)
303    },
304    _ => false,
305  }
306}
307
308/// Whether a bundled resource's embedded bytes are written to `dest`: only where it is missing or an empty regular file
309/// (#312's truncated leftover). A non-empty file in place is used as-is, a user's or an older release's; a directory
310/// still goes to the write and its error.
311pub fn needs_write(dest: &Path) -> bool {
312  !fs::metadata(dest).is_ok_and(|m| m.is_file() && m.len() > 0)
313}
314
315/// Whether `a` and `b` name the same existing file (by canonical path). A copy onto itself
316/// truncates the file: the destination directory on the resource search path made a stale
317/// resource its own only match (#312); a plain `!=` on two spellings (`./`, relative) misses it.
318pub fn same_file(a: impl AsRef<Path>, b: impl AsRef<Path>) -> bool {
319  latexml_core::util::pathname::same_file(a, b)
320}
321
322/// Atomically write `bytes` to `dest` through a [`Staged`] file.
323///
324/// Safe when multiple parallel render workers publish the same shared resource
325/// (`LaTeXML.css`, `LaTeXML.js`, etc.) concurrently: Unix readers never observe
326/// a truncated/interleaved file, and Windows avoids `ERROR_SHARING_VIOLATION`
327/// on concurrent writers.
328pub fn write_atomic(dest: &Path, bytes: &[u8]) -> io::Result<()> {
329  let (staged, mut file) = Staged::create(dest)?;
330  file.write_all(bytes)?;
331  drop(file);
332  staged.install(dest)
333}
334
335/// Atomically copy `src` to `dest` through a [`Staged`] file. Copying a file onto itself is
336/// refused: it would only rewrite it, and a caller that then changes `dest` would change its source.
337/// The copy is `dest`'s own: a hard link let an edit of one graphics output in place rewrite the
338/// cache entry and every other document's copy (GFXHARDLINK).
339pub fn copy_atomic(src: &Path, dest: &Path) -> io::Result<()> {
340  if same_file(src, dest) {
341    return Err(io::Error::other(format!(
342      "{} is the source itself",
343      dest.display()
344    )));
345  }
346  let (staged, file) = Staged::create(dest)?;
347  drop(file);
348  fs::copy(src, staged.path())?;
349  staged.install(dest)
350}
351
352/// Output format for the writer.
353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354pub enum OutputFormat {
355  Xml,
356  Html,
357}
358
359/// Writer post-processor: serializes document to file.
360///
361/// Port of `LaTeXML::Post::Writer`.
362pub struct Writer {
363  name:         String,
364  format:       OutputFormat,
365  omit_doctype: bool,
366  is_html:      bool,
367}
368
369impl Writer {
370  pub fn new(format: Option<OutputFormat>, omit_doctype: bool, is_html: bool) -> Self {
371    Writer {
372      name: "Writer".to_string(),
373      format: format.unwrap_or(OutputFormat::Xml),
374      omit_doctype,
375      is_html,
376    }
377  }
378}
379
380impl Processor for Writer {
381  fn get_name(&self) -> &str { &self.name }
382
383  fn to_process(&self, doc: &PostDocument) -> Vec<Node> {
384    match doc.get_document_element() {
385      Some(el) => vec![el],
386      None => vec![],
387    }
388  }
389
390  fn process(&mut self, mut doc: PostDocument, nodes: Vec<Node>) -> ProcessResult {
391    let mut root = match nodes.into_iter().next() {
392      Some(r) => r,
393      None => return Ok(vec![doc]),
394    };
395
396    // Remove the internal DTD subset if requested (Perl Writer.pm L38:
397    // `$doc->getDocument->removeInternalSubset if $$self{omit_doctype}`).
398    // Backed by `libxml::tree::Document::remove_internal_subset`, added
399    // in rust-libxml 0.3.11 specifically to close this gap.
400    if self.omit_doctype {
401      doc.get_document_mut().remove_internal_subset();
402    }
403
404    // Remove TEMPORARY_DOCUMENT_ID if present (Perl Writer.pm L41-42).
405    // NS-aware forms: the bare get/remove_attribute("xml:id") pair silently
406    // no-opped, so this last-chance strip never fired (the split path
407    // removes the temp id earlier via core_interface, but this writer-side
408    // guard is the one Perl relies on).
409    if let Some(id) = get_xml_id(&root) {
410      if id == "TEMPORARY_DOCUMENT_ID" {
411        let _ = root.remove_attribute_ns("id", latexml_core::common::xml::XML_NS);
412      }
413    }
414
415    // Serialize: HTML uses toStringHTML, XML uses toString(1)  (Perl Writer.pm L44-47)
416    let serialized = if self.is_html {
417      doc.get_document().to_string_with_options(SaveOptions {
418        as_html: true,
419        format: true,
420        ..SaveOptions::default()
421      })
422    } else {
423      doc.get_document().to_string_with_options(SaveOptions {
424        format: true,
425        ..SaveOptions::default()
426      })
427    };
428
429    if let Some(destination) = doc.get_destination() {
430      // Create destination directory if needed
431      if let Some(destdir) = doc.get_destination_directory() {
432        fs::create_dir_all(destdir).map_err(|e| {
433          PostError::Io(io::Error::new(
434            e.kind(),
435            format!("Couldn't create directory '{}': {}", destdir, e),
436          ))
437        })?;
438      }
439      fs::write(destination, &serialized).map_err(|e| {
440        PostError::Io(io::Error::new(
441          e.kind(),
442          format!("Couldn't write '{}': {}", destination, e),
443        ))
444      })?;
445      Info!(
446        "writer",
447        "wrote",
448        "Wrote '{}' ({})",
449        destination,
450        serialized.len()
451      );
452    } else {
453      print!("{}", serialized);
454    }
455
456    Ok(vec![doc])
457  }
458}
459
460#[cfg(test)]
461mod tests {
462  use super::*;
463
464  #[test]
465  fn output_format_variants() {
466    let _ = OutputFormat::Xml;
467    let _ = OutputFormat::Html;
468  }
469
470  #[test]
471  fn output_format_partial_eq() {
472    assert_eq!(OutputFormat::Xml, OutputFormat::Xml);
473    assert_ne!(OutputFormat::Xml, OutputFormat::Html);
474    assert_eq!(OutputFormat::Html, OutputFormat::Html);
475  }
476
477  #[test]
478  fn output_format_copy_clone() {
479    // Copy trait: move-after-use still works.
480    let a = OutputFormat::Xml;
481    let b = a;
482    let _ = a; // still usable due to Copy
483    assert_eq!(a, b);
484  }
485
486  #[test]
487  fn writer_new_default_format_xml() {
488    let w = Writer::new(None, false, false);
489    assert_eq!(w.get_name(), "Writer");
490    assert_eq!(w.format, OutputFormat::Xml);
491    assert!(!w.omit_doctype);
492    assert!(!w.is_html);
493  }
494
495  #[test]
496  fn writer_new_explicit_format() {
497    let w = Writer::new(Some(OutputFormat::Html), true, true);
498    assert_eq!(w.format, OutputFormat::Html);
499    assert!(w.omit_doctype);
500    assert!(w.is_html);
501  }
502
503  #[test]
504  fn writer_get_name_is_writer() {
505    let w = Writer::new(None, false, false);
506    assert_eq!(w.get_name(), "Writer");
507  }
508
509  #[test]
510  /// `Writer::process` with `omit_doctype = true` drops the
511  /// `<!DOCTYPE …>` preamble from the output, mirroring Perl
512  /// `Post::Writer` L38 behaviour.
513  fn writer_omit_doctype_strips_doctype_preamble() {
514    use crate::document::{PostDocument, PostDocumentOptions};
515
516    let xml = r#"<?xml version="1.0"?>
517<!DOCTYPE root SYSTEM "example.dtd">
518<root><child>hi</child></root>"#;
519    let doc = PostDocument::new_from_string(xml, PostDocumentOptions::default())
520      .expect("parse test fixture");
521
522    // omit_doctype=true → DOCTYPE stripped after Writer::process.
523    let mut writer = Writer::new(
524      None, /* omit_doctype= */ true, /* is_html= */ false,
525    );
526    let to_process = writer.to_process(&doc);
527    let result = writer.process(doc, to_process).expect("process");
528    let after = result
529      .into_iter()
530      .next()
531      .expect("at least one doc")
532      .get_document()
533      .to_string();
534    assert!(
535      !after.contains("<!DOCTYPE"),
536      "expected DOCTYPE stripped, got: {after}"
537    );
538    assert!(after.contains("<root>"));
539  }
540
541  #[test]
542  /// `Writer::process` with `omit_doctype = false` (the default)
543  /// preserves the `<!DOCTYPE …>` preamble — opt-in behaviour.
544  fn writer_default_preserves_doctype() {
545    use crate::document::{PostDocument, PostDocumentOptions};
546
547    let xml = r#"<?xml version="1.0"?>
548<!DOCTYPE root SYSTEM "example.dtd">
549<root><child>hi</child></root>"#;
550    let doc = PostDocument::new_from_string(xml, PostDocumentOptions::default())
551      .expect("parse test fixture");
552
553    let mut writer = Writer::new(
554      None, /* omit_doctype= */ false, /* is_html= */ false,
555    );
556    let to_process = writer.to_process(&doc);
557    let result = writer.process(doc, to_process).expect("process");
558    let after = result
559      .into_iter()
560      .next()
561      .expect("at least one doc")
562      .get_document()
563      .to_string();
564    assert!(
565      after.contains("<!DOCTYPE"),
566      "expected DOCTYPE preserved, got: {after}"
567    );
568  }
569
570  #[test]
571  fn write_and_copy_atomic_succeed_and_clean_up_on_error() {
572    let dir = tempfile::tempdir().unwrap();
573    let dst = dir.path().join("LaTeXML.css");
574    write_atomic(&dst, b"body { color: black; }\n").unwrap();
575    assert_eq!(fs::read(&dst).unwrap(), b"body { color: black; }\n");
576
577    let src = dir.path().join("custom.css");
578    fs::write(&src, b".a { color: red; }\n").unwrap();
579    copy_atomic(&src, &dst).unwrap();
580    assert_eq!(fs::read(&dst).unwrap(), b".a { color: red; }\n");
581
582    // Failing install onto a directory must return Err and leave no stray .tmp file.
583    let bad = dir.path().join("blocked.css");
584    fs::create_dir(&bad).unwrap();
585    assert!(write_atomic(&bad, b"x").is_err());
586    assert!(copy_atomic(&src, &bad).is_err());
587    let strays: Vec<_> = fs::read_dir(dir.path())
588      .unwrap()
589      .filter_map(|e| e.ok())
590      .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
591      .collect();
592    assert!(strays.is_empty(), "leftover atomic temp files: {strays:?}");
593  }
594
595  /// A failed rename stands only when the destination already holds the staged bytes — compared
596  /// before the temp is removed, so a stale file of the same length is never taken for them
597  /// (Windows' `MoveFileExW` refuses a file a sibling worker holds open). A read-only directory
598  /// stands in for the refusal; a root run renames regardless and skips visibly.
599  #[cfg(unix)]
600  #[test]
601  fn a_refused_install_stands_only_on_identical_bytes() {
602    use std::os::unix::fs::PermissionsExt;
603    let dir = tempfile::tempdir().unwrap();
604    let a = dir.path().join("a.svg");
605    let b = dir.path().join("b.svg");
606    fs::write(&a, b"<svg>1</svg>").unwrap();
607    fs::write(&b, b"<svg>2</svg>").unwrap();
608    assert!(same_bytes(&a, &a.clone()));
609    assert!(!same_bytes(&a, &b), "same length, other bytes");
610    assert!(!same_bytes(&a, &dir.path().join("missing.svg")));
611    assert!(
612      !same_bytes(dir.path(), dir.path()),
613      "a directory holds no bytes"
614    );
615
616    let stage = |bytes: &[u8]| {
617      let staged = Staged::beside(&a);
618      fs::write(staged.path(), bytes).unwrap();
619      staged
620    };
621    let (same, other) = (stage(b"<svg>1</svg>"), stage(b"<svg>9</svg>"));
622    fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o555)).unwrap();
623    let probe = fs::rename(&b, dir.path().join("probe.svg"));
624    let refused = probe.is_err();
625    let (same, other) = (same.install(&a), other.install(&a));
626    fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o755)).unwrap();
627    if !refused {
628      eprintln!(
629        "SKIP a_refused_install_stands_only_on_identical_bytes: renames are not refused (root)"
630      );
631      return;
632    }
633    assert!(same.is_ok(), "{same:?}");
634    assert!(
635      other.is_err(),
636      "a stale file of the same length is not the install"
637    );
638    assert_eq!(fs::read(&a).unwrap(), b"<svg>1</svg>");
639    let staged = Staged::beside(&a);
640    let temp = staged.path().to_path_buf();
641    fs::write(&temp, b"x").unwrap();
642    drop(staged);
643    assert!(
644      !temp.exists(),
645      "an uninstalled stage is removed when dropped"
646    );
647  }
648
649  /// A rename onto a hard link of the same file succeeds and keeps both names (POSIX): a
650  /// graphics-cache entry a sibling worker linked into the destination (before GFXHARDLINK's copy
651  /// delivery; a destination an older binary wrote is still one) left every later worker's staged
652  /// link behind.
653  #[test]
654  fn a_stage_installed_onto_its_own_hard_link_is_removed() {
655    let dir = tempfile::tempdir().unwrap();
656    let a = dir.path().join("fig.svg");
657    fs::write(&a, b"<svg/>").unwrap();
658    let staged = Staged::beside(&a);
659    let temp = staged.path().to_path_buf();
660    fs::hard_link(&a, &temp).unwrap();
661    staged.install(&a).unwrap();
662    assert!(!temp.exists(), "the staged link is left behind");
663    assert_eq!(fs::read(&a).unwrap(), b"<svg/>");
664  }
665
666  /// A figure's alias (`Graphics::reachable_source`, Windows) has a short name, its extension kept, in the temporary
667  /// directory, never beside the figure; it holds the figure's bytes and goes when dropped.
668  #[test]
669  fn an_alias_is_a_short_name_in_the_temporary_directory() {
670    let dir = tempfile::tempdir().unwrap();
671    let figure = dir.path().join(format!("{}.pdf", "f".repeat(200)));
672    fs::write(&figure, b"%PDF-1.4 figure").unwrap();
673    let alias = Staged::alias(&figure).unwrap();
674    let path = alias.path().to_path_buf();
675    assert_eq!(path.parent(), Some(std::env::temp_dir().as_path()));
676    let name = path.file_name().unwrap().to_str().unwrap();
677    assert!(name.len() < 40 && name.ends_with(".pdf"), "{name}");
678    assert_eq!(fs::read(&path).unwrap(), b"%PDF-1.4 figure");
679    drop(alias);
680    assert!(!path.exists(), "the alias outlived its drop");
681    assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
682  }
683
684  /// A 240-character figure name stays under NAME_MAX (255 bytes) through its stage and a stage of
685  /// that stage (a crop's `write_atomic` of a staged render), the extension kept last; two names
686  /// that differ only past the kept bytes stage apart.
687  #[test]
688  fn the_stages_of_a_long_figure_name_stay_under_name_max() {
689    let dir = tempfile::tempdir().unwrap();
690    let long = dir.path().join(format!("{}.svg", "g".repeat(240)));
691    let stage = Staged::beside(&long);
692    let again = Staged::beside(stage.path());
693    for path in [stage.path(), again.path()] {
694      let name = path.file_name().unwrap().to_str().unwrap();
695      assert!(name.len() <= 128, "{} bytes: {name}", name.len());
696      assert!(name.ends_with(".svg"), "{name}");
697      fs::write(path, b"<svg/>").unwrap();
698    }
699    write_atomic(&long, b"<svg>1</svg>").unwrap();
700    assert_eq!(fs::read(&long).unwrap(), b"<svg>1</svg>");
701    let (a, b) = (
702      format!("{}a", "é".repeat(40)),
703      format!("{}b", "é".repeat(40)),
704    );
705    assert_ne!(bounded_name(&a), bounded_name(&b));
706    assert_eq!(bounded_name("fig.svg"), "fig.svg", "a short name is kept");
707  }
708
709  /// A temp name already taken — a killed run's leftover, perhaps a hard link to a graphics-cache
710  /// entry, or a process with the same pid in another PID namespace sharing the cache — is never
711  /// written through: `write_atomic` and `copy_atomic` take the next name.
712  #[test]
713  fn a_taken_temp_name_is_never_written_through() {
714    let dir = tempfile::tempdir().unwrap();
715    let sentinel = dir.path().join("site.svg");
716    fs::write(&sentinel, b"<svg>site</svg>").unwrap();
717    let src = dir.path().join("cached.svg");
718    fs::write(&src, b"<svg>new</svg>").unwrap();
719    let dests = ["w.svg", "c.svg"].map(|name| dir.path().join(name));
720    let next = ATOMIC_TMP_SEQ.load(Ordering::Relaxed);
721    for dest in &dests {
722      for seq in next..next + 64 {
723        fs::hard_link(&sentinel, staged_path(dest, seq)).unwrap();
724      }
725    }
726    write_atomic(&dests[0], b"<svg>new</svg>").unwrap();
727    copy_atomic(&src, &dests[1]).unwrap();
728    assert_eq!(fs::read(&sentinel).unwrap(), b"<svg>site</svg>");
729    for dest in &dests {
730      assert_eq!(
731        fs::read(dest).unwrap(),
732        b"<svg>new</svg>",
733        "{}",
734        dest.display()
735      );
736    }
737  }
738
739  #[test]
740  fn concurrent_write_atomic_produces_intact_file_without_errors() {
741    let dir = tempfile::tempdir().unwrap();
742    let dst = dir.path().join("shared.css");
743    let payload: Vec<u8> = b"/* css */\n".repeat(4096);
744    std::thread::scope(|s| {
745      for _ in 0..8 {
746        let dst = &dst;
747        let payload = &payload;
748        s.spawn(move || {
749          for _ in 0..16 {
750            write_atomic(dst, payload).expect("concurrent atomic write");
751          }
752        });
753      }
754    });
755    assert_eq!(fs::read(&dst).unwrap(), payload);
756  }
757}