Files
texrra-engine/crates/texrra-tex-core/src/resources/project.rs
T

498 lines
19 KiB
Rust

//! Editor-owned immutable logical inputs. Construction and lookup never consult
//! the filesystem. Live generated I/O is an explicit, separate host contract.
use super::*;
use std::{collections::VecDeque, ffi::OsString, path::Component, sync::OnceLock};
#[derive(Clone, Debug)]
pub struct ProjectDefinition {
pub configuration: WorldConfig,
pub revision: u64,
/// Complete logical namespace coverage. Absence inside these roots is known;
/// outside them access fails rather than consulting the host filesystem.
pub roots: BTreeSet<PathBuf>,
pub files: BTreeMap<PathBuf, Arc<[u8]>>,
pub directories: BTreeSet<PathBuf>,
pub aliases: BTreeMap<PathBuf, PathBuf>,
/// Real TeX stream writes are permitted only below these directories.
pub generated_roots: BTreeSet<PathBuf>,
/// Explicit initial generated roles, in addition to genuine prior writes in
/// the host ledger. Bytes remain live; this is not a fixed generated state.
pub generated: BTreeSet<PathBuf>,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ProjectVersion {
pub revision: u64,
/// Content identity excludes the caller's revision counter. Request clock,
/// profile and actual generated state are separate compilation inputs.
pub sha256: String,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ProjectSnapshot {
schema: u32,
version: ProjectVersion,
configuration: WorldConfig,
roots: BTreeSet<PathBuf>,
files: BTreeMap<PathBuf, SnapshotFile>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
file_modifications: BTreeMap<PathBuf, FileModificationTime>,
directories: BTreeSet<PathBuf>,
aliases: BTreeMap<PathBuf, PathBuf>,
generated_roots: BTreeSet<PathBuf>,
generated: BTreeSet<PathBuf>,
#[serde(skip)]
validated: OnceLock<Result<(), String>>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum NodeKind {
File,
Directory,
}
pub(super) struct Location {
pub path: PathBuf,
pub kind: Option<NodeKind>,
/// A missing final component can be a new output; missing parents cannot.
pub final_component: bool,
}
impl ProjectSnapshot {
pub fn new(definition: ProjectDefinition) -> Result<Arc<Self>, String> {
Self::with_file_modifications(definition, BTreeMap::new())
}
pub fn with_file_modifications(
definition: ProjectDefinition,
file_modifications: BTreeMap<PathBuf, FileModificationTime>,
) -> Result<Arc<Self>, String> {
let mut files = BTreeMap::new();
for (path, data) in definition.files {
files.insert(path.clone(), Self::capture(path, data));
}
let mut directories = definition.directories;
for path in definition
.roots
.iter()
.chain(files.keys())
.chain(definition.aliases.keys())
.chain(&definition.generated)
{
let mut parent = if definition.roots.contains(path) {
Some(path.as_path())
} else {
path.parent()
};
while let Some(path) = parent {
directories.insert(path.into());
parent = path.parent();
}
}
Self {
schema: 1,
version: ProjectVersion {
revision: definition.revision,
sha256: String::new(),
},
configuration: definition.configuration,
roots: definition.roots,
files,
file_modifications,
directories,
aliases: definition.aliases,
generated_roots: definition.generated_roots,
generated: definition.generated,
validated: OnceLock::new(),
}
.seal()
}
/// Replace existing immutable buffers in an editor revision. Namespace
/// entries, generated-file roles and captured modification times are retained.
pub fn with_file_edits(
&self,
revision: u64,
edits: BTreeMap<PathBuf, Arc<[u8]>>,
) -> Result<Arc<Self>, String> {
self.validate()?;
let mut next = self.clone();
next.version.revision = revision;
next.validated = OnceLock::new();
for (path, data) in edits {
let previous = next.files.get_mut(&path).ok_or_else(|| {
format!("atomic edit requires an immutable file: {}", path.display())
})?;
if !Arc::ptr_eq(&previous.data, &data) {
*previous = Self::capture(path, data);
}
}
next.seal()
}
fn capture(path: PathBuf, data: Arc<[u8]>) -> SnapshotFile {
SnapshotFile {
version: ResourceVersion {
path,
bytes: data.len() as u64,
sha256: format!("{:x}", Sha256::digest(&data)),
},
data,
}
}
// The caller captured each buffer or retained it from a validated immutable
// snapshot. Deserialized snapshots go through validate() with byte checks.
fn seal(mut self) -> Result<Arc<Self>, String> {
self.version.sha256 = self.digest()?;
self.check_contents(false)?;
self.validated = OnceLock::from(Ok(()));
Ok(Arc::new(self))
}
pub fn version(&self) -> &ProjectVersion {
&self.version
}
pub fn configuration(&self) -> WorldConfig {
self.configuration.clone()
}
pub fn files(&self) -> impl Iterator<Item = (&Path, &SnapshotFile)> {
self.files.iter().map(|(p, f)| (p.as_path(), f))
}
pub fn file(&self, path: &Path) -> Option<&SnapshotFile> {
self.files.get(path)
}
pub fn modification_time(&self, path: &Path) -> Option<FileModificationTime> {
self.file_modifications.get(path).copied()
}
pub fn generated(&self) -> impl Iterator<Item = &Path> {
self.generated.iter().map(PathBuf::as_path)
}
pub fn immutable_paths(&self) -> impl Iterator<Item = &Path> {
self.files.keys().map(PathBuf::as_path)
}
pub fn protects_artifact(&self, path: &Path) -> bool {
self.files.contains_key(path) || self.aliases.contains_key(path)
}
pub fn permits_generated(&self, path: &Path) -> bool {
self.generated_roots.iter().any(|r| path.starts_with(r))
}
pub(super) fn validate_captured_file(
&self,
path: &Path,
value: &Result<SnapshotFile, String>,
) -> Result<(), String> {
if !normalized(path) {
return Err("atomic captured paths must be normalized".into());
}
if let Some(expected) = self.file(path) {
if !value.as_ref().is_ok_and(|f| f.version == expected.version) {
return Err("captured input conflicts with atomic project bytes".into());
}
} else if !self.permits_generated(path) {
return Err("captured input is outside atomic project roles".into());
}
Ok(())
}
/// Canonical schema-1 content descriptor. Byte payloads are represented by
/// their verified versions; this is also usable for independent auditing.
pub fn content_descriptor(&self) -> Result<Vec<u8>, String> {
let versions: Vec<_> = self.files.values().map(|f| &f.version).collect();
let descriptor = (
self.schema,
&self.configuration,
&self.roots,
versions,
&self.directories,
&self.aliases,
&self.generated_roots,
&self.generated,
);
if self.file_modifications.is_empty() {
serde_json::to_vec(&descriptor)
} else {
serde_json::to_vec(&(descriptor, &self.file_modifications))
}
.map_err(|e| e.to_string())
}
fn digest(&self) -> Result<String, String> {
Ok(format!("{:x}", Sha256::digest(self.content_descriptor()?)))
}
pub fn validate(&self) -> Result<(), String> {
self.validated
.get_or_init(|| self.check_contents(true))
.clone()
}
fn check_contents(&self, verify_digests: bool) -> Result<(), String> {
if self.schema != 1 || self.version.revision == 0 || self.roots.is_empty() {
return Err("invalid atomic project identity or namespace".into());
}
for (path, time) in &self.file_modifications {
if !self.files.contains_key(path) || !time.valid() {
return Err(format!(
"invalid atomic project modification time: {}",
path.display()
));
}
}
for p in [&self.configuration.cwd]
.into_iter()
.chain(&self.configuration.texmf_roots)
.chain(&self.roots)
.chain(self.files.keys())
.chain(&self.directories)
.chain(self.aliases.keys())
.chain(&self.generated_roots)
.chain(&self.generated)
{
if !normalized(p) {
return Err(format!(
"atomic project paths must be normalized absolute paths: {}",
p.display()
));
}
}
if !self.covered(&self.configuration.cwd)
|| !self.directories.contains(&self.configuration.cwd)
{
return Err("atomic project cwd must be a declared directory".into());
}
if self.files.len() + self.aliases.len() + self.directories.len() + self.generated.len()
> self.configuration.max_index_entries
{
return Err("atomic project namespace capacity exceeded".into());
}
for (path, file) in &self.files {
if !self.covered(path)
|| self.directories.contains(path)
|| self.aliases.contains_key(path)
|| self.generated.contains(path)
|| file.version.path != *path
|| file.version.bytes != file.data.len() as u64
|| (verify_digests
&& file.version.sha256 != format!("{:x}", Sha256::digest(&file.data)))
{
return Err(format!("invalid atomic project file: {}", path.display()));
}
}
for path in &self.directories {
if !self.covered(path) && !self.roots.iter().any(|r| r.starts_with(path)) {
return Err("atomic project directory is outside namespace coverage".into());
}
if self.aliases.contains_key(path) || self.generated.contains(path) {
return Err("atomic project node roles overlap".into());
}
}
for path in self
.files
.keys()
.chain(self.aliases.keys())
.chain(&self.generated)
.chain(&self.directories)
{
if let Some(parent) = path.parent() {
if !self.directories.contains(parent) {
return Err(format!(
"atomic project parent is not a directory: {}",
path.display()
));
}
}
}
for (path, target) in &self.aliases {
if !self.covered(path) || target.as_os_str().is_empty() || self.generated.contains(path)
{
return Err("invalid atomic project alias".into());
}
// Broken links are valid namespace entries. Cycles are not.
if let Err(error) = self.locate(path, &BTreeSet::new()) {
if error.contains("alias depth") {
return Err(error);
}
}
}
for path in &self.generated_roots {
if !self.covered(path) || !self.directories.contains(path) {
return Err("generated root must be a declared project directory".into());
}
}
if self.generated.iter().any(|p| !self.permits_generated(p)) {
return Err("generated role is outside declared writable roots".into());
}
if verify_digests && self.version.sha256 != self.digest()? {
return Err("atomic project content identity mismatch".into());
}
Ok(())
}
fn covered(&self, path: &Path) -> bool {
self.roots.iter().any(|root| path.starts_with(root))
}
pub(super) fn locate(&self, path: &Path, live: &BTreeSet<PathBuf>) -> Result<Location, String> {
if !path.is_absolute() {
return Err("atomic project lookup must be absolute".into());
}
let mut queue = lookup_components(path);
let mut current = PathBuf::new();
let mut links = 0;
while let Some(part) = queue.pop_front() {
match Path::new(&part).components().next().unwrap() {
Component::Prefix(_) => current.push(&part),
Component::RootDir => current.push(&part),
Component::CurDir => {}
Component::ParentDir => {
current.pop();
}
Component::Normal(_) => current.push(&part),
}
if let Some(target) = self.aliases.get(&current) {
links += 1;
if links > 40 {
return Err("atomic project alias depth exceeded".into());
}
let mut replaced = lookup_components(target);
replaced.append(&mut queue);
queue = replaced;
if target.is_absolute() {
current.clear();
} else {
current.pop();
}
continue;
}
let kind = if self.directories.contains(&current) {
Some(NodeKind::Directory)
} else if self.files.contains_key(&current) || live.contains(&current) {
Some(NodeKind::File)
} else {
None
};
if kind == Some(NodeKind::File) && !queue.is_empty() {
return Err(format!(
"atomic project path traverses a file: {}",
current.display()
));
}
if kind.is_none() {
if !self.covered(&current) {
return Err(format!(
"atomic project lookup is outside the resource universe: {}",
current.display()
));
}
return Ok(Location {
path: current,
kind: None,
final_component: queue.is_empty(),
});
}
}
let kind = if self.directories.contains(&current) {
Some(NodeKind::Directory)
} else if self.files.contains_key(&current) || live.contains(&current) {
Some(NodeKind::File)
} else {
None
};
if kind == Some(NodeKind::File)
&& path
.as_os_str()
.to_string_lossy()
.ends_with(std::path::MAIN_SEPARATOR)
{
return Err("atomic project trailing separator requires a directory".into());
}
Ok(Location {
path: current,
kind,
final_component: true,
})
}
pub(super) fn check_generated_output(
&self,
logical: &Path,
physical: &Path,
live: &BTreeSet<PathBuf>,
) -> Result<(), String> {
let location = self.locate(logical, live)?;
if location.path != physical
|| !location.final_component
|| location.kind == Some(NodeKind::Directory)
|| self.files.contains_key(&location.path)
|| !self.permits_generated(&location.path)
{
return Err("atomic project output conflicts with immutable input, writable roots or host path resolution".into());
}
Ok(())
}
pub(super) fn index(
&self,
root: &Path,
live: &BTreeSet<PathBuf>,
limit: usize,
) -> Result<DirectoryIndex, String> {
let mut index = DirectoryIndex {
directories: Vec::new(),
directory_aliases: BTreeMap::new(),
names: BTreeMap::new(),
};
let mut pending = vec![(root.to_path_buf(), Vec::<PathBuf>::new())];
let mut count = 0;
while let Some((logical, mut ancestors)) = pending.pop() {
let location = self.locate(&logical, live)?;
if location.kind != Some(NodeKind::Directory) || ancestors.contains(&location.path) {
continue;
}
ancestors.push(location.path.clone());
let mut names = BTreeSet::new();
for child in self
.files
.keys()
.chain(&self.directories)
.chain(self.aliases.keys())
.chain(live)
{
if child.parent() == Some(location.path.as_path()) {
if let Some(name) = child.file_name() {
names.insert(name.to_owned());
}
}
}
for name in names {
count += 1;
if count > limit {
return Err("native resource directory capacity exceeded".into());
}
let child = logical.join(&name);
let location = self.locate(&child, live)?;
match location.kind {
Some(NodeKind::Directory) => pending.push((child, ancestors.clone())),
Some(NodeKind::File) => index.names.entry(name).or_default().push(child),
None => {}
}
}
}
for paths in index.names.values_mut() {
paths.sort();
}
Ok(index)
}
}
fn normalized(path: &Path) -> bool {
path.is_absolute()
&& path.components().collect::<PathBuf>().as_os_str() == path.as_os_str()
&& !path
.components()
.any(|c| matches!(c, Component::CurDir | Component::ParentDir))
}
fn lookup_components(path: &Path) -> VecDeque<OsString> {
let mut parts: VecDeque<_> = path
.components()
.map(|c| c.as_os_str().to_owned())
.collect();
// Path::components removes a trailing slash or `/.`. Both require a
// directory, including at the end of an expanded alias target. Preserve
// that traversal instead of incorrectly reading `file/.` as `file`.
let raw = path.as_os_str().to_string_lossy();
if raw.ends_with(std::path::is_separator)
|| raw
.strip_suffix('.')
.is_some_and(|p| p.ends_with(std::path::is_separator))
{
parts.push_back(OsString::from("."));
}
parts
}