Skip to main content

uv_cache/
lib.rs

1use std::fmt::{Display, Formatter};
2use std::io;
3use std::io::Write;
4use std::ops::Deref;
5use std::path::{Path, PathBuf};
6use std::str::FromStr;
7use std::sync::Arc;
8
9use rustc_hash::FxHashMap;
10use tracing::{debug, trace, warn};
11
12use uv_cache_info::Timestamp;
13use uv_fs::{LockedFile, LockedFileError, LockedFileMode, Simplified, cachedir, directories};
14use uv_normalize::PackageName;
15use uv_pypi_types::ResolutionMetadata;
16
17pub use crate::by_timestamp::CachedByTimestamp;
18#[cfg(feature = "clap")]
19pub use crate::cli::CacheArgs;
20use crate::removal::Remover;
21pub use crate::removal::{Removal, rm_rf};
22pub use crate::wheel::WheelCache;
23use crate::wheel::WheelCacheKind;
24pub use archive::ArchiveId;
25
26mod archive;
27mod by_timestamp;
28#[cfg(feature = "clap")]
29mod cli;
30mod removal;
31mod wheel;
32
33/// The version of the archive bucket.
34///
35/// Must be kept in-sync with the version in [`CacheBucket::to_str`].
36pub const ARCHIVE_VERSION: u8 = 0;
37
38/// Error locking a cache entry or shard
39#[derive(Debug, thiserror::Error)]
40pub enum Error {
41    #[error(transparent)]
42    Io(#[from] io::Error),
43    #[error("Failed to initialize cache at `{}`", _0.user_display())]
44    Init(PathBuf, #[source] io::Error),
45    #[error("Could not make the path absolute")]
46    Absolute(#[source] io::Error),
47    #[error("Could not acquire lock")]
48    Acquire(#[from] LockedFileError),
49}
50
51/// A [`CacheEntry`] which may or may not exist yet.
52#[derive(Debug, Clone)]
53pub struct CacheEntry(PathBuf);
54
55impl CacheEntry {
56    /// Create a new [`CacheEntry`] from a directory and a file name.
57    pub fn new(dir: impl Into<PathBuf>, file: impl AsRef<Path>) -> Self {
58        Self(dir.into().join(file))
59    }
60
61    /// Create a new [`CacheEntry`] from a path.
62    pub fn from_path(path: impl Into<PathBuf>) -> Self {
63        Self(path.into())
64    }
65
66    /// Return the cache entry's parent directory.
67    pub fn shard(&self) -> CacheShard {
68        CacheShard(self.dir().to_path_buf())
69    }
70
71    /// Convert the [`CacheEntry`] into a [`PathBuf`].
72    #[inline]
73    pub fn into_path_buf(self) -> PathBuf {
74        self.0
75    }
76
77    /// Return the path to the [`CacheEntry`].
78    #[inline]
79    pub fn path(&self) -> &Path {
80        &self.0
81    }
82
83    /// Return the cache entry's parent directory.
84    #[inline]
85    pub fn dir(&self) -> &Path {
86        self.0.parent().expect("Cache entry has no parent")
87    }
88
89    /// Create a new [`CacheEntry`] with the given file name.
90    #[must_use]
91    pub fn with_file(&self, file: impl AsRef<Path>) -> Self {
92        Self(self.dir().join(file))
93    }
94
95    /// Acquire the [`CacheEntry`] as an exclusive lock.
96    pub async fn lock(&self) -> Result<LockedFile, Error> {
97        fs_err::create_dir_all(self.dir())?;
98        Ok(LockedFile::acquire(
99            self.path(),
100            LockedFileMode::Exclusive,
101            self.path().display(),
102        )
103        .await?)
104    }
105}
106
107impl AsRef<Path> for CacheEntry {
108    fn as_ref(&self) -> &Path {
109        &self.0
110    }
111}
112
113/// A subdirectory within the cache.
114#[derive(Debug, Clone)]
115pub struct CacheShard(PathBuf);
116
117impl CacheShard {
118    /// Return a [`CacheEntry`] within this shard.
119    pub fn entry(&self, file: impl AsRef<Path>) -> CacheEntry {
120        CacheEntry::new(&self.0, file)
121    }
122
123    /// Return a [`CacheShard`] within this shard.
124    #[must_use]
125    pub fn shard(&self, dir: impl AsRef<Path>) -> Self {
126        Self(self.0.join(dir.as_ref()))
127    }
128
129    /// Acquire the cache entry as an exclusive lock.
130    pub async fn lock(&self) -> Result<LockedFile, Error> {
131        fs_err::create_dir_all(self.as_ref())?;
132        Ok(LockedFile::acquire(
133            self.join(".lock"),
134            LockedFileMode::Exclusive,
135            self.display(),
136        )
137        .await?)
138    }
139
140    /// Return the [`CacheShard`] as a [`PathBuf`].
141    pub fn into_path_buf(self) -> PathBuf {
142        self.0
143    }
144}
145
146impl AsRef<Path> for CacheShard {
147    fn as_ref(&self) -> &Path {
148        &self.0
149    }
150}
151
152impl Deref for CacheShard {
153    type Target = Path;
154
155    fn deref(&self) -> &Self::Target {
156        &self.0
157    }
158}
159
160/// The main cache abstraction.
161///
162/// While the cache is active, it holds a read (shared) lock that prevents cache cleaning
163#[derive(Debug, Clone)]
164pub struct Cache {
165    /// The cache directory.
166    root: PathBuf,
167    /// The refresh strategy to use when reading from the cache.
168    refresh: Refresh,
169    /// A temporary cache directory, if the user requested `--no-cache`.
170    ///
171    /// Included to ensure that the temporary directory exists for the length of the operation, but
172    /// is dropped at the end as appropriate.
173    temp_dir: Option<Arc<tempfile::TempDir>>,
174    /// Ensure that `uv cache` operations don't remove items from the cache that are used by another
175    /// uv process.
176    lock_file: Option<Arc<LockedFile>>,
177}
178
179impl Cache {
180    /// A persistent cache directory at `root`.
181    pub fn from_path(root: impl Into<PathBuf>) -> Self {
182        Self {
183            root: root.into(),
184            refresh: Refresh::None(Timestamp::now()),
185            temp_dir: None,
186            lock_file: None,
187        }
188    }
189
190    /// Create a temporary cache directory.
191    pub fn temp() -> Result<Self, io::Error> {
192        let temp_dir = tempfile::tempdir()?;
193        Ok(Self {
194            root: temp_dir.path().to_path_buf(),
195            refresh: Refresh::None(Timestamp::now()),
196            temp_dir: Some(Arc::new(temp_dir)),
197            lock_file: None,
198        })
199    }
200
201    /// Set the [`Refresh`] policy for the cache.
202    #[must_use]
203    pub fn with_refresh(self, refresh: Refresh) -> Self {
204        Self { refresh, ..self }
205    }
206
207    /// Acquire a lock that allows removing entries from the cache.
208    pub async fn with_exclusive_lock(self) -> Result<Self, LockedFileError> {
209        let Self {
210            root,
211            refresh,
212            temp_dir,
213            lock_file,
214        } = self;
215
216        // Release the existing lock, avoid deadlocks from a cloned cache.
217        if let Some(lock_file) = lock_file {
218            drop(
219                Arc::try_unwrap(lock_file).expect(
220                    "cloning the cache before acquiring an exclusive lock causes a deadlock",
221                ),
222            );
223        }
224        let lock_file = LockedFile::acquire(
225            root.join(".lock"),
226            LockedFileMode::Exclusive,
227            root.simplified_display(),
228        )
229        .await?;
230
231        Ok(Self {
232            root,
233            refresh,
234            temp_dir,
235            lock_file: Some(Arc::new(lock_file)),
236        })
237    }
238
239    /// Acquire a lock that allows removing entries from the cache, if available.
240    ///
241    /// If the lock is not immediately available, returns [`Err`] with self.
242    pub fn with_exclusive_lock_no_wait(self) -> Result<Self, Self> {
243        let Self {
244            root,
245            refresh,
246            temp_dir,
247            lock_file,
248        } = self;
249
250        match LockedFile::acquire_no_wait(
251            root.join(".lock"),
252            LockedFileMode::Exclusive,
253            root.simplified_display(),
254        ) {
255            Some(lock_file) => Ok(Self {
256                root,
257                refresh,
258                temp_dir,
259                lock_file: Some(Arc::new(lock_file)),
260            }),
261            None => Err(Self {
262                root,
263                refresh,
264                temp_dir,
265                lock_file,
266            }),
267        }
268    }
269
270    /// Return the root of the cache.
271    pub fn root(&self) -> &Path {
272        &self.root
273    }
274
275    /// The folder for a specific cache bucket
276    pub fn bucket(&self, cache_bucket: CacheBucket) -> PathBuf {
277        self.root.join(cache_bucket.to_str())
278    }
279
280    /// Compute an entry in the cache.
281    pub fn shard(&self, cache_bucket: CacheBucket, dir: impl AsRef<Path>) -> CacheShard {
282        CacheShard(self.bucket(cache_bucket).join(dir.as_ref()))
283    }
284
285    /// Compute an entry in the cache.
286    pub fn entry(
287        &self,
288        cache_bucket: CacheBucket,
289        dir: impl AsRef<Path>,
290        file: impl AsRef<Path>,
291    ) -> CacheEntry {
292        CacheEntry::new(self.bucket(cache_bucket).join(dir), file)
293    }
294
295    /// Return the path to an archive in the cache.
296    pub fn archive(&self, id: &ArchiveId) -> PathBuf {
297        self.bucket(CacheBucket::Archive).join(id)
298    }
299
300    /// Create a temporary directory to be used as a Python virtual environment.
301    pub fn venv_dir(&self) -> io::Result<tempfile::TempDir> {
302        fs_err::create_dir_all(self.bucket(CacheBucket::Builds))?;
303        tempfile::tempdir_in(self.bucket(CacheBucket::Builds))
304    }
305
306    /// Create a temporary directory to be used for executing PEP 517 source distribution builds.
307    pub fn build_dir(&self) -> io::Result<tempfile::TempDir> {
308        fs_err::create_dir_all(self.bucket(CacheBucket::Builds))?;
309        tempfile::tempdir_in(self.bucket(CacheBucket::Builds))
310    }
311
312    /// Returns `true` if a cache entry must be revalidated given the [`Refresh`] policy.
313    pub fn must_revalidate_package(&self, package: &PackageName) -> bool {
314        match &self.refresh {
315            Refresh::None(_) => false,
316            Refresh::All(_) => true,
317            Refresh::Packages(packages, _, _) => packages.contains(package),
318        }
319    }
320
321    /// Returns `true` if a cache entry must be revalidated given the [`Refresh`] policy.
322    pub fn must_revalidate_path(&self, path: &Path) -> bool {
323        match &self.refresh {
324            Refresh::None(_) => false,
325            Refresh::All(_) => true,
326            Refresh::Packages(_, paths, _) => paths
327                .iter()
328                .any(|target| same_file::is_same_file(path, target).unwrap_or(false)),
329        }
330    }
331
332    /// Returns the [`Freshness`] for a cache entry, validating it against the [`Refresh`] policy.
333    ///
334    /// A cache entry is considered fresh if it was created after the cache itself was
335    /// initialized, or if the [`Refresh`] policy does not require revalidation.
336    pub fn freshness(
337        &self,
338        entry: &CacheEntry,
339        package: Option<&PackageName>,
340        path: Option<&Path>,
341    ) -> io::Result<Freshness> {
342        // Grab the cutoff timestamp, if it's relevant.
343        let timestamp = match &self.refresh {
344            Refresh::None(_) => return Ok(Freshness::Fresh),
345            Refresh::All(timestamp) => timestamp,
346            Refresh::Packages(packages, paths, timestamp) => {
347                if package.is_none_or(|package| packages.contains(package))
348                    || path.is_some_and(|path| {
349                        paths
350                            .iter()
351                            .any(|target| same_file::is_same_file(path, target).unwrap_or(false))
352                    })
353                {
354                    timestamp
355                } else {
356                    return Ok(Freshness::Fresh);
357                }
358            }
359        };
360
361        match fs_err::metadata(entry.path()) {
362            Ok(metadata) => {
363                if Timestamp::from_metadata(&metadata) >= *timestamp {
364                    Ok(Freshness::Fresh)
365                } else {
366                    Ok(Freshness::Stale)
367                }
368            }
369            Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Freshness::Missing),
370            Err(err) => Err(err),
371        }
372    }
373
374    /// Persist a temporary directory to the artifact store, returning its unique ID.
375    pub async fn persist(
376        &self,
377        temp_dir: impl AsRef<Path>,
378        path: impl AsRef<Path>,
379    ) -> io::Result<ArchiveId> {
380        // Create a unique ID for the artifact.
381        // TODO(charlie): Support content-addressed persistence via SHAs.
382        let id = ArchiveId::new();
383
384        // Move the temporary directory into the directory store.
385        let archive_entry = self.entry(CacheBucket::Archive, "", &id);
386        fs_err::create_dir_all(archive_entry.dir())?;
387        uv_fs::rename_with_retry(temp_dir.as_ref(), archive_entry.path()).await?;
388
389        // Create a symlink to the directory store.
390        fs_err::create_dir_all(path.as_ref().parent().expect("Cache entry to have parent"))?;
391        self.create_link(&id, path.as_ref())?;
392
393        Ok(id)
394    }
395
396    /// Returns `true` if the [`Cache`] is temporary.
397    pub fn is_temporary(&self) -> bool {
398        self.temp_dir.is_some()
399    }
400
401    /// Populate the cache scaffold.
402    fn create_base_files(root: &PathBuf) -> io::Result<()> {
403        // Create the cache directory, if it doesn't exist.
404        fs_err::create_dir_all(root)?;
405
406        // Add the CACHEDIR.TAG.
407        cachedir::ensure_tag(root)?;
408
409        // Add the .gitignore.
410        match fs_err::OpenOptions::new()
411            .write(true)
412            .create_new(true)
413            .open(root.join(".gitignore"))
414        {
415            Ok(mut file) => file.write_all(b"*")?,
416            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (),
417            Err(err) => return Err(err),
418        }
419
420        // Add an empty .gitignore to the build bucket, to ensure that the cache's own .gitignore
421        // doesn't interfere with source distribution builds. Build backends (like hatchling) will
422        // traverse upwards to look for .gitignore files.
423        fs_err::create_dir_all(root.join(CacheBucket::SourceDistributions.to_str()))?;
424        match fs_err::OpenOptions::new()
425            .write(true)
426            .create_new(true)
427            .open(
428                root.join(CacheBucket::SourceDistributions.to_str())
429                    .join(".gitignore"),
430            ) {
431            Ok(_) => {}
432            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (),
433            Err(err) => return Err(err),
434        }
435
436        // Add a phony .git, if it doesn't exist, to ensure that the cache isn't considered to be
437        // part of a Git repository. (Some packages will include Git metadata (like a hash) in the
438        // built version if they're in a Git repository, but the cache should be viewed as an
439        // isolated store.).
440        // We have to put this below the gitignore. Otherwise, if the build backend uses the rust
441        // ignore crate it will walk up to the top level .gitignore and ignore its python source
442        // files.
443        let phony_git = root
444            .join(CacheBucket::SourceDistributions.to_str())
445            .join(".git");
446        match fs_err::OpenOptions::new()
447            .create(true)
448            .write(true)
449            .open(&phony_git)
450        {
451            Ok(_) => {}
452            // Handle read-only caches including sandboxed environments.
453            Err(err) if err.kind() == io::ErrorKind::ReadOnlyFilesystem => {
454                if !phony_git.exists() {
455                    return Err(err);
456                }
457            }
458            Err(err) => return Err(err),
459        }
460
461        Ok(())
462    }
463
464    /// Initialize the [`Cache`].
465    pub async fn init(self) -> Result<Self, Error> {
466        let root = &self.root;
467
468        Self::create_base_files(root).map_err(|err| Error::Init(root.clone(), err))?;
469
470        // Block cache removal operations from interfering.
471        let lock_file = match LockedFile::acquire(
472            root.join(".lock"),
473            LockedFileMode::Shared,
474            root.simplified_display(),
475        )
476        .await
477        {
478            Ok(lock_file) => Some(Arc::new(lock_file)),
479            Err(err)
480                if err
481                    .as_io_error()
482                    .is_some_and(|err| err.kind() == io::ErrorKind::Unsupported) =>
483            {
484                warn!(
485                    "Shared locking is not supported by the current platform or filesystem, \
486                        reduced parallel process safety with `uv cache clean` and `uv cache prune`."
487                );
488                None
489            }
490            Err(err) => return Err(err.into()),
491        };
492
493        Ok(Self {
494            root: std::path::absolute(root).map_err(Error::Absolute)?,
495            lock_file,
496            ..self
497        })
498    }
499
500    /// Initialize the [`Cache`], assuming that there are no other uv processes running.
501    pub fn init_no_wait(self) -> Result<Option<Self>, Error> {
502        let root = &self.root;
503
504        Self::create_base_files(root).map_err(|err| Error::Init(root.clone(), err))?;
505
506        // Block cache removal operations from interfering.
507        let Some(lock_file) = LockedFile::acquire_no_wait(
508            root.join(".lock"),
509            LockedFileMode::Shared,
510            root.simplified_display(),
511        ) else {
512            return Ok(None);
513        };
514        Ok(Some(Self {
515            root: std::path::absolute(root).map_err(Error::Absolute)?,
516            lock_file: Some(Arc::new(lock_file)),
517            ..self
518        }))
519    }
520
521    /// Clear the cache, removing all entries.
522    pub fn clear(self, reporter: Box<dyn CleanReporter>) -> Result<Removal, io::Error> {
523        // Remove everything but `.lock`, Windows does not allow removal of a locked file
524        let mut removal = Remover::new(reporter).rm_rf(&self.root, true)?;
525        let Self {
526            root, lock_file, ..
527        } = self;
528
529        // Remove the `.lock` file, unlocking it first
530        if let Some(lock) = lock_file {
531            drop(lock);
532            fs_err::remove_file(root.join(".lock"))?;
533        }
534        removal.num_files += 1;
535
536        // Remove the root directory
537        match fs_err::remove_dir(root) {
538            Ok(()) => {
539                removal.num_dirs += 1;
540            }
541            // On Windows, when `--force` is used, the `.lock` file can exist and be unremovable,
542            // so we make this non-fatal
543            Err(err) if err.kind() == io::ErrorKind::DirectoryNotEmpty => {
544                trace!("Failed to remove root cache directory: not empty");
545            }
546            Err(err) => return Err(err),
547        }
548
549        Ok(removal)
550    }
551
552    /// Remove a package from the cache.
553    ///
554    /// Returns the number of entries removed from the cache.
555    pub fn remove(&self, name: &PackageName) -> io::Result<Removal> {
556        // Collect the set of referenced archives.
557        let references = self.find_archive_references()?;
558
559        // Remove any entries for the package from the cache.
560        let mut summary = Removal::default();
561        for bucket in CacheBucket::iter() {
562            summary += bucket.remove(self, name)?;
563        }
564
565        if references.is_empty() {
566            return Ok(summary);
567        }
568
569        // Only remove targets in the archive bucket. Cache entries may contain unexpected links
570        // to paths outside the cache.
571        let archive_root = fs_err::canonicalize(&self.root)?.join(CacheBucket::Archive.to_str());
572
573        // Remove any archives that are no longer referenced.
574        for (target, references) in references {
575            if target.starts_with(&archive_root) && references.iter().all(|path| !path.exists()) {
576                debug!("Removing dangling cache entry: {}", target.display());
577                summary += rm_rf(target)?;
578            }
579        }
580
581        Ok(summary)
582    }
583
584    /// Run the garbage collector on the cache, removing any dangling entries.
585    pub fn prune(&self, ci: bool) -> Result<Removal, io::Error> {
586        let mut summary = Removal::default();
587
588        // First, remove any top-level directories that are unused. These typically represent
589        // outdated cache buckets (e.g., `wheels-v0`, when latest is `wheels-v1`).
590        for entry in fs_err::read_dir(&self.root)? {
591            let entry = entry?;
592            let metadata = entry.metadata()?;
593
594            if entry.file_name() == "CACHEDIR.TAG"
595                || entry.file_name() == ".gitignore"
596                || entry.file_name() == ".git"
597                || entry.file_name() == ".lock"
598            {
599                continue;
600            }
601
602            if metadata.is_dir() {
603                // If the directory is not a cache bucket, remove it.
604                if CacheBucket::iter().all(|bucket| entry.file_name() != bucket.to_str()) {
605                    let path = entry.path();
606                    debug!("Removing dangling cache bucket: {}", path.display());
607                    summary += rm_rf(path)?;
608                }
609            } else {
610                // If the file is not a marker file, remove it.
611                let path = entry.path();
612                debug!("Removing dangling cache bucket: {}", path.display());
613                summary += rm_rf(path)?;
614            }
615        }
616
617        // Second, remove any cached environments. These are never referenced by symlinks, so we can
618        // remove them directly.
619        match fs_err::read_dir(self.bucket(CacheBucket::Environments)) {
620            Ok(entries) => {
621                for entry in entries {
622                    let entry = entry?;
623                    let path = entry.path();
624                    debug!("Removing dangling cache environment: {}", path.display());
625                    summary += rm_rf(path)?;
626                }
627            }
628            Err(err) if err.kind() == io::ErrorKind::NotFound => (),
629            Err(err) => return Err(err),
630        }
631
632        // Third, if enabled, remove all unzipped wheels, leaving only the wheel archives.
633        if ci {
634            // Remove the entire pre-built wheel cache, since every entry is an unzipped wheel.
635            match fs_err::read_dir(self.bucket(CacheBucket::Wheels)) {
636                Ok(entries) => {
637                    for entry in entries {
638                        let entry = entry?;
639                        let path = entry.path();
640                        if path.is_dir() {
641                            debug!("Removing unzipped wheel entry: {}", path.display());
642                            summary += rm_rf(path)?;
643                        }
644                    }
645                }
646                Err(err) if err.kind() == io::ErrorKind::NotFound => (),
647                Err(err) => return Err(err),
648            }
649
650            for entry in walkdir::WalkDir::new(self.bucket(CacheBucket::SourceDistributions)) {
651                let entry = entry?;
652
653                // If the directory contains a `metadata.msgpack`, then it's a built wheel revision.
654                if !entry.file_type().is_dir() {
655                    continue;
656                }
657
658                if !entry.path().join("metadata.msgpack").exists() {
659                    continue;
660                }
661
662                // Remove everything except the built wheel archive and the metadata.
663                for entry in fs_err::read_dir(entry.path())? {
664                    let entry = entry?;
665                    let path = entry.path();
666
667                    // Retain the resolved metadata (`metadata.msgpack`).
668                    if path
669                        .file_name()
670                        .is_some_and(|file_name| file_name == "metadata.msgpack")
671                    {
672                        continue;
673                    }
674
675                    // Retain any built wheel archives.
676                    if path
677                        .extension()
678                        .is_some_and(|ext| ext.eq_ignore_ascii_case("whl"))
679                    {
680                        continue;
681                    }
682
683                    debug!("Removing unzipped built wheel entry: {}", path.display());
684                    summary += rm_rf(path)?;
685                }
686            }
687        }
688
689        // Fourth, remove any unused archives (by searching for archives that are not symlinked).
690        let references = self.find_archive_references()?;
691
692        match fs_err::read_dir(self.bucket(CacheBucket::Archive)) {
693            Ok(entries) => {
694                for entry in entries {
695                    let entry = entry?;
696                    let path = entry.path();
697                    let target = fs_err::canonicalize(&path)?;
698                    if !references.contains_key(&target) {
699                        debug!("Removing dangling cache archive: {}", path.display());
700                        summary += rm_rf(path)?;
701                    }
702                }
703            }
704            Err(err) if err.kind() == io::ErrorKind::NotFound => (),
705            Err(err) => return Err(err),
706        }
707
708        Ok(summary)
709    }
710
711    /// Find all references to entries in the archive bucket.
712    ///
713    /// Archive entries are often referenced by symlinks in other cache buckets. This method
714    /// searches for all such references.
715    ///
716    /// Returns a map from archive path to paths that reference it.
717    fn find_archive_references(&self) -> Result<FxHashMap<PathBuf, Vec<PathBuf>>, io::Error> {
718        let mut references = FxHashMap::<PathBuf, Vec<PathBuf>>::default();
719        for bucket in [CacheBucket::SourceDistributions, CacheBucket::Wheels] {
720            let bucket_path = self.bucket(bucket);
721            if bucket_path.is_dir() {
722                let walker = walkdir::WalkDir::new(&bucket_path).into_iter();
723                for entry in walker.filter_entry(|entry| {
724                    !(
725                        // As an optimization, ignore any `.lock`, `.whl`, `.msgpack`, `.rev`, or
726                        // `.http` files, along with the `src` directory, which represents the
727                        // unpacked source distribution.
728                        entry.file_name() == "src"
729                            || entry.file_name() == ".lock"
730                            || entry.file_name() == ".gitignore"
731                            || entry.path().extension().is_some_and(|ext| {
732                                ext.eq_ignore_ascii_case("lock")
733                                    || ext.eq_ignore_ascii_case("whl")
734                                    || ext.eq_ignore_ascii_case("http")
735                                    || ext.eq_ignore_ascii_case("rev")
736                                    || ext.eq_ignore_ascii_case("msgpack")
737                            })
738                    )
739                }) {
740                    let entry = entry?;
741
742                    // On Unix, archive references use symlinks.
743                    if cfg!(unix) {
744                        if !entry.file_type().is_symlink() {
745                            continue;
746                        }
747                    }
748
749                    // On Windows, archive references are files containing structured data.
750                    if cfg!(windows) {
751                        if !entry.file_type().is_file() {
752                            continue;
753                        }
754                    }
755
756                    if let Ok(target) = self.resolve_link(entry.path()) {
757                        references
758                            .entry(target)
759                            .or_default()
760                            .push(entry.path().to_path_buf());
761                    }
762                }
763            }
764        }
765        Ok(references)
766    }
767
768    /// Create a link to a directory in the archive bucket.
769    ///
770    /// On Windows, we write structured data ([`Link`]) to a file containing the archive ID and
771    /// version. On Unix, we create a symlink to the target directory.
772    #[cfg(windows)]
773    #[expect(clippy::unused_self)]
774    fn create_link(&self, id: &ArchiveId, dst: impl AsRef<Path>) -> io::Result<()> {
775        // Serialize the link.
776        let link = Link::new(id.clone());
777        let contents = link.to_string();
778
779        // First, attempt to create a file at the location, but fail if it already exists.
780        match fs_err::OpenOptions::new()
781            .write(true)
782            .create_new(true)
783            .open(dst.as_ref())
784        {
785            Ok(mut file) => {
786                // Write the target path to the file.
787                file.write_all(contents.as_bytes())?;
788                Ok(())
789            }
790            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
791                // Write to a temporary file, then move it into place.
792                let temp_dir = tempfile::tempdir_in(dst.as_ref().parent().unwrap())?;
793                let temp_file = temp_dir.path().join("link");
794                fs_err::write(&temp_file, contents.as_bytes())?;
795
796                // Move the symlink into the target location.
797                fs_err::rename(&temp_file, dst.as_ref())?;
798
799                Ok(())
800            }
801            Err(err) => Err(err),
802        }
803    }
804
805    /// Resolve an archive link, returning the fully-resolved path.
806    ///
807    /// Returns an error if the link target does not exist.
808    #[cfg(windows)]
809    pub fn resolve_link(&self, path: impl AsRef<Path>) -> io::Result<PathBuf> {
810        // Deserialize the link.
811        let contents = fs_err::read_to_string(path.as_ref())?;
812        let link = Link::from_str(&contents)?;
813
814        // Ignore stale links.
815        if link.version != ARCHIVE_VERSION {
816            return Err(io::Error::new(
817                io::ErrorKind::NotFound,
818                "The link target does not exist.",
819            ));
820        }
821
822        // Reconstruct the path.
823        let path = self.archive(&link.id);
824        path.canonicalize()
825    }
826
827    /// Create a link to a directory in the archive bucket.
828    ///
829    /// On Windows, we write structured data ([`Link`]) to a file containing the archive ID and
830    /// version. On Unix, we create a symlink to the target directory.
831    #[cfg(unix)]
832    fn create_link(&self, id: &ArchiveId, dst: impl AsRef<Path>) -> io::Result<()> {
833        let dst = dst.as_ref();
834        let dst_parent = dst.parent().expect("Cache entry to have parent");
835        // Construct the relative link target.
836        let src = uv_fs::relative_to(self.archive(id), dst_parent)?;
837
838        // Attempt to create the symlink directly.
839        match fs_err::os::unix::fs::symlink(&src, dst) {
840            Ok(()) => Ok(()),
841            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
842                // Create a symlink, using a temporary file to ensure atomicity.
843                let temp_dir = tempfile::tempdir_in(dst_parent)?;
844                let temp_file = temp_dir.path().join("link");
845                fs_err::os::unix::fs::symlink(&src, &temp_file)?;
846
847                // Move the symlink into the target location.
848                fs_err::rename(&temp_file, dst)?;
849
850                Ok(())
851            }
852            Err(err) => Err(err),
853        }
854    }
855
856    /// Resolve an archive link, returning the fully-resolved path.
857    ///
858    /// Returns an error if the link target does not exist.
859    #[cfg(unix)]
860    pub fn resolve_link(&self, path: impl AsRef<Path>) -> io::Result<PathBuf> {
861        path.as_ref().canonicalize()
862    }
863}
864
865/// An archive (unzipped wheel) that exists in the local cache.
866#[derive(Debug, Clone)]
867#[allow(unused)]
868struct Link {
869    /// The unique ID of the entry in the archive bucket.
870    id: ArchiveId,
871    /// The version of the archive bucket.
872    version: u8,
873}
874
875#[allow(unused)]
876impl Link {
877    /// Create a new [`Archive`] with the given ID and hashes.
878    fn new(id: ArchiveId) -> Self {
879        Self {
880            id,
881            version: ARCHIVE_VERSION,
882        }
883    }
884}
885
886impl Display for Link {
887    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
888        write!(f, "archive-v{}/{}", self.version, self.id)
889    }
890}
891
892impl FromStr for Link {
893    type Err = io::Error;
894
895    fn from_str(s: &str) -> Result<Self, Self::Err> {
896        let mut parts = s.splitn(2, '/');
897        let version = parts
898            .next()
899            .filter(|s| !s.is_empty())
900            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing version"))?;
901        let id = parts
902            .next()
903            .filter(|s| !s.is_empty())
904            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing ID"))?;
905
906        // Parse the archive version from `archive-v{version}/{id}`.
907        let version = version
908            .strip_prefix("archive-v")
909            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing version prefix"))?;
910        let version = u8::from_str(version).map_err(|err| {
911            io::Error::new(
912                io::ErrorKind::InvalidData,
913                format!("failed to parse version: {err}"),
914            )
915        })?;
916
917        // Parse the ID from `archive-v{version}/{id}`.
918        let id = ArchiveId::from_str(id).map_err(|err| {
919            io::Error::new(
920                io::ErrorKind::InvalidData,
921                format!("failed to parse ID: {err}"),
922            )
923        })?;
924
925        Ok(Self { id, version })
926    }
927}
928
929pub trait CleanReporter: Send + Sync {
930    /// Called after one file or directory is removed.
931    fn on_clean(&self);
932
933    /// Called after all files and directories are removed.
934    fn on_complete(&self);
935}
936
937/// The different kinds of data in the cache are stored in different bucket, which in our case
938/// are subdirectories of the cache root.
939#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
940pub enum CacheBucket {
941    /// Wheels (excluding built wheels), alongside their metadata and cache policy.
942    ///
943    /// There are three kinds from cache entries: Wheel metadata and policy as `MsgPack` files, the
944    /// wheels themselves, and the unzipped wheel archives. If a wheel file is over an in-memory
945    /// size threshold, we first download the zip file into the cache, then unzip it into a
946    /// directory with the same name (exclusive of the `.whl` extension).
947    ///
948    /// Cache structure:
949    ///  * `wheel-metadata-v0/pypi/foo/{foo-1.0.0-py3-none-any.msgpack, foo-1.0.0-py3-none-any.whl}`
950    ///  * `wheel-metadata-v0/<digest(index-url)>/foo/{foo-1.0.0-py3-none-any.msgpack, foo-1.0.0-py3-none-any.whl}`
951    ///  * `wheel-metadata-v0/url/<digest(url)>/foo/{foo-1.0.0-py3-none-any.msgpack, foo-1.0.0-py3-none-any.whl}`
952    ///
953    /// See `uv_client::RegistryClient::wheel_metadata` for information on how wheel metadata
954    /// is fetched.
955    ///
956    /// # Example
957    ///
958    /// Consider the following `requirements.in`:
959    /// ```text
960    /// # pypi wheel
961    /// pandas
962    /// # url wheel
963    /// flask @ https://files.pythonhosted.org/packages/36/42/015c23096649b908c809c69388a805a571a3bea44362fe87e33fc3afa01f/flask-3.0.0-py3-none-any.whl
964    /// ```
965    ///
966    /// When we run `pip compile`, it will only fetch and cache the metadata (and cache policy), it
967    /// doesn't need the actual wheels yet:
968    /// ```text
969    /// wheel-v0
970    /// ├── pypi
971    /// │   ...
972    /// │   ├── pandas
973    /// │   │   └── pandas-2.1.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.msgpack
974    /// │   ...
975    /// └── url
976    ///     └── 4b8be67c801a7ecb
977    ///         └── flask
978    ///             └── flask-3.0.0-py3-none-any.msgpack
979    /// ```
980    ///
981    /// We get the following `requirement.txt` from `pip compile`:
982    ///
983    /// ```text
984    /// [...]
985    /// flask @ https://files.pythonhosted.org/packages/36/42/015c23096649b908c809c69388a805a571a3bea44362fe87e33fc3afa01f/flask-3.0.0-py3-none-any.whl
986    /// [...]
987    /// pandas==2.1.3
988    /// [...]
989    /// ```
990    ///
991    /// If we run `pip sync` on `requirements.txt` on a different machine, it also fetches the
992    /// wheels:
993    ///
994    /// TODO(konstin): This is still wrong, we need to store the cache policy too!
995    /// ```text
996    /// wheel-v0
997    /// ├── pypi
998    /// │   ...
999    /// │   ├── pandas
1000    /// │   │   ├── pandas-2.1.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
1001    /// │   │   ├── pandas-2.1.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64
1002    /// │   ...
1003    /// └── url
1004    ///     └── 4b8be67c801a7ecb
1005    ///         └── flask
1006    ///             └── flask-3.0.0-py3-none-any.whl
1007    ///                 ├── flask
1008    ///                 │   └── ...
1009    ///                 └── flask-3.0.0.dist-info
1010    ///                     └── ...
1011    /// ```
1012    ///
1013    /// If we run first `pip compile` and then `pip sync` on the same machine, we get both:
1014    ///
1015    /// ```text
1016    /// wheels-v0
1017    /// ├── pypi
1018    /// │   ├── ...
1019    /// │   ├── pandas
1020    /// │   │   ├── pandas-2.1.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.msgpack
1021    /// │   │   ├── pandas-2.1.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
1022    /// │   │   └── pandas-2.1.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64
1023    /// │   │       ├── pandas
1024    /// │   │       │   ├── ...
1025    /// │   │       ├── pandas-2.1.3.dist-info
1026    /// │   │       │   ├── ...
1027    /// │   │       └── pandas.libs
1028    /// │   ├── ...
1029    /// └── url
1030    ///     └── 4b8be67c801a7ecb
1031    ///         └── flask
1032    ///             ├── flask-3.0.0-py3-none-any.msgpack
1033    ///             ├── flask-3.0.0-py3-none-any.msgpack
1034    ///             └── flask-3.0.0-py3-none-any
1035    ///                 ├── flask
1036    ///                 │   └── ...
1037    ///                 └── flask-3.0.0.dist-info
1038    ///                     └── ...
1039    Wheels,
1040    /// Source distributions, wheels built from source distributions, their extracted metadata, and the
1041    /// cache policy of the source distribution.
1042    ///
1043    /// The structure is similar of that of the `Wheel` bucket, except we have an additional layer
1044    /// for the source distribution filename and the metadata is at the source distribution-level,
1045    /// not at the wheel level.
1046    ///
1047    /// TODO(konstin): The cache policy should be on the source distribution level, the metadata we
1048    /// can put next to the wheels as in the `Wheels` bucket.
1049    ///
1050    /// The unzipped source distribution is stored in a directory matching the source distribution
1051    /// archive name.
1052    ///
1053    /// Source distributions are built into zipped wheel files (as PEP 517 specifies) and unzipped
1054    /// lazily before installing. So when resolving, we only build the wheel and store the archive
1055    /// file in the cache, when installing, we unpack it under the same name (exclusive of the
1056    /// `.whl` extension). You may find a mix of wheel archive zip files and unzipped wheel
1057    /// directories in the cache.
1058    ///
1059    /// Cache structure:
1060    ///  * `built-wheels-v0/pypi/foo/34a17436ed1e9669/{manifest.msgpack, metadata.msgpack, foo-1.0.0.zip, foo-1.0.0-py3-none-any.whl, ...other wheels}`
1061    ///  * `built-wheels-v0/<digest(index-url)>/foo/foo-1.0.0.zip/{manifest.msgpack, metadata.msgpack, foo-1.0.0-py3-none-any.whl, ...other wheels}`
1062    ///  * `built-wheels-v0/url/<digest(url)>/foo/foo-1.0.0.zip/{manifest.msgpack, metadata.msgpack, foo-1.0.0-py3-none-any.whl, ...other wheels}`
1063    ///  * `built-wheels-v0/git/<digest(url)>/<git sha>/foo/foo-1.0.0.zip/{metadata.msgpack, foo-1.0.0-py3-none-any.whl, ...other wheels}`
1064    ///
1065    /// But the url filename does not need to be a valid source dist filename
1066    /// (<https://github.com/search?q=path%3A**%2Frequirements.txt+master.zip&type=code>),
1067    /// so it could also be the following and we have to take any string as filename:
1068    ///  * `built-wheels-v0/url/<sha256(url)>/master.zip/metadata.msgpack`
1069    ///
1070    /// # Example
1071    ///
1072    /// The following requirements:
1073    /// ```text
1074    /// # git source dist
1075    /// pydantic-extra-types @ git+https://github.com/pydantic/pydantic-extra-types.git
1076    /// # pypi source dist
1077    /// django_allauth==0.51.0
1078    /// # url source dist
1079    /// werkzeug @ https://files.pythonhosted.org/packages/0d/cc/ff1904eb5eb4b455e442834dabf9427331ac0fa02853bf83db817a7dd53d/werkzeug-3.0.1.tar.gz
1080    /// ```
1081    ///
1082    /// ...may be cached as:
1083    /// ```text
1084    /// built-wheels-v4/
1085    /// ├── git
1086    /// │   └── 2122faf3e081fb7a
1087    /// │       └── 7a2d650a4a7b4d04
1088    /// │           ├── metadata.msgpack
1089    /// │           └── pydantic_extra_types-2.9.0-py3-none-any.whl
1090    /// ├── pypi
1091    /// │   └── django-allauth
1092    /// │       └── 0.51.0
1093    /// │           ├── 0gH-_fwv8tdJ7JwwjJsUc
1094    /// │           │   ├── django-allauth-0.51.0.tar.gz
1095    /// │           │   │   └── [UNZIPPED CONTENTS]
1096    /// │           │   ├── django_allauth-0.51.0-py3-none-any.whl
1097    /// │           │   └── metadata.msgpack
1098    /// │           └── revision.http
1099    /// └── url
1100    ///     └── 6781bd6440ae72c2
1101    ///         ├── APYY01rbIfpAo_ij9sCY6
1102    ///         │   ├── metadata.msgpack
1103    ///         │   ├── werkzeug-3.0.1-py3-none-any.whl
1104    ///         │   └── werkzeug-3.0.1.tar.gz
1105    ///         │       └── [UNZIPPED CONTENTS]
1106    ///         └── revision.http
1107    /// ```
1108    ///
1109    /// Structurally, the `manifest.msgpack` is empty, and only contains the caching information
1110    /// needed to invalidate the cache. The `metadata.msgpack` contains the metadata of the source
1111    /// distribution.
1112    SourceDistributions,
1113    /// Flat index responses, a format very similar to the simple metadata API.
1114    ///
1115    /// Cache structure:
1116    ///  * `flat-index-v0/index/<digest(flat_index_url)>.msgpack`
1117    ///
1118    /// The response is stored as `Vec<File>`.
1119    FlatIndex,
1120    /// Git repositories.
1121    Git,
1122    /// Information about an interpreter at a path.
1123    ///
1124    /// To avoid caching pyenv shims, bash scripts which may redirect to a new python version
1125    /// without the shim itself changing, we only cache when the path equals `sys.executable`, i.e.
1126    /// the path we're running is the python executable itself and not a shim.
1127    ///
1128    /// Cache structure: `interpreter-v0/<digest(path)>.msgpack`
1129    ///
1130    /// # Example
1131    ///
1132    /// The contents of each of the `MsgPack` files has a timestamp field in unix time, the [PEP 508]
1133    /// markers and some information from the `sys`/`sysconfig` modules.
1134    ///
1135    /// ```json
1136    /// {
1137    ///   "timestamp": 1698047994491,
1138    ///   "data": {
1139    ///     "markers": {
1140    ///       "implementation_name": "cpython",
1141    ///       "implementation_version": "3.12.0",
1142    ///       "os_name": "posix",
1143    ///       "platform_machine": "x86_64",
1144    ///       "platform_python_implementation": "CPython",
1145    ///       "platform_release": "6.5.0-13-generic",
1146    ///       "platform_system": "Linux",
1147    ///       "platform_version": "#13-Ubuntu SMP PREEMPT_DYNAMIC Fri Nov  3 12:16:05 UTC 2023",
1148    ///       "python_full_version": "3.12.0",
1149    ///       "python_version": "3.12",
1150    ///       "sys_platform": "linux"
1151    ///     },
1152    ///     "base_exec_prefix": "/home/ferris/.pyenv/versions/3.12.0",
1153    ///     "base_prefix": "/home/ferris/.pyenv/versions/3.12.0",
1154    ///     "sys_executable": "/home/ferris/projects/uv/.venv/bin/python"
1155    ///   }
1156    /// }
1157    /// ```
1158    ///
1159    /// [PEP 508]: https://peps.python.org/pep-0508/#environment-markers
1160    Interpreter,
1161    /// Index responses through the simple metadata API.
1162    ///
1163    /// Cache structure:
1164    ///  * `simple-v0/pypi/<package_name>.rkyv`
1165    ///  * `simple-v0/<digest(index_url)>/<package_name>.rkyv`
1166    ///
1167    /// The response is parsed into `uv_client::SimpleDetailMetadata` before storage.
1168    Simple,
1169    /// A cache of unzipped wheels, stored as directories. This is used internally within the cache.
1170    /// When other buckets need to store directories, they should persist them to
1171    /// [`CacheBucket::Archive`], and then symlink them into the appropriate bucket. This ensures
1172    /// that cache entries can be atomically replaced and removed, as storing directories in the
1173    /// other buckets directly would make atomic operations impossible.
1174    Archive,
1175    /// Ephemeral virtual environments used to execute PEP 517 builds and other operations.
1176    Builds,
1177    /// Reusable virtual environments used to invoke Python tools.
1178    Environments,
1179    /// Cached Python downloads
1180    Python,
1181    /// Downloaded tool binaries (e.g., Ruff).
1182    Binaries,
1183    /// Cached vulnerability data from [OSV](https://osv.dev/).
1184    ///
1185    /// Cache structure:
1186    ///  * `osv-v0/vulnerability/<vuln_id>.msgpack` — cached full vulnerability records
1187    Osv,
1188}
1189
1190impl CacheBucket {
1191    fn to_str(self) -> &'static str {
1192        match self {
1193            // Note that when bumping this, you'll also need to bump it
1194            // in `crates/uv/tests/it/cache_prune.rs`.
1195            Self::SourceDistributions => "sdists-v9",
1196            Self::FlatIndex => "flat-index-v2",
1197            Self::Git => "git-v0",
1198            Self::Interpreter => "interpreter-v4",
1199            // Note that when bumping this, you'll also need to bump it
1200            // in `crates/uv/tests/it/cache_clean.rs`.
1201            Self::Simple => "simple-v21",
1202            // Note that when bumping this, you'll also need to bump it
1203            // in `crates/uv/tests/it/cache_prune.rs`.
1204            Self::Wheels => "wheels-v6",
1205            // Note that when bumping this, you'll also need to bump
1206            // `ARCHIVE_VERSION` in `crates/uv-cache/src/lib.rs`.
1207            Self::Archive => "archive-v0",
1208            Self::Builds => "builds-v0",
1209            Self::Environments => "environments-v2",
1210            Self::Python => "python-v0",
1211            Self::Binaries => "binaries-v0",
1212            Self::Osv => "osv-v0",
1213        }
1214    }
1215
1216    /// Remove a package from the cache bucket.
1217    ///
1218    /// Returns the number of entries removed from the cache.
1219    fn remove(self, cache: &Cache, name: &PackageName) -> Result<Removal, io::Error> {
1220        /// Returns `true` if the [`Path`] represents a built wheel for the given package.
1221        fn is_match(path: &Path, name: &PackageName) -> bool {
1222            let Ok(metadata) = fs_err::read(path.join("metadata.msgpack")) else {
1223                return false;
1224            };
1225            let Ok(metadata) = rmp_serde::from_slice::<ResolutionMetadata>(&metadata) else {
1226                return false;
1227            };
1228            metadata.name == *name
1229        }
1230
1231        let mut summary = Removal::default();
1232        match self {
1233            Self::Wheels => {
1234                // For `pypi` wheels, we expect a directory per package (indexed by name).
1235                let root = cache.bucket(self).join(WheelCacheKind::Pypi);
1236                summary += rm_rf(root.join(name.to_string()))?;
1237
1238                // For alternate indices, we expect a directory for every index (under an `index`
1239                // subdirectory), followed by a directory per package (indexed by name).
1240                let root = cache.bucket(self).join(WheelCacheKind::Index);
1241                for directory in directories(root)? {
1242                    summary += rm_rf(directory.join(name.to_string()))?;
1243                }
1244
1245                // For direct URLs, we expect a directory for every URL, followed by a
1246                // directory per package (indexed by name).
1247                let root = cache.bucket(self).join(WheelCacheKind::Url);
1248                for directory in directories(root)? {
1249                    summary += rm_rf(directory.join(name.to_string()))?;
1250                }
1251            }
1252            Self::SourceDistributions => {
1253                // For `pypi` wheels, we expect a directory per package (indexed by name).
1254                let root = cache.bucket(self).join(WheelCacheKind::Pypi);
1255                summary += rm_rf(root.join(name.to_string()))?;
1256
1257                // For alternate indices, we expect a directory for every index (under an `index`
1258                // subdirectory), followed by a directory per package (indexed by name).
1259                let root = cache.bucket(self).join(WheelCacheKind::Index);
1260                for directory in directories(root)? {
1261                    summary += rm_rf(directory.join(name.to_string()))?;
1262                }
1263
1264                // For direct URLs, we expect a directory for every URL, followed by a
1265                // directory per version. To determine whether the URL is relevant, we need to
1266                // search for a wheel matching the package name.
1267                let root = cache.bucket(self).join(WheelCacheKind::Url);
1268                for url in directories(root)? {
1269                    if directories(&url)?.any(|version| is_match(&version, name)) {
1270                        summary += rm_rf(url)?;
1271                    }
1272                }
1273
1274                // For local dependencies, we expect a directory for every path, followed by a
1275                // directory per version. To determine whether the path is relevant, we need to
1276                // search for a wheel matching the package name.
1277                let root = cache.bucket(self).join(WheelCacheKind::Path);
1278                for path in directories(root)? {
1279                    if directories(&path)?.any(|version| is_match(&version, name)) {
1280                        summary += rm_rf(path)?;
1281                    }
1282                }
1283
1284                // For Git dependencies, we expect a directory for every repository, followed by a
1285                // directory for every SHA. To determine whether the SHA is relevant, we need to
1286                // search for a wheel matching the package name.
1287                let root = cache.bucket(self).join(WheelCacheKind::Git);
1288                for repository in directories(root)? {
1289                    for sha in directories(repository)? {
1290                        if is_match(&sha, name) {
1291                            summary += rm_rf(sha)?;
1292                        }
1293                    }
1294                }
1295            }
1296            Self::Simple => {
1297                // For `pypi` wheels, we expect a rkyv file per package, indexed by name.
1298                let root = cache.bucket(self).join(WheelCacheKind::Pypi);
1299                summary += rm_rf(root.join(format!("{name}.rkyv")))?;
1300
1301                // For alternate indices, we expect a directory for every index (under an `index`
1302                // subdirectory), followed by a directory per package (indexed by name).
1303                let root = cache.bucket(self).join(WheelCacheKind::Index);
1304                for directory in directories(root)? {
1305                    summary += rm_rf(directory.join(format!("{name}.rkyv")))?;
1306                }
1307            }
1308            Self::FlatIndex => {
1309                // We can't know if the flat index includes a package, so we just remove the entire
1310                // cache entry.
1311                let root = cache.bucket(self);
1312                summary += rm_rf(root)?;
1313            }
1314            Self::Git
1315            | Self::Interpreter
1316            | Self::Archive
1317            | Self::Builds
1318            | Self::Environments
1319            | Self::Python
1320            | Self::Binaries
1321            | Self::Osv => {
1322                // Nothing to do.
1323            }
1324        }
1325        Ok(summary)
1326    }
1327
1328    /// Return an iterator over all cache buckets.
1329    fn iter() -> impl Iterator<Item = Self> {
1330        [
1331            Self::Wheels,
1332            Self::SourceDistributions,
1333            Self::FlatIndex,
1334            Self::Git,
1335            Self::Interpreter,
1336            Self::Simple,
1337            Self::Archive,
1338            Self::Builds,
1339            Self::Environments,
1340            Self::Binaries,
1341            Self::Osv,
1342        ]
1343        .iter()
1344        .copied()
1345    }
1346}
1347
1348impl Display for CacheBucket {
1349    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1350        f.write_str(self.to_str())
1351    }
1352}
1353
1354#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1355pub enum Freshness {
1356    /// The cache entry is fresh according to the [`Refresh`] policy.
1357    Fresh,
1358    /// The cache entry is stale according to the [`Refresh`] policy.
1359    Stale,
1360    /// The cache entry does not exist.
1361    Missing,
1362}
1363
1364impl Freshness {
1365    pub const fn is_fresh(self) -> bool {
1366        matches!(self, Self::Fresh)
1367    }
1368}
1369
1370/// A refresh policy for cache entries.
1371#[derive(Debug, Clone)]
1372pub enum Refresh {
1373    /// Don't refresh any entries.
1374    None(Timestamp),
1375    /// Refresh entries linked to the given packages, if created before the given timestamp.
1376    Packages(Vec<PackageName>, Vec<Box<Path>>, Timestamp),
1377    /// Refresh all entries created before the given timestamp.
1378    All(Timestamp),
1379}
1380
1381impl Refresh {
1382    /// Determine the refresh strategy to use based on the command-line arguments.
1383    pub fn from_args(refresh: Option<bool>, refresh_package: Vec<PackageName>) -> Self {
1384        let timestamp = Timestamp::now();
1385        match refresh {
1386            Some(true) => Self::All(timestamp),
1387            Some(false) => Self::None(timestamp),
1388            None => {
1389                if refresh_package.is_empty() {
1390                    Self::None(timestamp)
1391                } else {
1392                    Self::Packages(refresh_package, vec![], timestamp)
1393                }
1394            }
1395        }
1396    }
1397
1398    /// Combine two [`Refresh`] policies, taking the "max" of the two policies.
1399    #[must_use]
1400    pub fn combine(self, other: Self) -> Self {
1401        match (self, other) {
1402            // If the policy is `None`, return the existing refresh policy.
1403            // Take the `max` of the two timestamps.
1404            (Self::None(t1), Self::None(t2)) => Self::None(t1.max(t2)),
1405            (Self::None(t1), Self::All(t2)) => Self::All(t1.max(t2)),
1406            (Self::None(t1), Self::Packages(packages, paths, t2)) => {
1407                Self::Packages(packages, paths, t1.max(t2))
1408            }
1409
1410            // If the policy is `All`, refresh all packages.
1411            (Self::All(t1), Self::None(t2) | Self::All(t2) | Self::Packages(.., t2)) => {
1412                Self::All(t1.max(t2))
1413            }
1414
1415            // If the policy is `Packages`, take the "max" of the two policies.
1416            (Self::Packages(packages, paths, t1), Self::None(t2)) => {
1417                Self::Packages(packages, paths, t1.max(t2))
1418            }
1419            (Self::Packages(.., t1), Self::All(t2)) => Self::All(t1.max(t2)),
1420            (Self::Packages(packages1, paths1, t1), Self::Packages(packages2, paths2, t2)) => {
1421                Self::Packages(
1422                    packages1.into_iter().chain(packages2).collect(),
1423                    paths1.into_iter().chain(paths2).collect(),
1424                    t1.max(t2),
1425                )
1426            }
1427        }
1428    }
1429}
1430
1431#[cfg(test)]
1432mod tests {
1433    use std::str::FromStr;
1434
1435    use crate::ArchiveId;
1436
1437    use super::Link;
1438
1439    #[test]
1440    fn test_link_round_trip() {
1441        let id = ArchiveId::new();
1442        let link = Link::new(id);
1443        let s = link.to_string();
1444        let parsed = Link::from_str(&s).unwrap();
1445        assert_eq!(link.id, parsed.id);
1446        assert_eq!(link.version, parsed.version);
1447    }
1448
1449    #[test]
1450    fn test_link_deserialize() {
1451        assert!(Link::from_str("archive-v0/foo").is_ok());
1452        assert!(Link::from_str("archive/foo").is_err());
1453        assert!(Link::from_str("v1/foo").is_err());
1454        assert!(Link::from_str("archive-v0/").is_err());
1455    }
1456
1457    #[test]
1458    #[cfg(unix)]
1459    fn prune_does_not_follow_environment_symlinks() {
1460        use super::{Cache, CacheBucket};
1461
1462        let cache_root = tempfile::tempdir().unwrap();
1463        let victim_root = tempfile::tempdir().unwrap();
1464        let environments = cache_root.path().join(CacheBucket::Environments.to_str());
1465        let victim_dir = victim_root.path().join("victim-dir");
1466
1467        fs_err::create_dir_all(&environments).unwrap();
1468        fs_err::create_dir_all(&victim_dir).unwrap();
1469        fs_err::write(victim_dir.join("payload.txt"), "payload").unwrap();
1470        fs_err::os::unix::fs::symlink(&victim_dir, environments.join("escape")).unwrap();
1471
1472        let summary = Cache::from_path(cache_root.path()).prune(false).unwrap();
1473
1474        assert_eq!(summary.num_files, 1);
1475        assert_eq!(summary.num_dirs, 0);
1476        assert!(victim_dir.is_dir());
1477        assert!(victim_dir.join("payload.txt").is_file());
1478        assert!(fs_err::symlink_metadata(environments.join("escape")).is_err());
1479    }
1480
1481    #[test]
1482    #[cfg(unix)]
1483    fn prune_ci_does_not_follow_wheel_symlinks() {
1484        use super::{Cache, CacheBucket};
1485
1486        let cache_root = tempfile::tempdir().unwrap();
1487        let victim_root = tempfile::tempdir().unwrap();
1488        let wheels = cache_root.path().join(CacheBucket::Wheels.to_str());
1489        let source_distributions = cache_root
1490            .path()
1491            .join(CacheBucket::SourceDistributions.to_str());
1492        let victim_dir = victim_root.path().join("victim-dir");
1493        let symlink = wheels.join("escape");
1494
1495        fs_err::create_dir_all(&wheels).unwrap();
1496        fs_err::create_dir_all(&source_distributions).unwrap();
1497        fs_err::create_dir_all(&victim_dir).unwrap();
1498        fs_err::write(victim_dir.join("payload.txt"), "payload").unwrap();
1499        fs_err::os::unix::fs::symlink(&victim_dir, &symlink).unwrap();
1500
1501        let summary = Cache::from_path(cache_root.path()).prune(true).unwrap();
1502
1503        assert_eq!(summary.num_files, 1);
1504        assert_eq!(summary.num_dirs, 0);
1505        assert!(victim_dir.is_dir());
1506        assert!(victim_dir.join("payload.txt").is_file());
1507        assert!(fs_err::symlink_metadata(symlink).is_err());
1508    }
1509
1510    #[test]
1511    #[cfg(unix)]
1512    fn prune_does_not_follow_archive_symlinks() {
1513        use super::{Cache, CacheBucket};
1514
1515        let cache_root = tempfile::tempdir().unwrap();
1516        let victim_root = tempfile::tempdir().unwrap();
1517        let archives = cache_root.path().join(CacheBucket::Archive.to_str());
1518        let victim_dir = victim_root.path().join("victim-dir");
1519        let symlink = archives.join("escape");
1520
1521        fs_err::create_dir_all(&archives).unwrap();
1522        fs_err::create_dir_all(&victim_dir).unwrap();
1523        fs_err::write(victim_dir.join("payload.txt"), "payload").unwrap();
1524        fs_err::os::unix::fs::symlink(&victim_dir, &symlink).unwrap();
1525
1526        let summary = Cache::from_path(cache_root.path()).prune(false).unwrap();
1527
1528        assert_eq!(summary.num_files, 1);
1529        assert_eq!(summary.num_dirs, 0);
1530        assert!(victim_dir.is_dir());
1531        assert!(victim_dir.join("payload.txt").is_file());
1532        assert!(fs_err::symlink_metadata(symlink).is_err());
1533    }
1534}