Files
texrra-engine/src/native_host.rs
T

302 lines
9.9 KiB
Rust

//! 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>,
}
#[cfg(unix)]
#[derive(Clone, Copy, PartialEq, Eq)]
enum UnixPathIdentity {
Present(u64, u64),
Missing,
}
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 = a == b || self.same_file_target(a, b);
self.record_alias(a, b, same)
}
pub(crate) fn aliases_any<'a>(
&mut self,
path: &Path,
candidates: impl Iterator<Item = &'a Path> + Clone,
) -> bool {
#[cfg(unix)]
{
let mut candidates = candidates.peekable();
let Some(first) = candidates.peek().copied() else {
return false;
};
if path == first {
return self.same_file(first, path);
}
if let Some(identity) = self.path_identity(path) {
let same = candidates.clone().any(|candidate| {
let alias = if candidate == path {
true
} else if identity == UnixPathIdentity::Missing {
false
} else if let Some(candidate_identity) = self.path_identity(candidate) {
identity == candidate_identity
} else {
return self.same_file(candidate, path);
};
self.record_alias(candidate, path, alias)
});
// Keep observations local to this scan. If the fixed path
// changed during a negative scan, use fresh pairwise probes.
if same || self.path_identity(path) == Some(identity) {
return same;
}
}
return candidates.any(|candidate| self.same_file(candidate, path));
}
#[cfg(not(unix))]
{
let mut candidates = candidates;
candidates.any(|candidate| self.same_file(candidate, path))
}
}
#[cfg(unix)]
fn path_identity(&mut self, path: &Path) -> Option<UnixPathIdentity> {
use std::os::unix::fs::MetadataExt;
match self.metadata(path) {
Ok(metadata) => Some(UnixPathIdentity::Present(metadata.dev(), metadata.ino())),
Err(error) if error.kind() == io::ErrorKind::NotFound => {
Some(UnixPathIdentity::Missing)
}
Err(_) => None,
}
}
fn record_alias(&mut self, a: &Path, b: &Path, same: bool) -> bool {
self.observations.push(HostObservation::Alias {
left: a.into(),
right: b.into(),
same,
});
same
}
fn same_file_target(&mut self, a: &Path, b: &Path) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
// Metadata follows symlinks. The device and inode also identify
// hard links, so existing Unix paths need no canonicalization.
match (self.metadata(a), self.metadata(b)) {
(Ok(a), Ok(b)) => return a.dev() == b.dev() && a.ino() == b.ino(),
(Err(e), _) | (_, Err(e)) if e.kind() == io::ErrorKind::NotFound => return false,
_ => {}
}
}
self.canonicalize(a)
.ok()
.zip(self.canonicalize(b).ok())
.is_some_and(|(a, b)| a == b)
}
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))
}
}