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
284
285
286
//! MetaCPAN source adapter.
//!
//! `pkg:cpan/DIST` uses the MetaCPAN release endpoint for project metadata
//! and `/v1/release/_search` for the full version list. Release documents
//! carry the tarball URL, size, author, license, and a SHA-256 checksum, so
//! artifacts are reported without downloading them.
use std::collections::BTreeMap;
use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
use serde_json::{Map, Value};
use crate::release::http::RegistryHttp;
use crate::release::source::{
ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, UnsupportedReason,
VersionInfo,
};
use crate::release::versioning::{VersionScheme, compare, normalize_version};
pub const DEFAULT_METACPAN_BASE_URL: &str = "https://fastapi.metacpan.org";
const SEARCH_SIZE: usize = 100;
pub struct CpanSource {
http: Arc<dyn RegistryHttp>,
base_url: String,
}
impl CpanSource {
pub fn new(http: Arc<dyn RegistryHttp>) -> Self {
Self::with_base_url(http, DEFAULT_METACPAN_BASE_URL)
}
pub fn with_base_url(http: Arc<dyn RegistryHttp>, base_url: impl Into<String>) -> Self {
Self {
http,
base_url: base_url.into().trim_end_matches('/').to_owned(),
}
}
fn search_url(&self, dist: &str) -> String {
format!(
"{}/v1/release/_search?q=distribution:{dist}&size={SEARCH_SIZE}",
self.base_url
)
}
fn release_url(&self, dist: &str) -> String {
format!("{}/v1/release/{dist}", self.base_url)
}
async fn releases(&self, dist: &str) -> Result<Vec<Value>> {
let payload = self.http.get_json(&self.search_url(dist)).await?;
Ok(search_sources(&payload))
}
}
#[async_trait]
impl ReleaseSource for CpanSource {
fn name(&self) -> &'static str {
"cpan"
}
fn capabilities(&self) -> SourceCapabilities {
SourceCapabilities {
versions: true,
artifacts: true,
statuses: false,
project_meta: true,
}
}
async fn versions(&self, project: &ProjectRef) -> Result<Vec<VersionInfo>> {
let dist = dist_name(project)?;
let mut by_version = BTreeMap::new();
for release in self.releases(dist).await? {
let Some(raw) = release_version(&release) else {
continue;
};
let Some(version) = normalize(raw) else {
continue;
};
by_version.entry(version.clone()).or_insert_with(|| {
let status = release.get("status").and_then(Value::as_str).unwrap_or("");
let deprecated = status == "backpan";
VersionInfo {
raw: raw.to_owned(),
version,
deprecated,
reason: if deprecated {
"backpan release".to_owned()
} else {
String::new()
},
}
});
}
let mut versions: Vec<VersionInfo> = by_version.into_values().collect();
sort_versions(&mut versions);
if versions.is_empty() {
return Err(unsupported(UnsupportedReason::NoVersions));
}
Ok(versions)
}
async fn artifacts(
&self,
project: &ProjectRef,
version: &VersionInfo,
) -> Result<Vec<ArtifactInfo>> {
let dist = dist_name(project)?;
let release = self
.releases(dist)
.await?
.into_iter()
.find(|release| release_matches(release, version))
.ok_or_else(|| unsupported(UnsupportedReason::NoArtifacts))?;
let url = release
.get("download_url")
.and_then(Value::as_str)
.map(str::trim)
.filter(|url| !url.is_empty())
.ok_or_else(|| unsupported(UnsupportedReason::NoArtifacts))?;
let file_name = release
.get("archive")
.and_then(Value::as_str)
.map(str::trim)
.filter(|name| !name.is_empty())
.map(str::to_owned)
.or_else(|| url_file_name(url))
.ok_or_else(|| unsupported(UnsupportedReason::NoArtifacts))?;
let sha256 = release
.get("checksum_sha256")
.and_then(Value::as_str)
.and_then(hex64)
.or_else(|| {
release
.get("checksum")
.and_then(Value::as_str)
.and_then(parse_checksum)
});
Ok(vec![ArtifactInfo {
file_name,
url: url.to_owned(),
sha256,
size: release.get("size").and_then(Value::as_u64),
mime_type: mime_for(url).map(str::to_owned),
}])
}
async fn statuses(
&self,
_project: &ProjectRef,
_version: &VersionInfo,
) -> Result<Vec<StatusInfo>> {
Err(unsupported(UnsupportedReason::NoStatuses))
}
async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
let dist = dist_name(project)?;
let payload = self.http.get_json(&self.release_url(dist)).await?;
let mut meta = Map::new();
meta.insert("source".to_owned(), Value::String("cpan".to_owned()));
meta.insert("distribution".to_owned(), Value::String(dist.to_owned()));
for key in [
"author",
"version",
"license",
"abstract",
"status",
"date",
"download_url",
] {
if let Some(value) = payload.get(key) {
meta.insert(key.to_owned(), value.clone());
}
}
Ok(Value::Object(meta))
}
}
fn dist_name(project: &ProjectRef) -> Result<&str> {
if project.purl_type != "cpan" {
return Err(unsupported(UnsupportedReason::UnknownPurlType(
project.purl_type.clone(),
)));
}
let name = project.name.trim();
if name.is_empty()
|| !name.chars().all(|character| {
character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
})
{
return Err(unsupported(UnsupportedReason::Unavailable(
"invalid CPAN distribution name",
)));
}
Ok(name)
}
/// `_search` hits embed the release document under `_source`; tolerate a bare
/// release object so the same parser also handles the `/v1/release/{dist}`
/// shape.
fn search_sources(payload: &Value) -> Vec<Value> {
payload
.pointer("/hits/hits")
.and_then(Value::as_array)
.map(|hits| {
hits.iter()
.map(|hit| hit.get("_source").cloned().unwrap_or_else(|| hit.clone()))
.collect()
})
.unwrap_or_default()
}
fn release_version(release: &Value) -> Option<&str> {
release
.get("version")
.and_then(Value::as_str)
.map(str::trim)
.filter(|version| !version.is_empty())
}
fn normalize(raw: &str) -> Option<String> {
let raw = raw.trim();
let raw = match raw.strip_prefix(['v', 'V']) {
Some(rest) if rest.starts_with(|character: char| character.is_ascii_digit()) => rest,
_ => raw,
};
normalize_version(raw)
}
fn release_matches(release: &Value, version: &VersionInfo) -> bool {
release_version(release).is_some_and(|raw| {
raw == version.raw || normalize(raw).as_deref() == Some(&version.version)
})
}
fn url_file_name(url: &str) -> Option<String> {
let path = url.split(['?', '#']).next().unwrap_or(url);
path.trim_end_matches('/')
.rsplit('/')
.next()
.filter(|name| !name.is_empty())
.map(str::to_owned)
}
fn hex64(value: &str) -> Option<String> {
let value = value.trim().to_ascii_lowercase();
(value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit())).then_some(value)
}
fn parse_checksum(value: &str) -> Option<String> {
match value.trim().split_once(':') {
Some((algorithm, digest)) if algorithm.eq_ignore_ascii_case("sha256") => hex64(digest),
Some(_) => None,
None => hex64(value),
}
}
fn mime_for(url: &str) -> Option<&'static str> {
let path = url.split(['?', '#']).next().unwrap_or(url);
if path.ends_with(".tar.gz") || path.ends_with(".tgz") {
Some("application/gzip")
} else if path.ends_with(".tar.bz2") || path.ends_with(".tbz2") {
Some("application/x-bzip2")
} else if path.ends_with(".tar.xz") || path.ends_with(".txz") {
Some("application/x-xz")
} else if path.ends_with(".zip") {
Some("application/zip")
} else {
None
}
}
fn sort_versions(versions: &mut [VersionInfo]) {
versions.sort_by(|left, right| {
compare(VersionScheme::Lexical, &left.version, &right.version)
.then_with(|| left.raw.cmp(&right.raw))
});
}
fn unsupported(reason: UnsupportedReason) -> anyhow::Error {
anyhow::anyhow!("unsupported source input: {reason:?}")
}