1use std::borrow::Cow;
2use std::fmt::{Display, Formatter};
3use std::ops::Deref;
4use std::path::Path;
5use std::str::FromStr;
6use std::sync::{Arc, LazyLock, RwLock};
7
8use http::StatusCode;
9use itertools::Either;
10use rustc_hash::{FxHashMap, FxHashSet};
11use thiserror::Error;
12use url::{ParseError, Url};
13use uv_auth::RealmRef;
14use uv_cache_key::CanonicalUrl;
15use uv_pep508::{Scheme, VerbatimUrl, VerbatimUrlError, split_scheme};
16use uv_pypi_types::HashAlgorithm;
17use uv_redacted::DisplaySafeUrl;
18use uv_warnings::warn_user;
19
20use crate::{ExcludeNewerOverride, Index, IndexStatusCodeStrategy, Verbatim};
21
22pub static PYPI_URL: LazyLock<DisplaySafeUrl> =
23 LazyLock::new(|| DisplaySafeUrl::parse("https://pypi.org/simple").unwrap());
24
25static DEFAULT_INDEX: LazyLock<Index> = LazyLock::new(|| {
26 Index::from_index_url(IndexUrl::Pypi(Arc::new(VerbatimUrl::from_url(
27 PYPI_URL.clone(),
28 ))))
29});
30
31#[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
33pub enum IndexUrl {
34 Pypi(Arc<VerbatimUrl>),
35 Url(Arc<VerbatimUrl>),
36 Path(Arc<VerbatimUrl>),
37}
38
39impl IndexUrl {
40 pub fn parse(path: &str, root_dir: Option<&Path>) -> Result<Self, IndexUrlError> {
45 let url = VerbatimUrl::from_url_or_path(path, root_dir)?;
46 Ok(Self::from(url))
47 }
48
49 pub fn root(&self) -> Option<DisplaySafeUrl> {
54 let mut segments = self.url().path_segments()?;
55 let last = match segments.next_back()? {
56 "" => segments.next_back()?,
58 segment => segment,
59 };
60
61 if !(last.eq_ignore_ascii_case("simple") || last.eq_ignore_ascii_case("+simple")) {
63 return None;
64 }
65
66 let mut url = self.url().clone();
67 url.path_segments_mut().ok()?.pop_if_empty().pop();
68 Some(url)
69 }
70}
71
72#[cfg(feature = "schemars")]
73impl schemars::JsonSchema for IndexUrl {
74 fn schema_name() -> Cow<'static, str> {
75 Cow::Borrowed("IndexUrl")
76 }
77
78 fn json_schema(_generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema {
79 schemars::json_schema!({
80 "type": "string",
81 "description": "The URL of an index to use for fetching packages (e.g., `https://pypi.org/simple`), or a local path."
82 })
83 }
84}
85
86impl IndexUrl {
87 #[inline]
88 fn inner(&self) -> &VerbatimUrl {
89 match self {
90 Self::Pypi(url) | Self::Url(url) | Self::Path(url) => url,
91 }
92 }
93
94 pub fn url(&self) -> &DisplaySafeUrl {
96 self.inner().raw()
97 }
98
99 pub fn into_url(self) -> DisplaySafeUrl {
101 match self {
102 Self::Pypi(url) | Self::Url(url) | Self::Path(url) => {
103 Arc::unwrap_or_clone(url).into_url()
104 }
105 }
106 }
107
108 pub fn without_credentials(&self) -> Cow<'_, DisplaySafeUrl> {
110 let url = self.url();
111 if url.username().is_empty() && url.password().is_none() {
112 Cow::Borrowed(url)
113 } else {
114 let mut url = url.clone();
115 let _ = url.set_username("");
116 let _ = url.set_password(None);
117 Cow::Owned(url)
118 }
119 }
120
121 pub fn warn_on_disambiguated_relative_path(&self) {
126 let Self::Path(verbatim_url) = &self else {
127 return;
128 };
129
130 if let Some(path) = verbatim_url.given()
131 && !is_disambiguated_path(path)
132 {
133 if cfg!(windows) {
134 warn_user!(
135 "Relative paths passed to `--index` or `--default-index` should be disambiguated from index names (use `.\\{path}` or `./{path}`). Support for ambiguous values will be removed in the future"
136 );
137 } else {
138 warn_user!(
139 "Relative paths passed to `--index` or `--default-index` should be disambiguated from index names (use `./{path}`). Support for ambiguous values will be removed in the future"
140 );
141 }
142 }
143 }
144}
145
146impl Display for IndexUrl {
147 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
148 Display::fmt(self.inner(), f)
149 }
150}
151
152impl Verbatim for IndexUrl {
153 fn verbatim(&self) -> Cow<'_, str> {
154 self.inner().verbatim()
155 }
156}
157
158fn is_disambiguated_path(path: &str) -> bool {
164 if cfg!(windows) {
165 if path.starts_with(".\\") || path.starts_with("..\\") || path.starts_with('/') {
166 return true;
167 }
168 }
169 if path.starts_with("./") || path.starts_with("../") || Path::new(path).is_absolute() {
170 return true;
171 }
172 if let Some((scheme, _)) = split_scheme(path) {
174 return Scheme::parse(scheme).is_some();
175 }
176 false
178}
179
180#[derive(Error, Debug)]
182pub enum IndexUrlError {
183 #[error(transparent)]
184 Io(#[from] std::io::Error),
185 #[error(transparent)]
186 Url(#[from] ParseError),
187 #[error(transparent)]
188 VerbatimUrl(#[from] VerbatimUrlError),
189}
190
191impl FromStr for IndexUrl {
192 type Err = IndexUrlError;
193
194 fn from_str(s: &str) -> Result<Self, Self::Err> {
195 Self::parse(s, None)
196 }
197}
198
199impl serde::ser::Serialize for IndexUrl {
200 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
201 where
202 S: serde::ser::Serializer,
203 {
204 self.inner().without_credentials().serialize(serializer)
205 }
206}
207
208impl<'de> serde::de::Deserialize<'de> for IndexUrl {
209 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
210 where
211 D: serde::de::Deserializer<'de>,
212 {
213 struct Visitor;
214
215 impl serde::de::Visitor<'_> for Visitor {
216 type Value = IndexUrl;
217
218 fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
219 f.write_str("a string")
220 }
221
222 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
223 IndexUrl::from_str(v).map_err(serde::de::Error::custom)
224 }
225 }
226
227 deserializer.deserialize_str(Visitor)
228 }
229}
230
231impl From<VerbatimUrl> for IndexUrl {
232 fn from(url: VerbatimUrl) -> Self {
233 if url.scheme() == "file" {
234 Self::Path(Arc::new(url))
235 } else if *url.raw() == *PYPI_URL {
236 Self::Pypi(Arc::new(url))
237 } else {
238 Self::Url(Arc::new(url))
239 }
240 }
241}
242
243impl From<IndexUrl> for DisplaySafeUrl {
244 fn from(index: IndexUrl) -> Self {
245 index.into_url()
246 }
247}
248
249impl Deref for IndexUrl {
250 type Target = Url;
251
252 fn deref(&self) -> &Self::Target {
253 self.inner()
254 }
255}
256
257#[derive(Default, Debug, Clone, PartialEq, Eq)]
262pub struct IndexLocations {
263 indexes: Vec<Index>,
264 flat_index: Vec<Index>,
265 no_index: bool,
266}
267
268impl IndexLocations {
269 pub fn new(indexes: Vec<Index>, flat_index: Vec<Index>, no_index: bool) -> Self {
271 Self {
272 indexes,
273 flat_index,
274 no_index,
275 }
276 }
277
278 #[must_use]
285 pub fn combine(self, indexes: Vec<Index>, flat_index: Vec<Index>, no_index: bool) -> Self {
286 Self {
287 indexes: self.indexes.into_iter().chain(indexes).collect(),
288 flat_index: self.flat_index.into_iter().chain(flat_index).collect(),
289 no_index: self.no_index || no_index,
290 }
291 }
292
293 pub fn is_none(&self) -> bool {
296 *self == Self::default()
297 }
298}
299
300fn is_same_index(a: &IndexUrl, b: &IndexUrl) -> bool {
302 RealmRef::from(&**b.url()) == RealmRef::from(&**a.url())
303 && CanonicalUrl::new(a.url().clone()) == CanonicalUrl::new(b.url().clone())
304}
305
306impl<'a> IndexLocations {
307 fn configured_indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a {
309 let mut seen = FxHashSet::default();
310 self.indexes
311 .iter()
312 .filter(move |index| index.name.as_ref().is_none_or(|name| seen.insert(name)))
313 }
314
315 pub fn default_index(&'a self) -> Option<&'a Index> {
321 if self.no_index {
322 None
323 } else {
324 self.configured_indexes()
325 .find(|index| index.default)
326 .or_else(|| Some(&DEFAULT_INDEX))
327 }
328 }
329
330 pub fn implicit_indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a {
334 if self.no_index {
335 Either::Left(std::iter::empty())
336 } else {
337 Either::Right(
338 self.configured_indexes()
339 .filter(|index| !index.default && !index.explicit),
340 )
341 }
342 }
343
344 pub fn explicit_indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a {
348 if self.no_index {
349 Either::Left(std::iter::empty())
350 } else {
351 Either::Right(self.configured_indexes().filter(|index| index.explicit))
352 }
353 }
354
355 pub fn indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a {
364 self.implicit_indexes()
365 .chain(self.default_index())
366 .filter(|index| !index.explicit)
367 }
368
369 pub fn fetch_indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a {
373 let mut seen = FxHashSet::default();
374 self.indexes()
375 .filter(move |index| seen.insert(index.raw_url()))
376 }
377
378 pub fn simple_indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a {
382 if self.no_index {
383 Either::Left(std::iter::empty())
384 } else {
385 Either::Right(self.configured_indexes())
386 }
387 }
388
389 pub fn flat_indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a {
391 self.flat_index.iter()
392 }
393
394 pub fn no_index(&self) -> bool {
396 self.no_index
397 }
398
399 pub fn allowed_indexes(&'a self) -> Vec<&'a Index> {
406 if self.no_index {
407 self.flat_index.iter().rev().collect()
408 } else {
409 let mut indexes = vec![];
410
411 let mut seen = FxHashSet::default();
412 let mut default = false;
413 for index in {
414 self.indexes
415 .iter()
416 .chain(self.flat_index.iter())
417 .filter(move |index| index.name.as_ref().is_none_or(|name| seen.insert(name)))
418 } {
419 if index.default {
420 if default {
421 continue;
422 }
423 default = true;
424 }
425 indexes.push(index);
426 }
427 if !default {
428 indexes.push(&*DEFAULT_INDEX);
429 }
430
431 indexes.reverse();
432 indexes
433 }
434 }
435
436 pub fn known_indexes(&'a self) -> impl Iterator<Item = &'a Index> {
445 if self.no_index {
446 Either::Left(self.flat_index.iter().rev())
447 } else {
448 Either::Right(
449 std::iter::once(&*DEFAULT_INDEX)
450 .chain(self.flat_index.iter().rev())
451 .chain(self.indexes.iter().rev()),
452 )
453 }
454 }
455
456 pub fn defined_indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a {
466 if self.no_index {
467 return Either::Left(std::iter::empty());
468 }
469
470 let (non_default, default) = self
471 .configured_indexes()
472 .partition::<Vec<_>, _>(|index| !index.default);
473
474 Either::Right(non_default.into_iter().chain(default))
475 }
476
477 fn index_for_url(&self, url: &IndexUrl) -> Option<&Index> {
479 self.indexes
480 .iter()
481 .find(|index| is_same_index(index.url(), url))
482 }
483
484 pub fn status_code_strategy_for(&self, url: &IndexUrl) -> IndexStatusCodeStrategy {
486 self.index_for_url(url).map_or(
487 IndexStatusCodeStrategy::Default,
488 Index::status_code_strategy,
489 )
490 }
491
492 pub fn ignores_error_code_for(&self, url: &IndexUrl, status_code: StatusCode) -> bool {
494 self.index_for_url(url)
495 .is_some_and(|index| index.ignores_error_code(status_code))
496 }
497
498 pub fn simple_api_cache_control_for(&self, url: &IndexUrl) -> Option<http::HeaderValue> {
500 self.index_for_url(url)
501 .and_then(Index::simple_api_cache_control)
502 }
503
504 pub fn artifact_cache_control_for(&self, url: &IndexUrl) -> Option<http::HeaderValue> {
506 self.index_for_url(url)
507 .and_then(Index::artifact_cache_control)
508 }
509
510 pub fn hash_algorithm_for(&self, url: &IndexUrl) -> Option<HashAlgorithm> {
512 self.index_for_url(url)
513 .and_then(|index| index.hash_algorithm.map(HashAlgorithm::from))
514 }
515
516 pub fn exclude_newer_for(&self, url: &IndexUrl) -> Option<&ExcludeNewerOverride> {
518 self.index_for_url(url).and_then(Index::exclude_newer)
519 }
520}
521
522impl From<&IndexLocations> for uv_auth::Indexes {
523 fn from(index_locations: &IndexLocations) -> Self {
524 Self::from_indexes(index_locations.allowed_indexes().into_iter().map(|index| {
525 let mut url = index.url().url().clone();
526 url.set_username("").ok();
527 url.set_password(None).ok();
528 let mut root_url = index.url().root().unwrap_or_else(|| url.clone());
529 root_url.set_username("").ok();
530 root_url.set_password(None).ok();
531 uv_auth::Index {
532 url,
533 root_url,
534 auth_policy: index.authenticate,
535 }
536 }))
537 }
538}
539
540bitflags::bitflags! {
541 #[derive(Debug, Copy, Clone)]
542 struct Flags: u8 {
543 const NO_RANGE_REQUESTS = 1;
545 const UNAUTHORIZED = 1 << 2;
547 const FORBIDDEN = 1 << 1;
549 }
550}
551
552#[derive(Debug, Default, Clone)]
558pub struct IndexCapabilities(Arc<RwLock<FxHashMap<IndexUrl, Flags>>>);
559
560impl IndexCapabilities {
561 pub fn supports_range_requests(&self, index_url: &IndexUrl) -> bool {
563 !self
564 .0
565 .read()
566 .unwrap()
567 .get(index_url)
568 .is_some_and(|flags| flags.intersects(Flags::NO_RANGE_REQUESTS))
569 }
570
571 pub fn set_no_range_requests(&self, index_url: IndexUrl) {
573 self.0
574 .write()
575 .unwrap()
576 .entry(index_url)
577 .or_insert(Flags::empty())
578 .insert(Flags::NO_RANGE_REQUESTS);
579 }
580
581 pub fn unauthorized(&self, index_url: &IndexUrl) -> bool {
583 self.0
584 .read()
585 .unwrap()
586 .get(index_url)
587 .is_some_and(|flags| flags.intersects(Flags::UNAUTHORIZED))
588 }
589
590 pub(crate) fn set_unauthorized(&self, index_url: IndexUrl) {
592 self.0
593 .write()
594 .unwrap()
595 .entry(index_url)
596 .or_insert(Flags::empty())
597 .insert(Flags::UNAUTHORIZED);
598 }
599
600 pub fn forbidden(&self, index_url: &IndexUrl) -> bool {
602 self.0
603 .read()
604 .unwrap()
605 .get(index_url)
606 .is_some_and(|flags| flags.intersects(Flags::FORBIDDEN))
607 }
608
609 pub(crate) fn set_forbidden(&self, index_url: IndexUrl) {
611 self.0
612 .write()
613 .unwrap()
614 .entry(index_url)
615 .or_insert(Flags::empty())
616 .insert(Flags::FORBIDDEN);
617 }
618}
619
620#[cfg(test)]
621mod tests {
622 use std::error::Error;
623
624 use super::*;
625 use crate::{IndexCacheControl, IndexFormat, IndexName};
626 use http::HeaderValue;
627
628 fn index_urls<'a>(indexes: impl IntoIterator<Item = &'a Index>) -> Vec<&'a str> {
629 indexes
630 .into_iter()
631 .map(|index| index.url().url().as_str())
632 .collect()
633 }
634
635 #[test]
636 fn test_index_url_parse_valid_paths() {
637 assert!(is_disambiguated_path("/absolute/path"));
639 assert!(is_disambiguated_path("./relative/path"));
641 assert!(is_disambiguated_path("../../relative/path"));
642 if cfg!(windows) {
643 assert!(is_disambiguated_path("C:/absolute/path"));
645 assert!(is_disambiguated_path(".\\relative\\path"));
647 assert!(is_disambiguated_path("..\\..\\relative\\path"));
648 }
649 }
650
651 #[test]
652 fn test_index_url_parse_ambiguous_paths() {
653 assert!(!is_disambiguated_path("index"));
655 assert!(!is_disambiguated_path("relative/path"));
657 }
658
659 #[test]
660 fn test_index_url_parse_with_schemes() {
661 assert!(is_disambiguated_path("file:///absolute/path"));
662 assert!(is_disambiguated_path("https://registry.com/simple/"));
663 assert!(is_disambiguated_path(
664 "git+https://github.com/example/repo.git"
665 ));
666 }
667
668 #[test]
669 fn named_indexes_use_first_definition() -> Result<(), Box<dyn Error>> {
670 let first = Index::from_str("shared=https://first.example.com/simple")?;
671 let mut shadowed = Index::from_str("shared=https://shadowed.example.com/simple")?;
672 shadowed.explicit = true;
673 let mut explicit = Index::from_str("explicit=https://explicit.example.com/simple")?;
674 explicit.explicit = true;
675 let shadowed_implicit =
676 Index::from_str("explicit=https://shadowed-implicit.example.com/simple")?;
677 let mut default = Index::from_str("default=https://default.example.com/simple")?;
678 default.default = true;
679
680 let locations = IndexLocations::new(
681 vec![first, shadowed, explicit, shadowed_implicit, default],
682 vec![],
683 false,
684 );
685
686 assert_eq!(
687 index_urls(locations.simple_indexes()),
688 [
689 "https://first.example.com/simple",
690 "https://explicit.example.com/simple",
691 "https://default.example.com/simple",
692 ]
693 );
694 assert_eq!(
695 index_urls(locations.implicit_indexes()),
696 ["https://first.example.com/simple"]
697 );
698 assert_eq!(
699 index_urls(locations.explicit_indexes()),
700 ["https://explicit.example.com/simple"]
701 );
702 assert_eq!(
703 index_urls(locations.indexes()),
704 [
705 "https://first.example.com/simple",
706 "https://default.example.com/simple",
707 ]
708 );
709 assert_eq!(
710 index_urls(locations.defined_indexes()),
711 [
712 "https://first.example.com/simple",
713 "https://explicit.example.com/simple",
714 "https://default.example.com/simple",
715 ]
716 );
717
718 Ok(())
719 }
720
721 #[test]
722 fn unnamed_indexes_are_not_deduplicated() -> Result<(), Box<dyn Error>> {
723 let first = Index::from_str("https://first.example.com/simple")?;
724 let repeated = Index::from_str("https://first.example.com/simple")?;
725 let last = Index::from_str("https://last.example.com/simple")?;
726 let locations = IndexLocations::new(vec![first, repeated, last], vec![], false);
727 let expected = [
728 "https://first.example.com/simple",
729 "https://first.example.com/simple",
730 "https://last.example.com/simple",
731 ];
732
733 assert_eq!(index_urls(locations.simple_indexes()), expected);
734 assert_eq!(index_urls(locations.implicit_indexes()), expected);
735 assert_eq!(index_urls(locations.defined_indexes()), expected);
736 assert_eq!(
737 index_urls(locations.fetch_indexes()),
738 [
739 "https://first.example.com/simple",
740 "https://last.example.com/simple",
741 "https://pypi.org/simple",
742 ]
743 );
744
745 Ok(())
746 }
747
748 #[test]
749 fn shadowed_default_falls_back_to_pypi() -> Result<(), Box<dyn Error>> {
750 let first = Index::from_str("shared=https://first.example.com/simple")?;
751 let mut shadowed = Index::from_str("shared=https://shadowed.example.com/simple")?;
752 shadowed.default = true;
753 let locations = IndexLocations::new(vec![first, shadowed], vec![], false);
754
755 assert_eq!(
756 index_urls(locations.default_index()),
757 ["https://pypi.org/simple"]
758 );
759 assert_eq!(
760 index_urls(locations.indexes()),
761 [
762 "https://first.example.com/simple",
763 "https://pypi.org/simple",
764 ]
765 );
766
767 Ok(())
768 }
769
770 #[test]
771 fn fetch_indexes_deduplicates_raw_urls() {
772 let url = IndexUrl::from_str("https://index.example.com/simple").unwrap();
773 let mut first = Index::from(url.clone());
774 first.name = Some(IndexName::from_str("first").unwrap());
775 let mut second = Index::from(url);
776 second.name = Some(IndexName::from_str("second").unwrap());
777 second.default = true;
778 let locations = IndexLocations::new(vec![first, second], Vec::new(), false);
779
780 assert_eq!(locations.indexes().count(), 2);
781 assert_eq!(locations.fetch_indexes().count(), 1);
782 }
783
784 #[test]
785 fn test_cache_control_lookup() {
786 use std::str::FromStr;
787
788 use crate::IndexFormat;
789 use crate::index_name::IndexName;
790
791 let indexes = vec![
792 Index {
793 name: Some(IndexName::from_str("index1").unwrap()),
794 url: IndexUrl::from_str("https://index1.example.com/simple").unwrap(),
795 cache_control: Some(crate::IndexCacheControl {
796 api: Some(HeaderValue::from_static("max-age=300")),
797 files: Some(HeaderValue::from_static("max-age=1800")),
798 }),
799 explicit: false,
800 default: false,
801 origin: None,
802 format: IndexFormat::Simple,
803 publish_url: None,
804 authenticate: uv_auth::AuthPolicy::default(),
805 ignore_error_codes: None,
806 hash_algorithm: None,
807 exclude_newer: None,
808 },
809 Index {
810 name: Some(IndexName::from_str("index2").unwrap()),
811 url: IndexUrl::from_str("https://index2.example.com/simple").unwrap(),
812 cache_control: None,
813 explicit: false,
814 default: false,
815 origin: None,
816 format: IndexFormat::Simple,
817 publish_url: None,
818 authenticate: uv_auth::AuthPolicy::default(),
819 ignore_error_codes: None,
820 hash_algorithm: None,
821 exclude_newer: None,
822 },
823 ];
824
825 let index_locations = IndexLocations::new(indexes, Vec::new(), false);
826
827 let url1 = IndexUrl::from_str("https://index1.example.com/simple").unwrap();
828 assert_eq!(
829 index_locations.simple_api_cache_control_for(&url1),
830 Some(HeaderValue::from_static("max-age=300"))
831 );
832 assert_eq!(
833 index_locations.artifact_cache_control_for(&url1),
834 Some(HeaderValue::from_static("max-age=1800"))
835 );
836
837 let url2 = IndexUrl::from_str("https://index2.example.com/simple").unwrap();
838 assert_eq!(index_locations.simple_api_cache_control_for(&url2), None);
839 assert_eq!(index_locations.artifact_cache_control_for(&url2), None);
840
841 let url3 = IndexUrl::from_str("https://index3.example.com/simple").unwrap();
842 assert_eq!(index_locations.simple_api_cache_control_for(&url3), None);
843 assert_eq!(index_locations.artifact_cache_control_for(&url3), None);
844 }
845
846 #[test]
847 fn test_pytorch_default_cache_control() {
848 let indexes = vec![Index {
850 name: Some(IndexName::from_str("pytorch").unwrap()),
851 url: IndexUrl::from_str("https://download.pytorch.org/whl/cu118").unwrap(),
852 cache_control: None, explicit: false,
854 default: false,
855 origin: None,
856 format: IndexFormat::Simple,
857 publish_url: None,
858 authenticate: uv_auth::AuthPolicy::default(),
859 ignore_error_codes: None,
860 hash_algorithm: None,
861 exclude_newer: None,
862 }];
863
864 let index_locations = IndexLocations::new(indexes, Vec::new(), false);
865
866 let pytorch_url = IndexUrl::from_str("https://download.pytorch.org/whl/cu118").unwrap();
867
868 assert_eq!(
869 index_locations.simple_api_cache_control_for(&pytorch_url),
870 None
871 );
872 assert_eq!(
873 index_locations.artifact_cache_control_for(&pytorch_url),
874 Some(HeaderValue::from_static(
875 "max-age=365000000, immutable, public",
876 ))
877 );
878 }
879
880 #[test]
881 fn test_pytorch_user_override_cache_control() {
882 let indexes = vec![Index {
884 name: Some(IndexName::from_str("pytorch").unwrap()),
885 url: IndexUrl::from_str("https://download.pytorch.org/whl/cu118").unwrap(),
886 cache_control: Some(IndexCacheControl {
887 api: Some(HeaderValue::from_static("no-cache")),
888 files: Some(HeaderValue::from_static("max-age=3600")),
889 }),
890 explicit: false,
891 default: false,
892 origin: None,
893 format: IndexFormat::Simple,
894 publish_url: None,
895 authenticate: uv_auth::AuthPolicy::default(),
896 ignore_error_codes: None,
897 hash_algorithm: None,
898 exclude_newer: None,
899 }];
900
901 let index_locations = IndexLocations::new(indexes, Vec::new(), false);
902
903 let pytorch_url = IndexUrl::from_str("https://download.pytorch.org/whl/cu118").unwrap();
904
905 assert_eq!(
906 index_locations.simple_api_cache_control_for(&pytorch_url),
907 Some(HeaderValue::from_static("no-cache"))
908 );
909 assert_eq!(
910 index_locations.artifact_cache_control_for(&pytorch_url),
911 Some(HeaderValue::from_static("max-age=3600"))
912 );
913 }
914
915 #[test]
916 fn test_nvidia_default_cache_control() {
917 let indexes = vec![Index {
919 name: Some(IndexName::from_str("nvidia").unwrap()),
920 url: IndexUrl::from_str("https://pypi.nvidia.com").unwrap(),
921 cache_control: None, explicit: false,
923 default: false,
924 origin: None,
925 format: IndexFormat::Simple,
926 publish_url: None,
927 authenticate: uv_auth::AuthPolicy::default(),
928 ignore_error_codes: None,
929 hash_algorithm: None,
930 exclude_newer: None,
931 }];
932
933 let index_locations = IndexLocations::new(indexes, Vec::new(), false);
934
935 let nvidia_url = IndexUrl::from_str("https://pypi.nvidia.com").unwrap();
936
937 assert_eq!(
938 index_locations.simple_api_cache_control_for(&nvidia_url),
939 None
940 );
941 assert_eq!(
942 index_locations.artifact_cache_control_for(&nvidia_url),
943 Some(HeaderValue::from_static(
944 "max-age=365000000, immutable, public",
945 ))
946 );
947 }
948}