1use tame_index::flock::FileLock;
2use tame_index::krate::IndexKrate;
3
4use url::Url;
5
6use super::errors::{CargoResult, Context};
7
8#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
9pub enum CertsSource {
10 #[default]
12 Webpki,
13 Native,
15}
16
17pub struct IndexCache {
18 certs_source: CertsSource,
19 index: std::collections::HashMap<Url, AnyIndexCache>,
20}
21
22impl IndexCache {
23 #[inline]
24 pub fn new(certs_source: CertsSource) -> Self {
25 Self {
26 certs_source,
27 index: Default::default(),
28 }
29 }
30
31 #[inline]
33 pub fn has_krate(&mut self, registry: &Url, name: &str) -> CargoResult<bool> {
34 self.index(registry)
35 .with_context(|| format!("failed to look up {name}"))?
36 .has_krate(name)
37 }
38
39 #[inline]
41 pub fn has_krate_version(
42 &mut self,
43 registry: &Url,
44 name: &str,
45 version: &str,
46 ) -> CargoResult<Option<bool>> {
47 self.index(registry)
48 .with_context(|| format!("failed to look up {name}@{version}"))?
49 .has_krate_version(name, version)
50 }
51
52 #[inline]
53 pub fn update_krate(&mut self, registry: &Url, name: &str) -> CargoResult<()> {
54 self.index(registry)
55 .with_context(|| format!("failed to look up {name}"))?
56 .update_krate(name);
57 Ok(())
58 }
59
60 pub fn krate(&mut self, registry: &Url, name: &str) -> CargoResult<Option<IndexKrate>> {
61 self.index(registry)
62 .with_context(|| format!("failed to look up {name}"))?
63 .krate(name)
64 }
65
66 fn index<'s>(&'s mut self, registry: &Url) -> CargoResult<&'s mut AnyIndexCache> {
67 if !self.index.contains_key(registry) {
68 let index = AnyIndex::open(registry, self.certs_source)?;
69 let index = AnyIndexCache::new(index);
70 self.index.insert(registry.clone(), index);
71 }
72 Ok(self.index.get_mut(registry).unwrap())
73 }
74}
75
76struct AnyIndexCache {
77 index: AnyIndex,
78 cache: std::collections::HashMap<String, Option<IndexKrate>>,
79}
80
81impl AnyIndexCache {
82 #[inline]
83 fn new(index: AnyIndex) -> Self {
84 Self {
85 index,
86 cache: std::collections::HashMap::new(),
87 }
88 }
89
90 #[inline]
92 fn has_krate(&mut self, name: &str) -> CargoResult<bool> {
93 Ok(self.krate(name)?.map(|_| true).unwrap_or(false))
94 }
95
96 #[inline]
98 fn has_krate_version(&mut self, name: &str, version: &str) -> CargoResult<Option<bool>> {
99 let krate = self.krate(name)?;
100 Ok(krate.map(|ik| ik.versions.iter().any(|iv| iv.version == version)))
101 }
102
103 #[inline]
104 fn update_krate(&mut self, name: &str) {
105 self.cache.remove(name);
106 }
107
108 fn krate(&mut self, name: &str) -> CargoResult<Option<IndexKrate>> {
109 if let Some(entry) = self.cache.get(name) {
110 return Ok(entry.clone());
111 }
112
113 let entry = self.index.krate(name)?;
114 self.cache.insert(name.to_owned(), entry.clone());
115 Ok(entry)
116 }
117}
118
119enum AnyIndex {
120 Local(LocalIndex),
121 Remote(RemoteIndex),
122}
123
124impl AnyIndex {
125 fn open(url: &Url, certs_source: CertsSource) -> CargoResult<Self> {
126 if url.scheme() == "file" {
127 LocalIndex::open(url)
128 .map(Self::Local)
129 .with_context(|| format!("invalid local registry {url:?}"))
130 } else {
131 RemoteIndex::open(url, certs_source)
132 .map(Self::Remote)
133 .with_context(|| format!("invalid registry {url:?}"))
134 }
135 }
136
137 fn krate(&mut self, name: &str) -> CargoResult<Option<IndexKrate>> {
138 match self {
139 Self::Local(index) => index.krate(name),
140 Self::Remote(index) => index.krate(name),
141 }
142 }
143}
144
145struct LocalIndex {
146 index: tame_index::index::LocalIndex,
147}
148
149impl LocalIndex {
150 fn open(url: &Url) -> CargoResult<Self> {
151 let path = url
152 .to_file_path()
153 .map_err(|_err| anyhow::format_err!("invalid file path {url:?}"))?;
154 let path = tame_index::PathBuf::from_path_buf(path)
155 .map_err(|_err| anyhow::format_err!("invalid file path {url:?}"))?;
156 Ok(Self {
157 index: tame_index::index::LocalIndex::open(path)?,
158 })
159 }
160
161 fn krate(&mut self, name: &str) -> CargoResult<Option<IndexKrate>> {
162 let l = FileLock::unlocked();
163 let Some(entry) = self.index.krate(name.try_into()?, &l)? else {
164 return Ok(None);
165 };
166
167 Ok(entry.deserialize().map(Some)?)
168 }
169}
170
171struct RemoteIndex {
172 index: tame_index::SparseIndex,
173 client: ureq::Agent,
174 lock: FileLock,
175 etag_cache: tame_index::EtagCache,
176}
177
178impl RemoteIndex {
179 fn open(url: &Url, certs_source: CertsSource) -> CargoResult<Self> {
180 log::trace!("opening index entry for {url}");
181 let url = url.to_string();
182 let url = tame_index::IndexUrl::NonCratesIo(std::borrow::Cow::Owned(url));
183 let index = tame_index::SparseIndex::new(tame_index::IndexLocation::new(url))?;
184
185 let client = ureq::Agent::config_builder()
186 .http_status_as_error(false)
188 .tls_config(
189 ureq::tls::TlsConfig::builder()
190 .provider(ureq::tls::TlsProvider::Rustls)
191 .root_certs(match certs_source {
192 CertsSource::Webpki => ureq::tls::RootCerts::WebPki,
193 CertsSource::Native => ureq::tls::RootCerts::PlatformVerifier,
194 })
195 .build(),
196 )
197 .build()
198 .new_agent();
199
200 let lock = FileLock::unlocked();
201
202 Ok(Self {
203 index,
204 client,
205 lock,
206 etag_cache: Default::default(),
207 })
208 }
209
210 fn krate(&mut self, name: &str) -> CargoResult<Option<IndexKrate>> {
211 log::trace!("krate {name}");
212 let krate_name = name.try_into()?;
213 let req = self
214 .etag_cache
215 .make_remote_request(&self.index, krate_name, &self.lock)?;
216
217 let (parts, mut body) = self.client.run(req.into())?.into_parts();
218 let body = body.read_to_vec().context("failed to read response body")?;
219
220 self.etag_cache
221 .parse_remote_response(
222 &self.index,
223 krate_name,
224 &ureq::http::Response::from_parts(parts, body),
225 false,
226 &self.lock,
227 )
228 .and_then(|ie| {
229 if let Some(ie) = ie {
230 ie.deserialize().map(Some)
231 } else {
232 Ok(None)
233 }
234 })
235 .map_err(Into::into)
236 }
237}