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 // Visit nested build settings shards separately so their metadata survives.
809 if entry.file_name() != "src"
810 && entry.file_type()?.is_dir()
811 && path.join("metadata.msgpack").exists()
812 {
813 continue;
814 }
815
816 // Retain any built wheel archives.
817 if path
818 .extension()
819 .is_some_and(|ext| ext.eq_ignore_ascii_case("whl"))
820 {
821 continue;
822 }
823
824 debug!("Removing unzipped built wheel entry: {}", path.display());
825 summary += self.remove_path(path)?;
826 }
827 }
828 }
829 }
830
831 // Fifth, remove any unused archives (by searching for archives that are not symlinked).
832 let references = self.find_archive_references()?;
833
834 match fs_err::read_dir(self.bucket(CacheBucket::Archive)) {
835 Ok(entries) => {
836 for entry in entries {
837 let entry = entry?;
838 let path = entry.path();
839 let target = fs_err::canonicalize(&path)?;
840 if !references.contains_key(&target) {
841 debug!("Removing dangling cache archive: {}", path.display());
842 summary += self.remove_path(path)?;
843 }
844 }
845 }
846 Err(err) if err.kind() == io::ErrorKind::NotFound => (),
847 Err(err) => return Err(err),
848 }
849
850 summary += self.prune_archive_files()?;
851
852 Ok(summary)
853 }
854
855 /// Remove a cache path using the cache's configured storage accounting.
856 pub fn remove_path(&self, path: impl AsRef<Path>) -> io::Result<Removal> {
857 Remover::default()
858 .with_removal_accounting(self.removal_accounting)
859 .rm_rf(path, false)
860 }
861
862 /// Find all references to entries in the archive bucket.
863 ///
864 /// Archive entries are often referenced by symlinks in other cache buckets. This method
865 /// searches for all such references.
866 ///
867 /// Returns a map from archive path to paths that reference it.
868 fn find_archive_references(&self) -> Result<FxHashMap<PathBuf, Vec<PathBuf>>, io::Error> {
869 let mut references = FxHashMap::<PathBuf, Vec<PathBuf>>::default();
870 for bucket in [CacheBucket::SourceDistributions, CacheBucket::Wheels] {
871 let bucket_path = self.bucket(bucket);
872 if bucket_path.is_dir() {
873 let walker = walkdir::WalkDir::new(&bucket_path).into_iter();
874 for entry in walker.filter_entry(|entry| {
875 !(
876 // As an optimization, ignore any `.lock`, `.whl`, `.msgpack`, `.rev`, or
877 // `.http` files, along with the `src` directory, which represents the
878 // unpacked source distribution.
879 entry.file_name() == "src"
880 || entry.file_name() == ".lock"
881 || entry.file_name() == ".gitignore"
882 || entry.path().extension().is_some_and(|ext| {
883 ext.eq_ignore_ascii_case("lock")
884 || ext.eq_ignore_ascii_case("whl")
885 || ext.eq_ignore_ascii_case("http")
886 || ext.eq_ignore_ascii_case("rev")
887 || ext.eq_ignore_ascii_case("msgpack")
888 })
889 )
890 }) {
891 let entry = entry?;
892
893 // On Unix, archive references use symlinks.
894 if cfg!(unix) {
895 if !entry.file_type().is_symlink() {
896 continue;
897 }
898 }
899
900 // On Windows, archive references are files containing structured data.
901 if cfg!(windows) {
902 if !entry.file_type().is_file() {
903 continue;
904 }
905 }
906
907 if let Ok(target) = self.resolve_link(entry.path()) {
908 references
909 .entry(target)
910 .or_default()
911 .push(entry.path().to_path_buf());
912 }
913 }
914 }
915 }
916 Ok(references)
917 }
918
919 /// Create a link to a directory in the archive bucket.
920 ///
921 /// On Windows, we write structured data ([`Link`]) to a file containing the archive ID and
922 /// version. On Unix, we create a symlink to the target directory.
923 #[cfg(windows)]
924 #[expect(clippy::unused_self)]
925 fn create_link(&self, id: &ArchiveId, dst: impl AsRef<Path>) -> io::Result<()> {
926 // Serialize the link.
927 let link = Link::new(id.clone());
928 let contents = link.to_string();
929
930 // First, attempt to create a file at the location, but fail if it already exists.
931 match fs_err::OpenOptions::new()
932 .write(true)
933 .create_new(true)
934 .open(dst.as_ref())
935 {
936 Ok(mut file) => {
937 // Write the target path to the file.
938 file.write_all(contents.as_bytes())?;
939 Ok(())
940 }
941 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {
942 uv_fs::write_atomic_sync(dst, contents.as_bytes())
943 }
944 Err(err) => Err(err),
945 }
946 }
947
948 /// Resolve an archive link, returning the fully-resolved path.
949 ///
950 /// Returns an error if the link target does not exist.
951 #[cfg(windows)]
952 pub fn resolve_link(&self, path: impl AsRef<Path>) -> io::Result<PathBuf> {
953 // Deserialize the link.
954 let contents = fs_err::read_to_string(path.as_ref())?;
955 let link = Link::from_str(&contents)?;
956
957 // Ignore stale links.
958 if link.version != ARCHIVE_VERSION {
959 return Err(io::Error::new(
960 io::ErrorKind::NotFound,
961 "The link target does not exist.",
962 ));
963 }
964
965 // Reconstruct the path.
966 let path = self.archive(&link.id);
967 path.canonicalize()
968 }
969
970 /// Create a link to a directory in the archive bucket.
971 ///
972 /// On Windows, we write structured data ([`Link`]) to a file containing the archive ID and
973 /// version. On Unix, we create a symlink to the target directory.
974 #[cfg(unix)]
975 fn create_link(&self, id: &ArchiveId, dst: impl AsRef<Path>) -> io::Result<()> {
976 let dst = dst.as_ref();
977 let dst_parent = dst.parent().expect("Cache entry to have parent");
978 // Construct the relative link target.
979 let src = uv_fs::relative_to(self.archive(id), dst_parent)?;
980
981 uv_fs::replace_symlink(&src, dst)
982 }
983
984 /// Resolve an archive link, returning the fully-resolved path.
985 ///
986 /// Returns an error if the link target does not exist.
987 #[cfg(unix)]
988 pub fn resolve_link(&self, path: impl AsRef<Path>) -> io::Result<PathBuf> {
989 path.as_ref().canonicalize()
990 }
991}
992
993/// An archive (unzipped wheel) that exists in the local cache.
994#[derive(Debug, Clone)]
995#[allow(unused)]
996struct Link {
997 /// The unique ID of the entry in the archive bucket.
998 id: ArchiveId,
999 /// The version of the archive bucket.
1000 version: u8,
1001}
1002
1003#[allow(unused)]
1004impl Link {
1005 /// Create a new [`Archive`] with the given ID and hashes.
1006 fn new(id: ArchiveId) -> Self {
1007 Self {
1008 id,
1009 version: ARCHIVE_VERSION,
1010 }
1011 }
1012}
1013
1014impl Display for Link {
1015 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1016 write!(f, "archive-v{}/{}", self.version, self.id)
1017 }
1018}
1019
1020impl FromStr for Link {
1021 type Err = io::Error;
1022
1023 fn from_str(s: &str) -> Result<Self, Self::Err> {
1024 let mut parts = s.splitn(2, '/');
1025 let version = parts
1026 .next()
1027 .filter(|s| !s.is_empty())
1028 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing version"))?;
1029 let id = parts
1030 .next()
1031 .filter(|s| !s.is_empty())
1032 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing ID"))?;
1033
1034 // Parse the archive version from `archive-v{version}/{id}`.
1035 let version = version
1036 .strip_prefix("archive-v")
1037 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing version prefix"))?;
1038 let version = u8::from_str(version).map_err(|err| {
1039 io::Error::new(
1040 io::ErrorKind::InvalidData,
1041 format!("failed to parse version: {err}"),
1042 )
1043 })?;
1044
1045 // Parse the ID from `archive-v{version}/{id}`.
1046 let id = ArchiveId::from_str(id).map_err(|err| {
1047 io::Error::new(
1048 io::ErrorKind::InvalidData,
1049 format!("failed to parse ID: {err}"),
1050 )
1051 })?;
1052
1053 Ok(Self { id, version })
1054 }
1055}
1056
1057pub trait CleanReporter: Send + Sync {
1058 /// Called after one file or directory is removed.
1059 fn on_clean(&self);
1060
1061 /// Called after all files and directories are removed.
1062 fn on_complete(&self);
1063}
1064
1065/// The different kinds of data in the cache are stored in different bucket, which in our case
1066/// are subdirectories of the cache root.
1067#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
1068pub enum CacheBucket {
1069 /// Wheels (excluding built wheels), alongside their metadata and cache policy.
1070 ///
1071 /// There are three kinds from cache entries: Wheel metadata and policy as `MsgPack` files, the
1072 /// wheels themselves, and the unzipped wheel archives. If a wheel file is over an in-memory
1073 /// size threshold, we first download the zip file into the cache, then unzip it into a
1074 /// directory with the same name (exclusive of the `.whl` extension).
1075 ///
1076 /// Cache structure:
1077 /// * `wheel-metadata-v0/pypi/foo/{foo-1.0.0-py3-none-any.msgpack, foo-1.0.0-py3-none-any.whl}`
1078 /// * `wheel-metadata-v0/<digest(index-url)>/foo/{foo-1.0.0-py3-none-any.msgpack, foo-1.0.0-py3-none-any.whl}`
1079 /// * `wheel-metadata-v0/url/<digest(url)>/foo/{foo-1.0.0-py3-none-any.msgpack, foo-1.0.0-py3-none-any.whl}`
1080 ///
1081 /// See `uv_client::RegistryClient::wheel_metadata` for information on how wheel metadata
1082 /// is fetched.
1083 ///
1084 /// # Example
1085 ///
1086 /// Consider the following `requirements.in`:
1087 /// ```text
1088 /// # pypi wheel
1089 /// pandas
1090 /// # url wheel
1091 /// flask @ https://files.pythonhosted.org/packages/36/42/015c23096649b908c809c69388a805a571a3bea44362fe87e33fc3afa01f/flask-3.0.0-py3-none-any.whl
1092 /// ```
1093 ///
1094 /// When we run `pip compile`, it will only fetch and cache the metadata (and cache policy), it
1095 /// doesn't need the actual wheels yet:
1096 /// ```text
1097 /// wheel-v0
1098 /// ├── pypi
1099 /// │ ...
1100 /// │ ├── pandas
1101 /// │ │ └── pandas-2.1.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.msgpack
1102 /// │ ...
1103 /// └── url
1104 /// └── 4b8be67c801a7ecb
1105 /// └── flask
1106 /// └── flask-3.0.0-py3-none-any.msgpack
1107 /// ```
1108 ///
1109 /// We get the following `requirement.txt` from `pip compile`:
1110 ///
1111 /// ```text
1112 /// [...]
1113 /// flask @ https://files.pythonhosted.org/packages/36/42/015c23096649b908c809c69388a805a571a3bea44362fe87e33fc3afa01f/flask-3.0.0-py3-none-any.whl
1114 /// [...]
1115 /// pandas==2.1.3
1116 /// [...]
1117 /// ```
1118 ///
1119 /// If we run `pip sync` on `requirements.txt` on a different machine, it also fetches the
1120 /// wheels:
1121 ///
1122 /// TODO(konstin): This is still wrong, we need to store the cache policy too!
1123 /// ```text
1124 /// wheel-v0
1125 /// ├── pypi
1126 /// │ ...
1127 /// │ ├── pandas
1128 /// │ │ ├── pandas-2.1.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
1129 /// │ │ ├── pandas-2.1.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64
1130 /// │ ...
1131 /// └── url
1132 /// └── 4b8be67c801a7ecb
1133 /// └── flask
1134 /// └── flask-3.0.0-py3-none-any.whl
1135 /// ├── flask
1136 /// │ └── ...
1137 /// └── flask-3.0.0.dist-info
1138 /// └── ...
1139 /// ```
1140 ///
1141 /// If we run first `pip compile` and then `pip sync` on the same machine, we get both:
1142 ///
1143 /// ```text
1144 /// wheels-v0
1145 /// ├── pypi
1146 /// │ ├── ...
1147 /// │ ├── pandas
1148 /// │ │ ├── pandas-2.1.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.msgpack
1149 /// │ │ ├── pandas-2.1.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
1150 /// │ │ └── pandas-2.1.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64
1151 /// │ │ ├── pandas
1152 /// │ │ │ ├── ...
1153 /// │ │ ├── pandas-2.1.3.dist-info
1154 /// │ │ │ ├── ...
1155 /// │ │ └── pandas.libs
1156 /// │ ├── ...
1157 /// └── url
1158 /// └── 4b8be67c801a7ecb
1159 /// └── flask
1160 /// ├── flask-3.0.0-py3-none-any.msgpack
1161 /// ├── flask-3.0.0-py3-none-any.msgpack
1162 /// └── flask-3.0.0-py3-none-any
1163 /// ├── flask
1164 /// │ └── ...
1165 /// └── flask-3.0.0.dist-info
1166 /// └── ...
1167 Wheels,
1168 /// Source distributions, wheels built from source distributions, their extracted metadata, and the
1169 /// cache policy of the source distribution.
1170 ///
1171 /// The structure is similar of that of the `Wheel` bucket, except we have an additional layer
1172 /// for the source distribution filename and the metadata is at the source distribution-level,
1173 /// not at the wheel level.
1174 ///
1175 /// TODO(konstin): The cache policy should be on the source distribution level, the metadata we
1176 /// can put next to the wheels as in the `Wheels` bucket.
1177 ///
1178 /// The unzipped source distribution is stored in a directory matching the source distribution
1179 /// archive name.
1180 ///
1181 /// Source distributions are built into zipped wheel files (as PEP 517 specifies) and unzipped
1182 /// lazily before installing. So when resolving, we only build the wheel and store the archive
1183 /// file in the cache, when installing, we unpack it under the same name (exclusive of the
1184 /// `.whl` extension). You may find a mix of wheel archive zip files and unzipped wheel
1185 /// directories in the cache.
1186 ///
1187 /// Cache structure:
1188 /// * `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}`
1189 /// * `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}`
1190 /// * `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}`
1191 /// * `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}`
1192 ///
1193 /// But the url filename does not need to be a valid source dist filename
1194 /// (<https://github.com/search?q=path%3A**%2Frequirements.txt+master.zip&type=code>),
1195 /// so it could also be the following and we have to take any string as filename:
1196 /// * `built-wheels-v0/url/<sha256(url)>/master.zip/metadata.msgpack`
1197 ///
1198 /// # Example
1199 ///
1200 /// The following requirements:
1201 /// ```text
1202 /// # git source dist
1203 /// pydantic-extra-types @ git+https://github.com/pydantic/pydantic-extra-types.git
1204 /// # pypi source dist
1205 /// django_allauth==0.51.0
1206 /// # url source dist
1207 /// werkzeug @ https://files.pythonhosted.org/packages/0d/cc/ff1904eb5eb4b455e442834dabf9427331ac0fa02853bf83db817a7dd53d/werkzeug-3.0.1.tar.gz
1208 /// ```
1209 ///
1210 /// ...may be cached as:
1211 /// ```text
1212 /// built-wheels-v4/
1213 /// ├── git
1214 /// │ └── 2122faf3e081fb7a
1215 /// │ └── 7a2d650a4a7b4d04
1216 /// │ ├── metadata.msgpack
1217 /// │ └── pydantic_extra_types-2.9.0-py3-none-any.whl
1218 /// ├── pypi
1219 /// │ └── django-allauth
1220 /// │ └── 0.51.0
1221 /// │ ├── 0gH-_fwv8tdJ7JwwjJsUc
1222 /// │ │ ├── django-allauth-0.51.0.tar.gz
1223 /// │ │ │ └── [UNZIPPED CONTENTS]
1224 /// │ │ ├── django_allauth-0.51.0-py3-none-any.whl
1225 /// │ │ └── metadata.msgpack
1226 /// │ └── revision.http
1227 /// └── url
1228 /// └── 6781bd6440ae72c2
1229 /// ├── APYY01rbIfpAo_ij9sCY6
1230 /// │ ├── metadata.msgpack
1231 /// │ ├── werkzeug-3.0.1-py3-none-any.whl
1232 /// │ └── werkzeug-3.0.1.tar.gz
1233 /// │ └── [UNZIPPED CONTENTS]
1234 /// └── revision.http
1235 /// ```
1236 ///
1237 /// Structurally, the `manifest.msgpack` is empty, and only contains the caching information
1238 /// needed to invalidate the cache. The `metadata.msgpack` contains the metadata of the source
1239 /// distribution.
1240 SourceDistributions,
1241 /// Flat index responses, a format very similar to the simple metadata API.
1242 ///
1243 /// Cache structure:
1244 /// * `flat-index-v0/index/<digest(flat_index_url)>.msgpack`
1245 ///
1246 /// The response is stored as `Vec<File>`.
1247 FlatIndex,
1248 /// Git repositories.
1249 Git,
1250 /// Information about an interpreter at a path.
1251 ///
1252 /// To avoid caching pyenv shims, bash scripts which may redirect to a new python version
1253 /// without the shim itself changing, we only cache when the path equals `sys.executable`, i.e.
1254 /// the path we're running is the python executable itself and not a shim.
1255 ///
1256 /// Cache structure: `interpreter-v0/<digest(path)>.msgpack`
1257 ///
1258 /// # Example
1259 ///
1260 /// The contents of each of the `MsgPack` files has a timestamp field in unix time, the [PEP 508]
1261 /// markers and some information from the `sys`/`sysconfig` modules.
1262 ///
1263 /// ```json
1264 /// {
1265 /// "timestamp": 1698047994491,
1266 /// "data": {
1267 /// "markers": {
1268 /// "implementation_name": "cpython",
1269 /// "implementation_version": "3.12.0",
1270 /// "os_name": "posix",
1271 /// "platform_machine": "x86_64",
1272 /// "platform_python_implementation": "CPython",
1273 /// "platform_release": "6.5.0-13-generic",
1274 /// "platform_system": "Linux",
1275 /// "platform_version": "#13-Ubuntu SMP PREEMPT_DYNAMIC Fri Nov 3 12:16:05 UTC 2023",
1276 /// "python_full_version": "3.12.0",
1277 /// "python_version": "3.12",
1278 /// "sys_platform": "linux"
1279 /// },
1280 /// "base_exec_prefix": "/home/ferris/.pyenv/versions/3.12.0",
1281 /// "base_prefix": "/home/ferris/.pyenv/versions/3.12.0",
1282 /// "sys_executable": "/home/ferris/projects/uv/.venv/bin/python"
1283 /// }
1284 /// }
1285 /// ```
1286 ///
1287 /// [PEP 508]: https://peps.python.org/pep-0508/#environment-markers
1288 Interpreter,
1289 /// Index responses through the simple metadata API.
1290 ///
1291 /// Cache structure:
1292 /// * `simple-v0/pypi/<package_name>.rkyv`
1293 /// * `simple-v0/<digest(index_url)>/<package_name>.rkyv`
1294 ///
1295 /// The response is parsed into `uv_client::SimpleDetailMetadata` before storage.
1296 Simple,
1297 /// A cache of unzipped wheels, stored as directories. This is used internally within the cache.
1298 /// When other buckets need to store directories, they should persist them to
1299 /// [`CacheBucket::Archive`], and then symlink them into the appropriate bucket. This ensures
1300 /// that cache entries can be atomically replaced and removed, as storing directories in the
1301 /// other buckets directly would make atomic operations impossible.
1302 Archive,
1303 /// Content-addressed files that are hardlinked into cached archives.
1304 Files,
1305 /// Ephemeral virtual environments used to execute PEP 517 builds and other operations.
1306 Builds,
1307 /// Reusable virtual environments for Python tools and projects.
1308 Environments,
1309 /// Cached Python downloads
1310 Python,
1311 /// Downloaded tool binaries (e.g., Ruff).
1312 Binaries,
1313 /// Cached vulnerability data from [OSV](https://osv.dev/).
1314 ///
1315 /// Cache structure:
1316 /// * `osv-v1/vulnerability/<vuln_id>.msgpack` — cached full vulnerability records
1317 Osv,
1318}
1319
1320impl CacheBucket {
1321 fn to_str(self) -> &'static str {
1322 match self {
1323 // Note that when bumping this, you'll also need to bump it
1324 // in `crates/uv/tests/build/cache_prune.rs`.
1325 Self::SourceDistributions => "sdists-v10",
1326 // Note that when bumping this, you'll also need to bump it
1327 // in `crates/uv/tests/lock/lock.rs`.
1328 Self::FlatIndex => "flat-index-v6",
1329 Self::Git => "git-v1",
1330 Self::Interpreter => "interpreter-v4",
1331 // Note that when bumping this, you'll also need to bump it
1332 // in `crates/uv/tests/build/cache_clean.rs`.
1333 Self::Simple => "simple-v26",
1334 // Note that when bumping this, you'll also need to bump it
1335 // in `crates/uv/tests/build/cache_prune.rs`.
1336 Self::Wheels => "wheels-v7",
1337 // Note that when bumping this, you'll also need to bump
1338 // `ARCHIVE_VERSION` in `crates/uv-cache/src/lib.rs`.
1339 Self::Archive => "archive-v0",
1340 Self::Files => "files-v0",
1341 Self::Builds => "builds-v0",
1342 Self::Environments => "environments-v2",
1343 Self::Python => "python-v1",
1344 Self::Binaries => "binaries-v0",
1345 Self::Osv => "osv-v1",
1346 }
1347 }
1348
1349 /// Remove a package from the cache bucket.
1350 ///
1351 /// Returns the number of entries removed from the cache.
1352 fn remove(self, cache: &Cache, name: &PackageName) -> Result<Removal, io::Error> {
1353 /// Returns `true` if the [`Path`] represents a built wheel for the given package.
1354 fn is_match(path: &Path, name: &PackageName) -> bool {
1355 // The metadata can be in the revision itself or one shard down, if build settings
1356 // were used.
1357 let walker = walkdir::WalkDir::new(path)
1358 .min_depth(1)
1359 .max_depth(2)
1360 .into_iter();
1361 // Unpacked source contents aren't uv cache entries.
1362 for entry in walker.filter_entry(|entry| entry.file_name() != "src") {
1363 let Ok(entry) = entry else {
1364 continue;
1365 };
1366 if entry.file_name() != "metadata.msgpack" {
1367 continue;
1368 }
1369 let Ok(metadata) = fs_err::read(entry.path()) else {
1370 continue;
1371 };
1372 let Ok(metadata) = rmp_serde::from_slice::<ResolutionMetadata>(&metadata) else {
1373 continue;
1374 };
1375 if metadata.name == *name {
1376 return true;
1377 }
1378 }
1379 false
1380 }
1381
1382 let mut summary = cache.removal();
1383 match self {
1384 Self::Wheels => {
1385 // For `pypi` wheels, we expect a directory per package (indexed by name).
1386 let root = cache.bucket(self).join(WheelCacheKind::Pypi);
1387 summary += cache.remove_path(root.join(name.to_string()))?;
1388
1389 // For alternate indices, we expect a directory for every index (under an `index`
1390 // subdirectory), followed by a directory per package (indexed by name).
1391 let root = cache.bucket(self).join(WheelCacheKind::Index);
1392 for directory in directories(root)? {
1393 summary += cache.remove_path(directory.join(name.to_string()))?;
1394 }
1395
1396 // For direct URLs, we expect a directory for every URL, followed by a
1397 // directory per package (indexed by name).
1398 let root = cache.bucket(self).join(WheelCacheKind::Url);
1399 for directory in directories(root)? {
1400 summary += cache.remove_path(directory.join(name.to_string()))?;
1401 }
1402 }
1403 Self::SourceDistributions => {
1404 // For `pypi` wheels, we expect a directory per package (indexed by name).
1405 let root = cache.bucket(self).join(WheelCacheKind::Pypi);
1406 summary += cache.remove_path(root.join(name.to_string()))?;
1407
1408 // For alternate indices, we expect a directory for every index (under an `index`
1409 // subdirectory), followed by a directory per package (indexed by name).
1410 let root = cache.bucket(self).join(WheelCacheKind::Index);
1411 for directory in directories(root)? {
1412 summary += cache.remove_path(directory.join(name.to_string()))?;
1413 }
1414
1415 // For direct URLs, we expect a directory for every URL, followed by a
1416 // directory per version. To determine whether the URL is relevant, we need to
1417 // search for a wheel matching the package name.
1418 let root = cache.bucket(self).join(WheelCacheKind::Url);
1419 for url in directories(root)? {
1420 if directories(&url)?.any(|version| is_match(&version, name)) {
1421 summary += cache.remove_path(url)?;
1422 }
1423 }
1424
1425 // For local dependencies, we expect a directory for every path, followed by a
1426 // directory per version. To determine whether the path is relevant, we need to
1427 // search for a wheel matching the package name.
1428 let root = cache.bucket(self).join(WheelCacheKind::Path);
1429 for path in directories(root)? {
1430 if directories(&path)?.any(|version| is_match(&version, name)) {
1431 summary += cache.remove_path(path)?;
1432 }
1433 }
1434
1435 // For Git dependencies, we expect a directory for every repository, followed by a
1436 // directory for every SHA. To determine whether the SHA is relevant, we need to
1437 // search for a wheel matching the package name.
1438 let root = cache.bucket(self).join(WheelCacheKind::Git);
1439 for repository in directories(root)? {
1440 for sha in directories(repository)? {
1441 if is_match(&sha, name) {
1442 summary += cache.remove_path(sha)?;
1443 }
1444 }
1445 }
1446 }
1447 Self::Simple => {
1448 // For `pypi` wheels, we expect a rkyv file per package, indexed by name.
1449 let root = cache.bucket(self).join(WheelCacheKind::Pypi);
1450 summary += cache.remove_path(root.join(format!("{name}.rkyv")))?;
1451
1452 // For alternate indices, we expect a directory for every index (under an `index`
1453 // subdirectory), followed by a directory per package (indexed by name).
1454 let root = cache.bucket(self).join(WheelCacheKind::Index);
1455 for directory in directories(root)? {
1456 summary += cache.remove_path(directory.join(format!("{name}.rkyv")))?;
1457 }
1458 }
1459 Self::FlatIndex => {
1460 // We can't know if the flat index includes a package, so we just remove the entire
1461 // cache entry.
1462 let root = cache.bucket(self);
1463 summary += cache.remove_path(root)?;
1464 }
1465 Self::Git
1466 | Self::Interpreter
1467 | Self::Archive
1468 | Self::Files
1469 | Self::Builds
1470 | Self::Environments
1471 | Self::Python
1472 | Self::Binaries
1473 | Self::Osv => {
1474 // Nothing to do.
1475 }
1476 }
1477 Ok(summary)
1478 }
1479
1480 /// Return an iterator over all cache buckets.
1481 fn iter() -> impl Iterator<Item = Self> {
1482 [
1483 Self::Wheels,
1484 Self::SourceDistributions,
1485 Self::FlatIndex,
1486 Self::Git,
1487 Self::Interpreter,
1488 Self::Simple,
1489 Self::Archive,
1490 Self::Files,
1491 Self::Builds,
1492 Self::Environments,
1493 Self::Python,
1494 Self::Binaries,
1495 Self::Osv,
1496 ]
1497 .iter()
1498 .copied()
1499 }
1500}
1501
1502impl Display for CacheBucket {
1503 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1504 f.write_str(self.to_str())
1505 }
1506}
1507
1508#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1509pub enum Freshness {
1510 /// The cache entry is fresh according to the [`Refresh`] policy.
1511 Fresh,
1512 /// The cache entry is stale according to the [`Refresh`] policy.
1513 Stale,
1514 /// The cache entry does not exist.
1515 Missing,
1516}
1517
1518impl Freshness {
1519 pub const fn is_fresh(self) -> bool {
1520 matches!(self, Self::Fresh)
1521 }
1522}
1523
1524/// A refresh policy for cache entries.
1525#[derive(Debug, Clone)]
1526pub enum Refresh {
1527 /// Don't refresh any entries.
1528 None(Timestamp),
1529 /// Refresh entries linked to the given packages, if created before the given timestamp.
1530 Packages(Vec<PackageName>, Vec<Box<Path>>, Timestamp),
1531 /// Refresh all entries created before the given timestamp.
1532 All(Timestamp),
1533}
1534
1535impl Refresh {
1536 /// Determine the refresh strategy to use based on the command-line arguments.
1537 pub fn from_args(refresh: Option<bool>, refresh_package: Vec<PackageName>) -> Self {
1538 let timestamp = Timestamp::now();
1539 match refresh {
1540 Some(true) => Self::All(timestamp),
1541 Some(false) => Self::None(timestamp),
1542 None => {
1543 if refresh_package.is_empty() {
1544 Self::None(timestamp)
1545 } else {
1546 Self::Packages(refresh_package, vec![], timestamp)
1547 }
1548 }
1549 }
1550 }
1551
1552 /// Combine two [`Refresh`] policies, taking the "max" of the two policies.
1553 #[must_use]
1554 pub fn combine(self, other: Self) -> Self {
1555 match (self, other) {
1556 // If the policy is `None`, return the existing refresh policy.
1557 // Take the `max` of the two timestamps.
1558 (Self::None(t1), Self::None(t2)) => Self::None(t1.max(t2)),
1559 (Self::None(t1), Self::All(t2)) => Self::All(t1.max(t2)),
1560 (Self::None(t1), Self::Packages(packages, paths, t2)) => {
1561 Self::Packages(packages, paths, t1.max(t2))
1562 }
1563
1564 // If the policy is `All`, refresh all packages.
1565 (Self::All(t1), Self::None(t2) | Self::All(t2) | Self::Packages(.., t2)) => {
1566 Self::All(t1.max(t2))
1567 }
1568
1569 // If the policy is `Packages`, take the "max" of the two policies.
1570 (Self::Packages(packages, paths, t1), Self::None(t2)) => {
1571 Self::Packages(packages, paths, t1.max(t2))
1572 }
1573 (Self::Packages(.., t1), Self::All(t2)) => Self::All(t1.max(t2)),
1574 (Self::Packages(packages1, paths1, t1), Self::Packages(packages2, paths2, t2)) => {
1575 Self::Packages(
1576 packages1.into_iter().chain(packages2).collect(),
1577 paths1.into_iter().chain(paths2).collect(),
1578 t1.max(t2),
1579 )
1580 }
1581 }
1582 }
1583}
1584
1585#[cfg(test)]
1586mod tests {
1587 use std::str::FromStr;
1588
1589 use crate::ArchiveId;
1590
1591 use super::{Cache, Link};
1592
1593 #[test]
1594 fn test_link_round_trip() {
1595 let id = ArchiveId::new();
1596 let link = Link::new(id);
1597 let s = link.to_string();
1598 let parsed = Link::from_str(&s).unwrap();
1599 assert_eq!(link.id, parsed.id);
1600 assert_eq!(link.version, parsed.version);
1601 }
1602
1603 #[test]
1604 fn test_replace_archive_link() {
1605 let cache = Cache::temp().unwrap();
1606 let link = cache.root().join("link");
1607 for id in [ArchiveId::new(), ArchiveId::new()] {
1608 let archive = cache.archive(&id);
1609 fs_err::create_dir_all(&archive).unwrap();
1610 cache.create_link(&id, &link).unwrap();
1611 assert_eq!(
1612 cache.resolve_link(&link).unwrap(),
1613 archive.canonicalize().unwrap()
1614 );
1615 }
1616 }
1617
1618 #[test]
1619 fn test_link_deserialize() {
1620 assert!(Link::from_str("archive-v0/foo").is_ok());
1621 assert!(Link::from_str("archive/foo").is_err());
1622 assert!(Link::from_str("v1/foo").is_err());
1623 assert!(Link::from_str("archive-v0/").is_err());
1624 }
1625
1626 #[test]
1627 #[cfg(unix)]
1628 fn prune_does_not_follow_environment_symlinks() {
1629 use super::{Cache, CacheBucket};
1630
1631 let cache_root = tempfile::tempdir().unwrap();
1632 let victim_root = tempfile::tempdir().unwrap();
1633 let environments = cache_root.path().join(CacheBucket::Environments.to_str());
1634 let victim_dir = victim_root.path().join("victim-dir");
1635
1636 fs_err::create_dir_all(&environments).unwrap();
1637 fs_err::create_dir_all(&victim_dir).unwrap();
1638 fs_err::write(victim_dir.join("payload.txt"), "payload").unwrap();
1639 fs_err::os::unix::fs::symlink(&victim_dir, environments.join("escape")).unwrap();
1640
1641 let summary = Cache::from_path(cache_root.path()).prune(false).unwrap();
1642
1643 assert_eq!(summary.num_files, 1);
1644 assert_eq!(summary.num_dirs, 0);
1645 assert!(victim_dir.is_dir());
1646 assert!(victim_dir.join("payload.txt").is_file());
1647 assert!(fs_err::symlink_metadata(environments.join("escape")).is_err());
1648 }
1649
1650 #[test]
1651 #[cfg(unix)]
1652 fn prune_ci_does_not_follow_wheel_symlinks() {
1653 use super::{Cache, CacheBucket};
1654
1655 let cache_root = tempfile::tempdir().unwrap();
1656 let victim_root = tempfile::tempdir().unwrap();
1657 let wheels = cache_root.path().join(CacheBucket::Wheels.to_str());
1658 let source_distributions = cache_root
1659 .path()
1660 .join(CacheBucket::SourceDistributions.to_str());
1661 let victim_dir = victim_root.path().join("victim-dir");
1662 let symlink = wheels.join("escape");
1663
1664 fs_err::create_dir_all(&wheels).unwrap();
1665 fs_err::create_dir_all(&source_distributions).unwrap();
1666 fs_err::create_dir_all(&victim_dir).unwrap();
1667 fs_err::write(victim_dir.join("payload.txt"), "payload").unwrap();
1668 fs_err::os::unix::fs::symlink(&victim_dir, &symlink).unwrap();
1669
1670 let summary = Cache::from_path(cache_root.path()).prune(true).unwrap();
1671
1672 assert_eq!(summary.num_files, 1);
1673 assert_eq!(summary.num_dirs, 0);
1674 assert!(victim_dir.is_dir());
1675 assert!(victim_dir.join("payload.txt").is_file());
1676 assert!(fs_err::symlink_metadata(symlink).is_err());
1677 }
1678
1679 #[test]
1680 #[cfg(unix)]
1681 fn prune_does_not_follow_archive_symlinks() {
1682 use super::{Cache, CacheBucket};
1683
1684 let cache_root = tempfile::tempdir().unwrap();
1685 let victim_root = tempfile::tempdir().unwrap();
1686 let archives = cache_root.path().join(CacheBucket::Archive.to_str());
1687 let victim_dir = victim_root.path().join("victim-dir");
1688 let symlink = archives.join("escape");
1689
1690 fs_err::create_dir_all(&archives).unwrap();
1691 fs_err::create_dir_all(&victim_dir).unwrap();
1692 fs_err::write(victim_dir.join("payload.txt"), "payload").unwrap();
1693 fs_err::os::unix::fs::symlink(&victim_dir, &symlink).unwrap();
1694
1695 let summary = Cache::from_path(cache_root.path()).prune(false).unwrap();
1696
1697 assert_eq!(summary.num_files, 1);
1698 assert_eq!(summary.num_dirs, 0);
1699 assert!(victim_dir.is_dir());
1700 assert!(victim_dir.join("payload.txt").is_file());
1701 assert!(fs_err::symlink_metadata(symlink).is_err());
1702 }
1703}