//! 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, base_url: String, } impl CpanSource { pub fn new(http: Arc) -> Self { Self::with_base_url(http, DEFAULT_METACPAN_BASE_URL) } pub fn with_base_url(http: Arc, base_url: impl Into) -> 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> { 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> { 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 = 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> { 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> { Err(unsupported(UnsupportedReason::NoStatuses)) } async fn project_meta(&self, project: &ProjectRef) -> Result { 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 { 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 { 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 { 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 { 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 { 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:?}") }