//! Filesystem/clock policy for strict native jobs. The token kernel only //! calls SourceProvider; it neither opens files nor asks another TeX engine. use crate::native_generated::{GeneratedInitialState, GeneratedInputPolicy}; use crate::native_host::{HostPreparation, HostPreparationPhase}; use crate::native_stream::{ self, InputOpened, InputStorage, ReleaseCause, StreamEffect, StreamJournal, }; use chrono::{DateTime, Datelike, FixedOffset, Timelike}; use sha2::{Digest, Sha256}; use std::{ cell::RefCell, collections::{BTreeMap, BTreeSet}, ffi::OsStr, fs::{self, File, OpenOptions}, io::{self, BufRead, BufReader, BufWriter, Seek, Write}, path::{Path, PathBuf}, sync::{ Arc, atomic::{AtomicUsize, Ordering}, mpsc, }, time::Duration, }; use texrra_tex_core::artifacts::{ArtifactLedger, file_version}; use texrra_tex_core::execution::{ Cancellation, JobTime, NativeSession, SourceFile, SourceProvider, WriteDestination, }; use texrra_tex_core::resources::{FileWorld, LoadedResource, ResourceKind, ResourceVersion}; pub fn job_time() -> Result { let local = chrono::Local::now().fixed_offset(); let source_date = std::env::var_os("SOURCE_DATE_EPOCH"); let force_utc = std::env::var_os("FORCE_SOURCE_DATE").is_some_and(|value| value == "1"); let pdf_date = match source_date.as_deref() { Some(value) => source_date_epoch(value)?, None => local, }; let registers = if force_utc { pdf_date.to_utc().fixed_offset() } else { local }; // A declared build clock also fixes the random stream, so an independent // full build can replay an editor revision under the same inputs. let seed_clock = if source_date.is_some() { pdf_date } else { local }; let seed = i64::from(seed_clock.timestamp_subsec_micros()) * 1000 + seed_clock.timestamp().rem_euclid(1_000_000); Ok(pdf_clock(registers)? .with_pdf_date(pdf_clock(pdf_date)?) .with_random_seed(seed as i32)) } fn source_date_epoch(value: &OsStr) -> Result, String> { let invalid = || format!("invalid value for SOURCE_DATE_EPOCH: {value:?}"); let value = value.to_str().ok_or_else(invalid)?; if value.is_empty() { return Ok(DateTime::UNIX_EPOCH.fixed_offset()); } let number = value.trim_start_matches(|c: char| c.is_ascii_whitespace()); let digits = number.trim_start_matches(['-', '+']); let sign_len = number.len() - digits.len(); if sign_len > 1 || !digits.bytes().all(|b| b.is_ascii_digit()) { return Err(invalid()); } let magnitude = digits.parse::().map_err(|_| invalid())?; let seconds = if number.starts_with('-') { magnitude.wrapping_neg() } else { magnitude }; DateTime::from_timestamp(seconds as i64, 0) .map(|date| date.fixed_offset()) .ok_or_else(invalid) } fn pdf_clock(time: DateTime) -> Result { let seconds = time.second() as u8; let offset_minutes = (time.offset().local_minus_utc() / 60) as i16; JobTime::new( time.year(), time.month() as i32, time.day() as i32, (time.hour() * 60 + time.minute()) as i32, ) .and_then(|time| time.with_pdf_clock(seconds, offset_minutes)) .map_err(str::to_owned) } pub(crate) fn file_modification_date( world: &mut FileWorld, name: &str, from: &str, ) -> Result, String> { world.file_modification_date(name, Path::new(from), |modified| { let timestamp = DateTime::from_timestamp(modified.unix_seconds, modified.nanoseconds) .ok_or("native file modification time is out of range")?; let force_utc = std::env::var_os("SOURCE_DATE_EPOCH").is_some() && std::env::var_os("FORCE_SOURCE_DATE").is_some_and(|value| value == "1"); let time = if force_utc { timestamp.fixed_offset() } else { timestamp.with_timezone(&chrono::Local).fixed_offset() }; pdf_clock(time)? .pdf_creation_date() .ok_or_else(|| "native file modification date is unavailable".into()) }) } struct Input { handle: u64, reader: Box, path: PathBuf, offset: u64, xe_lookahead: std::collections::VecDeque, } struct Output { handle: u64, path: PathBuf, file: File, accepted: u64, } /// Release ownership explicitly, including on constructor failures. Closing /// one descriptor alone need not release a lock if another process inherited /// that open file description while spawning an unrelated external tool. struct ArtifactLock(File); impl Drop for ArtifactLock { fn drop(&mut self) { let _ = self.0.unlock(); } } pub struct HostPreparationFailure { pub error: String, pub trace: texrra_tex_core::resources::ResourceTrace, pub inputs: std::sync::Arc, } pub(crate) type PreparedInputsCheck<'a> = dyn FnOnce(&FileWorld, &HostPreparation) -> Result<(), String> + 'a; #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) enum EffectMode { Live, Draft, } struct DraftEffects { log: DraftArtifact, generated: BTreeMap, ledger_target: DraftDestination, ledger: Option, pdf: DraftDestination, finished: bool, } struct DraftLedger { file: File, staged: PreparedOutput, } #[derive(PartialEq, Eq)] pub(super) struct ReplayBoundary { entry_bytes: Option, state: ReplayState, } impl ReplayBoundary { /// Ignore only the first entry read's length. The caller authenticates /// that read and checks all later observations of the entry path. pub(super) fn matches_for_suffix(&self, prior: &Self) -> bool { self.entry_bytes.is_some() && prior.entry_bytes.is_some() && self.state == prior.state } pub(super) fn trace_for_suffix(&self) -> &texrra_tex_core::resources::ResourceTrace { &self.state.trace } /// The caller proves that all reads of this canonical path are the /// closed source or its typed size queries, and that none are in the tail. pub(super) fn matches_for_closed_source_suffix( &self, prior: &Self, previous: &ResourceVersion, current: &ResourceVersion, ) -> bool { if self.entry_bytes.is_none() || self.entry_bytes != prior.entry_bytes { return false; } let ReplayState { inputs, outputs, next_handle, columns, terminal_enabled, generated_reads, generated_before, generated_written, trace, stream_events, } = &self.state; let old = &prior.state; if inputs != &old.inputs || outputs != &old.outputs || next_handle != &old.next_handle || columns != &old.columns || terminal_enabled != &old.terminal_enabled || generated_reads != &old.generated_reads || generated_before != &old.generated_before || generated_written != &old.generated_written || stream_events != &old.stream_events { return false; } let mut old_trace = old.trace.clone(); for read in &mut old_trace.reads { if read == previous { *read = current.clone(); } } *trace == old_trace } } #[derive(PartialEq, Eq)] struct ReplayState { inputs: Vec<(u8, u64, PathBuf, u64, std::collections::VecDeque)>, outputs: Vec<(u8, u64, PathBuf, u64)>, next_handle: u64, columns: [usize; 2], terminal_enabled: bool, generated_reads: BTreeMap, generated_before: BTreeMap>, generated_written: BTreeSet, trace: texrra_tex_core::resources::ResourceTrace, stream_events: Vec, } pub struct Files { world: FileWorld, #[cfg(all(target_os = "linux", target_env = "gnu"))] regex_worker: Option, cwd: PathBuf, inputs: BTreeMap, outputs: BTreeMap, next_handle: u64, stream_io: StreamJournal, log_path: PathBuf, log: Option>, draft: Option, protected: Vec, producer: PathBuf, ledger: ArtifactLedger, ledger_path: PathBuf, ledger_input: Option, ledger_current: Option, _ledger_lock: ArtifactLock, generated_reads: BTreeMap, generated_before: BTreeMap>, generated_written: BTreeSet, log_column: usize, terminal_column: usize, terminal_enabled: bool, terminal_sink: bool, preparation: HostPreparation, runtime_observations: RefCell, } fn transcript_writer(file: File, draft: bool) -> BufWriter { // Draft bytes remain private until cleanup and publication. Live jobs // keep reporting actual writes to the transcript during execution. let capacity = if draft { 8192 } else { 0 }; BufWriter::with_capacity(capacity, file) } fn output_column(previous: usize, text: &str) -> usize { match text.rsplit_once('\n') { Some((_, tail)) => tail.chars().count(), None => previous + text.chars().count(), } } fn wrap_inline_diagnostic(mut column: usize, text: &str) -> String { let mut output = String::new(); for c in text.chars() { if c == '\n' { if column != 0 { output.push(c); column = 0; } } else { if column >= 79 { output.push('\n'); column = 0; } output.push(c); column += 1; } } output } impl Files { pub fn new_with_terminal( source: &Path, pdf: &Path, world: FileWorld, terminal: bool, generated_inputs: &GeneratedInputPolicy, preparation: &mut HostPreparation, check_inputs: Option>>, effects: EffectMode, ) -> Result { preparation.phase = HostPreparationPhase::Environment; let state = preparation .environment("TEXRRA_STATE_DIR") .map(PathBuf::from) .filter(|path| !path.as_os_str().is_empty()) .or_else(|| { #[cfg(windows)] { preparation .environment("LOCALAPPDATA") .filter(|path| Path::new(path).is_absolute()) .map(|p| PathBuf::from(p).join("Texrra/artifacts")) } #[cfg(not(windows))] { preparation .environment("XDG_STATE_HOME") .filter(|path| Path::new(path).is_absolute()) .map(|p| PathBuf::from(p).join("texrra/artifacts")) .or_else(|| { preparation .environment("HOME") .filter(|path| Path::new(path).is_absolute()) .map(|p| PathBuf::from(p).join(".local/state/texrra/artifacts")) }) } }) .ok_or_else(|| { "native artifact state directory is unavailable; set TEXRRA_STATE_DIR".to_owned() }); Self::prepare_observed( source, pdf, world, state, terminal, generated_inputs, preparation, check_inputs, effects, ) } #[cfg(test)] fn with_state_dir( source: &Path, pdf: &Path, world: FileWorld, state: &Path, ) -> Result { Self::prepare_observed( source, pdf, world, Ok(state.into()), true, &GeneratedInputPolicy::Live, &mut HostPreparation::default(), None, EffectMode::Live, ) .map_err(|f| f.error) } fn prepare_observed( source: &Path, pdf: &Path, world: FileWorld, state: Result, terminal: bool, generated_inputs: &GeneratedInputPolicy, preparation: &mut HostPreparation, check_inputs: Option>>, effects: EffectMode, ) -> Result { // Keep the world until all fallible preparation has succeeded. Failure // must return its final actual observations rather than an earlier copy. let mut stored_world = Some(world); let result = (|| -> Result { let state = state?; let world = stored_world.as_mut().unwrap(); preparation.phase = HostPreparationPhase::OutputPaths; let cwd = world.trace().cwd.clone(); if world.project().is_some() && preparation.canonicalize(&cwd).ok().as_ref() != Some(&cwd) { return Err( "atomic project workdir must match the real canonical output directory".into(), ); } let pdf = preparation.output(&cwd, pdf)?; let log_path = preparation.output(&cwd, &pdf.with_extension("log"))?; world.check_artifact_output(&pdf)?; world.check_artifact_output(&log_path)?; let existing_log = preparation.canonicalize(&log_path).ok(); let existing_output = preparation.canonicalize(&pdf).ok(); if log_path == source || log_path == pdf || existing_log.as_deref() == Some(source) || existing_log.is_some() && existing_log == existing_output || world.trace().reads.iter().any(|resource| { resource.path == log_path || resource.path == pdf || existing_log.as_ref() == Some(&resource.path) || existing_output.as_ref() == Some(&resource.path) }) || preparation.either_aliases_any( [&log_path, &pdf], world.trace().reads.iter().map(|r| r.path.as_path()), ) || preparation.same_file(source, &log_path) || preparation.same_file(&pdf, &log_path) { return Err("native log output must differ from the input source and PDF".into()); } preparation.phase = HostPreparationPhase::StateDirectory; let state = cwd.join(state); let mut builder = fs::DirBuilder::new(); builder.recursive(true); #[cfg(unix)] { use std::os::unix::fs::DirBuilderExt; builder.mode(0o700); } let created = builder.create(&state); preparation.operation("create state directory", &state, &created); created.map_err(|e| format!("native artifact state directory: {e}"))?; let state = preparation .canonicalize(&state) .map_err(|e| e.to_string())?; preparation.phase = HostPreparationPhase::MetadataPaths; let ledger_path = state.join(format!("{}.json", ArtifactLedger::storage_key(&cwd)?)); let lock_path = ledger_path.with_extension("lock"); let mut protected = vec![ source.to_owned(), pdf.clone(), ledger_path.clone(), lock_path.clone(), ]; protected.extend(world.trace().reads.iter().map(|r| r.path.clone())); if let Some(project) = world.project() { protected.extend(project.immutable_paths().map(Path::to_path_buf)); protected.sort(); protected.dedup(); if preparation.either_aliases_any([&pdf, &log_path], project.immutable_paths()) { return Err("native output would overwrite an atomic project input".into()); } } if [&ledger_path, &lock_path].iter().any(|p| { preparation.same_file(p, source) || preparation.same_file(p, &pdf) || preparation.same_file(p, &log_path) || preparation .aliases_any(p, world.trace().reads.iter().map(|r| r.path.as_path())) }) { return Err( "native artifact metadata must differ from protected inputs and outputs".into(), ); } preparation.phase = HostPreparationPhase::Lock; let opened = OpenOptions::new() .read(true) .write(true) .create(true) .truncate(false) .open(&lock_path); preparation.operation("open lock", &lock_path, &opened); let ledger_lock = opened.map_err(|e| format!("native artifact lock: {e}"))?; let locked = ledger_lock.try_lock(); preparation.operation("acquire lock", &lock_path, &locked); locked.map_err(|e| { format!("native project output is already in use or cannot be locked: {e}") })?; let ledger_lock = ArtifactLock(ledger_lock); preparation.phase = HostPreparationPhase::Ledger; if preparation .metadata(&ledger_path) .is_ok_and(|metadata| metadata.len() > 16 * 1024 * 1024) { return Err("native generated-file ledger capacity exceeded".into()); } let ledger_bytes = preparation.read_ledger(&ledger_path)?; let ledger_input = preparation.ledger.as_ref().and_then(|l| l.version.clone()); let mut ledger = if let Some(bytes) = ledger_bytes { ArtifactLedger::decode(&bytes, &cwd)? } else { ArtifactLedger::new(cwd.clone()) }; preparation.phase = HostPreparationPhase::Protection; let declared: BTreeSet<_> = world .project() .map(|project| project.generated().collect()) .unwrap_or_default(); // The explicit role validates this path immediately before // observing its actual version. Prune only the other claims here. let immutable_claims: Vec<_> = ledger .paths() .filter(|path| !declared.contains(path)) .filter(|path| { preparation.aliases_any( path, protected .iter() .chain(std::iter::once(&log_path)) .map(PathBuf::as_path), ) }) .map(Path::to_owned) .collect(); for path in immutable_claims { ledger.forget(&path); } for path in declared { if preparation.aliases_any( path, protected .iter() .chain(std::iter::once(&log_path)) .map(PathBuf::as_path), ) { return Err("atomic generated role aliases a protected input or output".into()); } let observed = file_version(path); preparation .observations .push(crate::native_host::HostObservation::VersionCheck { path: path.to_owned(), expected: crate::native_host::VersionExpectation::Any, observed: observed.clone(), }); if let Some(version) = observed? { ledger.record(source, version); } } for path in ledger.paths() { world.mark_generated_initial(path)?; } if !matches!(generated_inputs, GeneratedInputPolicy::Live) { preparation.phase = HostPreparationPhase::GeneratedInitial; let expected = match generated_inputs { GeneratedInputPolicy::Expect(state) => { state.validate()?; if state.cwd() != cwd { return Err( "generated initial workdir differs from the actual host".into() ); } if state.files().len() > world.configuration().max_index_entries { return Err("generated initial state capacity exceeded".into()); } Some(state) } _ => None, }; let paths: Vec<_> = world.generated_paths().map(Path::to_path_buf).collect(); if paths.len() > world.configuration().max_index_entries { return Err("generated initial state capacity exceeded".into()); } let mut versions = BTreeMap::new(); for path in paths { let observed = file_version(&path); preparation.observations.push( crate::native_host::HostObservation::VersionCheck { path: path.clone(), expected: expected .and_then(|s| s.files().get(&path)) .map_or(crate::native_host::VersionExpectation::Any, |v| { crate::native_host::VersionExpectation::Exact(v.clone()) }), observed: observed.clone(), }, ); versions.insert(path, observed?); } let actual = GeneratedInitialState::new(cwd.clone(), versions)?; preparation.generated_initial = Some(actual.clone()); if let Some(expected) = expected { expected.check(&actual)?; } } if let Some(check_inputs) = check_inputs { check_inputs(world, preparation)?; } if effects == EffectMode::Draft && (world.project().is_none() || terminal || preparation.generated_initial.is_none()) { return Err( "draft effects require an atomic project, observed generated versions and no terminal sink".into(), ); } preparation.phase = HostPreparationPhase::Log; // An input job really opens a transcript/terminal input entry. Keep // the resulting partial-line state; a later log-only diagnostic must // resume both streams from this actual output, even without message. let entry = format!("({}", source.display()); let opened = if effects == EffectMode::Draft { (|| { let pdf = DraftDestination::capture(&pdf)?; let ledger_target = DraftDestination::capture(&ledger_path)?; if ledger_target.version != ledger_input { return Err("native generated-file ledger changed before drafting".into()); } let target = DraftDestination::capture(&log_path)?; let (staged, file) = PreparedOutput::draft(&log_path)?; Ok(( file, Some(DraftEffects { log: DraftArtifact { target, staged }, generated: BTreeMap::new(), ledger_target, ledger: None, pdf, finished: false, }), )) })() } else { File::create(&log_path) .map(|file| (file, None)) .map_err(|e| format!("native log {}: {e}", log_path.display())) }; preparation.operation("open log", &log_path, &opened); let (mut log, draft) = opened?; let written = log.write_all(entry.as_bytes()); preparation.operation("write log entry", &log_path, &written); written.map_err(|e| e.to_string())?; if terminal { eprint!("{entry}"); } preparation.phase = HostPreparationPhase::Ready; Ok(Self { world: stored_world.take().unwrap(), #[cfg(all(target_os = "linux", target_env = "gnu"))] regex_worker: None, cwd, inputs: BTreeMap::new(), outputs: BTreeMap::new(), next_handle: 0, stream_io: StreamJournal::default(), log_path, log: Some(transcript_writer(log, draft.is_some())), draft, protected, producer: source.to_owned(), ledger, ledger_path, ledger_current: ledger_input.clone(), ledger_input, _ledger_lock: ledger_lock, generated_reads: BTreeMap::new(), generated_before: BTreeMap::new(), generated_written: BTreeSet::new(), log_column: entry.chars().count(), terminal_column: entry.chars().count(), terminal_enabled: true, terminal_sink: terminal, preparation: preparation.clone(), runtime_observations: RefCell::new(HostPreparation::default()), }) })(); result.map_err(|error| { let world = stored_world .as_ref() .expect("world is retained until preparation succeeds"); HostPreparationFailure { error, trace: world.trace().clone(), inputs: world.input_snapshot(), } }) } pub fn preparation(&self) -> &HostPreparation { &self.preparation } pub fn runtime_observations(&self) -> Vec { self.runtime_observations.borrow().observations.clone() } fn observe_version( &self, path: &Path, expected: Option>, ) -> Result, String> { let observed = (|| { let storage = if path == self.ledger_path { self.draft .as_ref() .and_then(|draft| draft.ledger.as_ref()) .map(|ledger| &ledger.staged) } else { None }; if let Some(storage) = storage { return storage.version(path).map(Some); } let mut observed = file_version(self.world.generated_storage(path))?; if let Some(version) = &mut observed { version.path = path.to_owned(); } Ok(observed) })(); self.runtime_observations.borrow_mut().observations.push( crate::native_host::HostObservation::VersionCheck { path: path.into(), expected: expected.map_or( crate::native_host::VersionExpectation::Any, crate::native_host::VersionExpectation::Exact, ), observed: observed.clone(), }, ); observed } fn same_file(&self, a: &Path, b: &Path) -> bool { self.runtime_observations.borrow_mut().same_file(a, b) } fn output(&self, path: &Path) -> Result { self.runtime_observations .borrow_mut() .output(&self.cwd, path) } fn operation(&self, name: &str, path: &Path, result: &Result) { self.runtime_observations .borrow_mut() .operation(name, path, result); } pub(super) fn replay_boundary(&self) -> ReplayBoundary { let mut trace = self.resource_trace().clone(); trace.project_version = None; // The entry scanner verifies source bytes separately. Retain the // first read's path in the comparison and store its length apart, // since later live checkpoints still require exact lengths. let entry_bytes = trace.reads.first_mut().map(|entry| { entry.sha256.clear(); std::mem::take(&mut entry.bytes) }); let mut stream_events = self.stream_io.events().to_vec(); for event in &mut stream_events { if let crate::native_stream::StreamEffect::OutputOpened { descriptor: Ok(identity), .. } = &mut event.effect { // A fresh draft has a different inode. The stream path, // opening version, accepted bytes and handle remain in the journal. identity.unix_identity = None; } } let state = ReplayState { inputs: self.inputs.iter().map(|(&index, input)| { (index, input.handle, input.path.clone(), input.offset, input.xe_lookahead.clone()) }).collect(), outputs: self.outputs.iter().map(|(&index, output)| { (index, output.handle, output.path.clone(), output.accepted) }).collect(), next_handle: self.next_handle, columns: [self.log_column, self.terminal_column], terminal_enabled: self.terminal_enabled, generated_reads: self.generated_reads.clone(), generated_before: self.generated_before.clone(), generated_written: self.generated_written.clone(), trace, stream_events, }; ReplayBoundary { entry_bytes, state } } pub(super) fn replay_world(&self) -> &FileWorld { &self.world } pub(super) fn generated_outputs(&self) -> &BTreeSet { &self.generated_written } pub fn resource_trace(&self) -> &texrra_tex_core::resources::ResourceTrace { self.world.trace() } pub fn write_resource_manifest(&self, name: &Path) -> Result<(), String> { let path = self.output(name)?; self.allow_report_output(&path)?; let generated_artifacts = self.generated_artifacts()?; #[derive(serde::Serialize)] struct Report<'a> { #[serde(flatten)] trace: &'a texrra_tex_core::resources::ResourceTrace, generated_artifacts: crate::native::GeneratedArtifacts, generated_initial: Option<&'a GeneratedInitialState>, stream_io: &'a StreamJournal, } let bytes = serde_json::to_vec_pretty(&Report { trace: self.world.trace(), generated_artifacts, generated_initial: self.preparation.generated_initial.as_ref(), stream_io: &self.stream_io, }) .map_err(|e| e.to_string())?; fs::write(&path, bytes) .map_err(|e| format!("native resource manifest {}: {e}", path.display())) } fn generated_artifacts(&self) -> Result { let mut outputs = Vec::new(); for path in &self.generated_written { outputs.push(crate::native::GeneratedWrite { path: path.clone(), producer: self.producer.clone(), before: self.generated_before[path].clone(), after: self.observe_version(path, None)?, }); } Ok(crate::native::GeneratedArtifacts { schema: 1, ledger_path: self.ledger_path.clone(), ledger_input: self.ledger_input.clone(), ledger_current: self.ledger_current.clone(), writes: outputs, }) } pub fn snapshot(&self) -> Result { Ok(crate::native::ResourceSnapshot { trace: self.world.trace().clone(), generated_artifacts: self.generated_artifacts()?, generated_initial: self.preparation.generated_initial.clone(), stream_io: self.stream_io.clone(), }) } pub fn input_snapshot(&self) -> std::sync::Arc { self.world.input_snapshot() } #[cfg(test)] pub(crate) fn draft_paths(&self) -> BTreeMap { let draft = self.draft.as_ref().expect("draft-mode host"); let mut paths: BTreeMap<_, _> = draft .generated .iter() .map(|(path, draft)| (path.clone(), draft.staged.path.clone())) .collect(); paths.insert(self.log_path.clone(), draft.log.staged.path.clone()); if let Some(ledger) = &draft.ledger { paths.insert(self.ledger_path.clone(), ledger.staged.path.clone()); } paths } pub fn check_layout_manifest_path( &self, layout: &Path, resources: Option<&Path>, ) -> Result<(), String> { let layout = self.output(layout)?; self.allow_output(&layout)?; if let Some(resources) = resources { let resources = self.output(resources)?; if layout == resources { return Err("native layout and resource manifests must use different paths".into()); } } Ok(()) } pub fn write_layout_manifest( &self, name: &Path, execution: &texrra_tex_core::execution::Execution, pages: &[texrra_tex_core::render::DisplayList], source_map: &texrra_tex_core::source_map::SourceMap, ) -> Result<(), String> { use serde_json::json; use texrra_tex_core::execution::Event; use texrra_tex_core::render::{DisplayItem, DisplayUnits}; let path = self.output(name)?; self.allow_report_output(&path)?; let shipouts: Vec<_> = execution .events .iter() .filter_map(|event| match event { Event::Shipout(shipout) => Some(shipout), _ => None, }) .collect(); if pages.len() != shipouts.len() { return Err("native layout requires actual shipout pages".into()); } let mut measured = Vec::with_capacity(pages.len()); for (page, shipout) in pages.iter().zip(shipouts) { if page.units != DisplayUnits::TeX { return Err("native layout requires scaled-point geometry".into()); } let mut glyphs = Vec::new(); let mut rules = Vec::new(); let mut images = Vec::new(); let mut graphics = Vec::new(); let mut paint_order = Vec::new(); for (index, item) in page.items.iter().enumerate() { let shift = page.xdv_horizontal_offset(index); match item { DisplayItem::NativeGlyph { x, y, size, slot, font, .. } => { paint_order.push(json!(["glyph", glyphs.len()])); glyphs.push( json!({"x": x - shift, "y": y, "size": size, "slot": slot, "font": font.name}), ); } DisplayItem::OpenTypeGlyph { x, y, size, glyph, text, font, .. } => { paint_order.push(json!(["glyph", glyphs.len()])); glyphs.push(json!({ "x": x - shift, "y": y, "size": size, "glyph": glyph, "font": font.name, "text": text, "resource": font.resource.version, })); } DisplayItem::Rule { x, y, width, height, } => { paint_order.push(json!(["rule", rules.len()])); rules.push(json!({"x": x - shift, "y": y, "width": width, "height": height})); } DisplayItem::PdfForm { x, y, form } => { paint_order.push(json!(["pdf_form", images.len()])); images.push(json!({"x": x - shift, "y": y, "width": form.width, "height": form.height, "depth": form.depth, "id": form.number})); } DisplayItem::PdfImage { x, y, width, height, image, } => { paint_order.push(json!(["pdf_image", images.len()])); images.push(json!({ "x": x - shift, "y":y, "width":width, "height":height, "id":image.id, "page":image.image.page, "resource":image.image.version, })); } DisplayItem::PdfImageObject(_) | DisplayItem::PdfColor { .. } | DisplayItem::PdfTextSpace { .. } | DisplayItem::OpenTypeActualText(_) | DisplayItem::OpenTypeColor(_) => {} DisplayItem::PdfGraphics { x, y, operation } => { paint_order.push(json!(["pdf_graphics", graphics.len()])); graphics.push(json!({"x": x - shift, "y": y, "operation": operation})); } _ => { return Err("unsupported material in native shipout layout manifest".into()); } } } let mut layout = json!({ "width": page.width, "height": page.height, "magnification": page.magnification, "span": shipout.box_node.span, "glyphs": glyphs, "rules": rules, "paint_order": paint_order, }); if !images.is_empty() { layout["pdf_images"] = json!(images); } if !graphics.is_empty() { layout["pdf_graphics"] = json!(graphics); } if !shipout.specials.is_empty() { layout["specials"] = json!(shipout.specials); } measured.push(layout); } let sources: Vec<_> = execution .sources .iter() .map(|source| &source.name) .collect(); let bytes = serde_json::to_vec_pretty(&json!({ "schema": 1, "units": "tex-sp", "sources": sources, "pages": measured, "source_map": source_map, })) .map_err(|error| error.to_string())?; PreparedOutput::write(&path, &bytes)?.commit(&path) } fn allow_output(&self, path: &Path) -> Result<(), String> { self.world.check_artifact_output(path)?; if self.is_protected(path) { return Err(format!( "native stream output would overwrite job source, PDF or log: {}", path.display() )); } Ok(()) } fn allow_report_output(&self, path: &Path) -> Result<(), String> { self.allow_output(path)?; if self .generated_written .iter() .any(|output| self.same_file(output, path)) { return Err(format!( "native report output collides with a TeX stream: {}", path.display() )); } Ok(()) } fn is_protected(&self, path: &Path) -> bool { self.runtime_observations.borrow_mut().aliases_any( path, self.protected .iter() .chain(std::iter::once(&self.log_path)) .map(PathBuf::as_path), ) } pub(crate) fn read_versioned_source( &mut self, name: &str, from: &str, ) -> Result<(SourceFile, ResourceVersion), String> { let resource = self.world.read_tex_input(name, Path::new(from))?; self.observe_resource(ResourceKind::Tex, &resource); let source = SourceFile { name: resource.version.path.display().to_string(), data: resource.data, }; Ok((source, resource.version)) } fn observe_resource(&mut self, kind: ResourceKind, resource: &LoadedResource) { let path = &resource.version.path; if kind == ResourceKind::Tex && self.ledger.owns(path) && !self.is_protected(path) { self.generated_reads .insert(path.clone(), resource.version.clone()); } else { self.world.protect_resource(resource); let aliases: Vec<_> = self .ledger .paths() .filter(|p| self.same_file(p, path)) .map(Path::to_owned) .collect(); for alias in aliases { self.ledger.forget(&alias); } if !self.protected.contains(path) { self.protected.push(path.clone()); } } } fn persist_ledger(&mut self) -> Result<(), String> { let path = self.ledger_path.clone(); if let Some(draft) = self.draft.as_mut() { draft.ledger_target.verify()?; let bytes = self.ledger.encode()?; let version = Some(ResourceVersion { path: path.clone(), bytes: bytes.len() as u64, sha256: format!("{:x}", Sha256::digest(&bytes)), }); if version == self.ledger_current { return Ok(()); } if version == draft.ledger_target.version { draft.ledger = None; } else { let ledger = match &mut draft.ledger { Some(ledger) => ledger, slot @ None => { let (staged, file) = PreparedOutput::create(&path)?; slot.insert(DraftLedger { file, staged }) } }; // A draft is private until its revision commits. Refresh the // same file for successive closes and sync only its final bytes. ledger .file .rewind() .and_then(|()| ledger.file.write_all(&bytes)) .and_then(|()| ledger.file.set_len(bytes.len() as u64)) .map_err(|error| format!("stage ledger {}: {error}", path.display()))?; } self.ledger_current = version; return Ok(()); } if self.observe_version(&path, Some(self.ledger_current.clone()))? != self.ledger_current { return Err("native generated-file ledger changed during the job".into()); } let staged = PreparedOutput::write(&self.ledger_path, &self.ledger.encode()?); self.operation("stage ledger", &self.ledger_path, &staged); let committed = staged?.commit(&self.ledger_path); self.operation("commit ledger", &self.ledger_path, &committed); committed?; self.ledger_current = self.observe_version(&path, None)?; Ok(()) } fn record_output_version(&mut self, path: &Path) -> Result<(), String> { if !self.is_protected(path) { let version = self .observe_version(path, None)? .ok_or("native generated output disappeared")?; self.ledger.record(&self.producer, version); } self.persist_ledger() } fn open_generated_output( &mut self, path: &Path, before: &Option, ) -> Result { let Some(draft) = self.draft.as_mut() else { return OpenOptions::new() .create(true) .truncate(true) .write(true) .open(path) .map_err(|e| format!("openout {}: {e}", path.display())); }; if let Some(staged) = draft.generated.get(path) { return OpenOptions::new() .truncate(true) .write(true) .open(&staged.staged.path) .map_err(|e| format!("openout {}: {e}", path.display())); } if self.inputs.values().any(|input| input.path == path) { return Err("cannot stage a generated file with a live input handle".into()); } let target = DraftDestination::capture(path)?; if &target.version != before { return Err(format!( "generated output changed before drafting: {}", path.display() )); } let (staged, file) = PreparedOutput::draft(path)?; self.world.mark_live(path); self.world.stage_generated(path, staged.path.clone())?; draft .generated .insert(path.to_owned(), DraftArtifact { target, staged }); Ok(file) } fn handle_id(&mut self) -> u64 { self.next_handle += 1; self.next_handle } fn release_input(&mut self, stream: u8, cause: ReleaseCause, record_missing: bool) { let input = self.inputs.remove(&stream); if input.is_some() || record_missing { let handle = input.as_ref().map(|i| i.handle); let path = input.as_ref().map(|i| i.path.clone()); let consumed = input.as_ref().map(|i| i.offset); drop(input); self.stream_io.push(StreamEffect::CloseInput { stream, handle, path, consumed, cause, }); } } fn release_output(&mut self, stream: u8, output: Option, cause: ReleaseCause) { let handle = output.as_ref().map(|o| o.handle); let path = output.as_ref().map(|o| o.path.clone()); let accepted = output.as_ref().map(|o| o.accepted); drop(output); self.stream_io.push(StreamEffect::ReleaseOutput { stream, handle, path, accepted, cause, }); } fn flush_output(&mut self, stream: u8, cause: ReleaseCause) -> Result<(), String> { let output = self.outputs.get_mut(&stream).unwrap(); let result = output.file.flush().map_err(|e| e.to_string()); self.stream_io.push(StreamEffect::FlushOutput { stream, handle: output.handle, path: output.path.clone(), result: result.clone(), cause, }); result } fn cleanup_boundary(&mut self, cause: ReleaseCause) { self.stream_io.push(StreamEffect::CleanupBoundary { cause, inputs: self.inputs.values().map(|i| i.handle).collect(), outputs: self.outputs.values().map(|o| o.handle).collect(), }); } fn emit_diagnostic( &mut self, destination: WriteDestination, text: &str, start_line: bool, ) -> Result<(), String> { self.emit_diagnostic_bytes(destination, text.as_bytes(), start_line) } fn emit_diagnostic_bytes( &mut self, destination: WriteDestination, bytes: &[u8], start_line: bool, ) -> Result<(), String> { let column = |previous| { let previous = if start_line { 0 } else { previous }; match std::str::from_utf8(bytes) { Ok(text) => output_column(previous, text), Err(_) => bytes.iter().rposition(|&b| b == b'\n') .map_or(previous + bytes.len(), |at| bytes.len() - at - 1), } }; if destination != WriteDestination::TerminalOnly { if self.log.is_none() { let path = self.draft .as_ref() .map_or(&self.log_path, |draft| &draft.log.staged.path); let file = File::create(path) .map_err(|e| format!("native log {}: {e}", self.log_path.display()))?; self.log = Some(transcript_writer(file, self.draft.is_some())); } let log = self.log.as_mut().unwrap(); if start_line && self.log_column != 0 { log.write_all(b"\n").map_err(|e| e.to_string())?; } log.write_all(bytes).map_err(|e| format!("native log: {e}"))?; self.log_column = column(self.log_column); } if self.terminal_sink && self.terminal_enabled && destination != WriteDestination::Log { let mut terminal = io::stderr().lock(); if start_line && self.terminal_column != 0 { terminal.write_all(b"\n").map_err(|e| e.to_string())?; } terminal.write_all(bytes).map_err(|e| e.to_string())?; self.terminal_column = column(self.terminal_column); } Ok(()) } /// Close actual handles and retain partial writes after failure. No normal /// success footer or rollback is invented; cleanup errors remain separate. pub fn finish_failed(&mut self) -> Vec { if let Some(draft) = &mut self.draft { draft.finished = false; } let mut errors = Vec::new(); self.cleanup_boundary(ReleaseCause::FailureCleanup); for stream in self.outputs.keys().copied().collect::>() { if let Err(e) = self.flush_output(stream, ReleaseCause::FailureCleanup) { errors.push(format!("native failed output flush: {e}")); } let output = self.outputs.remove(&stream); self.release_output(stream, output, ReleaseCause::FailureCleanup); } for stream in self.inputs.keys().copied().collect::>() { self.release_input(stream, ReleaseCause::FailureCleanup, false); } if let Some(log) = &mut self.log { if let Err(e) = log.flush() { errors.push(format!("native failed log flush: {e}")); } } for path in self.generated_written.clone() { if !self.is_protected(&path) { match self.observe_version(&path, None) { Ok(Some(version)) => self.ledger.record(&self.producer, version), Ok(None) => errors.push(format!( "native generated output disappeared: {}", path.display() )), Err(e) => errors.push(e), } } } if !self.generated_written.is_empty() { if let Err(e) = self.persist_ledger() { errors.push(e); } } errors } pub fn finish(&mut self) -> Result<(), String> { self.emit_diagnostic(WriteDestination::TerminalAndLog, ")\n", false)?; self.cleanup_boundary(ReleaseCause::Finish); for stream in self.outputs.keys().copied().collect::>() { self.flush_output(stream, ReleaseCause::Finish) .map_err(|e| format!("native output flush: {e}"))?; } for file in self.log.iter_mut() { file.flush() .map_err(|e| format!("native output flush: {e}"))?; } for (stream, output) in std::mem::take(&mut self.outputs) { self.release_output(stream, Some(output), ReleaseCause::Finish); } for stream in self.inputs.keys().copied().collect::>() { self.release_input(stream, ReleaseCause::Finish, false); } if !self.generated_written.is_empty() { for path in self.generated_written.clone() { if !self.is_protected(&path) { let version = self .observe_version(&path, None)? .ok_or("native generated output disappeared")?; self.ledger.record(&self.producer, version); } } self.persist_ledger()?; } if let Some(draft) = &mut self.draft { draft.finished = true; } Ok(()) } pub(crate) fn seal_draft( mut self, pdf: Option, queue: &DraftSyncQueue, cancellation: &Cancellation, ) -> Result, String> { let draft = self.draft.as_ref().ok_or("native draft host required")?; if !draft.finished { return Err("native draft must finish successfully before publication".into()); } let draft = self.draft.take().expect("finished draft"); let log = self.log.take().map(|log| { let (file, buffer) = log.into_parts(); debug_assert!(buffer.is_ok_and(|bytes| bytes.is_empty())); file }); let initial = self .preparation .generated_initial .as_ref() .ok_or("native draft lacks generated initial versions")?; for (path, artifact) in &draft.generated { if initial .files() .get(path) .is_some_and(|v| *v != artifact.target.version) { return Err(format!( "native draft output changed after preparation: {}", path.display() )); } } let untouched = initial .files() .iter() .filter(|(path, _)| !draft.generated.contains_key(*path)) .map(|(path, version)| (path.clone(), version.clone())) .collect::>(); let pending = PendingDraft { draft, log, pdf, untouched, ledger_current: self.ledger_current.clone(), }; // The worker owns private files only. The foreground retains this // host and its project lock until it can publish or has been cancelled. let synced = queue.sync(cancellation, move |stop| pending.sync(stop))?; Ok(synced.map(|synced| DraftPublication { synced, _host: self, })) } } #[derive(Default)] pub(crate) struct DraftSyncQueue { active: Arc, } struct DraftSyncSlot(Arc); impl Drop for DraftSyncSlot { fn drop(&mut self) { self.0.fetch_sub(1, Ordering::AcqRel); } } impl DraftSyncQueue { fn sync( &self, cancellation: &Cancellation, run: impl FnOnce(&Cancellation) -> Result, String> + Send + 'static, ) -> Result, String> { const WAIT: Duration = Duration::from_millis(5); // Allow one obsolete sync to drain while the current draft syncs. // If both calls are still in the OS, wait without starting more. let slot = loop { if cancellation.is_cancelled() { return Ok(None); } let active = self.active.load(Ordering::Acquire); if active < 2 && self .active .compare_exchange(active, active + 1, Ordering::AcqRel, Ordering::Acquire) .is_ok() { break DraftSyncSlot(self.active.clone()); } std::thread::sleep(WAIT); }; let stop = cancellation.clone(); let (send, receive) = mpsc::channel(); std::thread::Builder::new() .name("texrra-draft-sync".into()) .spawn(move || { let _slot = slot; let _ = send.send(run(&stop)); }) .map_err(|error| format!("start native draft sync: {error}"))?; loop { if cancellation.is_cancelled() { return Ok(None); } match receive.recv_timeout(WAIT) { Ok(result) => return result, Err(mpsc::RecvTimeoutError::Timeout) => {} Err(mpsc::RecvTimeoutError::Disconnected) => { return Err("native draft sync worker stopped".into()); } } } } } struct PendingDraft { log: Option, draft: DraftEffects, pdf: Option, untouched: BTreeMap>, ledger_current: Option, } impl PendingDraft { fn sync(self, cancellation: &Cancellation) -> Result, String> { if cancellation.is_cancelled() { return Ok(None); } let Self { draft, log, pdf, untouched, ledger_current, } = self; let mut artifacts: Vec<_> = draft.generated.into_values().collect(); let sync_pdf = || -> Result<(), String> { if let Some(file) = pdf.as_ref().and_then(|pdf| pdf.pending_sync.as_ref()) { file.sync_all().map_err(|error| { format!("sync native draft {}: {error}", draft.pdf.path.display()) })?; } Ok(()) }; let sync_log = || -> Result<(), String> { if let Some(file) = &log { file.sync_all() .map_err(|error| format!("sync native draft log: {error}"))?; } Ok(()) }; let sync_ledger = || -> Result<(), String> { if let Some(ledger) = &draft.ledger && !cancellation.is_cancelled() { ledger.file.sync_all().map_err(|e| { format!("sync native draft ledger {}: {e}", draft.ledger_target.path.display()) })?; } Ok(()) }; // Flush independent files concurrently and collect all results // before the revision gate can install any artifact. std::thread::scope(|scope| { let pdf_worker = pdf .as_ref() .and_then(|pdf| pdf.pending_sync.as_ref()) .and_then(|_| { std::thread::Builder::new() .spawn_scoped(scope, sync_pdf) .ok() }); let log_worker = log.as_ref().and_then(|_| { std::thread::Builder::new() .spawn_scoped(scope, sync_log) .ok() }); let ledger_worker = draft.ledger.as_ref().and_then(|_| { std::thread::Builder::new() .spawn_scoped(scope, sync_ledger) .ok() }); let generated = artifacts.iter().try_for_each(|artifact| { if cancellation.is_cancelled() { return Ok(()); } OpenOptions::new() .write(true) .open(&artifact.staged.path) .and_then(|file| file.sync_all()) .map_err(|error| { format!( "sync native draft {}: {error}", artifact.target.path.display() ) }) }); let pdf_result = pdf_worker.map_or_else(sync_pdf, |worker| { worker .join() .map_err(|_| "native draft PDF sync thread panicked".to_owned())? }); let log_result = log_worker.map_or_else(sync_log, |worker| { worker .join() .map_err(|_| "native draft log sync thread panicked".to_owned())? }); let ledger_result = ledger_worker.map_or_else(sync_ledger, |worker| { worker .join() .map_err(|_| "native draft ledger sync thread panicked".to_owned())? }); pdf_result.and(log_result).and(generated).and(ledger_result) })?; drop(log); if cancellation.is_cancelled() { return Ok(None); } artifacts.push(draft.log); let untouched_ledger = if let Some(DraftLedger { file, staged }) = draft.ledger { // Verify the final staged bytes after the other syncs finish. let target = &draft.ledger_target.path; let actual = fs::symlink_metadata(&staged.path).map_err(|e| e.to_string())?; let descriptor = file.metadata().map_err(|e| e.to_string())?; if !actual.is_file() || DraftFileStamp::from_metadata(&actual).map_err(|e| e.to_string())? != DraftFileStamp::from_metadata(&descriptor).map_err(|e| e.to_string())? || Some(staged.version(target)?) != ledger_current { return Err(format!( "native staged ledger changed: {}", target.display() )); } drop(file); artifacts.push(DraftArtifact { target: draft.ledger_target, staged, }); None } else { Some(draft.ledger_target) }; if let Some(mut staged) = pdf { drop(staged.pending_sync.take()); artifacts.push(DraftArtifact { target: draft.pdf, staged, }); } Ok(Some(SyncedDraft { artifacts, untouched, untouched_ledger, })) } } impl Drop for Files { fn drop(&mut self) { if self.draft.is_some() { // A discarded draft has no reader. Drop pending bytes without // triggering BufWriter's implicit flush on cancellation/rejection. if let Some(log) = self.log.take() { drop(log.into_parts()); } } // Keep the caller's fatal diagnostic on its own physical line when // execution aborts before finish closes the input entry. if self.terminal_sink && self.terminal_column != 0 { eprintln!(); } } } pub(crate) fn absolute_output(cwd: &Path, path: &Path) -> Result { let path = cwd.join(path); if path.exists() { return path.canonicalize().map_err(|e| e.to_string()); } let parent = path .parent() .unwrap_or(cwd) .canonicalize() .map_err(|e| format!("output directory: {e}"))?; Ok(parent.join(path.file_name().ok_or("output requires a filename")?)) } impl Files { fn read_input_line( &mut self, stream: u8, framing: Option, ) -> Result>, String> { let Some(input) = self.inputs.get_mut(&stream) else { let error = "host input stream is not open".to_owned(); self.stream_io.push(StreamEffect::ReadLine { stream, handle: None, consumed_before: None, consumed: std::sync::Arc::from([]), observed_eof: false, delivered: false, error: Some(error.clone()), }); return Err(error); }; let before = input.offset; let transfer = match framing { Some(framing) => native_stream::xe_physical_line( input.reader.as_mut(), &mut input.xe_lookahead, framing, ), None => native_stream::physical_line(input.reader.as_mut()), }; input.offset += transfer.bytes.len() as u64; let error = transfer.error.map(|e| format!("read stream {stream}: {e}")); self.stream_io.push(StreamEffect::ReadLine { stream, handle: Some(input.handle), consumed_before: Some(before), consumed: std::sync::Arc::from(transfer.bytes.clone()), observed_eof: transfer.observed_eof, delivered: error.is_none(), error: error.clone(), }); if let Some(error) = error { self.world.observe_read_error(&input.path, error.clone()); Err(error) } else { let line = (!transfer.bytes.is_empty()).then_some(transfer.bytes); self.world.observe_stream_read(&input.path, before, line.as_deref()); if framing == Some(texrra_tex_core::execution::XeLineFraming::Auto) { // The detection may have inspected bytes in the following // line. Validate those bytes without advancing delivered I/O. let peeked = input.xe_lookahead.make_contiguous(); if !peeked.is_empty() { self.world.observe_stream_read(&input.path, input.offset, Some(peeked)); } if transfer.observed_eof && line.is_some() { self.world.observe_stream_read( &input.path, input.offset + peeked.len() as u64, None, ); } } Ok(line) } } } impl SourceProvider for Files { #[cfg(all(target_os = "linux", target_env = "gnu"))] fn match_pdf_regex( &mut self, request: &texrra_tex_core::execution::RegexRequest, cancellation: Option<&Cancellation>, ) -> Result { use crate::native_regex::{self, Worker}; if !native_regex::enabled() { return texrra_tex_core::execution::match_pdf_regex(request); } if self.regex_worker.is_none() { self.regex_worker = Some(Worker::start()?); } self.regex_worker .as_mut() .expect("native matcher was started") .request(request, cancellation) } fn execution_resource_trace(&self) -> Option<&texrra_tex_core::resources::ResourceTrace> { Some(self.world.trace()) } fn replayed_entry_bytes(&self) -> Option { self.world.trace().reads.first().map(|read| read.bytes) } fn resource_usage( &mut self, ) -> Result, String> { let mut usage = texrra_tex_core::execution::HostResourceUsage::from_trace(self.world.trace()); usage.open_inputs = Some(self.inputs.len()); usage.open_outputs = Some(self.outputs.len()); Ok(Some(usage)) } fn default_pk_resolution(&mut self) -> Result { Ok(self.world.default_pk_resolution()) } fn pk_font(&mut self, name: &str, dpi: u32, from: &str) -> Result { let resource = self.world.read_pk(name, dpi, Path::new(from))?; self.observe_resource(ResourceKind::Pk, &resource); Ok(resource) } fn set_interaction_mode(&mut self, mode: u8) -> Result<(), String> { self.terminal_enabled = mode != 0; Ok(()) } fn observe_error(&mut self, error: &texrra_tex_core::execution::Error) -> Result<(), String> { let text = if error.message_reported { error.context.text.clone() } else { format!("! {}\n{}", error.message, error.context.text) }; self.emit_diagnostic(WriteDestination::TerminalAndLog, &text, true)?; if let Some(help) = &error.help { self.emit_diagnostic(WriteDestination::Log, help, true)?; } Ok(()) } fn observe_diagnostic( &mut self, destination: WriteDestination, text: &str, ) -> Result<(), String> { self.emit_diagnostic(destination, text, true) } fn observe_inline_diagnostic( &mut self, destination: WriteDestination, text: &str, ) -> Result<(), String> { if destination != WriteDestination::TerminalOnly { let text = wrap_inline_diagnostic(self.log_column, text); self.emit_diagnostic(WriteDestination::Log, &text, false)?; } if destination != WriteDestination::Log { let text = wrap_inline_diagnostic(self.terminal_column, text); self.emit_diagnostic(WriteDestination::TerminalOnly, &text, false)?; } Ok(()) } fn observe_raw_diagnostic( &mut self, destination: WriteDestination, text: &str, ) -> Result<(), String> { self.emit_diagnostic(destination, text, false) } fn observe_pseudo_input(&mut self, opening: bool) -> Result<(), String> { if opening { if self.terminal_column > 76 { self.emit_diagnostic(WriteDestination::TerminalAndLog, "\n", false)?; } else if self.terminal_column != 0 || self.log_column != 0 { self.emit_diagnostic(WriteDestination::TerminalAndLog, " ", false)?; } } self.observe_inline_diagnostic( WriteDestination::TerminalAndLog, if opening { "( " } else { ")" }, ) } fn observe_message(&mut self, text: &str) -> Result<(), String> { self.emit_diagnostic(WriteDestination::TerminalAndLog, text, false) } fn observe_message_bytes(&mut self, bytes: &[u8]) -> Result<(), String> { self.emit_diagnostic_bytes(WriteDestination::TerminalAndLog, bytes, false) } fn observe_diagnostic_pair(&mut self, log: &str, terminal: &str) -> Result<(), String> { if self.log_column != 0 || self.terminal_column != 0 { self.emit_diagnostic(WriteDestination::TerminalAndLog, "\n", false)?; } self.emit_diagnostic(WriteDestination::Log, log, false)?; self.emit_diagnostic(WriteDestination::TerminalOnly, terminal, false) } fn read(&mut self, name: &str, from: &str) -> Result { self.read_versioned_source(name, from).map(|(source, _)| source) } fn resource( &mut self, kind: ResourceKind, name: &str, from: &str, ) -> Result { let resource = self.world.read(kind, name, Path::new(from))?; self.observe_resource(kind, &resource); Ok(resource) } fn resource_with_lookup_path( &mut self, kind: ResourceKind, name: &str, from: &str, ) -> Result<(LoadedResource, PathBuf), String> { let (resource, path) = self.world.read_with_lookup_path(kind, name, Path::new(from))?; self.observe_resource(kind, &resource); Ok((resource, path)) } fn virtual_font(&mut self, name: &str, from: &str) -> Result, String> { let resource = self .world .read_optional(ResourceKind::Vf, name, Path::new(from))?; if let Some(resource) = &resource { self.observe_resource(ResourceKind::Vf, resource); } Ok(resource) } fn named_font( &mut self, name: &str, style: texrra_tex_core::resources::FontStyle, from: &str, ) -> Result, String> { self.named_font_with_size(name, style, None, from) } fn named_font_with_size( &mut self, name: &str, style: texrra_tex_core::resources::FontStyle, optical_points: Option, from: &str, ) -> Result, String> { let selected = self.world.read_named_font_with_size(name, style, optical_points, Path::new(from))?; if let Some(font) = &selected { let kind = match font.resource.version.path.extension().and_then(|ext| ext.to_str()) { Some(ext) if ext.eq_ignore_ascii_case("ttf") || ext.eq_ignore_ascii_case("ttc") => ResourceKind::TrueType, _ => ResourceKind::OpenType, }; self.observe_resource(kind, &font.resource); } Ok(selected) } fn pdf_truetype( &mut self, name: &str, from: &str, ) -> Result, String> { let selected = self.world.read_pdf_truetype(name, Path::new(from))?; if let Some(font) = &selected { self.observe_resource(ResourceKind::TrueType, &font.resource); } Ok(selected) } fn pdf_cff( &mut self, name: &str, from: &str, cid_keyed: bool, ) -> Result, String> { let selected = self.world.read_pdf_cff(name, Path::new(from), cid_keyed)?; if let Some(font) = &selected { self.observe_resource(ResourceKind::OpenType, &font.resource); } Ok(selected) } fn optional_font_file(&mut self, kind: ResourceKind, name: &str, from: &str) -> Result, String> { let resource = self.world.read_optional(kind, name, Path::new(from))?; if let Some(resource) = &resource { self.observe_resource(kind, resource); } Ok(resource) } fn optional_font_map(&mut self, name: &str, from: &str) -> Result, String> { let kind = ResourceKind::Map; let resource = self.world.read_optional(kind, name, Path::new(from))?; if let Some(resource) = &resource { self.observe_resource(kind, resource); } Ok(resource) } fn optional_tex_input( &mut self, name: &str, from: &str, ) -> Result, String> { let resource = self.world.read_tex_input_optional(name, Path::new(from))?; if let Some(resource) = &resource { self.observe_resource(ResourceKind::Tex, resource); } Ok(resource) } fn file_size(&mut self, name: &str, from: &str) -> Result, String> { Ok(self .optional_tex_input(name, from)? .map(|resource| resource.version.bytes)) } fn file_modification_date(&mut self, name: &str, from: &str) -> Result, String> { file_modification_date(&mut self.world, name, from) } fn open_in(&mut self, stream: u8, name: &str, from: &str) -> Result, String> { self.release_input(stream, ReleaseCause::Replaced, false); let result = (|| -> Result, String> { let Some(path) = self.world.resolve_tex_input(name, Path::new(from))? else { return Ok(None); }; let (reader, storage): (Box, InputStorage) = if let Some(snapshot) = self.world.stream_snapshot(&path)? { ( Box::new(io::Cursor::new(snapshot.data)), InputStorage::Snapshot(snapshot.version), ) } else { let file = File::open(self.world.generated_storage(&path)).map_err(|e| { let error = format!("openin {}: {e}", path.display()); self.world.observe_read_error(&path, error.clone()); error })?; let identity = native_stream::descriptor(&file); (Box::new(BufReader::new(file)), InputStorage::File(identity)) }; let handle = self.handle_id(); let opened = InputOpened { handle, path: path.clone(), storage, }; self.inputs.insert( stream, Input { handle, reader, path, offset: 0, xe_lookahead: Default::default(), }, ); Ok(Some(opened)) })(); self.stream_io.push(StreamEffect::OpenInput { stream, name: name.into(), from: from.into(), result: result.clone(), }); result.map(|opened| opened.map(|o| o.path.display().to_string())) } fn read_line(&mut self, stream: u8) -> Result>, String> { self.read_input_line(stream, None) } fn read_xe_line( &mut self, stream: u8, framing: texrra_tex_core::execution::XeLineFraming, ) -> Result>, String> { self.read_input_line(stream, Some(framing)) } fn close_in(&mut self, stream: u8) -> Result<(), String> { self.release_input(stream, ReleaseCause::Explicit, true); Ok(()) } fn open_out(&mut self, stream: u8, name: &str, from: &str) -> Result { self.stream_io.push(StreamEffect::OpenOutputRequested { stream, name: name.into(), from: from.into(), }); let mut opened_handle = None; let result = (|| { let mut path = self.cwd.join(name); if path.extension().is_none() { path.set_extension("tex"); } let logical = path; let target = self.world.generated_output_path(&logical); if self.world.project().is_some() { self.runtime_observations.borrow_mut().observations.push( crate::native_host::HostObservation::LogicalGeneratedPath { logical: logical.clone(), resolved: target.clone(), }, ); } let path = self.output(&target?)?; self.world.check_generated_output(&logical, &path)?; self.allow_output(&path)?; let expected = self.generated_reads.get(&path).cloned().map(Some); let before = self.observe_version(&path, expected)?; if self .generated_reads .get(&path) .is_some_and(|read| Some(read) != before.as_ref()) { return Err(format!( "native generated input changed after it was read: {}", path.display() )); } let opened = self.open_generated_output(&path, &before); self.operation("open output", &path, &opened); let file = opened?; let handle = self.handle_id(); opened_handle = Some(handle); self.stream_io.push(StreamEffect::OutputOpened { stream, handle, path: path.clone(), before: before.clone(), descriptor: native_stream::descriptor(&file), }); self.world.invalidate_directories(); self.world.mark_live(&path); self.generated_before.entry(path.clone()).or_insert(before); self.generated_written.insert(path.clone()); self.generated_reads.remove(&path); let new_claim = !self.ledger.owns(&path); let replaced = self.outputs.insert( stream, Output { handle, path: path.clone(), file, accepted: 0, }, ); if replaced.is_some() { self.release_output(stream, replaced, ReleaseCause::Replaced); } // Claim only after a real successful open/truncate. Persist new claims // even if a subsequent TeX error aborts, so recovery can reuse its files. if new_claim { self.record_output_version(&path)?; } Ok(path.display().to_string()) })(); self.stream_io.push(StreamEffect::OpenOutputResult { stream, opened: opened_handle, result: result.clone(), }); result } fn write_out(&mut self, stream: u8, text: &str) -> Result<(), String> { self.write_out_bytes(stream, text.as_bytes()) } fn write_out_bytes(&mut self, stream: u8, bytes: &[u8]) -> Result<(), String> { let Some(output) = self.outputs.get_mut(&stream) else { let error = "host output stream is not open".to_owned(); self.stream_io.push(StreamEffect::Write { stream, handle: None, accepted_before: None, requested: std::sync::Arc::from(bytes), accepted: 0, attempts: Vec::new(), error: Some(error.clone()), }); return Err(error); }; let before = output.accepted; let transfer = native_stream::write_all(&mut output.file, bytes); output.accepted += transfer.accepted as u64; let error = transfer .error .map(|e| format!("write stream {stream}: {e}")); self.stream_io.push(StreamEffect::Write { stream, handle: Some(output.handle), accepted_before: Some(before), requested: std::sync::Arc::from(bytes), accepted: transfer.accepted as u64, attempts: transfer.attempts, error: error.clone(), }); if let Some(error) = error { Err(error) } else { self.generated_reads.remove(&output.path); Ok(()) } } fn close_out(&mut self, stream: u8) -> Result<(), String> { let result = (|| { if let Some(mut output) = self.outputs.remove(&stream) { let flushed = output.file.flush().map_err(|e| e.to_string()); self.stream_io.push(StreamEffect::FlushOutput { stream, handle: output.handle, path: output.path.clone(), result: flushed.clone(), cause: ReleaseCause::Explicit, }); let path = output.path.clone(); self.release_output(stream, Some(output), ReleaseCause::Explicit); flushed.map_err(|e| format!("closeout {stream}: {e}"))?; self.record_output_version(&path)?; } else { self.release_output(stream, None, ReleaseCause::Explicit); } Ok(()) })(); self.stream_io.push(StreamEffect::CloseOutputResult { stream, result: result.clone(), }); result } fn diagnostic(&mut self, destination: WriteDestination, text: &str) -> Result<(), String> { self.emit_diagnostic(destination, text, true) } fn diagnostic_bytes(&mut self, destination: WriteDestination, bytes: &[u8]) -> Result<(), String> { self.emit_diagnostic_bytes(destination, bytes, true) } } #[derive(PartialEq, Eq)] struct DraftFileStamp { bytes: u64, modified: std::time::SystemTime, readonly: bool, #[cfg(unix)] identity: (u64, u64, u32), } impl DraftFileStamp { fn from_metadata(metadata: &fs::Metadata) -> io::Result { Ok(Self { bytes: metadata.len(), modified: metadata.modified()?, readonly: metadata.permissions().readonly(), #[cfg(unix)] identity: { use std::os::unix::fs::MetadataExt; (metadata.dev(), metadata.ino(), metadata.mode()) }, }) } } #[derive(PartialEq, Eq)] struct DraftDestination { path: PathBuf, parent: PathBuf, #[cfg(unix)] parent_identity: (u64, u64), stamp: Option, version: Option, } impl DraftDestination { fn capture(path: &Path) -> Result { let metadata = (|| -> io::Result<_> { let parent = path .parent() .ok_or(io::ErrorKind::InvalidInput)? .canonicalize()?; let target = match fs::symlink_metadata(path) { Ok(metadata) => Some(metadata), Err(e) if e.kind() == io::ErrorKind::NotFound => None, Err(e) => return Err(e), }; if let Some(metadata) = &target { if !metadata.is_file() { return Err(io::Error::other("target is not a regular file")); } #[cfg(unix)] { use std::os::unix::fs::MetadataExt; if metadata.nlink() != 1 { return Err(io::Error::other("target has file aliases")); } } } let stamp = target .as_ref() .map(DraftFileStamp::from_metadata) .transpose()?; Ok((parent, stamp)) })(); let (parent, stamp) = metadata.map_err(|e| format!("native draft target {}: {e}", path.display()))?; let version = file_version(path)?; if stamp.as_ref().map(|stamp| stamp.bytes) != version.as_ref().map(|version| version.bytes) { return Err(format!( "native draft target changed during inspection: {}", path.display() )); } #[cfg(unix)] let parent_identity = { use std::os::unix::fs::MetadataExt; let metadata = fs::metadata(&parent) .map_err(|e| format!("native draft directory {}: {e}", parent.display()))?; (metadata.dev(), metadata.ino()) }; Ok(Self { path: path.to_owned(), parent, stamp, version, #[cfg(unix)] parent_identity, }) } fn verify(&self) -> Result<(), String> { if *self == Self::capture(&self.path)? { return Ok(()); } Err(format!( "native draft destination changed: {}", self.path.display() )) } } struct DraftArtifact { target: DraftDestination, staged: PreparedOutput, } struct SyncedDraft { artifacts: Vec, untouched: BTreeMap>, untouched_ledger: Option, } pub(crate) struct DraftPublication { synced: SyncedDraft, // The native project lock covers validation, installation and rollback. _host: Files, } impl DraftPublication { /// Install host effects and expose the completed document under one /// session revision gate. The callback must not call the session. pub(crate) fn publish_current( self, session: &NativeSession, revision: u64, expose_document: impl FnOnce() -> T, ) -> Result, String> { let Self { synced: SyncedDraft { artifacts, untouched, untouched_ledger, }, _host, } = self; session.publish_current(revision, || { if let Some(ledger) = untouched_ledger { ledger.verify()?; } for (path, expected) in untouched { if DraftDestination::capture(&path)?.version != expected { return Err(format!("native draft input changed: {}", path.display())); } } install_draft( artifacts .into_iter() .map(DraftInstall::prepare) .collect::, _>>()?, )?; Ok(expose_document()) }) } } struct DraftInstall { artifact: DraftArtifact, installed: DraftFileStamp, backup: Option, } impl DraftInstall { fn prepare(artifact: DraftArtifact) -> Result { artifact.target.verify()?; let metadata = fs::symlink_metadata(&artifact.staged.path) .map_err(|e| format!("inspect staged {}: {e}", artifact.target.path.display()))?; if !metadata.is_file() { return Err(format!( "native staged output must be a regular file: {}", artifact.target.path.display() )); } let installed = DraftFileStamp::from_metadata(&metadata).map_err(|e| e.to_string())?; let backup = artifact .target .stamp .as_ref() .map(|_| PreparedOutput::backup(&artifact.target.path)) .transpose()?; Ok(Self { artifact, installed, backup, }) } } fn install_draft(installs: Vec) -> Result<(), String> { let mut applied: Vec<(PathBuf, DraftFileStamp, Option)> = Vec::new(); for DraftInstall { mut artifact, installed, backup, } in installs { let path = artifact.target.path; let result = match &backup { Some(_) => artifact.staged.replace(&path), None => artifact.staged.link(&path), }; if let Err(mut error) = result { while let Some((path, installed, backup)) = applied.pop() { if let Err(rollback) = restore_draft(&path, installed, backup) { error.push_str(&format!("; native draft rollback: {rollback}")); } } return Err(error); } applied.push((path, installed, backup)); } Ok(()) } fn restore_draft( path: &Path, installed: DraftFileStamp, mut backup: Option, ) -> Result<(), String> { let restore = (|| -> io::Result<()> { let metadata = fs::symlink_metadata(path)?; if !metadata.is_file() || DraftFileStamp::from_metadata(&metadata)? != installed { return Err(io::Error::other("installed file changed")); } match &backup { Some(backup) => fs::rename(&backup.path, path), None => fs::remove_file(path), } })(); if let Err(error) = restore { if let Some(backup) = &mut backup { let recovery = std::mem::take(&mut backup.path); return Err(format!( "{}: {error}; previous file retained at {}", path.display(), recovery.display() )); } return Err(format!("{}: {error}", path.display())); } if let Some(backup) = &mut backup { backup.path.clear(); } Ok(()) } /// Write complete bytes before publishing the output path. pub struct PreparedOutput { path: PathBuf, pending_sync: Option, } impl PreparedOutput { pub fn version(&self, destination: &Path) -> Result { let mut version = file_version(&self.path)?.ok_or("staged native output disappeared")?; version.path = destination.to_owned(); Ok(version) } pub fn write(output: &Path, bytes: &[u8]) -> Result { Self::write_with(output, |file| { file.write_all(bytes).map_err(|error| error.to_string()) }) } pub(crate) fn write_with( output: &Path, write: impl FnOnce(&mut File) -> Result<(), String>, ) -> Result { let (prepared, file) = Self::write_staged(output, write)?; let synced = file.sync_all(); drop(file); synced.map_err(|error| format!("stage output {}: {error}", output.display()))?; Ok(prepared) } pub(crate) fn write_for_draft(output: &Path, bytes: &[u8]) -> Result { let (mut prepared, file) = Self::write_staged(output, |file| { file.write_all(bytes).map_err(|error| error.to_string()) })?; prepared.pending_sync = Some(file); Ok(prepared) } fn write_staged( output: &Path, write: impl FnOnce(&mut File) -> Result<(), String>, ) -> Result<(Self, File), String> { let (prepared, mut file) = Self::create(output)?; write(&mut file).map_err(|error| format!("stage output {}: {error}", output.display()))?; Ok((prepared, file)) } fn draft(output: &Path) -> Result<(Self, File), String> { let existing = match fs::symlink_metadata(output) { Ok(metadata) => { if !metadata.is_file() { return Err(format!( "native draft needs a regular file: {}", output.display() )); } #[cfg(unix)] { use std::os::unix::fs::MetadataExt; if metadata.nlink() != 1 { return Err(format!( "native draft target has aliases: {}", output.display() )); } } OpenOptions::new() .write(true) .open(output) .map_err(|e| format!("native draft target {}: {e}", output.display()))?; Some(metadata.permissions()) } Err(e) if e.kind() == io::ErrorKind::NotFound => None, Err(e) => return Err(format!("native draft target {}: {e}", output.display())), }; let (prepared, file) = Self::create(output)?; if let Some(permissions) = existing { file.set_permissions(permissions) .map_err(|e| e.to_string())?; } Ok((prepared, file)) } fn create(output: &Path) -> Result<(Self, File), String> { Self::allocate(output, |path| { fs::OpenOptions::new() .write(true) .create_new(true) .open(path) }) } fn backup(output: &Path) -> Result { Self::allocate(output, |path| fs::hard_link(output, path)).map(|(backup, ())| backup) } fn allocate( output: &Path, create: impl Fn(&Path) -> io::Result, ) -> Result<(Self, T), String> { use std::sync::atomic::{AtomicU64, Ordering}; static NEXT: AtomicU64 = AtomicU64::new(0); for _ in 0..16 { let id = NEXT.fetch_add(1, Ordering::Relaxed); let path = output.with_file_name(format!(".texrra-{}-{id}.tmp", std::process::id())); if path != output { match create(&path) { Ok(value) => { return Ok(( Self { path, pending_sync: None, }, value, )); } Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, Err(error) => { return Err(format!("stage output {}: {error}", output.display())); } } } } Err(format!("could not stage output {}", output.display())) } /// Publish a new format without replacing an existing path. pub fn commit_new(self, output: &Path) -> Result<(), String> { self.link(output) } fn link(&self, output: &Path) -> Result<(), String> { fs::hard_link(&self.path, output) .map_err(|error| format!("output {}: {error}", output.display())) } pub fn commit(mut self, output: &Path) -> Result<(), String> { self.replace(output) } fn replace(&mut self, output: &Path) -> Result<(), String> { fs::rename(&self.path, output) .map_err(|error| format!("output {}: {error}", output.display()))?; self.path.clear(); Ok(()) } } impl Drop for PreparedOutput { fn drop(&mut self) { drop(self.pending_sync.take()); if !self.path.as_os_str().is_empty() { let _ = fs::remove_file(&self.path); } } } #[cfg(test)] mod generated_file_tests { use super::*; use std::sync::atomic::{AtomicU64, Ordering}; use texrra_tex_core::resources::WorldConfig; fn root() -> PathBuf { static NEXT: AtomicU64 = AtomicU64::new(0); let path = std::env::temp_dir().join(format!( "texrra-generated-host-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed) )); fs::create_dir_all(&path).unwrap(); fs::write(path.join("main.tex"), b"\\end").unwrap(); path } fn files(root: &Path, entry: &str) -> Result { let mut world = FileWorld::new(WorldConfig::new(root))?; let source = world.read(ResourceKind::Tex, entry, root)?.version.path; Files::with_state_dir(&source, &root.join("job.pdf"), world, &root.join("policy")) } fn write(files: &mut Files, name: &str, bytes: &str) { files.open_out(0, name, "").unwrap(); files.write_out(0, bytes).unwrap(); files.close_out(0).unwrap(); } #[test] fn draft_ledger_coalesces_closes_and_checks_the_last_physical_bytes() { use std::sync::Arc; use texrra_tex_core::resources::{ProjectDefinition, ProjectSnapshot}; let root = root(); let source = root.join("main.tex"); let generated = root.join("actual.aux"); let ledger_path = { let mut live = files(&root, "main.tex").unwrap(); write(&mut live, "actual.aux", "original"); live.finish().unwrap(); live.ledger_path.clone() }; let original_ledger = fs::read(&ledger_path).unwrap(); let original_version = file_version(&ledger_path).unwrap(); let project = ProjectSnapshot::new(ProjectDefinition { configuration: WorldConfig::new(&root), revision: 1, roots: BTreeSet::from([root.clone()]), files: BTreeMap::from([(source.clone(), Arc::from(b"\\end".as_slice()))]), directories: BTreeSet::new(), aliases: BTreeMap::new(), generated_roots: BTreeSet::from([root.clone()]), generated: BTreeSet::from([generated.clone()]), }) .unwrap(); let draft = || { Files::prepare_observed( &source, &root.join("job.pdf"), FileWorld::from_project(project.clone()).unwrap(), Ok(root.join("policy")), false, &GeneratedInputPolicy::Observe, &mut HostPreparation::default(), None, EffectMode::Draft, ) .unwrap_or_else(|failure| panic!("{}", failure.error)) }; let mut host = draft(); write(&mut host, "actual.aux", "original"); assert!(!host.draft_paths().contains_key(&ledger_path)); write(&mut host, "actual.aux", "new digest"); let staged = host.draft_paths()[&ledger_path].clone(); let written = fs::read(&staged).unwrap(); assert_ne!(written, original_ledger); write(&mut host, "actual.aux", "new digest"); assert_eq!(host.draft_paths()[&ledger_path], staged); assert_eq!(fs::read(&staged).unwrap(), written); write(&mut host, "actual.aux", "different digest"); assert_eq!(host.draft_paths()[&ledger_path], staged); assert_ne!(fs::read(&staged).unwrap(), written); assert_eq!( host.observe_version(&ledger_path, None).unwrap(), host.ledger_current ); write(&mut host, "actual.aux", "original"); assert!(!staged.exists()); assert!(!host.draft_paths().contains_key(&ledger_path)); host.finish().unwrap(); let queue = DraftSyncQueue::default(); let cancellation = Cancellation::default(); let sealed = host .seal_draft(None, &queue, &cancellation) .unwrap() .unwrap(); assert_eq!( sealed.synced.untouched_ledger.as_ref().unwrap().version, original_version ); let permissions = fs::metadata(&ledger_path).unwrap().permissions(); let mut restricted = permissions.clone(); restricted.set_readonly(true); fs::set_permissions(&ledger_path, restricted).unwrap(); let session = NativeSession::default(); let job = session.start(); let revision = job.revision(); job.run_detailed( texrra_tex_core::execution::Executor::new( texrra_tex_core::execution::State::initex(), texrra_tex_core::execution::Limits::default(), ), SourceFile { name: "empty.tex".into(), data: b"\\end".to_vec(), }, &mut texrra_tex_core::execution::NoFiles, ) .unwrap(); let failure = sealed .publish_current(&session, revision, || -> () { panic!("exposed with changed metadata") }) .unwrap_err(); assert!( failure.contains("native draft destination changed"), "{failure}" ); fs::set_permissions(&ledger_path, permissions).unwrap(); let mut host = draft(); write(&mut host, "actual.aux", "changed"); host.finish().unwrap(); let staged = host.draft_paths()[&ledger_path].clone(); let size = fs::metadata(&staged).unwrap().len() as usize; fs::write(&staged, vec![b'x'; size]).unwrap(); let error = host.seal_draft(None, &queue, &cancellation).err().unwrap(); assert!(error.contains("native staged ledger changed"), "{error}"); assert!(!staged.exists()); assert_eq!(fs::read(&ledger_path).unwrap(), original_ledger); assert_eq!(fs::read(&generated).unwrap(), b"original"); #[cfg(unix)] { let output = root.join("job.pdf"); let log = root.join("job.log"); fs::write(&output, b"already published PDF").unwrap(); let original_log = fs::read(&log).unwrap(); let mut host = draft(); write(&mut host, "actual.aux", "another draft"); host.finish().unwrap(); let mut pdf = PreparedOutput::write_for_draft(&output, b"new PDF").unwrap(); let path = pdf.path.clone(); pdf.pending_sync = Some(File::open("/dev/null").unwrap()); let error = host .seal_draft(Some(pdf), &queue, &cancellation) .err() .unwrap(); assert!( error.contains("sync native draft") && error.contains("job.pdf"), "{error}" ); assert!(!path.exists()); assert_eq!(fs::read(&output).unwrap(), b"already published PDF"); assert_eq!(fs::read(&log).unwrap(), original_log); assert_eq!(fs::read(&generated).unwrap(), b"original"); assert_eq!(fs::read(&ledger_path).unwrap(), original_ledger); } fs::remove_dir_all(root).unwrap(); } #[test] fn cancelled_draft_sync_releases_the_job_before_private_io_completes() { let queue = Arc::new(DraftSyncQueue::default()); let cancelled = Cancellation::default(); let (entered, entry) = mpsc::channel(); let (release, held) = mpsc::channel(); let (returned, result) = mpsc::channel(); let (completed, drained) = mpsc::channel(); let old = std::thread::spawn({ let queue = queue.clone(); let cancelled = cancelled.clone(); move || { let sealed = queue.sync(&cancelled, move |_| { entered.send(()).unwrap(); held.recv_timeout(Duration::from_secs(5)).unwrap(); completed.send(()).unwrap(); Ok(None) }); returned.send(sealed).unwrap(); } }); entry.recv_timeout(Duration::from_secs(3)).unwrap(); cancelled.cancel(); assert!( result .recv_timeout(Duration::from_secs(1)) .unwrap() .unwrap() .is_none() ); old.join().unwrap(); assert_eq!(queue.active.load(Ordering::Acquire), 1); queue .sync(&Cancellation::default(), { let queue = queue.clone(); move |_| { assert_eq!(queue.active.load(Ordering::Acquire), 2); Ok(None) } }) .unwrap(); assert!(matches!(drained.try_recv(), Err(mpsc::TryRecvError::Empty))); release.send(()).unwrap(); drained.recv_timeout(Duration::from_secs(3)).unwrap(); } #[test] fn stream_journal_distinguishes_pinned_bytes_live_handles_replacement_and_finish() { let root = root(); fs::write(root.join("fixed.dat"), b"PINNED\r\nTAIL").unwrap(); let mut host = files(&root, "main.tex").unwrap(); host.world.capture_inputs(); host.open_in(2, "fixed.dat", "").unwrap().unwrap(); fs::write(root.join("fixed.dat"), b"PHYSICAL CHANGE").unwrap(); assert_eq!(host.read_line(2).unwrap().unwrap(), b"PINNED\r\n"); assert_eq!(host.read_line(2).unwrap().unwrap(), b"TAIL"); assert_eq!(host.read_line(2).unwrap(), None); host.open_out(1, "first.dat", "").unwrap(); host.write_out(1, "FIRST\r\nTAIL").unwrap(); host.open_in(3, "first.dat", "").unwrap().unwrap(); assert_eq!(host.read_line(3).unwrap().unwrap(), b"FIRST\r\n"); // A rejected replacement must retain the previous real output handle. assert!(host.open_out(1, "main.tex", "").is_err()); host.write_out(1, "!").unwrap(); host.open_out(1, "second.dat", "").unwrap(); host.write_out(1, "SECOND").unwrap(); // Input replacement releases its old handle even when lookup is absent. assert_eq!(host.open_in(2, "missing.dat", "").unwrap(), None); host.close_in(2).unwrap(); host.finish().unwrap(); assert_eq!(fs::read(root.join("first.dat")).unwrap(), b"FIRST\r\nTAIL!"); assert_eq!(fs::read(root.join("second.dat")).unwrap(), b"SECOND"); let events = host.stream_io.events(); assert!( events .iter() .enumerate() .all(|(i, e)| e.sequence == i as u64 + 1) ); let input_ids: Vec<_> = events .iter() .filter_map(|e| match &e.effect { StreamEffect::OpenInput { result: Ok(Some(i)), .. } => Some(i), _ => None, }) .collect(); assert_eq!(input_ids.len(), 2); assert!(matches!(&input_ids[0].storage, InputStorage::Snapshot(v) if v.bytes == 12)); assert!( matches!(&input_ids[1].storage, InputStorage::File(Ok(d)) if d.regular_file && d.bytes == 11) ); let output_ids: Vec<_> = events .iter() .filter_map(|e| match &e.effect { StreamEffect::OutputOpened { handle, .. } => Some(*handle), _ => None, }) .collect(); assert_eq!(output_ids.len(), 2); let ids: std::collections::BTreeSet<_> = input_ids .iter() .map(|i| i.handle) .chain(output_ids.iter().copied()) .collect(); assert_eq!(ids.len(), 4); let replaced = events.iter().position(|e| matches!(e.effect, StreamEffect::ReleaseOutput {handle: Some(h), cause: ReleaseCause::Replaced, accepted: Some(12), ..} if h == output_ids[0])).unwrap(); let second_open = events.iter().position(|e| matches!(e.effect, StreamEffect::OutputOpened {handle, ..} if handle == output_ids[1])).unwrap(); assert!(second_open < replaced); assert!(events.iter().any(|e| matches!( &e.effect, StreamEffect::OpenOutputResult { opened: None, result: Err(_), .. } ))); assert!(events.iter().any(|e| matches!(&e.effect, StreamEffect::CleanupBoundary {cause: ReleaseCause::Finish, inputs, outputs} if inputs == &[input_ids[1].handle] && outputs == &[output_ids[1]]))); assert!(host.inputs.is_empty() && host.outputs.is_empty()); drop(host); fs::remove_dir_all(root).unwrap(); } #[cfg(unix)] #[test] fn stream_read_error_records_consumption_without_claiming_delivery() { use std::{io::Write, os::unix::net::UnixStream}; let root = root(); let mut host = files(&root, "main.tex").unwrap(); let (reader, mut writer) = UnixStream::pair().unwrap(); reader.set_nonblocking(true).unwrap(); writer.write_all(b"PART\r").unwrap(); let handle = host.handle_id(); host.inputs.insert( 4, Input { handle, path: root.join("actual-stream"), offset: 0, xe_lookahead: Default::default(), reader: Box::new(BufReader::new(reader)), }, ); let before = host.world.trace().stream_reads.len(); assert!(host.read_line(4).is_err()); assert_eq!(host.inputs[&4].offset, 5); assert_eq!(host.world.trace().stream_reads.len(), before); assert!( matches!(&host.stream_io.events().last().unwrap().effect, StreamEffect::ReadLine {handle:Some(h),consumed_before:Some(0),consumed,delivered:false,error:Some(_),..} if *h == handle && &**consumed == b"PART\r") ); writer.write_all(b"\nNEXT\r\nTAIL").unwrap(); drop(writer); assert_eq!(host.read_line(4).unwrap().unwrap(), b"\n"); assert_eq!(host.read_line(4).unwrap().unwrap(), b"NEXT\r\n"); assert_eq!(host.read_line(4).unwrap().unwrap(), b"TAIL"); assert_eq!(host.read_line(4).unwrap(), None); let reads = &host.world.trace().stream_reads[before..]; assert_eq!( reads .iter() .map(|r| (r.offset, r.bytes, r.eof)) .collect::>(), [(5, 1, false), (6, 6, false), (12, 4, false), (16, 0, true)] ); host.finish_failed(); assert!(matches!( &host.stream_io.events().last().unwrap().effect, StreamEffect::CloseInput { consumed: Some(16), cause: ReleaseCause::FailureCleanup, .. } )); drop(host); fs::remove_dir_all(root).unwrap(); } #[test] fn stream_journal_retains_real_truncation_when_ownership_persistence_fails() { let root = root(); let mut host = files(&root, "main.tex").unwrap(); // External metadata mutation is detected after the new file was opened. fs::write(&host.ledger_path, b"EXTERNAL METADATA").unwrap(); assert!(host.open_out(1, "created.dat", "").is_err()); assert_eq!(fs::read(root.join("created.dat")).unwrap(), b""); let handle = host.outputs[&1].handle; assert!(host.stream_io.events().iter().any(|e| matches!(e.effect, StreamEffect::OutputOpened {handle:h,before:None,..} if h == handle))); assert!( matches!(&host.stream_io.events().last().unwrap().effect, StreamEffect::OpenOutputResult {opened:Some(h),result:Err(_),..} if *h == handle) ); assert!(!host.finish_failed().is_empty()); assert!(host.outputs.is_empty()); assert!(host.stream_io.events().iter().any(|e| matches!(&e.effect, StreamEffect::CleanupBoundary {cause:ReleaseCause::FailureCleanup,outputs,..} if outputs == &[handle]))); assert!(host.stream_io.events().iter().any(|e| matches!(e.effect, StreamEffect::ReleaseOutput {handle:Some(h),accepted:Some(0),cause:ReleaseCause::FailureCleanup,..} if h == handle))); assert_eq!(fs::read(&host.ledger_path).unwrap(), b"EXTERNAL METADATA"); drop(host); fs::remove_dir_all(root).unwrap(); } fn observed( root: &Path, preparation: &mut HostPreparation, ) -> Result { let mut world = FileWorld::new(WorldConfig::new(root)).unwrap(); world.capture_inputs(); let source = world .read(ResourceKind::Tex, "main.tex", root) .unwrap() .version .path; Files::prepare_observed( &source, &root.join("job.pdf"), world, Ok(root.join("policy")), false, &GeneratedInputPolicy::Live, preparation, None, EffectMode::Live, ) } #[test] fn failed_preparation_retains_real_lock_results_without_releasing_other_owner() { let root = root(); let owner = files(&root, "main.tex").unwrap(); let mut preparation = HostPreparation::default(); let failure = observed(&root, &mut preparation).err().unwrap(); assert!(failure.error.contains("already in use")); assert_eq!(preparation.phase, HostPreparationPhase::Lock); assert!(preparation.ledger.is_none()); assert!(preparation.observations.iter().any(|o|matches!(o,crate::native_host::HostObservation::Operation {name,result:Err(_),..} if name=="acquire lock"))); assert!(failure.inputs.file(&root.join("main.tex")).is_some()); assert_eq!(failure.trace.reads.len(), 1); assert!(files(&root, "main.tex").is_err()); drop(owner); let recovered = observed(&root, &mut HostPreparation::default()) .unwrap_or_else(|f| panic!("{}", f.error)); drop(recovered); fs::remove_dir_all(root).unwrap(); } #[test] fn log_open_failure_preserves_prior_absence_and_releases_acquired_lock() { let root = root(); fs::create_dir(root.join("job.log")).unwrap(); let mut preparation = HostPreparation::default(); let failure = observed(&root, &mut preparation).err().unwrap(); assert!(failure.error.contains("native log")); assert_eq!(preparation.phase, HostPreparationPhase::Log); let ledger = preparation.ledger.as_ref().unwrap(); assert!( ledger.data.is_none() && ledger.version.is_none() && ledger.eof && ledger.error.is_none() ); assert!(preparation.observations.iter().any(|o|matches!(o,crate::native_host::HostObservation::Operation {name,result:Err(_),..} if name=="open log"))); fs::remove_dir(root.join("job.log")).unwrap(); let recovered = observed(&root, &mut HostPreparation::default()) .unwrap_or_else(|f| panic!("{}", f.error)); drop(recovered); fs::remove_dir_all(root).unwrap(); } #[test] fn bounded_ledger_read_distinguishes_complete_bytes_absence_and_partial_failure() { let root = root(); let path = root.join("ledger.json"); let mut p = HostPreparation::default(); assert!(p.read_ledger(&path).unwrap().is_none()); fs::write(&path, b"ACTUAL READ BYTES").unwrap(); let bytes = p.read_ledger(&path).unwrap().unwrap(); let read = p.ledger.as_ref().unwrap().clone(); assert_eq!(read.version, file_version(&path).unwrap()); fs::write(&path, b"MODIFIED LATER").unwrap(); assert_eq!(&*bytes, b"ACTUAL READ BYTES"); assert_eq!(read.data.unwrap(), bytes); fs::File::create(&path) .unwrap() .set_len(16 * 1024 * 1024 + 1) .unwrap(); assert!( p.read_ledger(&path) .err() .unwrap() .contains("capacity exceeded") ); let limited = p.ledger.as_ref().unwrap(); assert_eq!(limited.data.as_ref().unwrap().len(), 16 * 1024 * 1024 + 1); assert!(!limited.eof); assert!(limited.version.is_none() && limited.error.is_some()); assert!(p.read_ledger(&root).is_err()); assert!(!p.ledger.as_ref().unwrap().eof); assert!(p.ledger.as_ref().unwrap().version.is_none()); fs::remove_dir_all(root).unwrap(); } #[cfg(unix)] #[test] fn scanning_aliases_rechecks_a_changed_target() { let root = root(); let target = root.join("target"); let replacement = root.join("replacement"); let peer = root.join("main.tex"); let other = root.join("other"); fs::write(&target, b"original").unwrap(); fs::write(&other, b"other").unwrap(); fs::hard_link(&peer, &replacement).unwrap(); let switched = std::cell::Cell::new(false); let candidates = [other.as_path(), peer.as_path()] .into_iter() .inspect(|candidate| { if *candidate == peer && !switched.replace(true) { fs::rename(&replacement, &target).unwrap(); } }); let mut preparation = HostPreparation::default(); assert!(preparation.aliases_any(&target, candidates)); assert_eq!(fs::read(&target).unwrap(), fs::read(&peer).unwrap()); fs::remove_dir_all(root).unwrap(); } #[cfg(unix)] #[test] fn paired_alias_scan_reads_an_input_once_and_rechecks_either_destination() { use crate::native_host::HostObservation; use std::cell::Cell; let root = root(); let pdf = root.join("job.pdf"); let log = root.join("job.log"); let input = root.join("main.tex"); let replacement = root.join("pending-link"); for output in [&pdf, &log] { fs::write(output, b"independent destination").unwrap(); } let mut preparation = HostPreparation::default(); assert!(!preparation.either_aliases_any([&pdf, &log], [input.as_path()].into_iter())); let input_reads = preparation.observations.iter().filter(|observation| { matches!(observation, HostObservation::Metadata { path, .. } if path == &input) }); assert_eq!(input_reads.count(), 1); for output in [&pdf, &log] { fs::hard_link(&input, &replacement).unwrap(); let switched = Cell::new(false); let candidates = [input.as_path()].into_iter().inspect(|_| { if !switched.replace(true) { fs::rename(&replacement, output).unwrap(); } }); let mut preparation = HostPreparation::default(); assert!(preparation.either_aliases_any([&pdf, &log], candidates)); assert!(preparation.observations.iter().any(|observation| { matches!(observation, HostObservation::Alias { right, same: true, .. } if right == output) })); fs::remove_file(output).unwrap(); fs::write(output, b"independent destination").unwrap(); } fs::remove_dir_all(root).unwrap(); } #[cfg(unix)] #[test] fn preparation_checks_overlapping_generated_roles_once_before_reading_the_version() { use crate::native_host::HostObservation; use texrra_tex_core::resources::{ProjectDefinition, ProjectSnapshot}; let root = root().canonicalize().unwrap(); let source = root.join("main.tex"); let generated = root.join("actual.aux"); let ledger = { let mut seed = files(&root, "main.tex").unwrap(); write(&mut seed, "actual.aux", "prior version"); seed.finish().unwrap(); seed.ledger_path.clone() }; let original_ledger = fs::read(&ledger).unwrap(); let original_log = fs::read(root.join("job.log")).unwrap(); fs::write(&generated, b"new version before preparation").unwrap(); let expected = file_version(&generated).unwrap(); let project = ProjectSnapshot::new(ProjectDefinition { configuration: WorldConfig::new(&root), revision: 1, roots: BTreeSet::from([root.clone()]), files: BTreeMap::from([(source.clone(), Arc::from(br"\end".as_slice()))]), directories: BTreeSet::new(), aliases: BTreeMap::new(), generated_roots: BTreeSet::from([root.clone()]), generated: BTreeSet::from([generated.clone()]), }) .unwrap(); let prepare = |preparation: &mut HostPreparation| { let mut world = FileWorld::from_project(project.clone()).unwrap(); world.read(ResourceKind::Tex, "main.tex", &root).unwrap(); Files::prepare_observed( &source, &root.join("job.pdf"), world, Ok(root.join("policy")), false, &GeneratedInputPolicy::Observe, preparation, None, EffectMode::Draft, ) }; let mut preparation = HostPreparation::default(); let mut host = prepare(&mut preparation).unwrap_or_else(|error| panic!("{}", error.error)); let aliases = preparation.observations.iter().filter(|observation| { matches!(observation, HostObservation::Alias { left, right, same: false } if left == &source && right == &generated) }); assert_eq!(aliases.count(), 1); assert_eq!( preparation.generated_initial.as_ref().unwrap().files().get(&generated), Some(&expected) ); assert_eq!( host.read("actual.aux", "").unwrap().data, b"new version before preparation" ); assert_eq!(host.generated_reads.get(&generated), expected.as_ref()); drop(host); fs::remove_file(&generated).unwrap(); fs::hard_link(&source, &generated).unwrap(); let mut preparation = HostPreparation::default(); let failure = prepare(&mut preparation).err().expect("hardlink aliases a source"); assert!(failure.error.contains("atomic generated role aliases")); assert_eq!(preparation.phase, HostPreparationPhase::Protection); assert!(preparation.observations.iter().any(|observation| { matches!(observation, HostObservation::Alias { left, right, same: true } if left == &source && right == &generated) })); assert_eq!(fs::read(&source).unwrap(), br"\end"); assert_eq!(fs::read(&generated).unwrap(), br"\end"); assert_eq!(fs::read(root.join("job.log")).unwrap(), original_log); assert_eq!(fs::read(&ledger).unwrap(), original_ledger); fs::remove_dir_all(root).unwrap(); } #[cfg(unix)] #[test] fn preparation_alias_rejection_records_actual_hardlink_identity() { let root = root(); fs::hard_link(root.join("main.tex"), root.join("job.log")).unwrap(); let mut preparation = HostPreparation::default(); assert!(observed(&root, &mut preparation).is_err()); assert_eq!(preparation.phase, HostPreparationPhase::OutputPaths); assert!(preparation.observations.iter().any(|o| matches!( o, crate::native_host::HostObservation::Alias { same: true, .. } ))); assert!(preparation.observations.iter().any(|o| matches!( o, crate::native_host::HostObservation::Metadata { result: Ok(crate::native_host::HostMetadata { unix_identity: Some(_), .. }), .. } ))); assert_eq!(fs::read(root.join("main.tex")).unwrap(), b"\\end"); fs::remove_dir_all(root).unwrap(); } #[test] fn project_lock_ends_with_owner_even_when_an_open_description_is_retained() { let root = root(); let owner = files(&root, "main.tex").unwrap(); let duplicate = owner._ledger_lock.0.try_clone().unwrap(); assert!(files(&root, "main.tex").is_err()); drop(owner); let next = files(&root, "main.tex").unwrap(); drop(duplicate); assert!(files(&root, "main.tex").is_err()); drop(next); let final_owner = files(&root, "main.tex").unwrap(); drop(final_owner); fs::remove_dir_all(root).unwrap(); } #[test] fn actual_generated_inputs_survive_reopen_edit_and_different_project_entry() { let root = root(); let path = root.join("not-an-aux.dat"); { let mut host = files(&root, "main.tex").unwrap(); write(&mut host, "not-an-aux.dat", "ONE"); host.finish().unwrap(); } fs::write(&path, b"EXTERNAL EDIT").unwrap(); fs::write(root.join("other.tex"), b"\\end").unwrap(); let mut host = files(&root, "other.tex").unwrap(); assert_eq!( host.read("not-an-aux.dat", "").unwrap().data, b"EXTERNAL EDIT" ); write(&mut host, "not-an-aux.dat", "TWO"); assert_eq!(host.read("not-an-aux.dat", "").unwrap().data, b"TWO"); write(&mut host, "not-an-aux.dat", "THREE"); host.finish().unwrap(); host.write_resource_manifest(&root.join("trace.json")) .unwrap(); let report: serde_json::Value = serde_json::from_slice(&fs::read(root.join("trace.json")).unwrap()).unwrap(); let writes = report["generated_artifacts"]["writes"].as_array().unwrap(); assert_eq!(writes.len(), 1); assert_eq!(writes[0]["before"]["bytes"], 13); assert_eq!(writes[0]["after"]["bytes"], 5); assert_eq!( writes[0]["producer"], root.join("other.tex").to_str().unwrap() ); assert_eq!( host.ledger_current, file_version(&host.ledger_path).unwrap() ); assert!( host.resource_trace() .reads .iter() .any(|r| r.path == path && r.bytes == 13) ); drop(host); fs::remove_dir_all(root).unwrap(); } #[test] fn source_binary_and_metadata_roles_override_generated_claims() { let root = root(); { let mut host = files(&root, "main.tex").unwrap(); write(&mut host, "next.tex", "\\end"); write(&mut host, "font.data", "BINARY"); host.finish().unwrap(); } let mut host = files(&root, "next.tex").unwrap(); for name in [ "next.tex".into(), "job.pdf".into(), "job.log".into(), host.ledger_path.display().to_string(), host.ledger_path .with_extension("lock") .display() .to_string(), ] { assert!( host.open_out(0, &name, "") .unwrap_err() .contains("overwrite"), "{name}" ); } host.resource(ResourceKind::Tfm, "font.data", "").unwrap(); assert!( host.open_out(0, "font.data", "") .unwrap_err() .contains("overwrite") ); fs::write(root.join("unknown.aux"), b"SOURCE").unwrap(); host.read("unknown.aux", "").unwrap(); assert!( host.open_out(0, "unknown.aux", "") .unwrap_err() .contains("overwrite") ); assert_eq!(fs::read(root.join("font.data")).unwrap(), b"BINARY"); assert_eq!(fs::read(root.join("unknown.aux")).unwrap(), b"SOURCE"); drop(host); fs::remove_dir_all(root).unwrap(); } #[test] fn project_lock_and_observed_versions_reject_competing_mutations() { let root = root(); let mut host = files(&root, "main.tex").unwrap(); let log = fs::read(root.join("job.log")).unwrap(); assert!( files(&root, "main.tex") .err() .unwrap() .contains("already in use") ); assert_eq!(fs::read(root.join("job.log")).unwrap(), log); write(&mut host, "state.dat", "OLD"); host.read("state.dat", "").unwrap(); fs::write(root.join("state.dat"), b"NEW").unwrap(); assert!( host.open_out(0, "state.dat", "") .unwrap_err() .contains("changed after") ); assert_eq!(fs::read(root.join("state.dat")).unwrap(), b"NEW"); fs::write(&host.ledger_path, b"EXTERNAL METADATA").unwrap(); assert!(host.finish().unwrap_err().contains("ledger changed")); assert_eq!(fs::read(&host.ledger_path).unwrap(), b"EXTERNAL METADATA"); drop(host); assert!( files(&root, "main.tex") .err() .unwrap() .contains("invalid generated-file ledger") ); fs::remove_dir_all(root).unwrap(); } #[cfg(unix)] #[test] fn read_only_project_can_render_with_writable_external_state_and_output() { use std::os::unix::fs::PermissionsExt; let root = root(); let project = root.join("project"); let build = root.join("build"); fs::create_dir(&project).unwrap(); fs::create_dir(&build).unwrap(); fs::write(project.join("main.tex"), b"\\end").unwrap(); fs::set_permissions(&project, fs::Permissions::from_mode(0o555)).unwrap(); let result = (|| { let mut world = FileWorld::new(WorldConfig::new(&project))?; let source = world .read(ResourceKind::Tex, "main.tex", &project)? .version .path; let mut host = Files::with_state_dir( &source, &build.join("job.pdf"), world, &root.join("policy"), )?; host.finish() })(); fs::set_permissions(&project, fs::Permissions::from_mode(0o755)).unwrap(); result.unwrap(); assert_eq!(fs::read_dir(&project).unwrap().count(), 1); assert!(build.join("job.log").is_file()); fs::remove_dir_all(root).unwrap(); } #[cfg(unix)] #[test] fn generated_hardlinks_and_symlinks_cannot_alias_a_source() { use std::os::unix::fs::symlink; for hard in [true, false] { let root = root(); { let mut host = files(&root, "main.tex").unwrap(); write(&mut host, "owned.dat", "OLD"); host.finish().unwrap(); } fs::write(root.join("child.tex"), b"CHILD").unwrap(); fs::remove_file(root.join("owned.dat")).unwrap(); if hard { fs::hard_link(root.join("child.tex"), root.join("owned.dat")).unwrap(); } else { symlink(root.join("child.tex"), root.join("owned.dat")).unwrap(); } let mut host = files(&root, "main.tex").unwrap(); host.read("child.tex", "").unwrap(); assert!( host.open_out(0, "owned.dat", "") .unwrap_err() .contains("overwrite") ); assert_eq!(fs::read(root.join("child.tex")).unwrap(), b"CHILD"); drop(host); fs::remove_dir_all(root).unwrap(); } } } #[cfg(test)] mod prepared_output_tests { use super::*; use texrra_tex_core::execution::{Executor, Limits, NativeSession, State}; struct NoInputs; impl SourceProvider for NoInputs { fn read(&mut self, name: &str, _: &str) -> Result { Err(format!("unexpected input: {name}")) } } #[test] fn format_publication_exposes_complete_bytes_and_preserves_existing_file() { let root = std::env::temp_dir().join(format!("texrra-publish-format-{}", std::process::id())); fs::create_dir_all(&root).unwrap(); let output = root.join("format.tfx"); let first = PreparedOutput::write(&output, b"complete-format").unwrap(); assert!(!output.exists()); first.commit_new(&output).unwrap(); let second = PreparedOutput::write(&output, b"replacement").unwrap(); assert!(second.commit_new(&output).is_err()); assert_eq!(fs::read(&output).unwrap(), b"complete-format"); assert_eq!(fs::read_dir(&root).unwrap().count(), 1); fs::remove_dir_all(root).unwrap(); } #[test] fn failed_draft_install_restores_replaced_file_and_removes_new_file() { let root = std::env::temp_dir().join(format!("texrra-draft-rollback-{}", std::process::id())); fs::create_dir(&root).unwrap(); let replaced = root.join("entry.aux"); let new = root.join("entry.log"); let unavailable = root.join("entry.pdf"); fs::write(&replaced, b"old auxiliary file").unwrap(); let expected = DraftDestination::capture(&replaced).unwrap(); let installs = [&replaced, &new, &unavailable] .into_iter() .map(|path| { DraftInstall::prepare(DraftArtifact { target: DraftDestination::capture(path).unwrap(), staged: PreparedOutput::write(path, b"staged native bytes").unwrap(), }) .unwrap() }) .collect::>(); fs::remove_file(&installs[2].artifact.staged.path).unwrap(); let error = install_draft(installs).unwrap_err(); assert!(error.contains("entry.pdf"), "{error}"); expected.verify().unwrap(); assert_eq!(fs::read(&replaced).unwrap(), b"old auxiliary file"); assert!(!new.exists()); assert!(!unavailable.exists()); assert_eq!(fs::read_dir(&root).unwrap().count(), 1); fs::remove_dir_all(root).unwrap(); } #[test] fn staged_output_from_superseded_revision_cannot_replace_destination() { let root = std::env::temp_dir().join(format!("texrra-publish-revision-{}", std::process::id())); fs::create_dir_all(&root).unwrap(); let output = root.join("published.pdf"); fs::write(&output, b"existing").unwrap(); let session = NativeSession::default(); let result = session .start() .run( Executor::new(State::initex(), Limits::default()), SourceFile { name: "probe.tex".into(), data: br"\end".to_vec(), }, &mut NoInputs, ) .unwrap(); let prepared = PreparedOutput::write(&output, b"superseded").unwrap(); assert_eq!(fs::read(&output).unwrap(), b"existing"); let newer = session.start(); assert!(newer.revision() > result.revision); assert_eq!( session .publish_current(result.revision, || prepared.commit(&output)) .unwrap(), None ); assert_eq!(fs::read(&output).unwrap(), b"existing"); assert_eq!(fs::read_dir(&root).unwrap().count(), 1); fs::remove_dir_all(root).unwrap(); } }