Files
texrra-engine/src/native_job.rs
T

3014 lines
115 KiB
Rust

//! 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, 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<JobTime, String> {
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<DateTime<FixedOffset>, 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::<u64>().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<FixedOffset>) -> Result<JobTime, String> {
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<Option<String>, 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<dyn BufRead + Send>,
path: PathBuf,
offset: u64,
}
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<texrra_tex_core::resources::InputSnapshot>,
}
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<PathBuf, DraftArtifact>,
ledger_target: DraftDestination,
ledger: Option<DraftLedger>,
pdf: DraftDestination,
finished: bool,
}
struct DraftLedger {
file: File,
staged: PreparedOutput,
}
pub struct Files {
world: FileWorld,
#[cfg(all(target_os = "linux", target_env = "gnu"))]
regex_worker: Option<crate::native_regex::Worker>,
cwd: PathBuf,
inputs: BTreeMap<u8, Input>,
outputs: BTreeMap<u8, Output>,
next_handle: u64,
stream_io: StreamJournal,
log_path: PathBuf,
log: Option<File>,
draft: Option<DraftEffects>,
protected: Vec<PathBuf>,
producer: PathBuf,
ledger: ArtifactLedger,
ledger_path: PathBuf,
ledger_input: Option<ResourceVersion>,
ledger_current: Option<ResourceVersion>,
_ledger_lock: ArtifactLock,
generated_reads: BTreeMap<PathBuf, ResourceVersion>,
generated_before: BTreeMap<PathBuf, Option<ResourceVersion>>,
generated_written: BTreeSet<PathBuf>,
log_column: usize,
terminal_column: usize,
terminal_enabled: bool,
terminal_sink: bool,
preparation: HostPreparation,
runtime_observations: RefCell<HostPreparation>,
}
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<Box<PreparedInputsCheck<'_>>>,
effects: EffectMode,
) -> Result<Self, HostPreparationFailure> {
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, String> {
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<PathBuf, String>,
terminal: bool,
generated_inputs: &GeneratedInputPolicy,
preparation: &mut HostPreparation,
check_inputs: Option<Box<PreparedInputsCheck<'_>>>,
effects: EffectMode,
) -> Result<Self, HostPreparationFailure> {
// 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<Self, String> {
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.aliases_any(
&log_path,
world.trace().reads.iter().map(|r| r.path.as_path()),
)
|| preparation
.aliases_any(&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.aliases_any(&pdf, project.immutable_paths())
|| preparation.aliases_any(&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 immutable_claims: Vec<_> = ledger
.paths()
.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);
}
let declared: Vec<_> = world
.project()
.map(|p| p.generated().map(Path::to_path_buf).collect())
.unwrap_or_default();
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.clone(),
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(log),
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<crate::native_host::HostObservation> {
self.runtime_observations.borrow().observations.clone()
}
fn observe_version(
&self,
path: &Path,
expected: Option<Option<ResourceVersion>>,
) -> Result<Option<ResourceVersion>, 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<PathBuf, String> {
self.runtime_observations
.borrow_mut()
.output(&self.cwd, path)
}
fn operation<T>(&self, name: &str, path: &Path, result: &Result<T, impl ToString>) {
self.runtime_observations
.borrow_mut()
.operation(name, path, result);
}
pub(super) fn generated_outputs(&self) -> &BTreeSet<PathBuf> {
&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<crate::native::GeneratedArtifacts, String> {
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<crate::native::ResourceSnapshot, String> {
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<texrra_tex_core::resources::InputSnapshot> {
self.world.input_snapshot()
}
#[cfg(test)]
pub(crate) fn draft_paths(&self) -> BTreeMap<PathBuf, PathBuf> {
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 item in &page.items {
match item {
DisplayItem::NativeGlyph {
x,
y,
size,
slot,
font,
..
} => {
paint_order.push(json!(["glyph", glyphs.len()]));
glyphs.push(
json!({"x": x, "y": y, "size": size, "slot": slot, "font": font.name}),
);
}
DisplayItem::Rule {
x,
y,
width,
height,
} => {
paint_order.push(json!(["rule", rules.len()]));
rules.push(json!({"x": x, "y": y, "width": width, "height": height}));
}
DisplayItem::PdfImage {
x,
y,
width,
height,
image,
} => {
paint_order.push(json!(["pdf_image", images.len()]));
images.push(json!({
"x":x, "y":y, "width":width, "height":height,
"id":image.id, "page":image.image.page, "resource":image.image.version,
}));
}
DisplayItem::PdfImageObject(_) | DisplayItem::PdfColor(_) | DisplayItem::PdfTextSpace { .. } => {}
DisplayItem::PdfGraphics { x, y, operation } => {
paint_order.push(json!(["pdf_graphics", graphics.len()]));
graphics.push(json!({"x": x, "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);
}
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),
)
}
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<ResourceVersion>,
) -> Result<File, String> {
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<Output>, 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> {
if destination != WriteDestination::TerminalOnly {
if self.log.is_none() {
self.log = Some(
File::create(
self.draft
.as_ref()
.map_or(&self.log_path, |draft| &draft.log.staged.path),
)
.map_err(|e| format!("native log {}: {e}", self.log_path.display()))?,
);
}
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(text.as_bytes())
.map_err(|e| format!("native log: {e}"))?;
self.log_column = output_column(if start_line { 0 } else { self.log_column }, text);
}
if self.terminal_sink && self.terminal_enabled && destination != WriteDestination::Log {
if start_line && self.terminal_column != 0 {
eprintln!();
}
eprint!("{text}");
self.terminal_column =
output_column(if start_line { 0 } else { self.terminal_column }, text);
}
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<String> {
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::<Vec<_>>() {
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::<Vec<_>>() {
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::<Vec<_>>() {
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::<Vec<_>>() {
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<PreparedOutput>,
queue: &DraftSyncQueue,
cancellation: &Cancellation,
) -> Result<Option<DraftPublication>, String> {
let draft = self.draft.take().ok_or("native draft host required")?;
if !draft.finished {
return Err("native draft must finish successfully before publication".into());
}
let log = self.log.take();
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::<BTreeMap<_, _>>();
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<AtomicUsize>,
}
struct DraftSyncSlot(Arc<AtomicUsize>);
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<Option<SyncedDraft>, String> + Send + 'static,
) -> Result<Option<SyncedDraft>, 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<File>,
draft: DraftEffects,
pdf: Option<PreparedOutput>,
untouched: BTreeMap<PathBuf, Option<ResourceVersion>>,
ledger_current: Option<ResourceVersion>,
}
impl PendingDraft {
fn sync(self, cancellation: &Cancellation) -> Result<Option<SyncedDraft>, 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(())
};
// Flush independent files concurrently, then finish collecting 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 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())?
});
pdf_result.and(log_result).and(generated)
})?;
drop(log);
if cancellation.is_cancelled() {
return Ok(None);
}
artifacts.push(draft.log);
let untouched_ledger = if let Some(DraftLedger { file, staged }) = draft.ledger {
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()
));
}
file.sync_all()
.map_err(|e| format!("sync native draft ledger {}: {e}", 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) {
// 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<PathBuf, String> {
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 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<texrra_tex_core::execution::RegexOutcome, String> {
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 resource_usage(
&mut self,
) -> Result<Option<texrra_tex_core::execution::HostResourceUsage>, 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<i32, String> {
Ok(self.world.default_pk_resolution())
}
fn pk_font(&mut self, name: &str, dpi: u32, from: &str) -> Result<LoadedResource, String> {
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_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<SourceFile, String> {
let resource = self.world.read_tex_input(name, Path::new(from))?;
self.observe_resource(ResourceKind::Tex, &resource);
let path = resource.version.path;
Ok(SourceFile {
name: path.display().to_string(),
data: resource.data,
})
}
fn resource(
&mut self,
kind: ResourceKind,
name: &str,
from: &str,
) -> Result<LoadedResource, String> {
let resource = self.world.read(kind, name, Path::new(from))?;
self.observe_resource(kind, &resource);
Ok(resource)
}
fn virtual_font(&mut self, name: &str, from: &str) -> Result<Option<LoadedResource>, 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 file_size(&mut self, name: &str, from: &str) -> Result<Option<u64>, String> {
let Some(resource) = self.world.read_tex_input_optional(name, Path::new(from))? else {
return Ok(None);
};
self.observe_resource(ResourceKind::Tex, &resource);
Ok(Some(resource.version.bytes))
}
fn file_modification_date(&mut self, name: &str, from: &str) -> Result<Option<String>, String> {
file_modification_date(&mut self.world, name, from)
}
fn open_in(&mut self, stream: u8, name: &str, from: &str) -> Result<Option<String>, String> {
self.release_input(stream, ReleaseCause::Replaced, false);
let result = (|| -> Result<Option<InputOpened>, String> {
let Some(path) = self.world.resolve_tex_input(name, Path::new(from))? else {
return Ok(None);
};
let (reader, storage): (Box<dyn BufRead + Send>, 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,
},
);
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<Option<Vec<u8>>, 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 = 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());
Ok(line)
}
}
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<String, String> {
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> {
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(text.as_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, text.as_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(text.as_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)
}
}
#[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<Self> {
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<DraftFileStamp>,
version: Option<ResourceVersion>,
}
impl DraftDestination {
fn capture(path: &Path) -> Result<Self, String> {
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<DraftArtifact>,
untouched: BTreeMap<PathBuf, Option<ResourceVersion>>,
untouched_ledger: Option<DraftDestination>,
}
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<T>(
self,
session: &NativeSession,
revision: u64,
expose_document: impl FnOnce() -> T,
) -> Result<Option<T>, 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::<Result<Vec<_>, _>>()?,
)?;
Ok(expose_document())
})
}
}
struct DraftInstall {
artifact: DraftArtifact,
installed: DraftFileStamp,
backup: Option<PreparedOutput>,
}
impl DraftInstall {
fn prepare(artifact: DraftArtifact) -> Result<Self, String> {
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<DraftInstall>) -> Result<(), String> {
let mut applied: Vec<(PathBuf, DraftFileStamp, Option<PreparedOutput>)> = 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<PreparedOutput>,
) -> 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<File>,
}
impl PreparedOutput {
pub fn version(&self, destination: &Path) -> Result<ResourceVersion, String> {
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, String> {
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<Self, String> {
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<Self, String> {
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, String> {
Self::allocate(output, |path| fs::hard_link(output, path)).map(|(backup, ())| backup)
}
fn allocate<T>(
output: &Path,
create: impl Fn(&Path) -> io::Result<T>,
) -> 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<Files, String> {
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,
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::<Vec<_>>(),
[(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<Files, HostPreparationFailure> {
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 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<SourceFile, String> {
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::<Vec<_>>();
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();
}
}