1use fs2::FileExt as _;
2use std::{
3 fs::{self, File},
4 io::{self, Read as _},
5 path::{Path, PathBuf},
6 sync::Arc,
7 time::{Duration, Instant, SystemTime, UNIX_EPOCH},
8};
9
10use super::digest::read_stamp_with_limit;
11
12pub(super) fn canonicalize_allow_missing(path: &Path) -> io::Result<PathBuf> {
15 let base = if path.is_absolute() {
16 PathBuf::new()
17 } else {
18 std::env::current_dir()?
19 };
20 ic_host_fs::path::canonicalize_allow_missing(path, &base)
21}
22
23const CACHE_DIRECTORY_TAG: &str = "Signature: 8a477f597d28d172789f06886806bc55\n\
24# This file is a cache directory tag created by ic-testkit.\n\
25# For information about cache directory tags see https://bford.info/cachedir/\n";
26pub(super) const CACHE_DIRECTORY_TAG_SIGNATURE: &str =
27 "Signature: 8a477f597d28d172789f06886806bc55";
28pub(super) const LAST_USED_FILE: &str = ".ic-testkit-last-used";
29const LAST_MAINTENANCE_FILE: &str = ".ic-testkit-last-maintenance";
30const MAX_TIMESTAMP_BYTES: usize = 39;
32pub(super) const RETENTION_LOCK_FILE: &str = ".ic-testkit-retention-v1";
33
34#[derive(Clone, Debug)]
37pub(super) struct RetainedCacheEntry {
38 path: PathBuf,
39 _lock: Arc<RetentionLock>,
40}
41
42#[derive(Debug)]
43struct RetentionLock(File);
44
45impl Drop for RetentionLock {
46 fn drop(&mut self) {
47 let _ = fs2::FileExt::unlock(&self.0);
52 }
53}
54
55impl PartialEq for RetainedCacheEntry {
56 fn eq(&self, other: &Self) -> bool {
57 self.path == other.path
58 }
59}
60
61impl Eq for RetainedCacheEntry {}
62
63impl RetainedCacheEntry {
64 pub(super) fn path(&self) -> &Path {
65 &self.path
66 }
67
68 pub(super) fn acquire(path: &Path) -> Result<Self, CacheFsError> {
69 let file = open_cache_lock_file(&path.join(RETENTION_LOCK_FILE))?;
70 fs2::FileExt::lock_shared(&file).map_err(|source| CacheFsError {
71 operation: "retain cache entry",
72 path: path.to_owned(),
73 source,
74 })?;
75 Ok(Self {
76 path: path.to_owned(),
77 _lock: Arc::new(RetentionLock(file)),
78 })
79 }
80}
81
82pub(super) fn remove_unretained_entry(path: &Path) -> Result<(), CacheFsError> {
84 let metadata = match fs::symlink_metadata(path) {
85 Ok(metadata) => metadata,
86 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
87 Err(source) => {
88 return Err(CacheFsError {
89 operation: "inspect cache entry",
90 path: path.to_owned(),
91 source,
92 });
93 }
94 };
95 if !metadata.is_dir() {
96 return remove_path_if_present(path).map_err(|source| CacheFsError {
97 operation: "remove invalid cache entry",
98 path: path.to_owned(),
99 source,
100 });
101 }
102 let _lock =
103 try_lock_cache_file(&path.join(RETENTION_LOCK_FILE))?.ok_or_else(|| CacheFsError {
104 operation: "replace retained cache entry",
105 path: path.to_owned(),
106 source: io::Error::new(
107 io::ErrorKind::WouldBlock,
108 "cache entry is retained by a consumer",
109 ),
110 })?;
111 remove_path_if_present(path).map_err(|source| CacheFsError {
112 operation: "remove cache entry",
113 path: path.to_owned(),
114 source,
115 })
116}
117
118#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
126pub struct ArtifactCachePrunePolicy {
127 max_age: Option<Duration>,
128 max_size_bytes: Option<u64>,
129}
130
131#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
133pub struct ArtifactCachePruneReport {
134 entries_scanned: usize,
135 entries_removed: usize,
136 bytes_before: u64,
137 bytes_removed: u64,
138 uncommitted_directories_removed: usize,
139 uncommitted_bytes_removed: u64,
140}
141
142#[non_exhaustive]
144#[derive(Clone, Debug, Eq, PartialEq)]
145pub enum ArtifactCacheMaintenance {
146 Pruned(ArtifactCachePruneReport),
148 PruneFailed {
150 message: String,
152 },
153}
154
155impl ArtifactCachePrunePolicy {
156 #[must_use]
158 pub const fn new() -> Self {
159 Self {
160 max_age: None,
161 max_size_bytes: None,
162 }
163 }
164
165 #[must_use]
167 pub const fn with_max_age(mut self, max_age: Duration) -> Self {
168 self.max_age = Some(max_age);
169 self
170 }
171
172 #[must_use]
174 pub const fn with_max_size_bytes(mut self, bytes: u64) -> Self {
175 self.max_size_bytes = Some(bytes);
176 self
177 }
178
179 #[must_use]
181 pub const fn max_age(self) -> Option<Duration> {
182 self.max_age
183 }
184
185 #[must_use]
187 pub const fn max_size_bytes(self) -> Option<u64> {
188 self.max_size_bytes
189 }
190
191 pub(super) fn maintenance_identity(self) -> String {
192 format!(
193 "age={:?};size={:?}",
194 self.max_age.map(|duration| duration.as_nanos()),
195 self.max_size_bytes
196 )
197 }
198}
199
200impl ArtifactCachePruneReport {
201 #[must_use]
203 pub const fn entries_scanned(self) -> usize {
204 self.entries_scanned
205 }
206
207 #[must_use]
209 pub const fn entries_removed(self) -> usize {
210 self.entries_removed
211 }
212
213 #[must_use]
215 pub const fn entries_retained(self) -> usize {
216 self.entries_scanned.saturating_sub(self.entries_removed)
217 }
218
219 #[must_use]
221 pub const fn bytes_before(self) -> u64 {
222 self.bytes_before
223 }
224
225 #[must_use]
227 pub const fn bytes_removed(self) -> u64 {
228 self.bytes_removed
229 }
230
231 #[must_use]
233 pub const fn bytes_retained(self) -> u64 {
234 self.bytes_before.saturating_sub(self.bytes_removed)
235 }
236
237 #[must_use]
239 pub const fn uncommitted_directories_removed(self) -> usize {
240 self.uncommitted_directories_removed
241 }
242
243 #[must_use]
245 pub const fn uncommitted_bytes_removed(self) -> u64 {
246 self.uncommitted_bytes_removed
247 }
248
249 pub(super) const fn record_uncommitted_removal(&mut self, bytes: u64) {
250 self.uncommitted_directories_removed += 1;
251 self.uncommitted_bytes_removed = self.uncommitted_bytes_removed.saturating_add(bytes);
252 }
253}
254
255impl ArtifactCacheMaintenance {
256 #[must_use]
258 pub const fn prune_report(&self) -> Option<ArtifactCachePruneReport> {
259 match self {
260 Self::Pruned(report) => Some(*report),
261 Self::PruneFailed { .. } => None,
262 }
263 }
264
265 #[must_use]
267 pub fn failure_message(&self) -> Option<&str> {
268 match self {
269 Self::Pruned(_) => None,
270 Self::PruneFailed { message } => Some(message),
271 }
272 }
273}
274
275#[derive(Debug)]
276pub(super) struct CacheFsError {
277 pub(super) operation: &'static str,
278 pub(super) path: PathBuf,
279 pub(super) source: io::Error,
280}
281
282pub(super) fn ensure_cache_directory_tag(cache_root: &Path) -> Result<(), CacheFsError> {
283 let path = cache_root.join("CACHEDIR.TAG");
284 let mut signature = [0_u8; CACHE_DIRECTORY_TAG_SIGNATURE.len()];
287 if fs::symlink_metadata(&path).is_ok_and(|metadata| metadata.file_type().is_file())
288 && File::open(&path)
289 .and_then(|mut file| file.read_exact(&mut signature))
290 .is_ok()
291 && signature == CACHE_DIRECTORY_TAG_SIGNATURE.as_bytes()
292 {
293 return Ok(());
294 }
295 ic_host_fs::durable::write_bytes(&path, CACHE_DIRECTORY_TAG.as_bytes()).map_err(|source| {
296 CacheFsError {
297 operation: "write cache directory tag",
298 path,
299 source: io::Error::other(source),
300 }
301 })
302}
303
304pub(super) fn lock_cache_file(path: &Path) -> Result<(File, Duration), CacheFsError> {
305 let file = open_cache_lock_file(path)?;
306 let started = Instant::now();
307 file.lock_exclusive().map_err(|source| CacheFsError {
308 operation: "lock cache",
309 path: path.to_owned(),
310 source,
311 })?;
312 Ok((file, started.elapsed()))
313}
314
315pub(super) fn lock_cache_file_with_wait_observer(
316 path: &Path,
317 poll_interval: Duration,
318 mut observer: impl FnMut(Duration),
319) -> Result<(File, Duration), CacheFsError> {
320 let file = open_cache_lock_file(path)?;
321 let wait = ic_host_fs::durable::lock_exclusive_with_wait(
322 &file,
323 poll_interval.min(Duration::from_millis(25)),
324 |elapsed| {
325 observer(elapsed);
326 Ok(())
327 },
328 )
329 .map_err(|source| CacheFsError {
330 operation: "try lock cache",
331 path: path.to_owned(),
332 source,
333 })?;
334 Ok((file, wait))
335}
336
337pub(super) fn try_lock_cache_file(path: &Path) -> Result<Option<File>, CacheFsError> {
338 match ic_host_fs::durable::try_lock_regular_file_with_parents(path).map_err(io::Error::from) {
339 Ok(file) => Ok(Some(file)),
340 Err(error) if error.kind() == io::ErrorKind::WouldBlock => Ok(None),
341 Err(source) => Err(CacheFsError {
342 operation: "try lock cache",
343 path: path.to_owned(),
344 source,
345 }),
346 }
347}
348
349fn open_cache_lock_file(path: &Path) -> Result<File, CacheFsError> {
350 ic_host_fs::durable::open_regular_lock_file_with_parents(path)
351 .map_err(io::Error::from)
352 .map_err(|source| CacheFsError {
353 operation: "open cache lock",
354 path: path.to_owned(),
355 source,
356 })
357}
358
359pub(super) fn record_cache_entry_use(path: &Path) -> Result<(), CacheFsError> {
360 write_last_used(path, SystemTime::now())
361}
362
363pub(super) fn cache_maintenance_due(
364 path: &Path,
365 minimum_interval: Option<Duration>,
366 maintenance_identity: &str,
367) -> Result<bool, CacheFsError> {
368 let Some(minimum_interval) = minimum_interval else {
369 return Ok(true);
370 };
371 let marker = path.join(LAST_MAINTENANCE_FILE);
372 let maximum_len = MAX_TIMESTAMP_BYTES + maintenance_identity.len() + 4;
374 let contents = match read_stamp_with_limit(&marker, maximum_len) {
375 Ok(Some(contents)) => contents,
376 Ok(None) => return Ok(true),
377 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(true),
378 Err(source) => {
379 return Err(CacheFsError {
380 operation: "read cache maintenance time",
381 path: marker,
382 source,
383 });
384 }
385 };
386 let mut lines = contents.lines();
387 let Some(last_maintenance) = lines.next().and_then(decode_system_time) else {
388 return Ok(true);
389 };
390 if lines.next() != Some(maintenance_identity) {
391 return Ok(true);
392 }
393 Ok(match SystemTime::now().duration_since(last_maintenance) {
394 Ok(elapsed) => elapsed >= minimum_interval,
395 Err(_) => true,
396 })
397}
398
399pub(super) fn record_cache_maintenance(
400 path: &Path,
401 maintenance_identity: &str,
402) -> Result<(), CacheFsError> {
403 let marker = path.join(LAST_MAINTENANCE_FILE);
404 let elapsed = encode_system_time(&marker, SystemTime::now())?;
405 let contents = format!("{}\n{maintenance_identity}\n", elapsed.as_nanos());
406 ic_host_fs::durable::write_bytes(&marker, contents.as_bytes()).map_err(|source| CacheFsError {
407 operation: "record cache maintenance time",
408 path: marker,
409 source: io::Error::other(source),
410 })
411}
412
413pub(super) fn perform_scheduled_cache_maintenance(
414 path: &Path,
415 minimum_interval: Option<Duration>,
416 maintenance_identity: &str,
417 maintenance: impl FnOnce() -> Result<ArtifactCachePruneReport, String>,
418) -> (Option<ArtifactCacheMaintenance>, Option<Duration>) {
419 let started = Instant::now();
420 match cache_maintenance_due(path, minimum_interval, maintenance_identity) {
421 Ok(false) => return (None, Some(started.elapsed())),
422 Ok(true) => {}
423 Err(error) => {
424 return (
425 Some(ArtifactCacheMaintenance::PruneFailed {
426 message: error.to_string(),
427 }),
428 Some(started.elapsed()),
429 );
430 }
431 }
432
433 let result = maintenance();
434 let marker = record_cache_maintenance(path, maintenance_identity);
435 let outcome = match (result, marker) {
436 (Ok(report), Ok(())) => ArtifactCacheMaintenance::Pruned(report),
437 (Err(message), Ok(())) => ArtifactCacheMaintenance::PruneFailed { message },
438 (Ok(_), Err(error)) => ArtifactCacheMaintenance::PruneFailed {
439 message: error.to_string(),
440 },
441 (Err(message), Err(marker)) => ArtifactCacheMaintenance::PruneFailed {
442 message: format!(
443 "{message}; additionally failed to record the maintenance attempt: {marker}"
444 ),
445 },
446 };
447 (Some(outcome), Some(started.elapsed()))
448}
449
450pub(super) fn write_last_used(path: &Path, last_used: SystemTime) -> Result<(), CacheFsError> {
451 let marker = path.join(LAST_USED_FILE);
452 write_system_time(&marker, last_used, "record cache use time")
453}
454
455fn write_system_time(
456 path: &Path,
457 timestamp: SystemTime,
458 operation: &'static str,
459) -> Result<(), CacheFsError> {
460 let elapsed = encode_system_time(path, timestamp)?;
461 ic_host_fs::durable::write_bytes(path, elapsed.as_nanos().to_string().as_bytes()).map_err(
462 |source| CacheFsError {
463 operation,
464 path: path.to_owned(),
465 source: io::Error::other(source),
466 },
467 )
468}
469
470fn encode_system_time(path: &Path, timestamp: SystemTime) -> Result<Duration, CacheFsError> {
471 timestamp
472 .duration_since(UNIX_EPOCH)
473 .map_err(|source| CacheFsError {
474 operation: "encode cache time",
475 path: path.to_owned(),
476 source: io::Error::new(io::ErrorKind::InvalidInput, source),
477 })
478}
479
480fn decode_system_time(contents: &str) -> Option<SystemTime> {
481 let nanoseconds = contents.parse::<u128>().ok()?;
482 let seconds = u64::try_from(nanoseconds / 1_000_000_000).ok()?;
483 let subsecond_nanos = (nanoseconds % 1_000_000_000) as u32;
484 UNIX_EPOCH.checked_add(Duration::new(seconds, subsecond_nanos))
485}
486
487pub(super) fn prune_direct_child_directories(
488 cache_root: &Path,
489 policy: ArtifactCachePrunePolicy,
490 protected_entry: Option<&Path>,
491 is_eligible: impl Fn(&Path) -> bool,
492) -> Result<ArtifactCachePruneReport, CacheFsError> {
493 let mut entries = cache_entries(cache_root, is_eligible)?;
494 let bytes_before = entries
495 .iter()
496 .fold(0_u64, |total, entry| total.saturating_add(entry.bytes));
497 let mut report = ArtifactCachePruneReport {
498 entries_scanned: entries.len(),
499 entries_removed: 0,
500 bytes_before,
501 bytes_removed: 0,
502 uncommitted_directories_removed: 0,
503 uncommitted_bytes_removed: 0,
504 };
505 let now = SystemTime::now();
506
507 if let Some(max_age) = policy.max_age() {
508 for entry in &mut entries {
509 let age = now.duration_since(entry.last_used).unwrap_or_default();
510 if protected_entry != Some(entry.path.as_path()) && age > max_age {
511 remove_cache_entry(entry, &mut report)?;
512 }
513 }
514 }
515
516 if let Some(max_size_bytes) = policy.max_size_bytes()
517 && report.bytes_retained() > max_size_bytes
518 {
519 entries.sort_by(|left, right| {
520 left.last_used
521 .cmp(&right.last_used)
522 .then_with(|| left.path.cmp(&right.path))
523 });
524 for entry in &mut entries {
525 if report.bytes_retained() <= max_size_bytes {
526 break;
527 }
528 if protected_entry == Some(entry.path.as_path()) {
529 continue;
530 }
531 remove_cache_entry(entry, &mut report)?;
532 }
533 }
534
535 Ok(report)
536}
537
538pub(super) fn directory_logical_size(path: &Path) -> io::Result<u64> {
539 let mut total = 0_u64;
540 let mut pending = vec![path.to_owned()];
541 while let Some(current) = pending.pop() {
542 let metadata = fs::symlink_metadata(¤t)?;
543 if metadata.is_dir() {
544 for entry in fs::read_dir(¤t)? {
545 let path = entry?.path();
546 let metadata = fs::symlink_metadata(&path)?;
547 if metadata.is_dir() {
548 pending.push(path);
549 } else {
550 total = total.saturating_add(metadata.len());
551 }
552 }
553 } else {
554 total = total.saturating_add(metadata.len());
555 }
556 }
557 Ok(total)
558}
559
560pub(super) fn is_sha256_directory(path: &Path) -> bool {
561 path.file_name().is_some_and(|name| {
562 let bytes = name.as_encoded_bytes();
563 bytes.len() == 64 && bytes.iter().all(u8::is_ascii_hexdigit)
564 })
565}
566
567pub(super) fn remove_path_if_present(path: &Path) -> io::Result<()> {
568 let metadata = match fs::symlink_metadata(path) {
569 Ok(metadata) => metadata,
570 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
571 Err(error) => return Err(error),
572 };
573 if metadata.file_type().is_dir() {
574 fs::remove_dir_all(path)
575 } else {
576 fs::remove_file(path)
577 }
578}
579
580struct CacheEntry {
581 path: PathBuf,
582 bytes: u64,
583 last_used: SystemTime,
584 removed: bool,
585}
586
587impl std::fmt::Display for CacheFsError {
588 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
589 write!(
590 formatter,
591 "failed to {} at {}: {}",
592 self.operation,
593 self.path.display(),
594 self.source
595 )
596 }
597}
598
599impl std::error::Error for CacheFsError {
600 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
601 Some(&self.source)
602 }
603}
604
605fn cache_entries(
606 cache_root: &Path,
607 is_eligible: impl Fn(&Path) -> bool,
608) -> Result<Vec<CacheEntry>, CacheFsError> {
609 let read_dir = match fs::read_dir(cache_root) {
610 Ok(read_dir) => read_dir,
611 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
612 Err(source) => {
613 return Err(CacheFsError {
614 operation: "read cache directory",
615 path: cache_root.to_owned(),
616 source,
617 });
618 }
619 };
620 let mut entries = Vec::new();
621 for directory_entry in read_dir {
622 let directory_entry = directory_entry.map_err(|source| CacheFsError {
623 operation: "read cache entry",
624 path: cache_root.to_owned(),
625 source,
626 })?;
627 let path = directory_entry.path();
628 let file_type = directory_entry.file_type().map_err(|source| CacheFsError {
629 operation: "inspect cache entry",
630 path: path.clone(),
631 source,
632 })?;
633 if !file_type.is_dir() || !is_eligible(&path) {
634 continue;
635 }
636 let bytes = directory_logical_size(&path).map_err(|source| CacheFsError {
637 operation: "measure cache entry",
638 path: path.clone(),
639 source,
640 })?;
641 let last_used = cache_entry_last_used(&path).map_err(|source| CacheFsError {
642 operation: "read cache use time",
643 path: path.clone(),
644 source,
645 })?;
646 entries.push(CacheEntry {
647 path,
648 bytes,
649 last_used,
650 removed: false,
651 });
652 }
653 Ok(entries)
654}
655
656pub(super) fn cache_entry_last_used(path: &Path) -> io::Result<SystemTime> {
657 let marker = path.join(LAST_USED_FILE);
658 if let Ok(Some(contents)) = read_stamp_with_limit(&marker, MAX_TIMESTAMP_BYTES)
659 && let Some(timestamp) = decode_system_time(&contents)
660 {
661 return Ok(timestamp);
662 }
663 fs::metadata(path)?.modified()
664}
665
666fn remove_cache_entry(
667 entry: &mut CacheEntry,
668 report: &mut ArtifactCachePruneReport,
669) -> Result<(), CacheFsError> {
670 if entry.removed {
671 return Ok(());
672 }
673 let Some(_retention_lock) = try_lock_cache_file(&entry.path.join(RETENTION_LOCK_FILE))? else {
674 return Ok(());
675 };
676 remove_path_if_present(&entry.path).map_err(|source| CacheFsError {
677 operation: "prune cache entry",
678 path: entry.path.clone(),
679 source,
680 })?;
681 entry.removed = true;
682 report.entries_removed += 1;
683 report.bytes_removed = report.bytes_removed.saturating_add(entry.bytes);
684 Ok(())
685}
686
687#[cfg(test)]
688mod tests {
689 use super::directory_logical_size;
690 use crate::artifacts::test_support::unique_temp_directory;
691 use std::{
692 fs,
693 time::{Duration, SystemTime, UNIX_EPOCH},
694 };
695
696 #[cfg(unix)]
697 #[test]
698 fn cache_lock_admission_preserves_bytes_and_returns_an_unlocked_close_on_exec_file() {
699 use std::os::fd::AsRawFd as _;
700
701 let root = unique_temp_directory("cache-lock-admission");
702 let path = root.join("nested/lock");
703 let file = super::open_cache_lock_file(&path).unwrap();
704 assert!(super::try_lock_cache_file(&path).unwrap().is_some());
705 #[expect(
707 unsafe_code,
708 reason = "inspect flags of a live descriptor without changing them"
709 )]
710 let flags = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETFD) };
711 assert!(flags >= 0);
712 assert_ne!(flags & libc::FD_CLOEXEC, 0);
713 drop(file);
714 fs::write(&path, b"retained lock bytes").unwrap();
715 drop(super::lock_cache_file(&path).unwrap());
716 assert_eq!(fs::read(&path).unwrap(), b"retained lock bytes");
717 fs::remove_dir_all(root).unwrap();
718 }
719
720 #[cfg(unix)]
721 #[test]
722 fn cache_lock_callers_refuse_redirected_final_entries() {
723 use std::os::unix::fs::symlink;
724
725 let root = unique_temp_directory("cache-lock-redirected");
726 let target = root.join("target");
727 fs::write(&target, b"target bytes").unwrap();
728 let redirected = root.join("redirected");
729 symlink(&target, &redirected).unwrap();
730 for result in [
731 super::open_cache_lock_file(&redirected),
732 super::lock_cache_file(&redirected).map(|(file, _)| file),
733 super::lock_cache_file_with_wait_observer(
734 &redirected,
735 Duration::from_millis(5),
736 |_| panic!("redirected lock reached acquisition"),
737 )
738 .map(|(file, _)| file),
739 ] {
740 let error = result.unwrap_err();
741 assert_eq!(error.path, redirected);
742 assert!(matches!(
743 error.source.get_ref().and_then(|cause| cause
744 .downcast_ref::<ic_host_fs::durable::RegularFileLockError>(
745 )),
746 Some(ic_host_fs::durable::RegularFileLockError::NotRegular)
747 ));
748 }
749 symlink(&target, root.join(super::RETENTION_LOCK_FILE)).unwrap();
750 assert!(super::RetainedCacheEntry::acquire(&root).is_err());
751 assert_eq!(fs::read(&target).unwrap(), b"target bytes");
752 fs::remove_dir_all(root).unwrap();
753 }
754
755 #[cfg(unix)]
756 #[test]
757 fn nonblocking_cache_locks_preserve_contention_and_reject_redirected_files() {
758 use std::{os::unix::fs::symlink, process::Command};
759 const CHILD_ENV: &str = "IC_TESTKIT_NONBLOCKING_CACHE_LOCK_CHILD";
760
761 if std::env::var_os(CHILD_ENV).is_none() {
762 let thread = std::thread::current();
766 let test_name = thread.name().expect("libtest names each test thread");
767 let output = Command::new(std::env::current_exe().unwrap())
768 .args(["--exact", test_name, "--test-threads=1"])
769 .env(CHILD_ENV, "1")
770 .output()
771 .unwrap();
772 assert!(
773 output.status.success(),
774 "isolated nonblocking cache lock test failed: {}{}",
775 String::from_utf8_lossy(&output.stdout),
776 String::from_utf8_lossy(&output.stderr)
777 );
778 return;
779 }
780
781 let root = unique_temp_directory("nonblocking-cache-lock-admission");
782 let lock_path = root.join("lock");
783 fs::write(&lock_path, b"existing lock bytes").unwrap();
784 let held = super::try_lock_cache_file(&lock_path).unwrap().unwrap();
785 assert!(super::try_lock_cache_file(&lock_path).unwrap().is_none());
786 assert_eq!(fs::read(&lock_path).unwrap(), b"existing lock bytes");
787 drop(held);
788 assert!(super::try_lock_cache_file(&lock_path).unwrap().is_some());
789
790 let redirected = root.join("redirected-lock");
791 symlink(&lock_path, &redirected).unwrap();
792 let error = super::try_lock_cache_file(&redirected).unwrap_err();
793 assert_eq!(error.path, redirected);
794 assert!(matches!(
795 error.source.get_ref().and_then(|cause| cause
796 .downcast_ref::<ic_host_fs::durable::RegularFileLockError>(
797 )),
798 Some(ic_host_fs::durable::RegularFileLockError::NotRegular)
799 ));
800 assert_eq!(fs::read(&lock_path).unwrap(), b"existing lock bytes");
801 fs::remove_dir_all(root).unwrap();
802 }
803
804 #[cfg(unix)]
805 #[test]
806 fn final_retention_owner_releases_lock_with_a_duplicate_descriptor_open() {
807 let root = unique_temp_directory("retention-duplicate-descriptor");
808 let retained = super::RetainedCacheEntry::acquire(&root).unwrap();
809 let inherited = retained._lock.0.try_clone().unwrap();
811 let clone = retained.clone();
812 let independently_retained = super::RetainedCacheEntry::acquire(&root).unwrap();
813 let lock_path = root.join(super::RETENTION_LOCK_FILE);
814 let available = || super::try_lock_cache_file(&lock_path).unwrap().is_some();
815 drop(retained);
816 assert!(!available(), "a record clone still retains the entry");
817 drop(clone);
818 assert!(
819 !available(),
820 "an independent acquisition still retains the entry"
821 );
822 drop(independently_retained);
823 assert!(
824 available(),
825 "descriptor duplication must not extend record ownership"
826 );
827 drop(inherited);
828 fs::remove_dir_all(root).unwrap();
829 }
830
831 #[test]
832 fn last_use_markers_preserve_timestamps_and_bounded_fallbacks() {
833 let root = unique_temp_directory("bounded-last-use-marker");
834 let marker = root.join(super::LAST_USED_FILE);
835 let modified = || fs::metadata(&root).unwrap().modified().unwrap();
836 assert_eq!(super::cache_entry_last_used(&root).unwrap(), modified());
837 for timestamp in [
838 UNIX_EPOCH + Duration::from_nanos(123),
839 SystemTime::now() + Duration::from_secs(3600),
840 ] {
841 super::write_last_used(&root, timestamp).unwrap();
842 assert_eq!(super::cache_entry_last_used(&root).unwrap(), timestamp);
843 }
844 let overflowing_timestamp = u128::MAX.to_string();
845 for invalid in [
846 b"invalid".as_slice(),
847 overflowing_timestamp.as_bytes(),
848 &[0xff],
849 ] {
850 fs::write(&marker, invalid).unwrap();
851 assert_eq!(super::cache_entry_last_used(&root).unwrap(), modified());
852 }
853 fs::File::create(&marker)
854 .unwrap()
855 .set_len(1024 * 1024 * 1024)
856 .unwrap();
857 assert_eq!(super::cache_entry_last_used(&root).unwrap(), modified());
858 fs::remove_file(&marker).unwrap();
859 fs::create_dir(&marker).unwrap();
860 assert_eq!(super::cache_entry_last_used(&root).unwrap(), modified());
861 fs::remove_dir_all(root).unwrap();
862 }
863
864 #[test]
865 fn maintenance_markers_preserve_policy_intervals_and_read_errors() {
866 let root = unique_temp_directory("bounded-maintenance-marker");
867 let marker = root.join(super::LAST_MAINTENANCE_FILE);
868 let identity = super::ArtifactCachePrunePolicy::new().maintenance_identity();
869 let interval = Some(Duration::from_secs(3600));
870 let due = || super::cache_maintenance_due(&root, interval, &identity).unwrap();
871 assert!(due());
872 super::record_cache_maintenance(&root, &identity).unwrap();
873 assert!(!due());
874 assert!(super::cache_maintenance_due(&root, interval, "other-policy").unwrap());
875 assert!(super::cache_maintenance_due(&root, Some(Duration::ZERO), &identity).unwrap());
876
877 let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
878 for suffix in ["", "\r\n"] {
879 fs::write(&marker, format!("{}\r\n{identity}{suffix}", now.as_nanos())).unwrap();
880 assert!(!due());
881 }
882 for timestamp in [
883 "invalid".to_owned(),
884 "0".to_owned(),
885 (now + Duration::from_secs(3600)).as_nanos().to_string(),
886 ] {
887 fs::write(&marker, format!("{timestamp}\n{identity}\n")).unwrap();
888 assert!(due());
889 }
890 super::record_cache_maintenance(&root, &identity).unwrap();
891 fs::OpenOptions::new()
892 .write(true)
893 .open(&marker)
894 .unwrap()
895 .set_len(1024 * 1024 * 1024)
896 .unwrap();
897 assert!(due());
898
899 fs::write(&marker, [0xff]).unwrap();
900 let error = super::cache_maintenance_due(&root, interval, &identity).unwrap_err();
901 assert_eq!(error.operation, "read cache maintenance time");
902 assert_eq!(error.path, marker);
903 assert_eq!(error.source.kind(), std::io::ErrorKind::InvalidData);
904 fs::remove_file(&marker).unwrap();
905 fs::create_dir(&marker).unwrap();
906 assert!(super::cache_maintenance_due(&root, interval, &identity).is_err());
907 assert!(super::cache_maintenance_due(&root, None, &identity).unwrap());
908 fs::remove_dir_all(root).unwrap();
909 }
910
911 #[test]
912 fn cache_directory_tags_preserve_valid_standard_signatures() {
913 let root = unique_temp_directory("cache-tag-signatures");
914 let tag = root.join("CACHEDIR.TAG");
915 let signature = "Signature: 8a477f597d28d172789f06886806bc55";
916 for contents in [
917 signature.to_owned(),
918 format!("{signature}\r\n# Created by another application\r\n"),
919 format!("{signature}\n# {}\n", "comment".repeat(100_000)),
920 ] {
921 fs::write(&tag, &contents).unwrap();
922 super::ensure_cache_directory_tag(&root).unwrap();
923 assert_eq!(fs::read_to_string(&tag).unwrap(), contents);
924 }
925 for invalid in ["", &signature[..42], "Signature: incorrect"] {
926 fs::write(&tag, invalid).unwrap();
927 super::ensure_cache_directory_tag(&root).unwrap();
928 assert_eq!(
929 fs::read_to_string(&tag).unwrap(),
930 super::CACHE_DIRECTORY_TAG
931 );
932 }
933 fs::remove_dir_all(root).unwrap();
934 }
935
936 #[test]
937 #[cfg(unix)]
938 fn cache_directory_tag_replaces_symlinks_without_changing_referents() {
939 let root = unique_temp_directory("cache-tag-symlink");
940 let referent = root.join("other-application-tag");
941 let contents = "Signature: 8a477f597d28d172789f06886806bc55\n# Preserve this file\n";
942 fs::write(&referent, contents).unwrap();
943 let tag = root.join("CACHEDIR.TAG");
944 std::os::unix::fs::symlink(&referent, &tag).unwrap();
945 super::ensure_cache_directory_tag(&root).unwrap();
946 assert!(fs::symlink_metadata(&tag).unwrap().file_type().is_file());
947 assert_eq!(fs::read_to_string(&referent).unwrap(), contents);
948 assert_eq!(
949 fs::read_to_string(&tag).unwrap(),
950 super::CACHE_DIRECTORY_TAG
951 );
952
953 fs::remove_file(&tag).unwrap();
954 fs::create_dir(&tag).unwrap();
955 let error = super::ensure_cache_directory_tag(&root).unwrap_err();
956 assert!(matches!(
957 error
958 .source
959 .get_ref()
960 .unwrap()
961 .downcast_ref::<ic_host_fs::durable::NamedWriteError<std::io::Error>>()
962 .unwrap(),
963 ic_host_fs::durable::NamedWriteError::BeforePublication {
964 cleanup_error: None,
965 ..
966 }
967 ));
968 assert_eq!(error.operation, "write cache directory tag");
969 assert!(tag.is_dir());
970 fs::remove_dir_all(root).unwrap();
971 }
972
973 #[test]
974 fn directory_size_sums_wide_and_nested_files() {
975 let root = unique_temp_directory("directory-logical-size");
976 assert_eq!(directory_logical_size(&root).unwrap(), 0);
977 fs::create_dir_all(root.join("wide")).unwrap();
978 fs::create_dir_all(root.join("nested/deep/empty")).unwrap();
979 let mut expected = 0;
980 for index in 0..128 {
981 let bytes = vec![42; index % 13];
982 fs::write(root.join("wide").join(index.to_string()), &bytes).unwrap();
983 expected += bytes.len() as u64;
984 }
985 let sparse = root.join("nested/deep/sparse");
986 fs::File::create(&sparse)
987 .unwrap()
988 .set_len(1024 * 1024)
989 .unwrap();
990 assert_eq!(directory_logical_size(&sparse).unwrap(), 1024 * 1024);
991 assert_eq!(
992 directory_logical_size(&root).unwrap(),
993 expected + 1024 * 1024
994 );
995 assert_eq!(
996 directory_logical_size(&root.join("missing"))
997 .unwrap_err()
998 .kind(),
999 std::io::ErrorKind::NotFound,
1000 );
1001 fs::remove_dir_all(root).unwrap();
1002 }
1003
1004 #[test]
1005 #[cfg(unix)]
1006 fn directory_size_counts_symlinks_without_following_them() {
1007 let root = unique_temp_directory("directory-size-symlinks");
1008 let walked = root.join("walked");
1009 fs::create_dir_all(&walked).unwrap();
1010 fs::create_dir_all(root.join("external")).unwrap();
1011 fs::write(root.join("external/payload"), vec![42; 4096]).unwrap();
1012 fs::write(root.join("outside-file"), vec![42; 4096]).unwrap();
1013 fs::write(walked.join("payload"), b"abc").unwrap();
1014 let targets = ["../external", "../outside-file", "missing", "."];
1015 for (index, target) in targets.iter().enumerate() {
1016 std::os::unix::fs::symlink(target, walked.join(index.to_string())).unwrap();
1017 }
1018 let expected = 3 + targets
1019 .iter()
1020 .map(|target| target.len() as u64)
1021 .sum::<u64>();
1022 assert_eq!(directory_logical_size(&walked).unwrap(), expected);
1023 assert_eq!(
1024 directory_logical_size(&walked.join("0")).unwrap(),
1025 targets[0].len() as u64,
1026 );
1027 fs::remove_dir_all(root).unwrap();
1028 }
1029}