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

+232 -10
View File
@@ -13,19 +13,34 @@ pub(super) fn converted_relative_path(relative: &Path, bytes: &[u8]) -> Option<P
}
#[cfg(not(target_os = "linux"))]
pub(super) fn convert(_run: &Path, _source: &[u8]) -> std::io::Result<Option<Vec<u8>>> {
Ok(None)
pub(super) struct Preparation;
#[cfg(not(target_os = "linux"))]
impl Preparation {
pub(super) fn new(_run: &Path) -> Self {
Self
}
pub(super) fn convert(&self, _source: &[u8]) -> std::io::Result<Option<Vec<u8>>> {
Ok(None)
}
}
#[cfg(target_os = "linux")]
pub(super) use linux::convert;
pub(super) use linux::Preparation;
#[cfg(target_os = "linux")]
mod linux {
use sha2::{Digest, Sha256};
use std::{
cell::OnceCell,
env, fs,
io::{self, Read},
os::unix::{fs::DirBuilderExt, process::CommandExt},
io::{self, Read, Write},
os::unix::{
ffi::OsStrExt,
fs::{DirBuilderExt, MetadataExt, OpenOptionsExt},
process::CommandExt,
},
path::{Path, PathBuf},
process::{Command, Stdio},
sync::atomic::{AtomicU64, Ordering},
@@ -61,7 +76,203 @@ mod linux {
}
}
pub(crate) fn convert(run: &Path, source: &[u8]) -> io::Result<Option<Vec<u8>>> {
const CACHE_LIMIT: usize = 2 * 1024 * 1024;
const CACHE_SLOTS: u8 = 32;
const NODE_LIMIT: usize = 16_384;
struct CacheIdentity {
directory: PathBuf,
fingerprint: Sha256,
}
impl CacheIdentity {
fn for_desktop(run: &Path, bwrap: &Path, tools: &Path) -> Option<Self> {
env::var_os("TEXRRA_DESKTOP_INSTANCE")?;
let executable = env::current_exe().ok()?;
let runtime = executable.parent()?.parent()?;
// The desktop launcher verifies the bundle receipt and the EPS tarball
// before starting this executable. Keep arbitrary CLI tools uncached.
if runtime.parent()?.file_name()? != "runtime"
|| executable != runtime.join("bin/native_editor")
|| tools != runtime.join("eps-tools")
|| bwrap != tools.join("usr/bin/bwrap")
|| run.parent()? != runtime.join("web-runs")
|| fs::metadata("/etc/ld.so.preload").is_ok()
{
return None;
}
let receipt = read_regular(&runtime.join("desktop-bundle.json"), 128 * 1024).ok()?;
let bundle_version = Sha256::digest(&receipt);
if runtime.file_name()?.as_bytes() != format!("{bundle_version:x}").as_bytes() {
return None;
}
let receipt: serde_json::Value = serde_json::from_slice(&receipt).ok()?;
if receipt["sha256"]["eps-tools.tar"].as_str()?.len() != 64 {
return None;
}
// The converter binds the unpacked tool tree and host libraries
// read-only. Stat the bound trees to invalidate on updates, even
// when bytes are replaced without changing the modification time.
let mut key = Sha256::new();
key.update(b"texrra desktop EPS pdfwrite 1");
key.update(bundle_version);
let mut count = 0;
fingerprint_tree(&mut key, tools, tools, &mut count).ok()?;
let host = Path::new("/usr/lib64");
fingerprint_tree(&mut key, host, host, &mut count).ok()?;
if let Ok(metadata) = fs::symlink_metadata("/etc/ld.so.cache") {
fingerprint_metadata(&mut key, &metadata);
}
Some(Self {
directory: run.parent()?.join(".cached-eps"),
fingerprint: key,
})
}
fn for_source(&self, source: &[u8]) -> Cache<'_> {
let mut key = self.fingerprint.clone();
key.update(Sha256::digest(source));
Cache {
directory: &self.directory,
key: key.finalize().into(),
}
}
}
struct Cache<'a> {
directory: &'a Path,
key: [u8; 32],
}
impl Cache<'_> {
fn slot(&self) -> PathBuf {
self.directory
.join(format!("{:02x}.pdf-cache", self.key[0] % CACHE_SLOTS))
}
fn read(&self) -> Option<Vec<u8>> {
if !fs::symlink_metadata(self.directory).ok()?.is_dir() {
return None;
}
let record = read_regular(&self.slot(), CACHE_LIMIT + 64).ok()?;
let (key, digest, pdf) = (record.get(..32)?, record.get(32..64)?, record.get(64..)?);
let expected: [u8; 32] = Sha256::digest(pdf).into();
if key != self.key || digest != expected || !is_pdf(pdf) {
return None;
}
Some(pdf.to_vec())
}
fn write(&self, pdf: &[u8]) -> io::Result<()> {
if pdf.len() > CACHE_LIMIT {
return Ok(());
}
match fs::DirBuilder::new().mode(0o700).create(self.directory) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
if !fs::symlink_metadata(self.directory)?.is_dir() {
return Err(error);
}
}
Err(error) => return Err(error),
}
let scratch = Scratch::new(self.directory)?;
let temporary = scratch.0.join("artifact");
let mut file = fs::File::create_new(&temporary)?;
file.write_all(&self.key)?;
file.write_all(&Sha256::digest(pdf))?;
file.write_all(pdf)?;
file.sync_all()?;
fs::rename(temporary, self.slot())
}
}
fn read_regular(path: &Path, limit: usize) -> io::Result<Vec<u8>> {
let file = fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(path)?;
let metadata = file.metadata()?;
if !metadata.is_file() || metadata.len() > limit as u64 {
return Err(io::Error::other("invalid EPS cache file"));
}
let mut bytes = Vec::new();
file.take(limit as u64 + 1).read_to_end(&mut bytes)?;
if bytes.len() > limit {
return Err(io::Error::other("EPS cache file exceeds size limit"));
}
Ok(bytes)
}
fn fingerprint_tree(
key: &mut Sha256,
root: &Path,
path: &Path,
count: &mut usize,
) -> io::Result<()> {
*count += 1;
if *count > NODE_LIMIT {
return Err(io::Error::other("EPS tool tree exceeds cache scan limit"));
}
let relative = path
.strip_prefix(root)
.expect("collecting descendants only");
let relative = relative.as_os_str().as_bytes();
key.update((relative.len() as u64).to_le_bytes());
key.update(relative);
let metadata = fs::symlink_metadata(path)?;
fingerprint_metadata(key, &metadata);
if metadata.is_dir() {
let mut children = fs::read_dir(path)?
.map(|entry| entry.map(|entry| entry.path()))
.collect::<io::Result<Vec<_>>>()?;
children.sort_unstable();
for child in children {
fingerprint_tree(key, root, &child, count)?;
}
}
Ok(())
}
fn fingerprint_metadata(key: &mut Sha256, metadata: &fs::Metadata) {
key.update(metadata.dev().to_le_bytes());
key.update(metadata.ino().to_le_bytes());
key.update(metadata.mode().to_le_bytes());
key.update(metadata.len().to_le_bytes());
key.update(metadata.mtime().to_le_bytes());
key.update(metadata.mtime_nsec().to_le_bytes());
key.update(metadata.ctime().to_le_bytes());
key.update(metadata.ctime_nsec().to_le_bytes());
}
fn is_pdf(pdf: &[u8]) -> bool {
pdf.starts_with(b"%PDF-") && pdf.trim_ascii_end().ends_with(b"%%EOF")
}
pub(crate) struct Preparation<'a> {
run: &'a Path,
identity: OnceCell<Option<CacheIdentity>>,
}
impl<'a> Preparation<'a> {
pub(crate) fn new(run: &'a Path) -> Self {
Self {
run,
identity: OnceCell::new(),
}
}
pub(crate) fn convert(&self, source: &[u8]) -> io::Result<Option<Vec<u8>>> {
convert(self.run, source, &self.identity)
}
}
fn convert(
run: &Path,
source: &[u8],
cache_identity: &OnceCell<Option<CacheIdentity>>,
) -> io::Result<Option<Vec<u8>>> {
let bwrap = env::var_os("TEXRRA_EPS_BWRAP");
let tool_root = env::var_os("TEXRRA_EPS_GS_ROOT");
let (bwrap, tool_root) = match (bwrap, tool_root) {
@@ -83,6 +294,17 @@ mod linux {
));
}
let identity =
cache_identity.get_or_init(|| CacheIdentity::for_desktop(run, &bwrap, &tool_root));
let cache = identity
.as_ref()
.map(|identity| identity.for_source(source));
if let Some(pdf) = cache.as_ref().and_then(Cache::read) {
if env::var_os("TEXRRA_EDITOR_PREPARATION_TRACE").is_some_and(|value| value == "1") {
eprintln!("Editor EPS cache hit");
}
return Ok(Some(pdf));
}
let scratch = Scratch::new(run)?;
let input = scratch.0.join("input.eps");
let output = scratch.0.join("output.pdf");
@@ -209,15 +431,15 @@ mod linux {
fs::File::open(output)?
.take(MAX_PDF_BYTES + 1)
.read_to_end(&mut pdf)?;
if pdf.len() as u64 > MAX_PDF_BYTES
|| !pdf.starts_with(b"%PDF-")
|| !pdf.trim_ascii_end().ends_with(b"%%EOF")
{
if pdf.len() as u64 > MAX_PDF_BYTES || !is_pdf(&pdf) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"invalid converted EPS PDF",
));
}
if let Some(cache) = cache {
let _ = cache.write(&pdf);
}
Ok(Some(pdf))
}
}