1use std::{
18 path::{Path, PathBuf},
19 sync::{
20 Mutex, Once, OnceLock, PoisonError,
21 atomic::{AtomicBool, Ordering},
22 },
23 time::{Duration, Instant},
24};
25
26use latexml_core::util::private_files::{
27 private_dir, private_to_user, publish_read_only, trusted_dir, user_id,
28};
29use latexml_engine::dump_paths;
30
31const FAILED: &str = ".failed";
35
36const ATTEMPTS: &str = ".attempts";
42
43const MAX_ATTEMPTS: u32 = 2;
47
48const FAILED_LAPSE: Duration = Duration::from_secs(24 * 60 * 60);
51
52const LOCK_WAIT: Duration = Duration::from_secs(300);
55
56const LAST_USED: &str = ".last_used";
58
59const IN_USE: &str = ".inuse";
62
63const LOCK: &str = ".lock";
65
66const KINDS: [&str; 2] = ["plain", "latex"];
68
69const STAMP_REFRESH: Duration = Duration::from_secs(24 * 60 * 60);
72
73const BINARIES: &str = ".binaries";
75
76const PRUNE_AFTER: Duration = Duration::from_secs(30 * 24 * 60 * 60);
78
79const KEEP_NEWEST: usize = 3;
82
83const PRUNE_EVERY: Duration = Duration::from_secs(24 * 60 * 60);
87const LAST_PRUNE: &str = ".last_prune";
88const PRUNE_LOCK: &str = ".prune.lock";
89
90const TRASH: &str = ".trash-";
94const TRASH_LAPSE: Duration = Duration::from_secs(60 * 60);
95
96static CACHE_IN_USE: OnceLock<CacheInUse> = OnceLock::new();
99
100struct CacheInUse {
101 dir: PathBuf,
102 _inuse: Option<std::fs::File>,
103}
104
105const INTERRUPTED: i32 = 130;
108
109static CANCEL_ON_INTERRUPT: AtomicBool = AtomicBool::new(false);
111
112static IN_FLIGHT: Mutex<Option<InFlight>> = Mutex::new(None);
114
115struct InFlight {
117 attempts: PathBuf,
119 before: Option<String>,
120 partial: PathBuf,
122}
123
124pub fn cancel_builds_on_interrupt() { CANCEL_ON_INTERRUPT.store(true, Ordering::Release); }
138
139fn install_interrupt_handler() {
141 static INSTALLED: Once = Once::new();
142 INSTALLED.call_once(|| {
143 let installed = ctrlc::try_set_handler(|| {
145 let mut slot = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner);
148 if let Some(build) = slot.take() {
149 undo(build);
150 note(log::Level::Info, format_args!(
151 "\n[format_dumps] interrupted: the format build was cancelled; the next conversion builds it again"
152 ));
153 }
154 latexml_core::watchdog::exit_now(INTERRUPTED);
157 });
158 if let Err(e @ ctrlc::Error::System(_)) = installed {
159 note(log::Level::Warn, format_args!(
160 "[format_dumps] cannot take the interrupt ({e}): a build interrupted now counts as one that failed"
161 ));
162 }
163 });
164}
165
166fn note(level: log::Level, args: std::fmt::Arguments) {
169 if level <= log::Level::Error || latexml_core::util::logger::stderr_admits(level) {
170 eprintln!("{args}");
171 }
172}
173
174#[cfg(test)]
177fn cancel_in_flight_build() -> bool {
178 let build = IN_FLIGHT
179 .lock()
180 .unwrap_or_else(PoisonError::into_inner)
181 .take();
182 build.map(undo).is_some()
183}
184
185fn undo(build: InFlight) {
188 match build.before {
189 Some(before) => {
190 let _ = std::fs::write(&build.attempts, before);
191 },
192 None => {
193 let _ = std::fs::remove_file(&build.attempts);
194 },
195 }
196 let _ = std::fs::remove_file(&build.partial);
198}
199
200fn set_in_flight(build: Option<InFlight>) {
202 *IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner) = build;
203}
204
205pub fn ensure_format_dumps() {
213 if dump_paths::building_format() {
214 return;
215 }
216 static ENSURED: OnceLock<()> = OnceLock::new();
217 ENSURED.get_or_init(|| {
218 let ensured = latexml_core::watchdog::off_the_clock(
221 "the format build",
222 LOCK_WAIT + Duration::from_secs(300),
223 ensure,
224 );
225 if let Err(reason) = ensured {
226 note(log::Level::Warn, format_args!(
228 "[format_dumps] {reason}: the format loads from the engine's own definitions instead of a dump"
229 ));
230 dump_paths::set_format_build_failure(reason);
231 }
232 });
233 if let Some(in_use) = CACHE_IN_USE.get() {
234 refresh_last_used(&in_use.dir);
235 }
236}
237
238fn ensure() -> Result<(), String> {
239 if std::env::var_os("LATEXML_NODUMP").is_some() || dump_paths::ini_mode() {
240 return Ok(());
241 }
242 let kinds: Vec<&'static str> = ["plain", "latex"]
243 .into_iter()
244 .filter(|kind| dump_paths::runtime_source_stamps(kind).is_some())
245 .collect();
246 if kinds.is_empty() {
247 return Ok(());
248 }
249 let wanted: Vec<&'static str> = kinds
252 .into_iter()
253 .filter(|kind| !dump_paths::format_dump_on_disk(kind))
254 .collect();
255 if wanted.is_empty() {
256 return Ok(());
257 }
258 let year = dump_paths::detect_ambient_texlive_year().unwrap_or(2000);
260 let dir = match cache_dir() {
261 Ok(dir) => dir,
262 Err(_)
263 if wanted
264 .iter()
265 .all(|kind| dump_paths::format_dump_available(kind)) =>
266 {
267 return Ok(());
268 },
269 Err(reason) => return Err(reason),
270 };
271 refresh_last_used(&dir);
274 let mut in_use = if trusted_dir(&dir) {
275 hold_in_use(&dir)
276 } else {
277 None
278 };
279 let ensured = ensure_in(&dir, year, wanted);
280 if trusted_dir(&dir) {
281 refresh_last_used(&dir);
282 if in_use.is_none() {
284 in_use = hold_in_use(&dir);
285 }
286 let _ = CACHE_IN_USE.set(CacheInUse {
287 _inuse: in_use,
288 dir: dir.clone(),
289 });
290 }
291 if let Some(base) = dir.parent() {
292 prune(base, &dir);
293 }
294 ensured
295}
296
297fn ensure_in(dir: &Path, year: u32, wanted: Vec<&'static str>) -> Result<(), String> {
299 let use_cached = |kind: &str| match cached_dump(dir, kind, year) {
301 Some((path, found_year)) => {
302 dump_paths::set_rebuilt_dump(kind, path, found_year);
303 true
304 },
305 None => false,
306 };
307 let missing: Vec<&'static str> = wanted
308 .into_iter()
309 .filter(|kind| !use_cached(kind) && !dump_paths::format_dump_available(kind))
310 .collect();
311 if missing.is_empty() {
312 return Ok(());
313 }
314 private_dir(dir)?;
315 let mut reasons = Vec::new();
316 let missing: Vec<&'static str> = missing
317 .into_iter()
318 .filter(|kind| match failed_before(dir, kind) {
319 Some(reason) => {
320 reasons.push(reason);
321 false
322 },
323 None => true,
324 })
325 .collect();
326 if !missing.is_empty() {
327 let seen: Vec<Option<String>> = missing
331 .iter()
332 .map(|kind| attempts_text(dir, kind))
333 .collect();
334 let _lock = match lock_dir(dir) {
336 Ok(lock) => lock,
337 Err(reason) => {
338 reasons.push(reason);
339 return Err(reasons.join("; "));
340 },
341 };
342 remove_partial_dumps(dir);
345 for (kind, seen) in missing.into_iter().zip(seen) {
346 if use_cached(kind) {
348 continue;
349 }
350 if let Some(reason) = failed_before(dir, kind) {
351 reasons.push(reason);
352 continue;
353 }
354 let now = attempts_text(dir, kind);
357 if now.is_some() && now != seen {
358 reasons.push(previous_attempts(dir, kind).1);
359 continue;
360 }
361 if let Err(reason) = attempt(kind, year, dir, &use_cached) {
362 reasons.push(reason);
363 }
364 }
365 }
366 if reasons.is_empty() {
367 Ok(())
368 } else {
369 Err(reasons.join("; "))
370 }
371}
372
373fn attempt(
376 kind: &'static str,
377 year: u32,
378 dir: &Path,
379 use_cached: &dyn Fn(&str) -> bool,
380) -> Result<(), String> {
381 let (failed, last_reason) = previous_attempts(dir, kind);
382 if failed >= MAX_ATTEMPTS {
383 return Err(mark_failed(dir, kind, &last_reason));
384 }
385 if CANCEL_ON_INTERRUPT.load(Ordering::Acquire) {
387 install_interrupt_handler();
388 }
389 {
390 let mut slot = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner);
393 *slot = Some(InFlight {
394 attempts: kind_file(dir, ATTEMPTS, kind),
395 before: attempts_text(dir, kind),
396 partial: partial_dump(dir, kind, year),
397 });
398 if let Err(reason) = note_attempt(
399 dir,
400 kind,
401 failed + 1,
402 &format!("the {kind} format build died with its process"),
403 ) {
404 *slot = None;
405 return Err(reason);
406 }
407 }
408 note(
409 log::Level::Info,
410 format_args!(
411 "[format_dumps] no {kind} dump matches this TeX tree; building one into {} (once for this tree; later \
412 conversions reuse it)",
413 dir.display()
414 ),
415 );
416 let built = build(kind, year, dir);
417 set_in_flight(None);
420 let built = built.and_then(|()| {
421 if use_cached(kind) {
422 Ok(())
423 } else {
424 Err(format!(
425 "the {kind} dump built into {} does not match this TeX tree",
426 dir.display()
427 ))
428 }
429 });
430 match built {
431 Ok(()) => {
432 let _ = std::fs::remove_file(kind_file(dir, ATTEMPTS, kind));
433 Ok(())
434 },
435 Err(reason) => {
436 let _ = note_attempt(dir, kind, failed + 1, &reason);
437 if failed + 1 >= MAX_ATTEMPTS {
438 Err(mark_failed(dir, kind, &reason))
439 } else {
440 Err(reason)
441 }
442 },
443 }
444}
445
446fn kind_file(dir: &Path, marker: &str, kind: &str) -> PathBuf {
448 dir.join(format!("{marker}.{kind}"))
449}
450
451fn attempts_text(dir: &Path, kind: &str) -> Option<String> {
453 std::fs::read_to_string(kind_file(dir, ATTEMPTS, kind)).ok()
454}
455
456fn previous_attempts(dir: &Path, kind: &str) -> (u32, String) {
459 let Some(text) = attempts_text(dir, kind) else {
460 return (0, String::new());
461 };
462 let (count, reason) = text.split_once('\t').unwrap_or((&text, ""));
463 let reason = if reason.is_empty() {
464 format!("the {kind} format build did not succeed")
465 } else {
466 reason.to_string()
467 };
468 (count.trim().parse().unwrap_or(1), reason)
469}
470
471fn note_attempt(dir: &Path, kind: &str, count: u32, reason: &str) -> Result<(), String> {
474 let path = kind_file(dir, ATTEMPTS, kind);
475 std::fs::write(&path, format!("{count}\t{reason}"))
476 .map_err(|e| format!("cannot write {}: {e}", path.display()))
477}
478
479fn mark_failed(dir: &Path, kind: &str, reason: &str) -> String {
482 let path = kind_file(dir, FAILED, kind);
483 if std::fs::write(&path, reason).is_ok() {
484 let _ = std::fs::remove_file(kind_file(dir, ATTEMPTS, kind));
485 }
486 failure_message(&path, reason)
487}
488
489fn failure_message(path: &Path, reason: &str) -> String {
491 format!(
492 "no dump matches this TeX tree and none could be built ({reason}; remove {} to retry)",
493 path.display()
494 )
495}
496
497fn cache_dir() -> Result<PathBuf, String> {
504 let base = cache_base(|name| std::env::var_os(name))?;
505 let tree: String = ["plain", "latex"]
506 .into_iter()
507 .filter_map(dump_paths::runtime_source_stamps)
508 .flatten()
509 .map(|stamp| format!("{:08x}", stamp.checksum))
510 .collect::<Vec<_>>()
511 .join("-");
512 let build = build_key(&running_executable()?, |exe| executable_digest(&base, exe))?;
513 Ok(base.join(format!("{}-{build}-{tree}", crate::identity::VERSION)))
514}
515
516fn build_key(
520 exe: &Path,
521 digest: impl FnOnce(&Path) -> Result<String, String>,
522) -> Result<String, String> {
523 match digest(exe) {
524 Ok(digest) => Ok(digest[..16].to_string()),
525 Err(unreadable) => {
526 let meta = std::fs::metadata(exe).map_err(|_| unreadable)?;
527 let modified = meta
528 .modified()
529 .ok()
530 .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
531 .map_or(0, |since| since.as_nanos());
532 Ok(format!("m{:x}.{modified:x}", meta.len()))
533 },
534 }
535}
536
537fn is_cache_key(name: &str) -> bool {
541 let hex = |s: &str| !s.is_empty() && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
542 let version = |segments: &[&str]| {
543 segments.first().is_some_and(|first| {
544 first.starts_with(|c: char| c.is_ascii_digit())
545 && segments
546 .iter()
547 .all(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '.'))
548 })
549 };
550 let build_and_version = |head: &[&str]| match head {
551 [rest @ .., build] if build.len() == 16 && hex(build) => version(rest),
552 [rest @ .., build]
553 if build
554 .strip_prefix('m')
555 .and_then(|b| b.split_once('.'))
556 .is_some_and(|(size, mtime)| hex(size) && hex(mtime)) =>
557 {
558 version(rest)
559 },
560 [rest @ .., size, mtime] if hex(size) && hex(mtime) && version(rest) => true,
561 [rest @ .., ""] => version(rest),
562 _ => false,
563 };
564 let segments: Vec<&str> = name.split('-').collect();
565 (1..segments.len()).any(|k| {
566 let (head, tree) = segments.split_at(segments.len() - k);
567 tree.iter().all(|s| s.len() == 8 && hex(s)) && build_and_version(head)
568 })
569}
570
571fn is_cache_file(name: &str) -> bool {
575 let dump = |name: &str| {
576 name
577 .strip_suffix(".dump.txt")
578 .and_then(|stem| stem.split_once('.'))
579 .is_some_and(|(kind, year)| {
580 KINDS.contains(&kind) && !year.is_empty() && year.bytes().all(|b| b.is_ascii_digit())
581 })
582 };
583 let partial = || {
584 name
585 .strip_prefix('.')
586 .and_then(|name| name.strip_suffix(".partial"))
587 .and_then(|name| name.rsplit_once('.'))
588 .is_some_and(|(dump_name, pid)| {
589 dump(dump_name) && !pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit())
590 })
591 };
592 let marker = |marker: &str| {
593 name
594 .strip_prefix(marker)
595 .and_then(|kind| kind.strip_prefix('.'))
596 .is_some_and(|kind| KINDS.contains(&kind))
597 };
598 [LOCK, LAST_USED, IN_USE, FAILED].contains(&name)
599 || dump(name)
600 || partial()
601 || marker(ATTEMPTS)
602 || marker(FAILED)
603}
604
605fn holds_only_cache_files(dir: &Path) -> bool {
608 let Ok(entries) = std::fs::read_dir(dir) else {
609 return false;
610 };
611 let mut stamped = false;
612 for entry in entries {
613 let Ok(entry) = entry else {
614 return false;
615 };
616 let name = entry.file_name();
617 let Some(name) = name.to_str() else {
618 return false;
619 };
620 if !entry.file_type().is_ok_and(|kind| kind.is_file()) || !is_cache_file(name) {
621 return false;
622 }
623 stamped |= name == LOCK || name == LAST_USED;
624 }
625 stamped
626}
627
628fn cache_base(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> Result<PathBuf, String> {
630 let absolute_var = |name: &str| var(name).map(PathBuf::from).filter(|dir| dir.is_absolute());
631 let base = var("LATEXML_FORMAT_CACHE")
632 .map(PathBuf::from)
633 .or_else(|| absolute_var("XDG_CACHE_HOME").map(|dir| dir.join("latexml-oxide/formats")))
634 .or_else(|| absolute_var("HOME").map(|dir| dir.join(".cache/latexml-oxide/formats")))
635 .unwrap_or_else(|| std::env::temp_dir().join(format!("latexml-oxide-formats-{}", user_id())));
636 std::path::absolute(&base)
637 .map_err(|e| format!("cannot place the format cache {}: {e}", base.display()))
638}
639
640fn running_executable() -> Result<PathBuf, String> {
643 if cfg!(target_os = "linux") && Path::new("/proc/self/exe").exists() {
644 return Ok(PathBuf::from("/proc/self/exe"));
645 }
646 std::env::current_exe().map_err(|e| format!("cannot find this executable: {e}"))
647}
648
649fn executable_digest(base: &Path, exe: &Path) -> Result<String, String> {
654 use std::io::Read;
655
656 use sha2::{Digest, Sha256};
657 let unreadable = |e: std::io::Error| format!("cannot read {}: {e}", exe.display());
658 let mut file = std::fs::File::open(exe).map_err(unreadable)?;
659 let meta = file.metadata().map_err(unreadable)?;
661 let memo_dir = base.join(BINARIES);
662 let memo = memo_dir.join(file_identity(exe, &meta));
663 if trusted_dir(&memo_dir) && private_to_user(&memo) {
664 let remembered = std::fs::read_to_string(&memo).unwrap_or_default();
665 if remembered.len() == 64 && remembered.bytes().all(|b| b.is_ascii_hexdigit()) {
666 touch_if_stale(&memo);
667 return Ok(remembered);
668 }
669 }
670 let mut hasher = Sha256::new();
671 let mut buf = vec![0u8; 1 << 20];
672 loop {
673 match file.read(&mut buf).map_err(unreadable)? {
674 0 => break,
675 n => hasher.update(&buf[..n]),
676 }
677 }
678 let digest = hex(&hasher.finalize());
679 if private_dir(&memo_dir).is_ok() {
681 let partial = memo.with_extension(format!("{}.partial", std::process::id()));
682 let written = std::fs::write(&partial, &digest)
684 .and_then(|()| publish_read_only(&partial))
685 .and_then(|()| std::fs::rename(&partial, &memo));
686 if written.is_err() {
687 let _ = std::fs::remove_file(&partial);
688 }
689 }
690 Ok(digest)
691}
692
693fn file_identity(exe: &Path, meta: &std::fs::Metadata) -> String {
697 use sha2::{Digest, Sha256};
698 #[cfg(unix)]
699 let identity = {
700 use std::os::unix::fs::MetadataExt;
701 let _ = exe;
702 format!(
703 "{}:{}:{}:{}.{}:{}.{}",
704 meta.dev(),
705 meta.ino(),
706 meta.size(),
707 meta.mtime(),
708 meta.mtime_nsec(),
709 meta.ctime(),
710 meta.ctime_nsec()
711 )
712 };
713 #[cfg(not(unix))]
714 let identity = {
715 let nanos = |time: std::io::Result<std::time::SystemTime>| {
716 time
717 .ok()
718 .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
719 .map_or(0, |since| since.as_nanos())
720 };
721 format!(
722 "{}:{}:{}:{}",
723 exe.display(),
724 meta.len(),
725 nanos(meta.modified()),
726 nanos(meta.created())
727 )
728 };
729 hex(&Sha256::digest(identity.as_bytes()))[..32].to_string()
730}
731
732fn hex(bytes: &[u8]) -> String {
734 use std::fmt::Write as _;
735 bytes.iter().fold(String::new(), |mut out, byte| {
736 let _ = write!(out, "{byte:02x}");
737 out
738 })
739}
740
741fn touch_if_stale(path: &Path) -> bool {
744 if age(path).is_some_and(|age| age < STAMP_REFRESH) {
745 return true;
746 }
747 open_to_lock(path, true)
748 .and_then(|file| file.set_modified(std::time::SystemTime::now()))
749 .is_ok()
750}
751
752fn age(path: &Path) -> Option<Duration> {
754 std::fs::metadata(path)
755 .and_then(|meta| meta.modified())
756 .ok()
757 .and_then(|time| time.elapsed().ok())
758}
759
760fn last_used(dir: &Path) -> Option<std::time::SystemTime> {
764 let modified = |path: &Path| {
765 std::fs::metadata(path)
766 .and_then(|meta| meta.modified())
767 .ok()
768 };
769 if let Some(stamp) = modified(&dir.join(LAST_USED)) {
770 return Some(stamp);
771 }
772 let read = std::fs::read_dir(dir)
773 .into_iter()
774 .flatten()
775 .flatten()
776 .filter(|entry| entry.file_name().to_string_lossy().ends_with(".dump.txt"))
777 .filter_map(|entry| entry.metadata().and_then(|meta| meta.accessed()).ok());
778 modified(dir).into_iter().chain(read).max()
779}
780
781fn refresh_last_used(dir: &Path) {
787 let stamp = dir.join(LAST_USED);
788 if age(&stamp).is_some_and(|age| age < STAMP_REFRESH) || !trusted_dir(dir) {
789 return;
790 }
791 let lock = open_to_lock(&dir.join(LOCK), true);
792 if let Ok(lock) = &lock {
795 lock_shared_waiting(lock);
796 }
797 if dir.is_dir() {
798 touch_if_stale(&stamp);
799 }
800}
801
802fn lock_shared_waiting(file: &std::fs::File) {
805 let deadline = Instant::now() + LOCK_WAIT;
806 while let Err(std::fs::TryLockError::WouldBlock) = file.try_lock_shared() {
807 if Instant::now() >= deadline {
808 break;
809 }
810 std::thread::sleep(Duration::from_millis(100));
811 }
812}
813
814fn hold_in_use(dir: &Path) -> Option<std::fs::File> {
819 let path = dir.join(IN_USE);
820 for _ in 0..3 {
823 let file = open_to_lock(&path, true).ok()?;
824 lock_shared_waiting(&file);
825 if same_file(&file, &path) {
826 return Some(file);
827 }
828 }
829 None
830}
831
832#[cfg(unix)]
834fn same_file(file: &std::fs::File, path: &Path) -> bool {
835 use std::os::unix::fs::MetadataExt;
836 match (file.metadata(), std::fs::symlink_metadata(path)) {
837 (Ok(open), Ok(named)) => open.dev() == named.dev() && open.ino() == named.ino(),
838 _ => false,
839 }
840}
841#[cfg(not(unix))]
843fn same_file(_file: &std::fs::File, path: &Path) -> bool { path.is_file() }
844
845fn open_to_lock(path: &Path, create: bool) -> std::io::Result<std::fs::File> {
848 let mut options = std::fs::OpenOptions::new();
849 options.write(true).create(create).truncate(false);
850 #[cfg(unix)]
851 {
852 use std::os::unix::fs::OpenOptionsExt;
853 options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
854 }
855 let file = options.open(path)?;
856 if file.metadata()?.is_file() {
857 Ok(file)
858 } else {
859 Err(std::io::Error::other(format!(
860 "{} is not a regular file",
861 path.display()
862 )))
863 }
864}
865
866fn prune(base: &Path, current: &Path) {
872 let binaries = base.join(BINARIES);
873 let last_prune = binaries.join(LAST_PRUNE);
874 if !owned_by_user(base) || age(&last_prune).is_some_and(|age| age < PRUNE_EVERY) {
875 return;
876 }
877 if private_dir(&binaries).is_err() {
878 return;
879 }
880 let Ok(lock) = open_to_lock(&binaries.join(PRUNE_LOCK), true) else {
881 return;
882 };
883 if lock.try_lock().is_err()
884 || age(&last_prune).is_some_and(|age| age < PRUNE_EVERY)
885 || !touch_if_stale(&last_prune)
886 {
887 return;
888 }
889 sweep(base, current, std::time::SystemTime::now());
890}
891
892#[cfg(unix)]
894fn owned_by_user(path: &Path) -> bool {
895 use std::os::unix::fs::MetadataExt;
896 std::fs::symlink_metadata(path).is_ok_and(|meta| meta.is_dir() && meta.uid() == user_id())
897}
898#[cfg(not(unix))]
900fn owned_by_user(path: &Path) -> bool { path.is_dir() }
901
902fn sweep(base: &Path, current: &Path, now: std::time::SystemTime) {
908 let older_than = |time: Option<std::time::SystemTime>, lapse: Duration| {
909 time.is_some_and(|time| now.duration_since(time).is_ok_and(|age| age > lapse))
910 };
911 let Ok(entries) = std::fs::read_dir(base) else {
912 return;
913 };
914 let mut caches = Vec::new();
915 for entry in entries.flatten() {
916 let path = entry.path();
917 let Some(name) = entry.file_name().to_str().map(str::to_string) else {
918 continue;
919 };
920 if !private_to_user(&path) || path == current {
921 continue;
922 }
923 if name == BINARIES {
924 for memo in std::fs::read_dir(&path).into_iter().flatten().flatten() {
925 let memo_name = memo.file_name();
926 let memo_name = memo_name.to_string_lossy();
927 let digest = memo_name.split('.').next().is_some_and(|identity| {
929 identity.len() == 32 && identity.bytes().all(|b| b.is_ascii_hexdigit())
930 });
931 if digest && older_than(memo.metadata().and_then(|m| m.modified()).ok(), PRUNE_AFTER) {
932 let _ = std::fs::remove_file(memo.path());
933 }
934 }
935 } else if let Some(trashed) = name.strip_prefix(TRASH) {
936 let removed = trashed
938 .split_once('-')
939 .and_then(|(secs, rest)| Some((secs.parse::<u64>().ok()?, rest.split_once('-')?)))
940 .filter(|(_, (pid, key))| pid.parse::<u32>().is_ok() && is_cache_key(key))
941 .map(|(secs, _)| std::time::UNIX_EPOCH + Duration::from_secs(secs));
942 if removed.is_some()
943 && older_than(removed, TRASH_LAPSE)
944 && holds_only_cache_files_or_nothing(&path)
945 {
946 let _ = std::fs::remove_dir_all(&path);
947 }
948 } else if is_cache_key(&name) && holds_only_cache_files(&path) {
949 caches.push((last_used(&path), path, name));
950 }
951 }
952 caches.sort_by_key(|cache| std::cmp::Reverse(cache.0));
953 for (used, dir, name) in caches.into_iter().skip(KEEP_NEWEST) {
954 if older_than(used, PRUNE_AFTER) {
955 remove_cache(base, &dir, &name, now, |dir| {
956 older_than(last_used(dir), PRUNE_AFTER)
957 });
958 }
959 }
960}
961
962fn holds_only_cache_files_or_nothing(dir: &Path) -> bool {
965 std::fs::read_dir(dir).is_ok_and(|mut entries| {
966 entries.all(|entry| {
967 entry.is_ok_and(|entry| {
968 entry.file_type().is_ok_and(|kind| kind.is_file())
969 && entry.file_name().to_str().is_some_and(is_cache_file)
970 })
971 })
972 })
973}
974
975fn remove_cache(
979 base: &Path,
980 dir: &Path,
981 name: &str,
982 now: std::time::SystemTime,
983 unused: impl Fn(&Path) -> bool,
984) {
985 let Ok(lock) = open_to_lock(&dir.join(LOCK), false) else {
988 return;
989 };
990 if lock.try_lock().is_err() {
991 return;
992 }
993 let in_use = match open_to_lock(&dir.join(IN_USE), false) {
995 Ok(in_use) => Some(in_use),
996 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
997 Err(_) => return,
998 };
999 if in_use
1000 .as_ref()
1001 .is_some_and(|in_use| in_use.try_lock().is_err())
1002 || !unused(dir)
1003 {
1004 return;
1005 }
1006 let removed = now
1007 .duration_since(std::time::UNIX_EPOCH)
1008 .map_or(0, |since| since.as_secs());
1009 let trash = base.join(format!("{TRASH}{removed}-{}-{name}", std::process::id()));
1010 if std::fs::rename(dir, &trash).is_ok() {
1013 drop((lock, in_use));
1014 if holds_only_cache_files_or_nothing(&trash) {
1015 let _ = std::fs::remove_dir_all(&trash);
1016 }
1017 }
1018}
1019
1020fn cached_dump(dir: &Path, kind: &str, year: u32) -> Option<(PathBuf, u32)> {
1023 if !trusted_dir(dir) {
1024 return None;
1025 }
1026 dump_paths::resolve_versioned_in_dir(dir, kind, Some(year))
1027 .filter(|(path, _)| private_to_user(path))
1028}
1029
1030fn failed_before(dir: &Path, kind: &str) -> Option<String> {
1033 let path = kind_file(dir, FAILED, kind);
1034 let reason = std::fs::read_to_string(&path).ok()?;
1035 let lapsed = std::fs::metadata(&path)
1036 .and_then(|meta| meta.modified())
1037 .ok()
1038 .and_then(|marked| marked.elapsed().ok())
1039 .is_some_and(|age| age > FAILED_LAPSE);
1040 if lapsed {
1041 let _ = std::fs::remove_file(&path);
1042 return None;
1043 }
1044 Some(failure_message(&path, &reason))
1045}
1046
1047fn lock_dir(dir: &Path) -> Result<std::fs::File, String> {
1049 let file = open_to_lock(&dir.join(LOCK), true)
1050 .map_err(|e| format!("cannot lock {}: {e}", dir.display()))?;
1051 let deadline = Instant::now() + LOCK_WAIT;
1052 loop {
1053 match file.try_lock() {
1054 Ok(()) => return Ok(file),
1055 Err(std::fs::TryLockError::WouldBlock) if Instant::now() < deadline => {
1056 std::thread::sleep(Duration::from_millis(100));
1057 },
1058 Err(std::fs::TryLockError::WouldBlock) => {
1059 return Err(format!(
1060 "another process has been building into {} for {} s",
1061 dir.display(),
1062 LOCK_WAIT.as_secs()
1063 ));
1064 },
1065 Err(std::fs::TryLockError::Error(e)) => {
1066 return Err(format!("cannot lock {}: {e}", dir.display()));
1067 },
1068 }
1069 }
1070}
1071
1072fn partial_dump(dir: &Path, kind: &str, year: u32) -> PathBuf {
1074 dir.join(format!(
1075 ".{}.{}.partial",
1076 dump_paths::dump_filename(kind, year),
1077 std::process::id()
1078 ))
1079}
1080
1081fn remove_partial_dumps(dir: &Path) {
1083 let Ok(entries) = std::fs::read_dir(dir) else {
1084 return;
1085 };
1086 for entry in entries.flatten() {
1087 if entry.file_name().to_string_lossy().ends_with(".partial") {
1088 let _ = std::fs::remove_file(entry.path());
1089 }
1090 }
1091}
1092
1093fn build(kind: &'static str, year: u32, dir: &Path) -> Result<(), String> {
1102 let dest = dir.join(dump_paths::dump_filename(kind, year));
1103 let partial = partial_dump(dir, kind, year);
1104 let partial_name = partial.to_string_lossy().into_owned();
1105 let init_file = if kind == "latex" {
1106 "latex.ltx"
1107 } else {
1108 "plain.tex"
1109 };
1110 let previous = std::env::current_dir().map_err(|e| format!("no working directory: {e}"))?;
1111 let workdir = dir.to_path_buf();
1112 let joined = std::thread::Builder::new()
1113 .name(format!("{kind}-format"))
1114 .stack_size(256 * 1024 * 1024)
1115 .spawn(move || -> Result<(), String> {
1116 dump_paths::set_building_format(true);
1117 std::env::set_current_dir(&workdir)
1118 .map_err(|e| format!("cannot enter {}: {e}", workdir.display()))?;
1119 let opts = latexml_core::common::Config {
1120 bindings_dispatch: Some(std::rc::Rc::new(latexml_package::dispatch)),
1121 extra_bindings_dispatch: Some(std::rc::Rc::new(latexml_contrib::dispatch)),
1122 ..latexml_core::common::Config::default()
1123 };
1124 let mut converter = crate::converter::Converter::from_config(opts.clone());
1125 let result = converter
1126 .prepare_session(&opts)
1127 .map_err(|e| format!("cannot prepare the {kind} format build: {e}"))
1128 .and_then(|()| crate::ini_tex::dump_format(&mut converter, init_file, Some(&partial_name)))
1129 .and_then(|_| {
1130 let counts = latexml_core::common::error::snapshot_report_counts();
1131 if counts.fatal || counts.error > 0 {
1132 Err(format!(
1133 "building the {kind} format logged {} error(s){}",
1134 counts.error,
1135 if counts.fatal { " and a fatal one" } else { "" }
1136 ))
1137 } else {
1138 Ok(())
1139 }
1140 });
1141 drop(converter);
1142 latexml_core::reset_thread_engine();
1143 result
1144 })
1145 .map_err(|e| format!("cannot start the {kind} format build: {e}"))?
1146 .join();
1147 let returned = std::env::set_current_dir(&previous);
1148 let built = joined
1149 .map_err(|_| format!("the {kind} format build panicked"))
1150 .and_then(|built| built)
1151 .and_then(|()| returned.map_err(|e| format!("cannot return to {}: {e}", previous.display())))
1152 .and_then(|()| publish(kind, &partial, &dest));
1153 if built.is_err() {
1154 let _ = std::fs::remove_file(&partial);
1155 }
1156 built
1157}
1158
1159fn publish(kind: &str, partial: &Path, dest: &Path) -> Result<(), String> {
1163 publish_read_only(partial)
1164 .map_err(|e| format!("cannot set the {kind} dump's permissions: {e}"))?;
1165 let mut slot = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner);
1166 std::fs::rename(partial, dest)
1167 .map_err(|e| format!("cannot move the {kind} dump to {}: {e}", dest.display()))?;
1168 *slot = None;
1169 Ok(())
1170}
1171
1172#[cfg(test)]
1173mod tests {
1174 use super::*;
1175
1176 static SERIAL: Mutex<()> = Mutex::new(());
1178
1179 #[test]
1184 fn an_interrupted_build_is_undone() {
1185 let _serial = SERIAL.lock().unwrap_or_else(PoisonError::into_inner);
1186 let dir = tempfile::tempdir().expect("create tempdir");
1187 let dir = dir.path();
1188 for before in [None, Some("1\tbuilding the latex format logged 3 error(s)")] {
1189 if let Some(text) = before {
1190 std::fs::write(kind_file(dir, ATTEMPTS, "latex"), text).expect("write the earlier note");
1191 }
1192 let count = previous_attempts(dir, "latex").0 + 1;
1193 let before_build = attempts_text(dir, "latex");
1194 note_attempt(
1195 dir,
1196 "latex",
1197 count,
1198 "the latex format build died with its process",
1199 )
1200 .expect("note the attempt");
1201 let partial = partial_dump(dir, "latex", 2025);
1202 std::fs::write(&partial, "half a dump").expect("write the partial dump");
1203 set_in_flight(Some(InFlight {
1204 attempts: kind_file(dir, ATTEMPTS, "latex"),
1205 before: before_build,
1206 partial: partial.clone(),
1207 }));
1208 assert!(cancel_in_flight_build());
1209 assert_eq!(attempts_text(dir, "latex").as_deref(), before);
1210 assert!(!partial.exists(), "the partial dump stayed");
1211 assert!(!cancel_in_flight_build(), "a build is undone once");
1212 }
1213 }
1214
1215 #[test]
1218 fn a_published_build_is_not_undone() {
1219 let _serial = SERIAL.lock().unwrap_or_else(PoisonError::into_inner);
1220 let dir = tempfile::tempdir().expect("create tempdir");
1221 let dir = dir.path();
1222 let before = "1\tbuilding the latex format logged 3 error(s)";
1223 std::fs::write(kind_file(dir, ATTEMPTS, "latex"), before).expect("write the earlier note");
1224 note_attempt(
1225 dir,
1226 "latex",
1227 2,
1228 "the latex format build died with its process",
1229 )
1230 .expect("note the attempt");
1231 let partial = partial_dump(dir, "latex", 2025);
1232 std::fs::write(&partial, "a dump").expect("write the dump");
1233 set_in_flight(Some(InFlight {
1234 attempts: kind_file(dir, ATTEMPTS, "latex"),
1235 before: Some(before.to_string()),
1236 partial: partial.clone(),
1237 }));
1238 let dest = dir.join(dump_paths::dump_filename("latex", 2025));
1239 publish("latex", &partial, &dest).expect("publish");
1240 assert!(!cancel_in_flight_build(), "the published build was undone");
1241 assert_eq!(
1242 attempts_text(dir, "latex").as_deref(),
1243 Some("2\tthe latex format build died with its process")
1244 );
1245 assert!(dest.is_file());
1246 }
1247
1248 fn executable(dir: &Path, name: &str, seed: u8, len: usize) -> PathBuf {
1250 let path = dir.join(name);
1251 let bytes: Vec<u8> = (0..len)
1252 .map(|i| (i as u8).wrapping_mul(31) ^ seed)
1253 .collect();
1254 std::fs::write(&path, bytes).expect("write the executable");
1255 path
1256 }
1257
1258 fn set_mtime(path: &Path, time: std::time::SystemTime) {
1261 std::fs::set_times(path, std::fs::FileTimes::new().set_modified(time))
1262 .unwrap_or_else(|e| panic!("set the time of {}: {e}", path.display()));
1263 }
1264
1265 #[test]
1270 fn a_copied_binary_keeps_its_cache_key() {
1271 let base = tempfile::tempdir().expect("create tempdir");
1272 let bin = tempfile::tempdir().expect("create tempdir");
1273 let original = executable(bin.path(), "latexml_oxide", 1, 3 << 20);
1274 let copy = bin.path().join("copy");
1275 std::fs::copy(&original, ©).expect("copy the executable");
1276 set_mtime(
1277 ©,
1278 std::time::SystemTime::now() - Duration::from_secs(3600),
1279 );
1280 let digest = executable_digest(base.path(), &original).expect("hash the original");
1281 assert_eq!(
1282 executable_digest(base.path(), ©).expect("hash the copy"),
1283 digest
1284 );
1285 let memos = std::fs::read_dir(base.path().join(BINARIES))
1286 .expect("read the digests")
1287 .count();
1288 assert_eq!(memos, 2, "one digest per file");
1289 let identity = file_identity(&original, &std::fs::metadata(&original).expect("stat"));
1291 let memo = base.path().join(BINARIES).join(identity);
1292 assert!(
1293 private_to_user(&memo),
1294 "the digest is written for this user alone"
1295 );
1296 let remembered = "ab".repeat(32);
1297 std::fs::remove_file(&memo).expect("remove the digest");
1298 std::fs::write(&memo, &remembered).expect("write the digest");
1299 publish_read_only(&memo).expect("publish the digest");
1300 assert_eq!(
1301 executable_digest(base.path(), &original).expect("hash the original again"),
1302 remembered
1303 );
1304 #[cfg(unix)]
1306 {
1307 use std::os::unix::fs::PermissionsExt;
1308 std::fs::set_permissions(&memo, std::fs::Permissions::from_mode(0o666)).expect("chmod");
1309 assert_eq!(
1310 executable_digest(base.path(), &original).expect("hash the original again"),
1311 digest
1312 );
1313 }
1314 }
1315
1316 #[test]
1320 fn builds_of_one_size_and_time_have_their_own_cache_keys() {
1321 let base = tempfile::tempdir().expect("create tempdir");
1322 let bin = tempfile::tempdir().expect("create tempdir");
1323 let nix_time = std::time::UNIX_EPOCH + Duration::from_secs(1);
1324 let one = executable(bin.path(), "one", 1, 1 << 20);
1325 let two = executable(bin.path(), "two", 2, 1 << 20);
1326 set_mtime(&one, nix_time);
1327 set_mtime(&two, nix_time);
1328 assert_ne!(
1329 executable_digest(base.path(), &one).expect("hash one"),
1330 executable_digest(base.path(), &two).expect("hash two")
1331 );
1332 }
1333
1334 #[test]
1337 fn latexml_format_cache_places_the_cache() {
1338 let abs = |unix: &str| {
1341 if cfg!(windows) {
1342 PathBuf::from(format!("C:{}", unix.replace('/', "\\")))
1343 } else {
1344 PathBuf::from(unix)
1345 }
1346 };
1347 let env = |vars: Vec<(&'static str, PathBuf)>| {
1348 move |name: &str| {
1349 vars
1350 .iter()
1351 .find(|(var, _)| *var == name)
1352 .map(|(_, value)| value.clone().into_os_string())
1353 }
1354 };
1355 let all = vec![
1356 ("LATEXML_FORMAT_CACHE", abs("/pinned/cache")),
1357 ("XDG_CACHE_HOME", abs("/xdg")),
1358 ("HOME", abs("/home/u")),
1359 ];
1360 assert_eq!(
1361 cache_base(env(all.clone())).expect("place the cache"),
1362 abs("/pinned/cache")
1363 );
1364 assert_eq!(
1365 cache_base(env(all[1..].to_vec())).expect("place the cache"),
1366 abs("/xdg").join("latexml-oxide").join("formats")
1367 );
1368 assert_eq!(
1369 cache_base(env(vec![
1370 ("XDG_CACHE_HOME", PathBuf::from("xdg")),
1371 ("HOME", abs("/home/u"))
1372 ]))
1373 .expect("place the cache"),
1374 abs("/home/u")
1375 .join(".cache")
1376 .join("latexml-oxide")
1377 .join("formats")
1378 );
1379 }
1380
1381 fn key(version: &str, n: u64) -> String { format!("{version}-{n:016x}-00000001-0000abcd") }
1383
1384 fn days_ago(days: u64) -> std::time::SystemTime {
1386 std::time::SystemTime::now() - Duration::from_secs(days * 24 * 60 * 60)
1387 }
1388
1389 fn cache(base: &Path, name: &str, days: Option<u64>) -> PathBuf {
1392 let dir = base.join(name);
1393 private_dir(&dir).expect("create the cache directory");
1394 std::fs::write(dir.join(LOCK), "").expect("write the lock");
1395 if let Some(days) = days {
1396 let stamp = dir.join(LAST_USED);
1397 std::fs::write(&stamp, "").expect("write the stamp");
1398 set_mtime(&stamp, days_ago(days));
1399 }
1400 dir
1401 }
1402
1403 #[test]
1405 fn only_cache_keys_name_cache_directories() {
1406 let version = crate::identity::VERSION;
1407 for name in [
1408 key(version, 0xda9a63d0ed92e3af),
1409 key("0.8.1-rc6", 7),
1410 "0.8.1-m482b030.1870c1d8a2b1c000-7d8eda0f-3d2c3c06".to_string(),
1412 "0.8.0-482b030-1870c1d8a2b1c000-7d8eda0f-3d2c3c06-a418eeb3".to_string(),
1413 "0.8.0--7d8eda0f".to_string(),
1414 ] {
1415 assert!(is_cache_key(&name), "{name}");
1416 }
1417 for name in [
1418 "2023-notes",
1419 "0.9.1-x-0",
1420 "notes",
1421 "0.8.1-da9a63d0ed92e3af",
1422 "0.8.1-da9a63d0ed92e3af-7d8eda0",
1423 "v0.8.1-da9a63d0ed92e3af-7d8eda0f",
1424 "0.8.1-DA9A63D0ED92E3AF-7D8EDA0F",
1425 ] {
1426 assert!(!is_cache_key(name), "{name}");
1427 }
1428 for name in [
1429 ".lock",
1430 ".last_used",
1431 ".inuse",
1432 ".attempts.latex",
1433 ".failed.plain",
1434 ".failed",
1435 "latex.2025.dump.txt",
1436 ".plain.2025.dump.txt.4242.partial",
1437 ] {
1438 assert!(is_cache_file(name), "{name}");
1439 }
1440 for name in [
1441 "thesis.txt",
1442 "latex.dump.txt",
1443 "beamer.2025.dump.txt",
1444 ".attempts.beamer",
1445 ".latex.2025.dump.txt.partial",
1446 ] {
1447 assert!(!is_cache_file(name), "{name}");
1448 }
1449 }
1450
1451 #[test]
1455 fn an_unreadable_executable_keeps_a_cache_key() {
1456 let bin = tempfile::tempdir().expect("create tempdir");
1457 let exe = executable(bin.path(), "latexml_oxide", 1, 1 << 10);
1458 let unreadable = |_: &Path| Err("cannot read it: Permission denied".to_string());
1459 let key = build_key(&exe, unreadable).expect("a key from the file's metadata");
1460 assert!(key.starts_with('m'), "{key}");
1461 assert_eq!(
1462 build_key(&exe, unreadable).expect("again"),
1463 key,
1464 "the key is stable"
1465 );
1466 assert!(is_cache_key(&format!("0.8.1-{key}-00000001")), "{key}");
1467 let digest = executable_digest(bin.path(), &exe).expect("hash it");
1468 assert_eq!(
1469 build_key(&exe, |_| Ok(digest.clone())).expect("a digest key"),
1470 digest[..16]
1471 );
1472 assert!(build_key(&bin.path().join("gone"), unreadable).is_err());
1473 }
1474
1475 #[test]
1480 #[cfg_attr(
1481 not(unix),
1482 ignore = "Windows never prunes the format cache: it will not rename a directory a file is open in (row R FMTCACHE-WINPRUNE)"
1483 )]
1484 fn caches_unused_for_a_month_are_pruned() {
1485 let base = tempfile::tempdir().expect("create tempdir");
1486 let base = base.path();
1487 let current = cache(base, &key("0.8.1", 1), Some(90));
1488 let new = cache(base, &key("0.8.1", 2), None);
1489 let kept = cache(base, &key("0.8.0", 40), Some(40));
1490 let pruned: Vec<PathBuf> = [50, 60, 70]
1491 .iter()
1492 .map(|days| cache(base, &key("0.7.6", *days), Some(*days)))
1493 .collect();
1494 let recent = cache(base, &key("0.8.0", 1), Some(1));
1495 let theirs = base.join("notes");
1496 private_dir(&theirs).expect("create a directory of the user's");
1497 std::fs::write(theirs.join(LOCK), "").expect("write a file of the user's");
1498 set_mtime(&theirs, std::time::UNIX_EPOCH + Duration::from_secs(1));
1499 let removed = days_ago(0) - Duration::from_secs(2 * 60 * 60);
1500 let since = |time: std::time::SystemTime| {
1501 time
1502 .duration_since(std::time::UNIX_EPOCH)
1503 .expect("after 1970")
1504 .as_secs()
1505 };
1506 let trash = base.join(format!("{TRASH}{}-1-{}", since(removed), key("0.7.4", 1)));
1507 private_dir(&trash).expect("create the trash");
1508 let fresh_trash = base.join(format!(
1510 "{TRASH}{}-1-{}",
1511 since(days_ago(0)),
1512 key("0.7.4", 2)
1513 ));
1514 private_dir(&fresh_trash).expect("create the trash");
1515 set_mtime(&fresh_trash, days_ago(60));
1516 let binaries = base.join(BINARIES);
1519 private_dir(&binaries).expect("create the digests");
1520 let [old_digest, digest, prune_lock, last_prune] =
1521 [&"a".repeat(32), &"b".repeat(32), PRUNE_LOCK, LAST_PRUNE].map(|name| binaries.join(name));
1522 for (file, days) in [
1523 (&old_digest, 40),
1524 (&digest, 1),
1525 (&prune_lock, 90),
1526 (&last_prune, 90),
1527 ] {
1528 std::fs::write(file, "").expect("write the file");
1529 set_mtime(file, days_ago(days));
1530 }
1531 sweep(base, ¤t, std::time::SystemTime::now());
1532 assert!(!old_digest.exists(), "a digest unread for 40 days was kept");
1533 for file in [&digest, &prune_lock, &last_prune] {
1534 assert!(file.is_file(), "{} was removed", file.display());
1535 }
1536 for dir in [¤t, &new, &recent, &kept, &theirs, &fresh_trash] {
1538 assert!(dir.is_dir(), "{} was pruned", dir.display());
1539 }
1540 for dir in pruned.iter().chain([&trash]) {
1541 assert!(!dir.exists(), "{} was kept", dir.display());
1542 }
1543 }
1544
1545 #[test]
1550 #[cfg_attr(
1551 not(unix),
1552 ignore = "Windows never prunes the format cache: it will not rename a directory a file is open in (row R FMTCACHE-WINPRUNE)"
1553 )]
1554 fn only_the_caches_own_directories_are_pruned() {
1555 let base = tempfile::tempdir().expect("create tempdir");
1556 let base = base.path();
1557 let current = cache(base, &key("0.8.1", 1), None);
1558 for i in 0..KEEP_NEWEST as u64 {
1559 cache(base, &key("0.9.0", 10 + i), Some(i));
1560 }
1561 let notes = cache(base, "2023-notes", Some(300));
1562 std::fs::write(notes.join("thesis.txt"), "a thesis").expect("write the user's file");
1563 let only_cache_files = cache(base, "0.9.1-x-0", Some(300));
1564 let beside = cache(base, &key("0.7.0", 1), Some(300));
1565 std::fs::write(beside.join("thesis.txt"), "a thesis").expect("write the user's file");
1566 let nested = cache(base, &key("0.7.0", 2), Some(300));
1567 private_dir(&nested.join("drafts")).expect("create the user's directory");
1568 let their_trash = base.join(format!("{TRASH}notes"));
1569 private_dir(&their_trash).expect("create the user's directory");
1570 std::fs::write(their_trash.join("thesis.txt"), "a thesis").expect("write the user's file");
1571 set_mtime(&their_trash, std::time::UNIX_EPOCH + Duration::from_secs(1));
1572 let named_as_trash = base.join(format!("{TRASH}1-1-{}", key("0.7.0", 4)));
1573 private_dir(&named_as_trash).expect("create the user's directory");
1574 std::fs::write(named_as_trash.join("thesis.txt"), "a thesis").expect("write the user's file");
1575 let pruned = cache(base, &key("0.7.0", 3), Some(300));
1576 sweep(base, ¤t, std::time::SystemTime::now());
1577 for dir in [
1578 ¬es,
1579 &only_cache_files,
1580 &beside,
1581 &nested,
1582 &their_trash,
1583 &named_as_trash,
1584 ] {
1585 assert!(dir.is_dir(), "{} was pruned", dir.display());
1586 }
1587 assert!(notes.join("thesis.txt").is_file());
1588 assert!(beside.join("thesis.txt").is_file());
1589 assert!(!pruned.exists(), "the cache's own directory was kept");
1590 }
1591
1592 #[test]
1595 #[cfg_attr(
1596 not(unix),
1597 ignore = "Windows never prunes the format cache: it will not rename a directory a file is open in (row R FMTCACHE-WINPRUNE)"
1598 )]
1599 fn a_locked_cache_is_not_pruned() {
1600 let base = tempfile::tempdir().expect("create tempdir");
1601 let base = base.path();
1602 let current = cache(base, &key("0.8.1", 1), None);
1603 let others: Vec<PathBuf> = (0..KEEP_NEWEST as u64)
1604 .map(|i| cache(base, &key("0.8.1", 10 + i), None))
1605 .collect();
1606 let locked = cache(base, &key("0.7.6", 1), Some(60));
1607 let held = std::fs::File::open(locked.join(LOCK)).expect("open the lock");
1608 held.lock_shared().expect("take the lock");
1609 sweep(base, ¤t, std::time::SystemTime::now());
1610 assert!(locked.is_dir(), "the locked cache was pruned");
1611 drop(held);
1612 sweep(base, ¤t, std::time::SystemTime::now());
1613 assert!(!locked.exists(), "the cache, unlocked, was kept");
1614 assert!(others.iter().all(|dir| dir.is_dir()));
1615 }
1616
1617 #[test]
1620 #[cfg_attr(
1621 not(unix),
1622 ignore = "Windows never prunes the format cache: it will not rename a directory a file is open in (row R FMTCACHE-WINPRUNE)"
1623 )]
1624 fn a_cache_in_use_is_not_pruned() {
1625 let base = tempfile::tempdir().expect("create tempdir");
1626 let base = base.path();
1627 let current = cache(base, &key("0.8.1", 1), None);
1628 for i in 0..KEEP_NEWEST as u64 {
1629 cache(base, &key("0.8.1", 10 + i), None);
1630 }
1631 let in_use = cache(base, &key("0.7.6", 1), Some(60));
1632 let held = hold_in_use(&in_use).expect("hold it in use");
1633 sweep(base, ¤t, std::time::SystemTime::now());
1634 assert!(in_use.is_dir(), "the cache in use was pruned");
1635 drop(held);
1636 let moved = cache(base, &key("0.7.6", 2), None);
1639 let file = std::fs::File::create(moved.join(IN_USE)).expect("open .inuse");
1640 assert!(same_file(&file, &moved.join(IN_USE)));
1641 std::fs::rename(&moved, base.join("moved")).expect("move it");
1642 std::fs::create_dir(&moved).expect("make it again");
1643 std::fs::write(moved.join(IN_USE), "").expect("write .inuse");
1644 assert!(
1645 !same_file(&file, &moved.join(IN_USE)),
1646 "a moved file is the directory's"
1647 );
1648 std::fs::remove_dir_all(&moved).expect("remove it");
1649 sweep(base, ¤t, std::time::SystemTime::now());
1650 assert!(!in_use.exists(), "the cache, no longer in use, was kept");
1651 }
1652
1653 #[cfg(unix)]
1655 #[test]
1656 fn a_cache_whose_use_cannot_be_read_is_not_pruned() {
1657 use std::os::unix::fs::PermissionsExt;
1658 let base = tempfile::tempdir().expect("create tempdir");
1659 let base = base.path();
1660 let current = cache(base, &key("0.8.1", 1), None);
1661 for i in 0..KEEP_NEWEST as u64 {
1662 cache(base, &key("0.8.1", 10 + i), None);
1663 }
1664 let unreadable = cache(base, &key("0.7.6", 1), Some(60));
1665 let in_use = unreadable.join(IN_USE);
1666 std::fs::write(&in_use, "").expect("write .inuse");
1667 std::fs::set_permissions(&in_use, std::fs::Permissions::from_mode(0o000)).expect("chmod");
1668 sweep(base, ¤t, std::time::SystemTime::now());
1669 assert!(
1670 unreadable.is_dir(),
1671 "a cache whose .inuse could not be opened was pruned"
1672 );
1673 std::fs::set_permissions(&in_use, std::fs::Permissions::from_mode(0o644)).expect("chmod");
1674 }
1675
1676 #[test]
1679 #[cfg_attr(
1680 not(unix),
1681 ignore = "Windows never prunes the format cache: it will not rename a directory a file is open in (row R FMTCACHE-WINPRUNE)"
1682 )]
1683 fn an_unstamped_cache_read_lately_is_not_pruned() {
1684 let base = tempfile::tempdir().expect("create tempdir");
1685 let base = base.path();
1686 let current = cache(base, &key("0.8.1", 1), None);
1687 for i in 0..KEEP_NEWEST as u64 {
1688 cache(base, &key("0.8.1", 10 + i), Some(i));
1689 }
1690 let unstamped = |n: u64, read: std::time::SystemTime| {
1691 let dir = cache(base, &key("0.8.0", n), None);
1692 let dump = dir.join("latex.2025.dump.txt");
1693 std::fs::write(&dump, "a dump").expect("write the dump");
1694 std::fs::File::options()
1695 .write(true)
1696 .open(&dump)
1697 .and_then(|file| {
1698 file.set_times(
1699 std::fs::FileTimes::new()
1700 .set_accessed(read)
1701 .set_modified(days_ago(90)),
1702 )
1703 })
1704 .expect("set the dump's times");
1705 set_mtime(&dir, days_ago(90));
1706 dir
1707 };
1708 let read_lately = unstamped(1, days_ago(2));
1709 let unread = unstamped(2, days_ago(60));
1710 sweep(base, ¤t, std::time::SystemTime::now());
1711 assert!(read_lately.is_dir(), "the cache read lately was pruned");
1712 assert!(!unread.exists(), "the cache unread for 60 days was kept");
1713 }
1714
1715 #[cfg(unix)]
1718 #[test]
1719 fn the_cache_is_pruned_once_a_day() {
1720 use std::os::unix::fs::PermissionsExt;
1721 let base = tempfile::tempdir().expect("create tempdir");
1722 let base = base.path();
1723 std::fs::set_permissions(base, std::fs::Permissions::from_mode(0o775)).expect("chmod");
1724 let current = cache(base, &key("0.8.1", 1), None);
1725 let others: Vec<PathBuf> = (0..=KEEP_NEWEST as u64)
1726 .map(|i| cache(base, &key("0.8.0", 40 + i), Some(40 + i)))
1727 .collect();
1728 prune(base, ¤t);
1729 assert!(base.join(BINARIES).join(LAST_PRUNE).is_file(), "no sweep");
1730 assert!(!others[KEEP_NEWEST].exists(), "the oldest cache was kept");
1731 assert!(others[..KEEP_NEWEST].iter().all(|dir| dir.is_dir()));
1732 let later = cache(base, &key("0.7.6", 90), Some(90));
1733 prune(base, ¤t);
1734 assert!(later.is_dir(), "swept twice in a day");
1735 }
1736
1737 #[cfg(unix)]
1741 #[test]
1742 fn links_in_the_base_are_not_followed() {
1743 use std::os::unix::fs::PermissionsExt;
1744 let base = tempfile::tempdir().expect("create tempdir");
1745 let base = base.path();
1746 std::fs::set_permissions(base, std::fs::Permissions::from_mode(0o775)).expect("chmod");
1747 let victim_dir = tempfile::tempdir().expect("create tempdir");
1748 let victim = victim_dir.path().join("victim.txt");
1749 std::fs::write(&victim, "precious").expect("write the victim");
1750 let old = std::time::UNIX_EPOCH + Duration::from_secs(1);
1751 set_mtime(&victim, old);
1752 for name in [PRUNE_LOCK, LAST_PRUNE] {
1753 std::os::unix::fs::symlink(&victim, base.join(name)).expect("plant the link");
1754 }
1755 let current = cache(base, &key("0.8.1", 1), None);
1756 prune(base, ¤t);
1757 assert!(base.join(BINARIES).join(LAST_PRUNE).is_file(), "no sweep");
1758 assert_eq!(
1759 std::fs::read_to_string(&victim).expect("read the victim"),
1760 "precious"
1761 );
1762 assert_eq!(
1763 std::fs::metadata(&victim)
1764 .and_then(|meta| meta.modified())
1765 .expect("stat the victim"),
1766 old,
1767 "the victim was touched"
1768 );
1769 }
1770
1771 #[cfg(unix)]
1776 #[test]
1777 fn fifos_and_links_in_the_cache_directory_are_not_opened() {
1778 let victims = tempfile::tempdir().expect("create tempdir");
1779 let victim = victims.path().join("victim.txt");
1780 std::fs::write(&victim, "precious").expect("write the victim");
1781 let old = std::time::UNIX_EPOCH + Duration::from_secs(1);
1782 set_mtime(&victim, old);
1783 let dangling = victims.path().join("made.txt");
1784 let fifo = |path: &Path| {
1785 let made = std::process::Command::new("mkfifo").arg(path).status();
1786 assert!(
1787 made.is_ok_and(|status| status.success()),
1788 "mkfifo {}",
1789 path.display()
1790 );
1791 };
1792 let link = |target: &Path, path: &Path| {
1793 std::os::unix::fs::symlink(target, path).expect("plant the link");
1794 };
1795 type Plant<'a> = &'a dyn Fn(&Path);
1796 let plants: [(&str, Plant); 3] = [
1797 ("FIFOs", &|dir| {
1798 fifo(&dir.join(LOCK));
1799 fifo(&dir.join(IN_USE));
1800 }),
1801 ("links", &|dir| {
1802 link(&victim, &dir.join(LOCK));
1803 link(&victim, &dir.join(IN_USE));
1804 link(&victim, &dir.join(LAST_USED));
1805 }),
1806 ("dangling links", &|dir| {
1807 link(&dangling, &dir.join(LOCK));
1808 link(&dangling, &dir.join(IN_USE));
1809 }),
1810 ];
1811 for (what, plant) in plants {
1812 let base = tempfile::tempdir().expect("create tempdir");
1813 let dir = cache(base.path(), &key("0.8.1", 1), None);
1814 std::fs::remove_file(dir.join(LOCK)).expect("remove the lock");
1815 plant(&dir);
1816 let (done, finished) = std::sync::mpsc::channel();
1817 let in_thread = dir.clone();
1818 std::thread::spawn(move || {
1819 refresh_last_used(&in_thread);
1820 let held = hold_in_use(&in_thread).is_some();
1821 let locked = lock_dir(&in_thread).is_ok();
1822 let _ = done.send((held, locked));
1823 });
1824 let (held, locked) = finished
1825 .recv_timeout(Duration::from_secs(20))
1826 .unwrap_or_else(|_| panic!("{what}: a lock or stamp file was waited on"));
1827 assert!(!held && !locked, "{what}: a file not regular was locked");
1828 assert_eq!(
1829 std::fs::read_to_string(&victim).expect("read the victim"),
1830 "precious",
1831 "{what}"
1832 );
1833 assert_eq!(
1834 std::fs::metadata(&victim)
1835 .and_then(|meta| meta.modified())
1836 .expect("stat the victim"),
1837 old,
1838 "{what}: the victim was touched"
1839 );
1840 assert!(!dangling.exists(), "{what}: a dangling link was followed");
1841 }
1842 }
1843
1844 #[test]
1847 #[cfg_attr(
1848 not(unix),
1849 ignore = "Windows never prunes the format cache: it will not rename a directory a file is open in (row R FMTCACHE-WINPRUNE)"
1850 )]
1851 fn a_file_put_in_a_cache_being_pruned_stays() {
1852 let base = tempfile::tempdir().expect("create tempdir");
1853 let base = base.path();
1854 let current = cache(base, &key("0.8.1", 1), None);
1855 let name = key("0.7.6", 1);
1856 let old = cache(base, &name, Some(60));
1857 assert!(holds_only_cache_files(&old));
1858 let now = std::time::SystemTime::now();
1859 remove_cache(base, &old, &name, now, |dir| {
1861 std::fs::write(dir.join("thesis.txt"), "a thesis").is_ok()
1862 });
1863 let trash: Vec<PathBuf> = std::fs::read_dir(base)
1864 .expect("read the base")
1865 .flatten()
1866 .filter(|entry| entry.file_name().to_string_lossy().starts_with(TRASH))
1867 .map(|entry| entry.path())
1868 .collect();
1869 assert_eq!(
1870 trash.len(),
1871 1,
1872 "the trash holding the user's file was removed"
1873 );
1874 sweep(base, ¤t, now + TRASH_LAPSE * 2);
1875 assert_eq!(
1876 std::fs::read_to_string(trash[0].join("thesis.txt")).expect("read the user's file"),
1877 "a thesis"
1878 );
1879 }
1880}