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