Prewarm LaTeX format and cache verified project preparation artifacts

This commit is contained in:
gloamxun committed 2026-12-02 18:01:20 +08:00
1 parent fdd327eb01
commit c1742e1c10
10 files changed
+668 -28

No files matched your search

+80 -4
View File
@@ -15,6 +15,8 @@ use std::{
use texrra_engine::native::{CompileRequest, GeneratedArtifacts, ProjectSnapshot};
use texrra_tex_core::resources::ResourceVersion;
mod cache;
const MAX_AUX_BYTES: u64 = 2 * 1024 * 1024;
const MAX_INPUT_BYTES: u64 = 32 * 1024 * 1024;
const MAX_BBL_BYTES: u64 = 4 * 1024 * 1024;
@@ -24,6 +26,7 @@ pub(super) fn from_seed(
request: &CompileRequest,
artifacts: &GeneratedArtifacts,
files: &BTreeMap<PathBuf, Arc<[u8]>>,
cached_bbl: Option<&Path>,
) -> Result<Option<(Plan, Arc<[u8]>)>, String> {
let cwd = &request.world.cwd;
let Some(name) = request.input.file_stem() else {
@@ -83,7 +86,9 @@ pub(super) fn from_seed(
&request.world.texmf_roots,
)?);
}
let data = plan.run(&scratch.0, |path| files.get(path).map(Arc::as_ref))?;
let data = plan.run(&scratch.0, cached_bbl, |path| {
files.get(path).map(Arc::as_ref)
})?;
Ok(Some((plan, data)))
}
@@ -120,7 +125,7 @@ impl Plan {
return Ok(None);
}
let scratch = Scratch::new(&self.cwd).map_err(bib_error)?;
self.run(&scratch.0, |path| {
self.run(&scratch.0, None, |path| {
edits.get(path).map_or_else(
|| project.file(path).map(|file| file.data.as_ref()),
Option::as_deref,
@@ -132,9 +137,12 @@ impl Plan {
fn run<'a>(
&self,
scratch: &Path,
cached_bbl: Option<&Path>,
mut contents: impl FnMut(&Path) -> Option<&'a [u8]>,
) -> Result<Arc<[u8]>, String> {
let started = Instant::now();
let mut total = 0;
let mut inputs = Vec::new();
// Stage only named databases and a single style from trusted inputs.
for path in self.databases.iter().chain(std::iter::once(&self.style)) {
let relative = if path == &self.style {
@@ -156,10 +164,39 @@ impl Plan {
if total > MAX_INPUT_BYTES {
return Err("BibTeX inputs exceed the size limit".into());
}
inputs.push((relative, data));
}
let identity = cached_bbl.and_then(|_| cache::tool_identity(scratch));
let cache_entry = cached_bbl.zip(identity.map(|identity| {
let mut hash = Sha256::new();
hash.update(identity);
cache::field(&mut hash, &self.records);
for (relative, bytes) in &inputs {
cache::field(&mut hash, relative.as_os_str().as_encoded_bytes());
cache::field(&mut hash, bytes);
}
<[u8; 32]>::from(hash.finalize())
}));
if let Some((path, key)) = &cache_entry
&& let Some(data) = cache::read(path, key)
{
trace_preparation("hit", started);
return Ok(data.into());
}
for (relative, data) in inputs {
stage(scratch, relative, data).map_err(bib_error)?;
}
fs::write(scratch.join(format!("{JOB}.aux")), &self.records).map_err(bib_error)?;
run_bibtex(scratch).map(Into::into)
let (data, complete) = run_bibtex(scratch)?;
if let Some((path, key)) = cache_entry {
if complete && cache::tool_identity(scratch) == identity {
let _ = cache::write(path, &key, &data);
}
trace_preparation("miss", started);
} else if cached_bbl.is_some() {
trace_preparation("bypass", started);
}
Ok(data.into())
}
}
@@ -372,7 +409,20 @@ fn find_style(scratch: &Path, style: &Path, roots: &[PathBuf]) -> Result<Arc<[u8
.map_err(bib_error)
}
fn run_bibtex(scratch: &Path) -> Result<Vec<u8>, String> {
fn trace_preparation(result: &str, started: Instant) {
if std::env::var_os("TEXRRA_EDITOR_PREPARATION_TRACE").is_some_and(|value| value == "1") {
eprintln!(
"Texrra editor preparation {}",
serde_json::json!({
"stage": "bibtex",
"cache": result,
"ms": started.elapsed().as_secs_f64() * 1000.0,
})
);
}
}
fn run_bibtex(scratch: &Path) -> Result<(Vec<u8>, bool), String> {
#[cfg(target_os = "linux")]
let mut command = {
// Bound project-provided .bst programs on our Linux backend.
@@ -401,6 +451,7 @@ fn run_bibtex(scratch: &Path) -> Result<Vec<u8>, String> {
match child.try_wait() {
Ok(Some(status)) if status.success() || status.code() == Some(1) => {
return read_limited(&scratch.join(format!("{JOB}.bbl")), MAX_BBL_BYTES)
.map(|data| (data, status.success()))
.map_err(bib_error);
}
Ok(Some(status)) => return Err(format!("BibTeX failed ({status})")),
@@ -452,6 +503,31 @@ impl Drop for Scratch {
mod tests {
use super::*;
#[test]
fn cached_bibliography_requires_the_current_key_and_untampered_output() {
let scratch = Scratch::new(&std::env::temp_dir()).unwrap();
let path = scratch.0.join("project.bbl-cache");
let first = [1; 32];
let second = [2; 32];
assert_eq!(cache::read(&path, &first), None);
cache::write(&path, &first, b"first").unwrap();
assert_eq!(
cache::read(&path, &first).as_deref(),
Some(b"first".as_slice())
);
assert_eq!(cache::read(&path, &second), None);
cache::write(&path, &second, b"second").unwrap();
assert_eq!(cache::read(&path, &first), None);
assert_eq!(
cache::read(&path, &second).as_deref(),
Some(b"second".as_slice())
);
let mut bytes = fs::read(&path).unwrap();
*bytes.last_mut().unwrap() ^= 1;
fs::write(&path, bytes).unwrap();
assert_eq!(cache::read(&path, &second), None);
}
#[test]
fn bibliography_names_stay_inside_scratch_paths() {
assert_eq!(