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!(
@@ -0,0 +1,220 @@
use super::{MAX_BBL_BYTES, read_limited};
use sha2::{Digest, Sha256};
use std::{
fs::{self, OpenOptions},
io::{self, Write},
path::Path,
sync::atomic::{AtomicU64, Ordering},
};
const MAGIC: &[u8; 8] = b"TEXBBL01";
const HEADER: usize = MAGIC.len() + 2 * 32;
static NEXT: AtomicU64 = AtomicU64::new(0);
pub(super) fn field(hash: &mut Sha256, bytes: &[u8]) {
hash.update((bytes.len() as u64).to_le_bytes());
hash.update(bytes);
}
pub(super) fn read(path: &Path, key: &[u8; 32]) -> Option<Vec<u8>> {
if !fs::symlink_metadata(path).ok()?.is_file() {
return None;
}
let bytes = read_limited(path, MAX_BBL_BYTES + HEADER as u64).ok()?;
let rest = bytes.strip_prefix(MAGIC)?;
let rest = rest.strip_prefix(key.as_slice())?;
let (digest, output) = rest.split_at_checked(32)?;
(Sha256::digest(output).as_slice() == digest).then(|| output.to_vec())
}
pub(super) fn write(path: &Path, key: &[u8; 32], output: &[u8]) -> io::Result<()> {
if output.len() as u64 > MAX_BBL_BYTES {
return Err(io::Error::other("BibTeX cache output exceeds size limit"));
}
let parent = path.parent().expect("cache entry has a parent");
fs::create_dir_all(parent)?;
if !fs::symlink_metadata(parent)?.is_dir() {
return Err(io::Error::other("BibTeX cache needs a private directory"));
}
let temporary = path.with_extension(format!(
"{}.{}.pending",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)?;
let result = (|| {
file.write_all(MAGIC)?;
file.write_all(key)?;
file.write_all(&Sha256::digest(output))?;
file.write_all(output)?;
file.sync_all()?;
fs::rename(&temporary, path)
})();
if result.is_err() {
let _ = fs::remove_file(&temporary);
}
result
}
#[cfg(not(all(target_os = "linux", target_arch = "x86_64", target_env = "gnu")))]
pub(super) fn tool_identity(_scratch: &Path) -> Option<[u8; 32]> {
None
}
#[cfg(all(target_os = "linux", target_arch = "x86_64", target_env = "gnu"))]
pub(super) fn tool_identity(scratch: &Path) -> Option<[u8; 32]> {
use std::{env, path::PathBuf, process::Command};
const LOADER: &str = "/lib64/ld-linux-x86-64.so.2";
// A preloaded library can execute initialization outside the ordinary
// dependency list. Let the regular invocation handle such hosts.
if fs::symlink_metadata("/etc/ld.so.preload").err()?.kind() != io::ErrorKind::NotFound {
return None;
}
let search = env::var_os("PATH")?;
let bibtex = executable(&search, "bibtex")?;
let prlimit = executable(&search, "prlimit")?;
let kpsewhich = executable(&search, "kpsewhich")?;
if bibtex.parent() != kpsewhich.parent() {
return None;
}
let mut digest = Sha256::new();
field(&mut digest, search.as_encoded_bytes());
hash_file(&mut digest, Path::new(LOADER))?;
for command in [&bibtex, &prlimit] {
hash_file(&mut digest, command)?;
let listing = super::private_environment(&mut Command::new(LOADER), scratch)
.arg("--list")
.arg(command)
.output()
.ok()?;
if !listing.status.success() {
return None;
}
let mut listed_any = false;
for line in std::str::from_utf8(&listing.stdout).ok()?.lines() {
let (name, _) = line.trim().rsplit_once(" (")?;
if name.starts_with("linux-vdso.so.") {
continue;
}
let path = name.split_once(" => ").map_or(name, |(_, path)| path);
if !Path::new(path).is_absolute() {
return None;
}
hash_file(&mut digest, Path::new(path))?;
listed_any = true;
}
if !listed_any {
return None;
}
}
// Re-resolve configuration files. A new higher-priority texmf.cnf can
// alter BibTeX's search or capacity even when the binaries are unchanged.
let configs = super::private_environment(&mut Command::new(&kpsewhich), scratch)
.env("BIBINPUTS", ".")
.env("BSTINPUTS", ".")
.args(["--progname=bibtex", "--all", "texmf.cnf"])
.output()
.ok()?;
if !configs.status.success() || configs.stdout.len() > 64 * 1024 {
return None;
}
hash_file(&mut digest, &kpsewhich)?;
for line in std::str::from_utf8(&configs.stdout).ok()?.lines() {
let path = PathBuf::from(line);
if !path.is_absolute() {
return None;
}
hash_file(&mut digest, &path)?;
}
Some(digest.finalize().into())
}
#[cfg(all(target_os = "linux", target_arch = "x86_64", target_env = "gnu"))]
fn executable(search: &std::ffi::OsStr, name: &str) -> Option<std::path::PathBuf> {
use std::os::unix::fs::PermissionsExt;
for directory in std::env::split_paths(search) {
if !directory.is_absolute() {
return None;
}
let path = directory.join(name);
match fs::metadata(&path) {
Ok(metadata) if metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 => {
return Some(path);
}
Ok(_) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(_) => return None,
}
}
None
}
#[cfg(all(target_os = "linux", target_arch = "x86_64", target_env = "gnu"))]
fn hash_file(hash: &mut Sha256, path: &Path) -> Option<()> {
use std::{
collections::BTreeMap,
fs::Metadata,
io::Read,
os::unix::fs::MetadataExt,
path::PathBuf,
sync::{Mutex, OnceLock},
};
#[derive(Clone, Copy, PartialEq, Eq)]
struct Stamp {
inode: (u64, u64),
bytes: u64,
modified: (i64, i64),
changed: (i64, i64),
}
impl From<&Metadata> for Stamp {
fn from(m: &Metadata) -> Self {
Self {
inode: (m.dev(), m.ino()),
bytes: m.len(),
modified: (m.mtime(), m.mtime_nsec()),
changed: (m.ctime(), m.ctime_nsec()),
}
}
}
type FileHashes = BTreeMap<PathBuf, (Stamp, [u8; 32])>;
static HASHES: OnceLock<Mutex<FileHashes>> = OnceLock::new();
let real = path.canonicalize().ok()?;
let file = fs::File::open(&real).ok()?;
let metadata = file.metadata().ok()?;
let stamp = Stamp::from(&metadata);
const MAX_TOOL_BYTES: u64 = 32 * 1024 * 1024;
if !metadata.is_file() || stamp.bytes > MAX_TOOL_BYTES {
return None;
}
let mut hashes = HASHES
.get_or_init(|| Mutex::new(BTreeMap::new()))
.lock()
.ok()?;
let sum = match hashes.get(&real) {
Some((previous, sum)) if *previous == stamp => *sum,
_ => {
let mut contents = Sha256::new();
let length = io::copy(&mut (&file).take(MAX_TOOL_BYTES + 1), &mut contents).ok()?;
if length != stamp.bytes || Stamp::from(&file.metadata().ok()?) != stamp {
return None;
}
let sum: [u8; 32] = contents.finalize().into();
if hashes.len() >= 64 {
hashes.clear();
}
hashes.insert(real.clone(), (stamp, sum));
sum
}
};
field(hash, path.as_os_str().as_encoded_bytes());
field(hash, real.as_os_str().as_encoded_bytes());
hash.update(sum);
Some(())
}
+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))
}
}
+33 -2
View File
@@ -1,7 +1,11 @@
use super::{InputProfile, OpeningEditor, fs, json, projects::ProjectStore, reply, stage_sources};
use super::{
InputProfile, NativeCompiler, OpeningEditor, fs, json, projects::ProjectStore, reply,
stage_sources,
};
use std::{
io::{ErrorKind, Read},
path::{Path, PathBuf},
time::Instant,
};
use tiny_http::Request;
@@ -14,6 +18,7 @@ pub(super) struct Library {
manifest: PathBuf,
runs: PathBuf,
profile: InputProfile,
compiler: NativeCompiler,
}
impl Library {
@@ -37,9 +42,33 @@ impl Library {
manifest,
runs,
profile,
compiler: NativeCompiler::default(),
})
}
pub(super) fn prewarm_format(&self) {
let compiler = self.compiler.clone();
let format = self.format.clone();
let _ = std::thread::Builder::new()
.name("texrra-prewarm-format".into())
.spawn(move || {
let trace = std::env::var_os("TEXRRA_EDITOR_PREPARATION_TRACE")
.is_some_and(|value| value == "1");
let started = Instant::now();
let result = compiler.prewarm_format(&format);
if trace {
eprintln!("Texrra editor preparation {}", json!({
"stage": "prewarm-format",
"ms": started.elapsed().as_secs_f64() * 1000.0,
"ok": result.is_ok(),
}));
}
if let Err(error) = result {
eprintln!("Editor format prewarm: {error}");
}
});
}
pub(super) fn list(&self, request: Request) {
match self.store.list() {
Ok(projects) => reply(request, 200, json!({"projects": projects})),
@@ -127,7 +156,9 @@ impl Library {
let cache = super::preview_cache::PreviewCache::for_project(
&self.runs, &info.id, &run, &staged, &self.format, &self.manifest,
);
OpeningEditor::start(info.id, run, staged, cache)
let compiler = self.compiler.new_session_sharing_format()
.with_automatic_entry_checkpoints();
OpeningEditor::start(info.id, run, staged, cache, compiler)
}
}
+40 -9
View File
@@ -334,13 +334,16 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
root, &source, &format, &manifest, &run, &additional, input_profile,
)?;
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
let editor = finish_prepare(staged, &run, &compiler, None)?;
let editor = finish_prepare(staged, &run, &compiler, None, None)?;
(port, Some(EditorSession::new(run, editor, compiler, None)))
};
let mut session = session.map(|session| Arc::new(Mutex::new(session)));
let mut opening: Option<OpeningEditor> = None;
let server = Server::http(("127.0.0.1", port)).map_err(|e| e.to_string())?;
println!("Native editor http://{}", server.server_addr());
if let Some(library) = &library {
library.prewarm_format();
}
for request in server.incoming_requests() {
let url = request.url().to_owned();
let path = url.as_str();
@@ -712,6 +715,7 @@ impl OpeningEditor {
run: PathBuf,
staged: StagedProject,
cache: Option<preview_cache::PreviewCache>,
compiler: NativeCompiler,
) -> Result<Self, Box<dyn std::error::Error>> {
let files = staged.editable.iter().filter_map(|(name, path)| {
staged.files.get(path).map(|bytes| (name.as_str(), bytes.as_ref()))
@@ -726,7 +730,7 @@ impl OpeningEditor {
cache,
sources,
ready: Arc::new(OnceLock::new()),
compiler: NativeCompiler::default().with_automatic_entry_checkpoints(),
compiler,
superseded: Arc::new(AtomicBool::new(false)),
};
let id = opening.id.clone();
@@ -735,7 +739,7 @@ impl OpeningEditor {
let superseded = opening.superseded.clone();
let cache = opening.cache.clone();
std::thread::Builder::new().name("texrra-open-project".into()).spawn(move || {
let result = finish_prepare(staged, &run, &compiler, Some(&superseded))
let result = finish_prepare(staged, &run, &compiler, Some(&superseded), Some(&id))
.map(|editor| {
let mut session = EditorSession::new(run, editor, compiler, cache);
session.id = Some(id);
@@ -1092,6 +1096,7 @@ fn finish_prepare(
run: &Path,
compiler: &NativeCompiler,
superseded: Option<&AtomicBool>,
project_id: Option<&str>,
) -> Result<EditorProject, Box<dyn std::error::Error>> {
let StagedProject {
world,
@@ -1119,9 +1124,10 @@ fn finish_prepare(
let date = dates.get(input).and_then(|time| time.to_system_time());
Some((converted, data.clone(), date))
}).collect::<Vec<_>>();
let figure_preparation = figure_conversion::Preparation::new(run);
for (path, source, date) in figures {
check_current()?;
match figure_conversion::convert(run, &source) {
match figure_preparation.convert(&source) {
Ok(Some(pdf)) => {
let modified = date.unwrap_or_else(SystemTime::now);
copy_with_date(&path, &pdf, Some(modified), &mut dates)?;
@@ -1133,21 +1139,46 @@ fn finish_prepare(
}
// Provision the finite, immutable resource bundle used by this trial.
// The seed uses the same native compiler and actual package bytes.
let compile_seed = || -> Result<_, Box<dyn std::error::Error>> {
let trace_preparation = std::env::var_os("TEXRRA_EDITOR_PREPARATION_TRACE")
.is_some_and(|value| value == "1");
let compile_seed = |pass| -> Result<_, Box<dyn std::error::Error>> {
let job = compiler.start();
check_current()?;
Ok(job.compile_detailed(request.clone()))
let started = Instant::now();
let result = job.compile_detailed(request.clone());
if trace_preparation {
eprintln!("Texrra editor preparation {}", serde_json::json!({
"stage": "seed",
"pass": pass,
"ms": started.elapsed().as_secs_f64() * 1000.0,
"format": result.as_ref().ok().and_then(|doc| doc.format_preparation.as_ref())
.map(|format| format!("{format:?}")),
"ok": result.is_ok(),
}));
}
Ok(result)
};
let mut seed = compile_seed()?;
let mut seed = compile_seed(1)?;
let mut bibliography = None;
if let Ok(initial) = &seed {
match bibliography::from_seed(&request, &initial.resources.generated_artifacts, &files) {
let cached_bbl = project_id
.filter(|id| {
!id.is_empty() && id.bytes().all(|byte| byte.is_ascii_alphanumeric()
|| matches!(byte, b'-' | b'_'))
})
.and_then(|id| {
run.parent().map(|root| root.join(".cached-bibliographies")
.join(format!("{id}.bbl-cache")))
});
match bibliography::from_seed(
&request, &initial.resources.generated_artifacts, &files, cached_bbl.as_deref(),
) {
Ok(Some((plan, contents))) => {
let path = plan.output().to_owned();
copy_with_date(&path, &contents, Some(SystemTime::now()), &mut dates)?;
files.insert(path, contents);
bibliography = Some(plan);
seed = compile_seed()?;
seed = compile_seed(2)?;
}
Ok(None) => {}
Err(error) => eprintln!("Editor bibliography: {error}"),