Advance native LaTeX execution and preview

This commit is contained in:
gloamxun committed 2026-11-18 22:17:21 +08:00
1 parent 91f9d76b16
commit 2741546ca8
414 files changed
+99872 -933

No files matched your search

+242
View File
@@ -0,0 +1,242 @@
//! Actual host preparation observations. Locks and filesystem policy must be
//! checked live on every attempt; these records never grant cache permission.
use sha2::{Digest, Sha256};
use std::{
ffi::OsString,
fs,
io::{self, Read},
path::{Path, PathBuf},
sync::Arc,
time::SystemTime,
};
use texrra_tex_core::resources::ResourceVersion;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum HostPreparationPhase {
#[default]
Environment,
OutputPaths,
StateDirectory,
MetadataPaths,
Lock,
Ledger,
Protection,
GeneratedInitial,
Log,
Ready,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct HostMetadata {
pub directory: bool,
pub file: bool,
pub bytes: u64,
pub modified: Result<SystemTime, String>,
pub readonly: bool,
pub unix_identity: Option<(u64, u64)>,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum VersionExpectation {
Any,
Exact(Option<ResourceVersion>),
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum HostObservation {
LogicalGeneratedPath {
logical: PathBuf,
resolved: Result<PathBuf, String>,
},
VersionCheck {
path: PathBuf,
expected: VersionExpectation,
observed: Result<Option<ResourceVersion>, String>,
},
Environment {
name: String,
value: Option<OsString>,
},
Canonicalize {
path: PathBuf,
result: Result<PathBuf, String>,
},
Metadata {
path: PathBuf,
result: Result<HostMetadata, String>,
},
Alias {
left: PathBuf,
right: PathBuf,
same: bool,
},
Operation {
name: String,
path: PathBuf,
result: Result<(), String>,
},
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct LedgerRead {
pub path: PathBuf,
/// None records absence. A failed/limited read can retain an actual prefix.
pub data: Option<Arc<[u8]>>,
pub eof: bool,
pub error: Option<String>,
/// Only present for bytes read through EOF, never for a partial prefix.
pub version: Option<ResourceVersion>,
}
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct HostPreparation {
pub phase: HostPreparationPhase,
pub observations: Vec<HostObservation>,
pub ledger: Option<LedgerRead>,
#[serde(default)]
pub generated_initial: Option<crate::native_generated::GeneratedInitialState>,
}
impl HostPreparation {
pub(crate) fn environment(&mut self, name: &str) -> Option<OsString> {
let value = std::env::var_os(name);
self.observations.push(HostObservation::Environment {
name: name.into(),
value: value.clone(),
});
value
}
pub(crate) fn canonicalize(&mut self, path: &Path) -> io::Result<PathBuf> {
let result = path.canonicalize();
self.observations.push(HostObservation::Canonicalize {
path: path.into(),
result: result
.as_ref()
.map(Clone::clone)
.map_err(ToString::to_string),
});
result
}
pub(crate) fn metadata(&mut self, path: &Path) -> io::Result<fs::Metadata> {
let result = path.metadata();
let observed = result
.as_ref()
.map(|m| {
#[cfg(unix)]
let identity = {
use std::os::unix::fs::MetadataExt;
Some((m.dev(), m.ino()))
};
#[cfg(not(unix))]
let identity = None;
HostMetadata {
directory: m.is_dir(),
file: m.is_file(),
bytes: m.len(),
modified: m.modified().map_err(|e| e.to_string()),
readonly: m.permissions().readonly(),
unix_identity: identity,
}
})
.map_err(ToString::to_string);
self.observations.push(HostObservation::Metadata {
path: path.into(),
result: observed,
});
result
}
pub(crate) fn same_file(&mut self, a: &Path, b: &Path) -> bool {
let same = if a == b {
true
} else if self
.canonicalize(a)
.ok()
.zip(self.canonicalize(b).ok())
.is_some_and(|(a, b)| a == b)
{
true
} else {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if let (Ok(a), Ok(b)) = (self.metadata(a), self.metadata(b)) {
a.dev() == b.dev() && a.ino() == b.ino()
} else {
false
}
}
#[cfg(not(unix))]
{
false
}
};
self.observations.push(HostObservation::Alias {
left: a.into(),
right: b.into(),
same,
});
same
}
pub(crate) fn output(&mut self, cwd: &Path, path: &Path) -> Result<PathBuf, String> {
let path = cwd.join(path);
if self.metadata(&path).is_ok() {
return self.canonicalize(&path).map_err(|e| e.to_string());
}
let parent = self
.canonicalize(path.parent().unwrap_or(cwd))
.map_err(|e| format!("output directory: {e}"))?;
Ok(parent.join(path.file_name().ok_or("output requires a filename")?))
}
pub(crate) fn operation<T>(
&mut self,
name: &str,
path: &Path,
result: &Result<T, impl ToString>,
) {
self.observations.push(HostObservation::Operation {
name: name.into(),
path: path.into(),
result: result.as_ref().map(|_| ()).map_err(ToString::to_string),
});
}
pub(crate) fn read_ledger(&mut self, path: &Path) -> Result<Option<Arc<[u8]>>, String> {
const LIMIT: u64 = 16 * 1024 * 1024;
let mut data = Vec::new();
let opened = fs::File::open(path);
self.operation("open ledger", path, &opened);
let result = match opened {
Ok(file) => file
.take(LIMIT + 1)
.read_to_end(&mut data)
.map(|_| ())
.map_err(|e| e.to_string()),
Err(e) if e.kind() == io::ErrorKind::NotFound => {
self.ledger = Some(LedgerRead {
path: path.into(),
data: None,
eof: true,
error: None,
version: None,
});
return Ok(None);
}
Err(e) => Err(format!("generated-file version {}: {e}", path.display())),
};
let result = result.and_then(|()| {
if data.len() as u64 > LIMIT {
Err("native generated-file ledger capacity exceeded".into())
} else {
Ok(())
}
});
self.operation("read ledger", path, &result);
let version = result.as_ref().ok().map(|()| ResourceVersion {
path: path.into(),
bytes: data.len() as u64,
sha256: format!("{:x}", Sha256::digest(&data)),
});
let data: Arc<[u8]> = Arc::from(data);
self.ledger = Some(LedgerRead {
path: path.into(),
data: Some(data.clone()),
eof: result.is_ok(),
error: result.as_ref().err().cloned(),
version,
});
result.map(|()| Some(data))
}
}