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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! 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<String>,
/// Declared size, used for the early max-bytes rejection.
pub size: Option<u64>,
/// Empty means derive from the file extension.
pub mime_type: String,
pub metadata: Value,
}
impl From<Artifact> 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<Vec<ArtifactCandidate>>;
}
/// 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<Option<Vec<u8>>>;
/// `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<Option<Vec<u8>>> {
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<String>,
prefix: impl Into<String>,
) -> 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<Option<Vec<u8>>> {
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<dyn RegistryHttp>,
db: Option<DbHandle>,
repo_did: Option<String>,
mirror: Arc<dyn ArtifactMirror>,
selectors: Vec<Arc<dyn ArtifactSelector>>,
stats: Arc<ArtifactStats>,
}
impl ArtifactResolver {
pub fn new(http: Arc<dyn RegistryHttp>) -> 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<String>) -> 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<dyn ArtifactMirror>) -> Self {
self.mirror = mirror;
self
}
/// Add a multi-artifact selector. Only [`Self::resolve_many`] uses it.
pub fn with_selector(mut self, selector: Arc<dyn ArtifactSelector>) -> 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<ResolvedArtifact> {
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<ResolvedArtifact> {
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<Vec<ResolvedArtifact>> {
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<ResolvedArtifact> {
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<ResolvedArtifact> {
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<Vec<u8>> {
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::<DownloadTooLarge>() {
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<Option<ResolvedArtifact>> {
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<Vec<ResolvedArtifact>> {
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<Value> {
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<u8> {
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"
}
}