Skip to main content

latexml_core/sxml/
segment_store.rs

1//! The on-disk spill area for fragmented conversion.
2//!
3//! A segment file holds RAW, splice-ready text at every lifecycle stage —
4//! never a wrapper element. An enclosing subtree that spills LATER keeps its
5//! children's `<_spilled_ ref=…/>` placeholders as LITERAL elements in its
6//! own file (inlining them once rebuilt multi-GB segments out of chapter
7//! shells); the final assembly resolves placeholders recursively
8//! (`Document::splice_segment_text`).
9//!
10//! 1. **Spilled** ([`SegmentStore::write_segment`]) — pass 1 stores the
11//!    pre-finalize serialization of one or more sibling subtrees.
12//! 2. **Processed** ([`SegmentStore::finalize_segment`]) — pass 2 replaces
13//!    the file with the fragment's FINAL output text (post-rewrite,
14//!    post-finalize, correctly indented).
15//!
16//! Parsing a segment (pass 2) goes through [`SegmentStore::wrapped_segment`],
17//! which wraps the raw text in a `<_lxfragment>` root carrying the recorded
18//! namespace declarations — in memory, never on disk.
19//!
20//! The directory lives beside the destination file — same volume, so
21//! [`crate::watchdog::available_disk_bytes`] measures the filesystem the spill
22//! actually consumes — and is removed on [`Drop`]. After a hard kill the
23//! directory survives; its name (`.latexml-spill-<pid>-<seq>`) is deliberately
24//! self-describing so a user knows what to delete.
25
26use std::{
27  fs,
28  path::{Path, PathBuf},
29};
30
31use crate::common::error::{Error, ErrorCategory, ErrorTarget, Result};
32
33/// Identifies one spilled segment within its [`SegmentStore`].
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub struct SegmentId(pub u32);
36
37impl std::fmt::Display for SegmentId {
38  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) }
39}
40
41/// Per-segment facts recorded at spill time and consumed when the segment is
42/// re-materialized in pass 2.
43#[derive(Debug, Clone, Default)]
44pub struct SegmentMeta {
45  /// Spine depth of the spilled subtree's insertion point (the depth the
46  /// serializer must resume at for indentation to match the eager output).
47  pub depth:      usize,
48  /// The spill parent's `noindent_children` — the `noindent` value the eager
49  /// serializer would have passed when recursing into these children
50  /// (schema-driven: whether the parent can contain `#PCDATA`). Pass-2
51  /// re-serialization must use the same value or indentation diverges.
52  pub noindent:   bool,
53  /// The font `finalize_rec` declares for the spill parent's children (`Document::finalize_context_font`), as its
54  /// `node_fonts` key: per-fragment finalize resolves fonts as the whole-document walk would have.
55  pub font:       Option<String>,
56  /// Namespace declarations (`(prefix, uri)`) the wrapper must carry so the
57  /// segment parses stand-alone. In the eager DOM these live on the document
58  /// root (hoisted during build); a spilled subtree's own serialization does
59  /// not repeat them.
60  pub namespaces: Vec<(String, String)>,
61  /// The qname of the spilled run's PARENT element (the spine node the
62  /// segment splices back under). Pass-2 finalize consults the parent for
63  /// schema decisions — e.g. collapsing an attribute-less `ltx:text` font
64  /// wrapper requires `can_contain(parent, grandchild)` — and the parse
65  /// wrapper (`ltx:_lxfragment`) is not in the model, so the recorded real
66  /// parent substitutes for it (witness: tests/digestion/dollar.tex kept an
67  /// empty `<text>` around an inline-block that eager collapsed).
68  pub parent:     Option<String>,
69  /// Every `xml:id` on the spilled run's ANCESTOR chain at the spill point.
70  /// A `label:`/`id:`-scoped rewrite whose scope node is one of these
71  /// ancestors covers the WHOLE fragment (the fragment sits inside the
72  /// scope subtree), but the node itself lives in another fragment — the
73  /// selection would come up empty (witness: tests/math/simplemath.tex,
74  /// where `label:sec:restricted` stamps `role=FUNCTION` inside a section
75  /// whose shell spills separately from its paragraphs).
76  pub ancestors:  Vec<String>,
77  /// The nearest ancestor `xml:id` below the root: the element eager finalize mints the run's id-less top nodes
78  /// under (`S1.p1.1` under `S1.p1`), its counters carried through pass 2 (`Document::fragment_anchor_id`).
79  pub anchor:     Option<String>,
80}
81
82/// The element wrapping a spilled segment's sibling subtrees. Matches the
83/// existing fragment-parsing convention (`common/xml.rs::FRAGMENT_WRAPPER`):
84/// never part of a document, only a parse vehicle.
85const SEGMENT_WRAPPER: &str = "_lxfragment";
86
87/// The on-disk spill area: numbered segment files plus their in-RAM metadata.
88pub struct SegmentStore {
89  dir:      PathBuf,
90  metas:    Vec<SegmentMeta>,
91  /// Historical: segments inlined into an enclosing one. Nested spills now
92  /// stay nested (literal placeholders + recursive assembly splice), so
93  /// nothing retires in the current pipeline; the mechanism remains for the
94  /// store's API stability.
95  retired:  Vec<bool>,
96  /// Ensures watchdog timeout/OOM exits (which skip `Drop`) still remove the
97  /// spill directory instead of leaving multi-GB scratch trees behind.
98  _on_exit: crate::watchdog::RemoveOnExit,
99}
100
101impl std::fmt::Debug for SegmentStore {
102  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103    f.debug_struct("SegmentStore")
104      .field("dir", &self.dir)
105      .field("metas", &self.metas)
106      .field("retired", &self.retired)
107      .finish()
108  }
109}
110
111impl SegmentStore {
112  /// Create the spill directory beside `dest` (the conversion's output file or
113  /// directory), so disk-headroom checks and the spill share a volume.
114  pub fn create(dest: &Path) -> Result<Self> {
115    let parent = if dest.is_dir() {
116      dest
117    } else {
118      dest.parent().unwrap_or_else(|| Path::new("."))
119    };
120    // Pid alone is NOT unique: two concurrent streaming conversions in one
121    // process with destinations in the same parent (in-process test harnesses;
122    // any embedder running conversions on several threads) would share the
123    // directory, and the first store's Drop removes it under the other
124    // (witness: 113_streaming_core's two byte-identity tests under plain
125    // `cargo test`, which shares one process — segment-store write ENOENT).
126    // A process-wide sequence keeps the name self-describing AND unique.
127    static SPILL_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
128    let seq = SPILL_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
129    let dir = parent.join(format!(".latexml-spill-{}-{seq}", std::process::id()));
130    fs::create_dir_all(&dir).map_err(|e| store_error(format!("create {}: {e}", dir.display())))?;
131    let on_exit = crate::watchdog::remove_on_exit(&dir);
132    Ok(SegmentStore {
133      dir,
134      metas: Vec::new(),
135      retired: Vec::new(),
136      _on_exit: on_exit,
137    })
138  }
139
140  /// The spill directory (for disk-headroom checks against its volume).
141  pub fn dir(&self) -> &Path { &self.dir }
142
143  /// Number of segments written so far.
144  pub fn len(&self) -> usize { self.metas.len() }
145
146  /// True when nothing has been spilled.
147  pub fn is_empty(&self) -> bool { self.metas.is_empty() }
148
149  /// The segment ids in spill (= document) order.
150  pub fn ids(&self) -> impl Iterator<Item = SegmentId> {
151    (0..self.metas.len() as u32).map(SegmentId)
152  }
153
154  /// The path of a segment's file (exists only after `write_segment`).
155  pub fn segment_path(&self, id: SegmentId) -> PathBuf {
156    self.dir.join(format!("segment-{:06}.xml", id.0))
157  }
158
159  /// Spill one or more serialized sibling subtrees as a new segment (raw,
160  /// splice-ready text — see the module doc for why no wrapper is written).
161  pub fn write_segment(&mut self, xml: &str, meta: SegmentMeta) -> Result<SegmentId> {
162    let id = SegmentId(self.metas.len() as u32);
163    let path = self.segment_path(id);
164    fs::write(&path, xml).map_err(|e| store_error(format!("write {}: {e}", path.display())))?;
165    self.metas.push(meta);
166    self.retired.push(false);
167    Ok(id)
168  }
169
170  /// The segment's content wrapped for stand-alone PARSING: a `_lxfragment`
171  /// root carrying the namespace declarations recorded at spill time. Built
172  /// in memory — the file itself stays raw and splice-ready.
173  pub fn wrapped_segment(&self, id: SegmentId) -> Result<String> {
174    let meta = self.meta(id)?;
175    let mut out = String::with_capacity(256);
176    out.push('<');
177    out.push_str(SEGMENT_WRAPPER);
178    for (prefix, uri) in &meta.namespaces {
179      if prefix.is_empty() {
180        out.push_str(&format!(" xmlns=\"{uri}\""));
181      } else {
182        out.push_str(&format!(" xmlns:{prefix}=\"{uri}\""));
183      }
184    }
185    out.push('>');
186    out.push_str(&self.read_segment(id)?);
187    out.push_str(&format!("</{SEGMENT_WRAPPER}>"));
188    Ok(out)
189  }
190
191  /// Replace a spilled segment with its processed, splice-ready output text
192  /// (raw — no wrapper; appended verbatim at the placeholder during assembly).
193  pub fn finalize_segment(&mut self, id: SegmentId, output: &str) -> Result<()> {
194    let _ = self.meta(id)?; // reject unknown ids before touching the disk
195    let path = self.segment_path(id);
196    fs::write(&path, output).map_err(|e| store_error(format!("write {}: {e}", path.display())))
197  }
198
199  /// The file's current content, whichever lifecycle stage it is in.
200  pub fn read_segment(&self, id: SegmentId) -> Result<String> {
201    let _ = self.meta(id)?;
202    let path = self.segment_path(id);
203    fs::read_to_string(&path).map_err(|e| store_error(format!("read {}: {e}", path.display())))
204  }
205
206  /// Mark a segment retired: its text was inlined into an enclosing segment,
207  /// so pass 2 skips it and assembly never asks for it. The file is truncated
208  /// (the content lives in the outer segment now).
209  pub fn retire_segment(&mut self, id: SegmentId) -> Result<()> {
210    let _ = self.meta(id)?;
211    self.retired[id.0 as usize] = true;
212    let path = self.segment_path(id);
213    fs::write(&path, "").map_err(|e| store_error(format!("truncate {}: {e}", path.display())))
214  }
215
216  /// Was this segment inlined into an enclosing one?
217  pub fn is_retired(&self, id: SegmentId) -> bool {
218    self.retired.get(id.0 as usize).copied().unwrap_or(false)
219  }
220
221  /// The metadata recorded when the segment was spilled.
222  pub fn meta(&self, id: SegmentId) -> Result<&SegmentMeta> {
223    self
224      .metas
225      .get(id.0 as usize)
226      .ok_or_else(|| store_error(format!("unknown segment {id}")))
227  }
228}
229
230impl Drop for SegmentStore {
231  fn drop(&mut self) {
232    // Best-effort: a failure to clean up must never mask the conversion's own
233    // outcome. After a hard kill the directory simply survives under its
234    // self-describing name.
235    let _ = fs::remove_dir_all(&self.dir);
236  }
237}
238
239fn store_error(details: String) -> Error {
240  Error::from(crate::common::error::ErrorData {
241    target:   ErrorTarget::Internal,
242    category: ErrorCategory::Unexpected,
243    message:  format!("segment-store: {details}"),
244  })
245}
246
247#[cfg(test)]
248mod tests {
249  use super::*;
250
251  fn meta_with_ns() -> SegmentMeta {
252    SegmentMeta {
253      depth:      2,
254      noindent:   false,
255      parent:     None,
256      ancestors:  vec![],
257      anchor:     None,
258      font:       Some(String::from("italic")),
259      namespaces: vec![(
260        String::from("ltx"),
261        String::from("http://dlmf.nist.gov/LaTeXML"),
262      )],
263    }
264  }
265
266  #[test]
267  fn segment_round_trip_and_lifecycle() {
268    let tmp = std::env::temp_dir().join(format!("lxsxml-store-{}", std::process::id()));
269    fs::create_dir_all(&tmp).unwrap();
270    let dest = tmp.join("doc.xml");
271    let mut store = SegmentStore::create(&dest).expect("create store");
272    assert!(store.is_empty());
273
274    // Two sibling subtrees, non-ASCII content, in one segment.
275    let xml = "<ltx:para xml:id=\"p1\"><ltx:p>Gr\u{00fc}\u{00df}e \u{6570}\u{5b66}</ltx:p></ltx:para><ltx:para xml:id=\"p2\"/>";
276    let id = store.write_segment(xml, meta_with_ns()).expect("write");
277    assert_eq!(store.len(), 1);
278
279    // The FILE stays raw and splice-ready; the wrapped form is in-memory.
280    let raw = store.read_segment(id).expect("read");
281    assert_eq!(raw, xml, "file content is exactly the spilled text");
282    let wrapped = store.wrapped_segment(id).expect("wrap");
283    assert!(wrapped.starts_with("<_lxfragment"), "wrapped: {wrapped}");
284    assert!(wrapped.contains("xmlns:ltx=\"http://dlmf.nist.gov/LaTeXML\""));
285    assert!(wrapped.ends_with("</_lxfragment>"));
286    assert!(wrapped.contains("Gr\u{00fc}\u{00df}e \u{6570}\u{5b66}"));
287
288    // Metadata survives.
289    let meta = store.meta(id).expect("meta");
290    assert_eq!(meta.depth, 2);
291    assert_eq!(meta.font.as_deref(), Some("italic"));
292
293    // Processed form replaces the file verbatim, no wrapper.
294    store
295      .finalize_segment(id, "  <final>out</final>\n")
296      .expect("finalize");
297    assert_eq!(store.read_segment(id).unwrap(), "  <final>out</final>\n");
298
299    // Unknown ids are refused, not silently empty (fail toward flagging).
300    assert!(store.read_segment(SegmentId(7)).is_err());
301    assert!(store.finalize_segment(SegmentId(7), "x").is_err());
302
303    // Drop removes the spill dir but never the destination's directory.
304    let spill_dir = store.segment_path(id).parent().unwrap().to_path_buf();
305    drop(store);
306    assert!(!spill_dir.exists(), "spill dir cleaned on drop");
307    assert!(tmp.exists());
308    let _ = fs::remove_dir_all(&tmp);
309  }
310
311  #[test]
312  fn segment_ids_iterate_in_document_order() {
313    let tmp = std::env::temp_dir().join(format!("lxsxml-order-{}", std::process::id()));
314    fs::create_dir_all(&tmp).unwrap();
315    let mut store = SegmentStore::create(&tmp).expect("create store");
316    for k in 0..3 {
317      store
318        .write_segment(&format!("<ltx:p>{k}</ltx:p>"), meta_with_ns())
319        .expect("write");
320    }
321    let order: Vec<u32> = store.ids().map(|s| s.0).collect();
322    assert_eq!(order, vec![0, 1, 2]);
323    drop(store);
324    let _ = fs::remove_dir_all(&tmp);
325  }
326}