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