Cache published project previews for the next desktop launch

This commit is contained in:
gloamxun committed 2026-12-02 16:20:18 +08:00
1 parent 11ec5c853c
commit f727188c41
8 files changed
+350 -17

No files matched your search

+244
View File
@@ -0,0 +1,244 @@
use super::StagedProject;
use flate2::{Compression, read::GzDecoder, write::GzEncoder};
use serde::Serialize;
use sha2::{Digest, Sha256};
use std::{
collections::BTreeMap,
fs::{self, File, OpenOptions},
io::{self, BufReader, BufWriter, Read, Write},
path::{Path, PathBuf},
sync::{
Arc, OnceLock,
atomic::{AtomicU64, Ordering},
mpsc,
},
};
use texrra_engine::native::{CompiledDocument, PreviewPage, PreviewUpdate, ProjectSnapshot};
use texrra_tex_core::resources::FileModificationTime;
const MAGIC: &[u8; 16] = b"texrra-preview1\n";
const LIMIT: usize = 32 * 1024 * 1024;
#[derive(Clone)]
pub(super) struct PreviewCache(Arc<CacheEntry>);
struct CacheEntry {
path: PathBuf,
key: [u8; 32],
originals: BTreeMap<PathBuf, (Option<Arc<[u8]>>, Option<FileModificationTime>)>,
}
impl PreviewCache {
pub(super) fn for_project(
runs: &Path,
id: &str,
run: &Path,
staged: &StagedProject,
format: &Path,
manifest: &Path,
) -> Option<Self> {
let mut key = Sha256::new();
hash_field(
&mut key,
staged
.entry
.strip_prefix(run)
.ok()?
.as_os_str()
.as_encoded_bytes(),
);
hash_field(
&mut key,
&serde_json::to_vec(&staged.options.input_profile).ok()?,
);
// Desktop run directories already belong to the verified package digest.
// Including file stamps also gives direct library runs a format/engine namespace.
for path in [format, manifest, &std::env::current_exe().ok()?] {
let metadata = fs::metadata(path).ok()?;
hash_field(&mut key, path.as_os_str().as_encoded_bytes());
key.update(metadata.len().to_le_bytes());
hash_date(
&mut key,
FileModificationTime::from_system_time(metadata.modified().ok()?).ok(),
);
}
for path in &staged.declared {
hash_field(
&mut key,
path.strip_prefix(run).ok()?.as_os_str().as_encoded_bytes(),
);
let data = staged.files.get(path);
key.update([u8::from(data.is_some())]);
if let Some(data) = data {
hash_field(&mut key, data);
}
hash_date(&mut key, staged.dates.get(path).copied());
}
let originals = staged
.editable
.values()
.map(|path| {
(
path.clone(),
(
staged.files.get(path).cloned(),
staged.dates.get(path).copied(),
),
)
})
.collect();
Some(Self(Arc::new(CacheEntry {
path: runs.join(".cached-previews").join(format!("{id}.preview")),
key: key.finalize().into(),
originals,
})))
}
pub(super) fn matches_saved_sources(&self, project: &ProjectSnapshot) -> bool {
self.0.originals.iter().all(|(path, (original, date))| {
let current = project.file(path).map(|file| &file.data);
current == original.as_ref() && project.modification_time(path) == *date
})
}
pub(super) fn exists(&self) -> bool {
self.open().is_ok()
}
pub(super) fn read(&self) -> io::Result<Vec<u8>> {
let mut bytes = Vec::new();
// The gzip trailer protects the completed JSON from truncated or corrupt
// cache files. Bound both the compressed file and the decoded body.
GzDecoder::new(self.open()?)
.take(LIMIT as u64 + 1)
.read_to_end(&mut bytes)?;
if bytes.is_empty() || bytes.len() > LIMIT {
return Err(io::Error::other("Invalid cached preview size"));
}
Ok(bytes)
}
fn open(&self) -> io::Result<BufReader<File>> {
let metadata = fs::symlink_metadata(&self.0.path)?;
if !metadata.is_file() || metadata.len() > LIMIT as u64 {
return Err(io::Error::other("Invalid cached preview file"));
}
let mut file = BufReader::new(File::open(&self.0.path)?);
let mut magic = [0; MAGIC.len()];
let mut key = [0; 32];
file.read_exact(&mut magic)?;
file.read_exact(&mut key)?;
if &magic != MAGIC || key != self.0.key {
return Err(io::Error::other("Cached preview version changed"));
}
Ok(file)
}
pub(super) fn refresh(self, document: Arc<CompiledDocument>) {
type CacheJob = (PreviewCache, Arc<CompiledDocument>);
static WRITER: OnceLock<Option<mpsc::SyncSender<CacheJob>>> = OnceLock::new();
let writer = WRITER.get_or_init(|| {
let (sender, receiver) = mpsc::sync_channel::<CacheJob>(1);
std::thread::Builder::new()
.name("texrra-preview-cache".into())
.spawn(move || {
while let Ok((cache, doc)) = receiver.recv() {
if let Ok(preview) = doc.preview_since(None) {
let _ = cache.write(&preview);
}
}
})
.ok()?;
Some(sender)
});
if let Some(writer) = writer {
let _ = writer.try_send((self, document));
}
}
fn write(&self, preview: &PreviewUpdate) -> io::Result<()> {
if preview.base_revision.is_some()
|| preview.page_count == 0
|| preview.pages.len() != preview.page_count
{
return Ok(());
}
#[derive(Serialize)]
struct Pages<'a> {
page_count: usize,
pages: &'a [PreviewPage],
}
static TEMP_NUMBER: AtomicU64 = AtomicU64::new(0);
let directory = self.0.path.parent().expect("cache has a directory");
fs::create_dir_all(directory)?;
let temporary = self.0.path.with_extension(format!(
"preview.{}.{}.new",
std::process::id(),
TEMP_NUMBER.fetch_add(1, Ordering::Relaxed)
));
let file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)?;
let result = (|| {
let mut file = BufWriter::new(file);
file.write_all(MAGIC)?;
file.write_all(&self.0.key)?;
let mut compressed = GzEncoder::new(file, Compression::fast());
serde_json::to_writer(
LimitedWriter {
inner: &mut compressed,
remaining: LIMIT,
},
&Pages {
page_count: preview.page_count,
pages: &preview.pages,
},
)?;
let mut file = compressed.finish()?;
file.flush()?;
if file.get_ref().metadata()?.len() > LIMIT as u64 {
return Err(io::Error::other("Cached preview exceeds the size limit"));
}
file.get_ref().sync_all()?;
fs::rename(&temporary, &self.0.path)
})();
if result.is_err() {
let _ = fs::remove_file(&temporary);
}
result
}
}
fn hash_field(key: &mut Sha256, data: &[u8]) {
key.update((data.len() as u64).to_le_bytes());
key.update(data);
}
fn hash_date(key: &mut Sha256, date: Option<FileModificationTime>) {
key.update([u8::from(date.is_some())]);
if let Some(date) = date {
key.update(date.unix_seconds.to_le_bytes());
key.update(date.nanoseconds.to_le_bytes());
}
}
struct LimitedWriter<W> {
inner: W,
remaining: usize,
}
impl<W: Write> Write for LimitedWriter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if buf.len() > self.remaining {
return Err(io::Error::other("Cached preview exceeds the size limit"));
}
let written = self.inner.write(buf)?;
self.remaining -= written;
Ok(written)
}
fn flush(&mut self) -> io::Result<()> {
self.inner.flush()
}
}