//! Release artifact resolution, digest verification, and caching. //! //! [`ArtifactResolver`] reuses the per-ecosystem [`artifact_for`] lookup for the //! primary artifact, then downloads under a byte cap, verifies (or computes) //! the SHA-256, derives the raw-codec CIDv1, and records the result in //! `release_artifacts`. The cache key is //! `(repo_did, source, package, version, url)`, so a verified artifact is never //! downloaded twice. //! //! Source adapters that expose several files per version (wheel + sdist, //! jar + sources, release assets) implement [`ArtifactSelector`] and are added //! with [`ArtifactResolver::with_selector`]; the single-artifact `resolve` path //! never consults them. //! //! A byte mirror is optional. It is best-effort by design: mirror failures fall //! back to the registry, and the artifact digest is still verified whenever the //! registry declared one. // This module is also compiled directly by `tests/release_artifacts.rs`; the // S3 mirror and counter surface is exercised by the integration runtime there. #![allow(dead_code)] use std::collections::HashSet; use std::io::Write; use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; use anyhow::{Context, Result, bail}; use async_trait::async_trait; use flate2::{Compression, GzBuilder}; use serde::Serialize; use serde_json::{Value, json}; use thiserror::Error; use crate::db::DbHandle; use crate::db::model::{ReleaseArtifactMark, ReleaseArtifactRow}; use crate::pds::Publisher; use crate::records::{cidv1_raw, sha256_hex}; use crate::release::artifact::{Artifact, Purl, artifact_for}; use crate::release::http::{DownloadTooLarge, RegistryHttp}; /// Typed artifact failures; match with `anyhow::Error::downcast_ref`. #[derive(Debug, Error)] pub enum ArtifactError { #[error("artifact {url} exceeds the {limit}-byte limit")] TooLarge { url: String, limit: u64 }, #[error("artifact digest mismatch for {url}: declared {declared}, computed {computed}")] DigestMismatch { url: String, declared: String, computed: String, }, } /// One verified artifact: registry identity plus the computed content digest. #[derive(Debug, Clone, PartialEq)] pub struct ResolvedArtifact { pub file_name: String, pub url: String, pub sha256: String, pub cid: String, pub size: u64, pub mime_type: String, pub metadata: Value, } impl ResolvedArtifact { fn from_row(row: ReleaseArtifactRow) -> Self { let sha256 = row.sha256.unwrap_or_default(); Self { file_name: row.file_name.unwrap_or_default(), url: row.url, cid: row.cid.unwrap_or_else(|| cidv1_raw(&sha256)), sha256, size: row.size.unwrap_or(0).max(0) as u64, mime_type: row.mime_type.unwrap_or_default(), metadata: row .metadata_json .and_then(|json| serde_json::from_str(&json).ok()) .unwrap_or(Value::Null), } } } /// A secondary artifact proposed by an [`ArtifactSelector`]. /// /// The resolver downloads and verifies it exactly like the primary artifact. #[derive(Debug, Clone, Default)] pub struct ArtifactCandidate { pub file_name: String, pub url: String, /// Declared hex SHA-256; `None` (or empty) means compute it from the bytes. pub sha256: Option, /// Declared size, used for the early max-bytes rejection. pub size: Option, /// Empty means derive from the file extension. pub mime_type: String, pub metadata: Value, } impl From for ArtifactCandidate { fn from(artifact: Artifact) -> Self { Self { file_name: artifact.file_name, url: artifact.url, sha256: (!artifact.sha256.is_empty()).then_some(artifact.sha256), size: (artifact.size > 0).then_some(artifact.size), mime_type: artifact.mime_type, metadata: Value::Null, } } } /// Multi-artifact hook for source adapters (wheel + sdist, jar + sources, /// release assets). Selectors never replace the primary artifact. #[async_trait] pub trait ArtifactSelector: Send + Sync { async fn candidates(&self, purl: &Purl, raw_version: &str) -> Result>; } /// Optional artifact-byte mirror (S3 in production). Keys are opaque. #[async_trait] pub trait ArtifactMirror: Send + Sync { async fn put(&self, key: &str, bytes: &[u8]) -> Result<()>; async fn get(&self, key: &str) -> Result>>; /// `false` for the default no-op mirror so counters do not report phantom /// writes. Real mirrors keep the default. fn enabled(&self) -> bool { true } } /// Default mirror: stores nothing. #[derive(Debug, Default)] pub struct NoopMirror; #[async_trait] impl ArtifactMirror for NoopMirror { async fn put(&self, _key: &str, _bytes: &[u8]) -> Result<()> { Ok(()) } async fn get(&self, _key: &str) -> Result>> { Ok(None) } fn enabled(&self) -> bool { false } } /// S3-backed artifact mirror. Keys are stored under `prefix`. pub struct S3Mirror { client: aws_sdk_s3::Client, bucket: String, prefix: String, } impl S3Mirror { pub fn new( client: aws_sdk_s3::Client, bucket: impl Into, prefix: impl Into, ) -> Self { Self { client, bucket: bucket.into(), prefix: prefix.into().trim_matches('/').to_owned(), } } fn object_key(&self, key: &str) -> String { let key = key.trim_start_matches('/'); if self.prefix.is_empty() { key.to_owned() } else { format!("{}/{key}", self.prefix) } } } #[async_trait] impl ArtifactMirror for S3Mirror { async fn put(&self, key: &str, bytes: &[u8]) -> Result<()> { let object_key = self.object_key(key); self.client .put_object() .bucket(&self.bucket) .key(&object_key) .content_type("application/octet-stream") .body(aws_sdk_s3::primitives::ByteStream::from(bytes.to_vec())) .send() .await .map_err(|error| { anyhow::Error::new(error) .context(format!("s3 put s3://{}/{object_key}", self.bucket)) })?; Ok(()) } async fn get(&self, key: &str) -> Result>> { let object_key = self.object_key(key); let object = match self .client .get_object() .bucket(&self.bucket) .key(&object_key) .send() .await { Ok(object) => object, Err(error) => { let not_found = match &error { aws_sdk_s3::error::SdkError::ServiceError(context) => { context.err().is_no_such_key() || context.raw().status().as_u16() == 404 } _ => false, }; if not_found { return Ok(None); } return Err(anyhow::Error::new(error) .context(format!("s3 get s3://{}/{object_key}", self.bucket))); } }; let bytes = object .body .collect() .await .context(format!("read s3://{}/{object_key} body", self.bucket))? .into_bytes(); Ok(Some(bytes.to_vec())) } } /// Artifact counters for `CycleStats`. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] pub struct ArtifactCounters { pub downloads: u64, pub bytes: u64, pub cache_hits: u64, pub mirror_puts: u64, pub errors: u64, } #[derive(Debug, Default)] struct ArtifactStats { downloads: AtomicU64, bytes: AtomicU64, cache_hits: AtomicU64, mirror_puts: AtomicU64, errors: AtomicU64, } impl ArtifactStats { fn counters(&self) -> ArtifactCounters { ArtifactCounters { downloads: self.downloads.load(Ordering::Relaxed), bytes: self.bytes.load(Ordering::Relaxed), cache_hits: self.cache_hits.load(Ordering::Relaxed), mirror_puts: self.mirror_puts.load(Ordering::Relaxed), errors: self.errors.load(Ordering::Relaxed), } } } /// Stable mirror key for one artifact URL. pub fn mirror_key(url: &str) -> String { format!("artifacts/{}", sha256_hex(url.as_bytes())) } /// Primary artifact resolver with an optional durable digest cache and mirror. pub struct ArtifactResolver { http: Arc, db: Option, repo_did: Option, mirror: Arc, selectors: Vec>, stats: Arc, } impl ArtifactResolver { pub fn new(http: Arc) -> Self { Self { http, db: None, repo_did: None, mirror: Arc::new(NoopMirror), selectors: Vec::new(), stats: Arc::new(ArtifactStats::default()), } } /// Counters accumulated by this resolver. pub fn counters(&self) -> ArtifactCounters { self.stats.counters() } /// Enable the `release_artifacts` digest cache for one repository. pub fn with_cache(mut self, db: DbHandle, repo_did: impl Into) -> Self { self.db = Some(db); self.repo_did = Some(repo_did.into()); self } /// Inject a byte mirror. Absent by default; the runtime wires S3 later. pub fn with_mirror(mut self, mirror: Arc) -> Self { self.mirror = mirror; self } /// Add a multi-artifact selector. Only [`Self::resolve_many`] uses it. pub fn with_selector(mut self, selector: Arc) -> Self { self.selectors.push(selector); self } /// Resolve the single preferred artifact via [`artifact_for`]. /// /// `max_bytes == 0` means no cap. pub async fn resolve( &self, purl: &Purl, raw_version: &str, max_bytes: u64, ) -> Result { let artifact = artifact_for(self.http.as_ref(), purl, raw_version).await?; self.resolve_candidate(purl, raw_version, artifact.into(), max_bytes) .await } /// Resolve a source-declared candidate (extra ecosystems) through the same /// cap/verify/cache/mirror path. /// /// `max_bytes == 0` means no cap. pub async fn resolve_declared( &self, purl: &Purl, raw_version: &str, candidate: ArtifactCandidate, max_bytes: u64, ) -> Result { self.resolve_candidate(purl, raw_version, candidate, max_bytes) .await } /// Resolve the primary artifact plus every selector candidate, deduped by /// URL. With no selectors this is the single-artifact path. pub async fn resolve_many( &self, purl: &Purl, raw_version: &str, max_bytes: u64, ) -> Result> { if self.selectors.is_empty() { let cached = self.cached(purl, raw_version).await?; if !cached.is_empty() { self.stats .cache_hits .fetch_add(cached.len() as u64, Ordering::Relaxed); return Ok(cached); } } let primary = self.resolve(purl, raw_version, max_bytes).await?; let mut seen = HashSet::from([primary.url.clone()]); let mut resolved = vec![primary]; for selector in &self.selectors { for candidate in selector.candidates(purl, raw_version).await? { if !seen.insert(candidate.url.clone()) { continue; } resolved.push( self.resolve_candidate(purl, raw_version, candidate, max_bytes) .await?, ); } } Ok(resolved) } async fn resolve_candidate( &self, purl: &Purl, raw_version: &str, candidate: ArtifactCandidate, max_bytes: u64, ) -> Result { match self .resolve_candidate_inner(purl, raw_version, candidate, max_bytes) .await { Ok(artifact) => Ok(artifact), Err(error) => { self.stats.errors.fetch_add(1, Ordering::Relaxed); Err(error) } } } async fn resolve_candidate_inner( &self, purl: &Purl, raw_version: &str, candidate: ArtifactCandidate, max_bytes: u64, ) -> Result { if let Some(cached) = self.cache_get(purl, raw_version, &candidate.url).await? { self.stats.cache_hits.fetch_add(1, Ordering::Relaxed); return Ok(cached); } let limit = if max_bytes == 0 { u64::MAX } else { max_bytes }; if candidate.size.is_some_and(|size| size > limit) { return Err(ArtifactError::TooLarge { url: candidate.url, limit, } .into()); } let bytes = self.fetch_bytes(&candidate.url, limit).await?; if bytes.is_empty() { bail!("empty artifact: {}", candidate.url); } let computed = sha256_hex(&bytes); let sha256 = match candidate .sha256 .as_deref() .filter(|declared| !declared.is_empty()) { Some(declared) => { if !declared.eq_ignore_ascii_case(&computed) { return Err(ArtifactError::DigestMismatch { url: candidate.url, declared: declared.to_owned(), computed, } .into()); } computed } None => computed, }; let mime_type = if candidate.mime_type.is_empty() { mime_for(&candidate.file_name).to_owned() } else { candidate.mime_type }; let cid = cidv1_raw(&sha256); let artifact = ResolvedArtifact { file_name: candidate.file_name, url: candidate.url, sha256, cid, size: bytes.len() as u64, mime_type, metadata: candidate.metadata, }; self.cache_mark(purl, raw_version, &artifact).await?; Ok(artifact) } /// Mirror first, then the registry; a mirror error is not fatal. async fn fetch_bytes(&self, url: &str, limit: u64) -> Result> { let key = mirror_key(url); if let Ok(Some(bytes)) = self.mirror.get(&key).await && bytes.len() as u64 <= limit { self.stats.cache_hits.fetch_add(1, Ordering::Relaxed); return Ok(bytes); } let bytes = self .http .download_limited(url, limit) .await .map_err(|error| match error.downcast::() { Ok(too_large) => ArtifactError::TooLarge { url: too_large.url, limit: too_large.limit, } .into(), Err(error) => error, })?; self.stats.downloads.fetch_add(1, Ordering::Relaxed); self.stats .bytes .fetch_add(bytes.len() as u64, Ordering::Relaxed); // ponytail: best-effort mirror write; a miss just re-downloads. if self.mirror.enabled() && self.mirror.put(&key, &bytes).await.is_ok() { self.stats.mirror_puts.fetch_add(1, Ordering::Relaxed); } Ok(bytes) } async fn cache_get( &self, purl: &Purl, raw_version: &str, url: &str, ) -> Result> { let (Some(db), Some(repo_did)) = (self.db.as_ref(), self.repo_did.as_deref()) else { return Ok(None); }; let row = db .get_release_artifact(repo_did, &purl.r#type, &purl.name, raw_version, url) .await?; Ok(row.map(ResolvedArtifact::from_row)) } async fn cached(&self, purl: &Purl, raw_version: &str) -> Result> { let (Some(db), Some(repo_did)) = (self.db.as_ref(), self.repo_did.as_deref()) else { return Ok(Vec::new()); }; let rows = db .list_release_artifacts(repo_did, &purl.r#type, &purl.name, raw_version) .await?; Ok(rows.into_iter().map(ResolvedArtifact::from_row).collect()) } async fn cache_mark( &self, purl: &Purl, raw_version: &str, artifact: &ResolvedArtifact, ) -> Result<()> { let (Some(db), Some(repo_did)) = (self.db.as_ref(), self.repo_did.as_deref()) else { return Ok(()); }; db.mark_release_artifact(ReleaseArtifactMark { repo_did: repo_did.to_owned(), source: purl.r#type.clone(), package: purl.name.clone(), version: raw_version.to_owned(), file_name: Some(artifact.file_name.clone()), url: artifact.url.clone(), sha256: Some(artifact.sha256.clone()), cid: Some(artifact.cid.clone()), size: Some(artifact.size as i64), mime_type: Some(artifact.mime_type.clone()), metadata_json: (!artifact.metadata.is_null()).then(|| artifact.metadata.to_string()), }) .await } } /// `software.release.defs#httpArtifact` fragment. pub fn http_artifact_record(artifact: &ResolvedArtifact) -> Value { json!({ "$type": "software.release.defs#httpArtifact", "fileName": artifact.file_name, "url": artifact.url, "cid": artifact.cid, "size": artifact.size, "mimeType": artifact.mime_type, }) } /// Gzip and upload an artifact as a `blobArtifact` fragment. /// /// Blob uploads cost zero write points. When the gzipped bytes exceed /// `max_bytes` (pass [`crate::constants::BLOB_MAX`] in production), the /// artifact stays an `httpArtifact` instead. pub async fn blob_artifact_record( publisher: &Publisher, artifact: &ResolvedArtifact, bytes: &[u8], max_bytes: usize, ) -> Result { let gzipped = gzip_bytes(bytes); if gzipped.len() > max_bytes { return Ok(http_artifact_record(artifact)); } let blob = publisher.upload_blob(&gzipped, "application/gzip").await?; Ok(json!({ "$type": "software.release.defs#blobArtifact", "fileName": artifact.file_name, "blob": blob, })) } fn gzip_bytes(bytes: &[u8]) -> Vec { let mut encoder = GzBuilder::new() .mtime(0) .operating_system(255) .write(Vec::new(), Compression::new(9)); encoder.write_all(bytes).expect("gzip write to memory"); encoder.finish().expect("gzip finish to memory") } fn mime_for(file_name: &str) -> &'static str { let lower = file_name.to_ascii_lowercase(); if [".whl", ".zip", ".jar", ".nupkg"] .iter() .any(|suffix| lower.ends_with(suffix)) { "application/zip" } else if [".tar.gz", ".tgz", ".crate", ".gem"] .iter() .any(|suffix| lower.ends_with(suffix)) { "application/gzip" } else if lower.ends_with(".tar") { "application/x-tar" } else if lower.ends_with(".deb") { "application/vnd.debian.binary-package" } else if lower.ends_with(".rpm") { "application/x-rpm" } else if lower.ends_with(".json") { "application/json" } else if lower.ends_with(".xml") { "application/xml" } else if [".txt", ".asc", ".sig"] .iter() .any(|suffix| lower.ends_with(suffix)) { "text/plain" } else { "application/octet-stream" } }