1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
//! crates.io source: full version history, crate checksums, and yank state.
//!
//! Every JSON request is throttled to one per second per source instance;
//! crates.io asks crawlers to stay at or below 1 req/s, and the injected
//! [`RegistryHttp`] transport sends the shared user agent. Pagination follows
//! the keyset `meta.next_page` cursor because the API rejects page-number
//! queries. Declared checksums and sizes come from `/versions`, so artifacts
//! never need a download or HEAD.
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use serde_json::{Map, Value};
use tokio::sync::Mutex;
use tokio::time::Instant;
use crate::release::http::RegistryHttp;
use crate::release::source::{
ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, VersionInfo,
};
use crate::release::versioning::{VersionScheme, compare, normalize_version};
pub const API_BASE: &str = "https://crates.io/api/v1/crates";
pub const STATIC_BASE: &str = "https://static.crates.io/crates";
pub const RATE_LIMIT_INTERVAL: Duration = Duration::from_secs(1);
const PER_PAGE: usize = 100;
/// ~100k versions; no real crate comes close.
const MAX_PAGES: usize = 1000;
pub struct CargoSource {
http: Arc<dyn RegistryHttp>,
min_interval: Duration,
last_request: Mutex<Option<Instant>>,
}
impl CargoSource {
pub fn new(http: Arc<dyn RegistryHttp>) -> Self {
Self::with_interval(http, RATE_LIMIT_INTERVAL)
}
/// Override the per-host interval; tests use [`Duration::ZERO`].
pub fn with_interval(http: Arc<dyn RegistryHttp>, min_interval: Duration) -> Self {
Self {
http,
min_interval,
last_request: Mutex::new(None),
}
}
async fn throttle(&self) {
let mut last_request = self.last_request.lock().await;
if let Some(previous) = *last_request {
let elapsed = previous.elapsed();
if elapsed < self.min_interval {
tokio::time::sleep(self.min_interval - elapsed).await;
}
}
*last_request = Some(Instant::now());
}
async fn get_json(&self, url: &str) -> Result<Value> {
self.throttle().await;
self.http.get_json(url).await
}
async fn crate_json(&self, name: &str) -> Result<Value> {
self.get_json(&format!("{API_BASE}/{name}")).await
}
async fn raw_versions(&self, name: &str) -> Result<Vec<Value>> {
let mut all = Vec::new();
let mut next_page: Option<String> = None;
for _ in 0..MAX_PAGES {
let url = match &next_page {
Some(query) => format!("{API_BASE}/{name}/versions{query}"),
None => format!("{API_BASE}/{name}/versions?per_page={PER_PAGE}"),
};
let payload = self.get_json(&url).await?;
let versions = payload
.get("versions")
.and_then(Value::as_array)
.ok_or_else(|| {
anyhow!("crates versions payload missing versions array for {name}")
})?;
let empty = versions.is_empty();
all.extend(versions.iter().cloned());
next_page = payload
.get("meta")
.and_then(|meta| meta.get("next_page"))
.and_then(Value::as_str)
.filter(|next| !next.is_empty())
.map(str::to_owned);
if empty || next_page.is_none() {
break;
}
}
Ok(all)
}
}
#[async_trait]
impl ReleaseSource for CargoSource {
fn name(&self) -> &'static str {
"cargo"
}
fn capabilities(&self) -> SourceCapabilities {
SourceCapabilities {
versions: true,
artifacts: true,
statuses: true,
project_meta: true,
}
}
async fn versions(&self, project: &ProjectRef) -> Result<Vec<VersionInfo>> {
let entries = self.raw_versions(&project.name).await?;
Ok(version_infos(&entries))
}
async fn artifacts(
&self,
project: &ProjectRef,
version: &VersionInfo,
) -> Result<Vec<ArtifactInfo>> {
let entries = self.raw_versions(&project.name).await?;
let Some(entry) = version_entry(&entries, &version.raw) else {
return Ok(Vec::new());
};
let name = text_field(entry, "crate").unwrap_or(project.name.as_str());
let file_name = format!("{name}-{}.crate", version.raw);
let url = format!("{STATIC_BASE}/{name}/{file_name}");
Ok(vec![ArtifactInfo {
file_name,
url,
sha256: text_field(entry, "checksum").map(str::to_owned),
size: entry
.get("crate_size")
.and_then(Value::as_u64)
.filter(|size| *size > 0),
mime_type: Some("application/gzip".to_owned()),
}])
}
async fn statuses(
&self,
project: &ProjectRef,
version: &VersionInfo,
) -> Result<Vec<StatusInfo>> {
let entries = self.raw_versions(&project.name).await?;
let Some(entry) = version_entry(&entries, &version.raw) else {
return Ok(Vec::new());
};
if !truthy(entry.get("yanked")) {
return Ok(Vec::new());
}
let reason = text_field(entry, "yank_message")
.unwrap_or_default()
.to_owned();
Ok(vec![StatusInfo {
status: "yanked".to_owned(),
kind: Some(status_kind(&reason).to_owned()),
reason,
}])
}
async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
let payload = self.crate_json(&project.name).await?;
let crate_obj = payload.get("crate").unwrap_or(&Value::Null);
let versions = payload
.get("versions")
.and_then(Value::as_array)
.map(Vec::as_slice)
.unwrap_or(&[]);
let newest = text_field(crate_obj, "newest_version")
.or_else(|| text_field(crate_obj, "max_version"));
let license = text_field(crate_obj, "license")
.or_else(|| {
newest.and_then(|newest| {
versions
.iter()
.find(|version| text_field(version, "num") == Some(newest))
.and_then(|version| text_field(version, "license"))
})
})
.or_else(|| {
versions
.iter()
.find_map(|version| text_field(version, "license"))
});
let mut meta = Map::new();
insert_text(
&mut meta,
"name",
Some(text_field(crate_obj, "name").unwrap_or(project.name.as_str())),
);
insert_text(
&mut meta,
"description",
text_field(crate_obj, "description"),
);
insert_text(&mut meta, "homepage", text_field(crate_obj, "homepage"));
insert_text(&mut meta, "repository", text_field(crate_obj, "repository"));
insert_text(
&mut meta,
"documentation",
text_field(crate_obj, "documentation"),
);
insert_text(&mut meta, "license", license);
Ok(Value::Object(meta))
}
}
fn version_entry<'a>(entries: &'a [Value], raw: &str) -> Option<&'a Value> {
entries
.iter()
.find(|entry| text_field(entry, "num") == Some(raw))
}
fn version_infos(entries: &[Value]) -> Vec<VersionInfo> {
let mut versions = entries
.iter()
.filter_map(|entry| {
let raw = text_field(entry, "num")?;
let yanked = truthy(entry.get("yanked"));
Some(VersionInfo {
raw: raw.to_owned(),
version: normalize_version(raw).unwrap_or_else(|| raw.to_owned()),
deprecated: yanked,
reason: if yanked {
text_field(entry, "yank_message")
.unwrap_or_default()
.to_owned()
} else {
String::new()
},
})
})
.collect::<Vec<_>>();
versions.sort_by(|left, right| {
compare(VersionScheme::Semver, &left.raw, &right.raw).then_with(|| left.raw.cmp(&right.raw))
});
versions
}
fn truthy(value: Option<&Value>) -> bool {
match value {
Some(Value::Bool(value)) => *value,
Some(Value::String(value)) => !value.is_empty(),
Some(Value::Number(number)) => number.as_f64().is_some_and(|value| value != 0.0),
Some(Value::Array(values)) => !values.is_empty(),
Some(Value::Object(values)) => !values.is_empty(),
Some(Value::Null) | None => false,
}
}
fn text_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
value
.get(key)
.and_then(Value::as_str)
.filter(|text| !text.is_empty())
}
fn status_kind(reason: &str) -> &'static str {
let reason = reason.to_ascii_lowercase();
if ["security", "malware", "cve", "vulnerab"]
.iter()
.any(|needle| reason.contains(needle))
{
"security"
} else {
"registry"
}
}
fn insert_text(meta: &mut Map<String, Value>, key: &str, value: Option<&str>) {
if let Some(value) = value.filter(|value| !value.is_empty()) {
meta.insert(key.to_owned(), Value::String(value.to_owned()));
}
}