1use std::sync::Arc;
8
9use a3s_box_core::error::{BoxError, Result};
10use a3s_box_core::StoredImage;
11
12use super::image::OciImage;
13use super::reference::ImageReference;
14use super::registry::{RegistryAuth, RegistryPuller};
15use super::store::ImageStore;
16
17type PullProgressFn = Arc<dyn Fn(usize, usize, &str, i64) + Send + Sync>;
19
20pub struct ImagePuller {
22 store: Arc<ImageStore>,
23 puller: RegistryPuller,
24 metrics: Option<crate::prom::RuntimeMetrics>,
25 mirrors: std::collections::HashMap<String, String>,
31}
32
33fn parse_registry_mirrors() -> std::collections::HashMap<String, String> {
35 std::env::var("A3S_REGISTRY_MIRRORS")
36 .ok()
37 .map(|raw| {
38 raw.split(',')
39 .filter_map(|pair| pair.split_once('='))
40 .map(|(host, mirror)| (host.trim().to_string(), mirror.trim().to_string()))
41 .filter(|(host, mirror)| !host.is_empty() && !mirror.is_empty())
42 .collect()
43 })
44 .unwrap_or_default()
45}
46
47impl ImagePuller {
48 pub fn new(store: Arc<ImageStore>, auth: RegistryAuth) -> Self {
50 Self::with_platform(store, auth, None)
51 }
52
53 pub fn with_platform(
57 store: Arc<ImageStore>,
58 auth: RegistryAuth,
59 platform: Option<String>,
60 ) -> Self {
61 Self {
62 store,
63 puller: RegistryPuller::with_auth_and_platform(auth, platform),
64 metrics: None,
65 mirrors: parse_registry_mirrors(),
66 }
67 }
68
69 fn mirror_reference(&self, reference: &ImageReference) -> ImageReference {
73 match self.mirrors.get(&reference.registry) {
74 Some(mirror) if !mirror.is_empty() => {
75 tracing::info!(
76 registry = %reference.registry,
77 mirror = %mirror,
78 "Pulling via configured registry mirror"
79 );
80 let mut mirrored = reference.clone();
81 mirror.clone_into(&mut mirrored.registry);
82 mirrored
83 }
84 _ => reference.clone(),
85 }
86 }
87
88 pub fn set_metrics(mut self, metrics: crate::prom::RuntimeMetrics) -> Self {
90 self.metrics = Some(metrics);
91 self
92 }
93
94 pub fn with_signature_policy(mut self, policy: super::signing::SignaturePolicy) -> Self {
96 self.puller = self.puller.with_signature_policy(policy);
97 self
98 }
99
100 pub fn with_progress_fn(mut self, f: PullProgressFn) -> Self {
102 self.puller = self.puller.with_progress_fn(f);
103 self
104 }
105
106 pub async fn pull(&self, reference: &str) -> Result<OciImage> {
110 self.pull_resolved(reference).await.map(|(image, _)| image)
111 }
112
113 async fn pull_resolved(&self, reference: &str) -> Result<(OciImage, String)> {
114 let reference = reference.trim();
115 if is_digest_reference(reference) {
116 let Some((matched_reference, stored)) = self.cached_digest_image(reference).await?
117 else {
118 return Err(BoxError::OciImageError(format!(
119 "Image digest not found in local cache: {reference}"
120 )));
121 };
122 tracing::info!(
123 requested_reference = %reference,
124 matched_reference = %matched_reference,
125 digest = %stored.digest,
126 "Using cached image by digest"
127 );
128 return Ok((OciImage::from_path(&stored.path)?, matched_reference));
129 }
130
131 let parsed = ImageReference::parse(reference)?;
132
133 if let Some((matched_reference, stored)) = self.cached_image(reference, &parsed).await? {
134 tracing::info!(
135 requested_reference = %reference,
136 matched_reference = %matched_reference,
137 digest = %stored.digest,
138 "Using cached image"
139 );
140 return Ok((OciImage::from_path(&stored.path)?, matched_reference));
141 }
142
143 Ok((self.pull_and_store(&parsed).await?, parsed.full_reference()))
144 }
145
146 pub async fn force_pull(&self, reference: &str) -> Result<OciImage> {
148 let reference = reference.trim();
149 if is_digest_reference(reference) {
150 return Err(BoxError::OciImageError(format!(
151 "Cannot force-pull digest-only reference {reference}; use a tagged registry reference"
152 )));
153 }
154
155 let parsed = ImageReference::parse(reference)?;
156
157 for candidate in cache_reference_candidates(reference, &parsed) {
158 if self.store.get(&candidate).await.is_some() {
159 let _ = self.store.remove(&candidate).await;
160 }
161 }
162
163 self.pull_and_store(&parsed).await
164 }
165
166 pub async fn is_cached(&self, reference: &str) -> bool {
168 let reference = reference.trim();
169 if is_digest_reference(reference) {
170 return matches!(self.cached_digest_image(reference).await, Ok(Some(_)));
171 }
172
173 let parsed = match ImageReference::parse(reference) {
174 Ok(p) => p,
175 Err(_) => return false,
176 };
177 matches!(self.cached_image(reference, &parsed).await, Ok(Some(_)))
178 }
179
180 pub async fn remove_cached(&self, reference: &str) -> Result<bool> {
182 let reference = reference.trim();
183 if is_digest_reference(reference) {
184 if let Some((matched_reference, _)) = self.cached_digest_image(reference).await? {
185 self.store.remove(&matched_reference).await?;
186 return Ok(true);
187 }
188 return Ok(false);
189 }
190
191 let parsed = ImageReference::parse(reference)?;
192 if let Some((matched_reference, _)) = self.cached_image(reference, &parsed).await? {
193 self.store.remove(&matched_reference).await?;
194 Ok(true)
195 } else {
196 Ok(false)
197 }
198 }
199
200 pub async fn list_cached(&self) -> Result<Vec<String>> {
202 Ok(self
203 .store
204 .list()
205 .await
206 .into_iter()
207 .map(|img| img.reference)
208 .collect())
209 }
210
211 async fn pull_and_store(&self, reference: &ImageReference) -> Result<OciImage> {
213 let full_ref = reference.full_reference();
214
215 let fetch = self.mirror_reference(reference);
218
219 let digest = self.puller.pull_manifest_digest(&fetch).await?;
221
222 if let Some(stored) = self.store.get_by_digest(&digest).await {
224 tracing::info!(
225 reference = %full_ref,
226 digest = %digest,
227 "Image content already cached under different reference"
228 );
229 self.store.put(&full_ref, &digest, &stored.path).await?;
231 return OciImage::from_path(&stored.path);
232 }
233
234 let digest_hex = digest.strip_prefix("sha256:").unwrap_or(&digest);
238 let tmp_dir = self.store.store_dir().join("tmp").join(digest_hex);
239 if tmp_dir.exists() {
240 std::fs::remove_dir_all(&tmp_dir).map_err(|e| {
241 BoxError::OciImageError(format!(
242 "Failed to clean temp directory {}: {}",
243 tmp_dir.display(),
244 e
245 ))
246 })?;
247 }
248
249 let pull_start = std::time::Instant::now();
250 if let Err(e) = self.puller.pull(&fetch, &tmp_dir).await {
255 let _ = std::fs::remove_dir_all(&tmp_dir);
256 return Err(e);
257 }
258 if let Some(ref m) = self.metrics {
259 m.image_pull_total.inc();
260 m.image_pull_duration
261 .observe(pull_start.elapsed().as_secs_f64());
262 }
263
264 let stored = match self.store.put(&full_ref, &digest, &tmp_dir).await {
266 Ok(stored) => stored,
267 Err(e) => {
268 let _ = std::fs::remove_dir_all(&tmp_dir);
269 return Err(e);
270 }
271 };
272
273 if let Err(e) = std::fs::remove_dir_all(&tmp_dir) {
275 tracing::warn!(path = %tmp_dir.display(), error = %e, "Failed to remove temp dir after pull");
276 }
277
278 let evicted = self.store.evict().await?;
280 if !evicted.is_empty() {
281 tracing::info!(
282 count = evicted.len(),
283 references = ?evicted,
284 "Evicted images from cache"
285 );
286 }
287
288 OciImage::from_path(&stored.path)
289 }
290
291 async fn cached_image(
292 &self,
293 reference: &str,
294 parsed: &ImageReference,
295 ) -> Result<Option<(String, StoredImage)>> {
296 for candidate in cache_reference_candidates(reference, parsed) {
297 if let Some(stored) = self.store.get(&candidate).await {
298 return Ok(Some((candidate, stored)));
299 }
300 }
301 if let Some(digest) = parsed.digest.as_deref() {
302 return self.cached_digest_image(digest).await;
303 }
304 Ok(None)
305 }
306
307 async fn cached_digest_image(&self, digest: &str) -> Result<Option<(String, StoredImage)>> {
308 let images = self.store.list().await;
309 let mut matches = Vec::new();
310
311 for image in images {
312 let already_matched = matches
313 .iter()
314 .any(|matched: &StoredImage| matched.reference == image.reference);
315 if (digest_matches(&image.digest, digest) || image.reference == digest)
316 && !already_matched
317 {
318 matches.push(image);
319 }
320 }
321
322 match matches.len() {
323 0 => Ok(None),
324 1 => {
325 let stored = matches.pop().expect("checked one match");
326 let stored = self.store.get(&stored.reference).await.unwrap_or(stored);
327 Ok(Some((stored.reference.clone(), stored)))
328 }
329 _ => Err(BoxError::OciImageError(ambiguous_digest_error(
330 digest, &matches,
331 ))),
332 }
333 }
334}
335
336fn ambiguous_digest_error(query: &str, matches: &[StoredImage]) -> String {
337 let mut references: Vec<_> = matches
338 .iter()
339 .map(|image| image.reference.as_str())
340 .collect();
341 references.sort_unstable();
342 format!(
343 "Image digest '{query}' is ambiguous; it matches: {}",
344 references.join(", ")
345 )
346}
347
348fn is_digest_reference(reference: &str) -> bool {
349 reference.starts_with("sha256:")
350}
351
352fn digest_matches(stored_digest: &str, query: &str) -> bool {
353 if stored_digest == query {
354 return true;
355 }
356 let Some(query_hex) = query.strip_prefix("sha256:") else {
357 return false;
358 };
359 !query_hex.is_empty() && stored_digest.starts_with(query)
360}
361
362fn cache_reference_candidates(reference: &str, parsed: &ImageReference) -> Vec<String> {
363 let mut candidates = Vec::new();
364 push_unique(&mut candidates, reference.trim().to_string());
365 push_unique(&mut candidates, parsed.full_reference());
366
367 if parsed.registry == "docker.io" {
368 let repository = parsed
369 .repository
370 .strip_prefix("library/")
371 .unwrap_or(&parsed.repository);
372 push_unique(
373 &mut candidates,
374 reference_from_repository(repository, parsed.tag.as_deref(), parsed.digest.as_deref()),
375 );
376
377 if parsed.digest.is_none() && parsed.tag.as_deref() == Some("latest") {
378 push_unique(&mut candidates, repository.to_string());
379 }
380 }
381
382 if let Some(digest) = &parsed.digest {
383 push_unique(&mut candidates, digest.clone());
384 }
385
386 candidates
387}
388
389fn reference_from_repository(repository: &str, tag: Option<&str>, digest: Option<&str>) -> String {
390 let mut reference = repository.to_string();
391 if let Some(tag) = tag {
392 reference.push(':');
393 reference.push_str(tag);
394 }
395 if let Some(digest) = digest {
396 reference.push('@');
397 reference.push_str(digest);
398 }
399 reference
400}
401
402fn push_unique(values: &mut Vec<String>, value: String) {
403 if !value.is_empty() && !values.iter().any(|existing| existing == &value) {
404 values.push(value);
405 }
406}
407
408#[async_trait::async_trait]
409impl a3s_box_core::traits::ImageRegistry for ImagePuller {
410 async fn pull(&self, reference: &str) -> Result<a3s_box_core::traits::PulledImage> {
411 let (image, resolved_reference) = self.pull_resolved(reference).await?;
412 Ok(a3s_box_core::traits::PulledImage {
413 path: image.root_dir().to_path_buf(),
414 digest: image.manifest_digest().to_string(),
415 reference: resolved_reference,
416 })
417 }
418
419 async fn force_pull(&self, reference: &str) -> Result<a3s_box_core::traits::PulledImage> {
420 let image = self.force_pull(reference).await?;
421 let parsed = ImageReference::parse(reference)?;
422 Ok(a3s_box_core::traits::PulledImage {
423 path: image.root_dir().to_path_buf(),
424 digest: image.manifest_digest().to_string(),
425 reference: parsed.full_reference(),
426 })
427 }
428
429 async fn is_cached(&self, reference: &str) -> bool {
430 self.is_cached(reference).await
431 }
432
433 async fn remove(&self, reference: &str) -> Result<bool> {
434 self.remove_cached(reference).await
435 }
436
437 async fn list_cached(&self) -> Result<Vec<String>> {
438 self.list_cached().await
439 }
440}
441
442#[cfg(test)]
443mod tests {
444 use super::*;
445 use crate::oci::store::ImageStore;
446 use std::path::Path;
447 use tempfile::TempDir;
448
449 #[test]
450 fn test_image_puller_creation() {
451 let tmp = TempDir::new().unwrap();
452 let store = Arc::new(ImageStore::new(tmp.path(), 10 * 1024 * 1024).unwrap());
453 let _puller = ImagePuller::new(store, RegistryAuth::anonymous());
454 }
455
456 #[tokio::test]
457 async fn test_is_cached_empty_store() {
458 let tmp = TempDir::new().unwrap();
459 let store = Arc::new(ImageStore::new(tmp.path(), 10 * 1024 * 1024).unwrap());
460 let puller = ImagePuller::new(store, RegistryAuth::anonymous());
461 assert!(!puller.is_cached("nginx:latest").await);
462 }
463
464 #[tokio::test]
465 async fn test_is_cached_invalid_reference() {
466 let tmp = TempDir::new().unwrap();
467 let store = Arc::new(ImageStore::new(tmp.path(), 10 * 1024 * 1024).unwrap());
468 let puller = ImagePuller::new(store, RegistryAuth::anonymous());
469 assert!(!puller.is_cached("").await);
470 }
471
472 #[tokio::test]
473 async fn test_is_cached_matches_docker_hub_aliases() {
474 let tmp = TempDir::new().unwrap();
475 let source = TempDir::new().unwrap();
476 create_complete_oci_image(source.path());
477 let store = Arc::new(ImageStore::new(tmp.path(), 10 * 1024 * 1024).unwrap());
478 store
479 .put("alpine:latest", "sha256:manifestxyz789", source.path())
480 .await
481 .unwrap();
482
483 let puller = ImagePuller::new(store, RegistryAuth::anonymous());
484
485 assert!(puller.is_cached("alpine:latest").await);
486 assert!(puller.is_cached("docker.io/library/alpine:latest").await);
487 assert!(puller.is_cached("alpine").await);
488 }
489
490 #[tokio::test]
491 async fn test_pull_uses_cached_short_alias_for_full_reference() {
492 let tmp = TempDir::new().unwrap();
493 let source = TempDir::new().unwrap();
494 create_complete_oci_image(source.path());
495 let store = Arc::new(ImageStore::new(tmp.path(), 10 * 1024 * 1024).unwrap());
496 store
497 .put("alpine:latest", "sha256:manifestxyz789", source.path())
498 .await
499 .unwrap();
500 let puller = ImagePuller::new(store, RegistryAuth::anonymous());
501
502 let image = puller
503 .pull("docker.io/library/alpine:latest")
504 .await
505 .unwrap();
506
507 assert_eq!(image.manifest_digest(), "sha256:manifestxyz789");
508 }
509
510 #[tokio::test]
511 async fn test_pull_uses_cached_digest_reference_without_registry_parse() {
512 let tmp = TempDir::new().unwrap();
513 let source = TempDir::new().unwrap();
514 create_complete_oci_image(source.path());
515 let store = Arc::new(ImageStore::new(tmp.path(), 10 * 1024 * 1024).unwrap());
516 store
517 .put("alpine:latest", "sha256:manifestxyz789", source.path())
518 .await
519 .unwrap();
520 let puller = ImagePuller::new(store, RegistryAuth::anonymous());
521
522 let image = puller.pull("sha256:manifestxyz789").await.unwrap();
523
524 assert_eq!(image.manifest_digest(), "sha256:manifestxyz789");
525 }
526
527 #[tokio::test]
528 async fn test_is_cached_matches_digest_prefix() {
529 let tmp = TempDir::new().unwrap();
530 let source = TempDir::new().unwrap();
531 create_complete_oci_image(source.path());
532 let store = Arc::new(ImageStore::new(tmp.path(), 10 * 1024 * 1024).unwrap());
533 store
534 .put("alpine:latest", "sha256:manifestxyz789", source.path())
535 .await
536 .unwrap();
537 let puller = ImagePuller::new(store, RegistryAuth::anonymous());
538
539 assert!(puller.is_cached("sha256:manifest").await);
540 }
541
542 #[tokio::test]
543 async fn test_pull_reports_missing_digest_reference_as_local_cache_miss() {
544 let tmp = TempDir::new().unwrap();
545 let store = Arc::new(ImageStore::new(tmp.path(), 10 * 1024 * 1024).unwrap());
546 let puller = ImagePuller::new(store, RegistryAuth::anonymous());
547
548 let error = puller.pull("sha256:notfound").await.unwrap_err();
549
550 assert!(error.to_string().contains("not found in local cache"));
551 }
552
553 #[tokio::test]
554 async fn test_pull_reports_ambiguous_digest_prefix() {
555 let tmp = TempDir::new().unwrap();
556 let source = TempDir::new().unwrap();
557 create_complete_oci_image(source.path());
558 let store = Arc::new(ImageStore::new(tmp.path(), 10 * 1024 * 1024).unwrap());
559 store
560 .put("alpine:latest", "sha256:manifestaaa", source.path())
561 .await
562 .unwrap();
563 store
564 .put("busybox:latest", "sha256:manifestbbb", source.path())
565 .await
566 .unwrap();
567 let puller = ImagePuller::new(store, RegistryAuth::anonymous());
568
569 let error = puller.pull("sha256:manifest").await.unwrap_err();
570
571 assert!(error.to_string().contains("ambiguous"));
572 assert!(error.to_string().contains("alpine:latest"));
573 assert!(error.to_string().contains("busybox:latest"));
574 }
575
576 #[tokio::test]
577 async fn test_remove_cached_matches_docker_hub_alias() {
578 let tmp = TempDir::new().unwrap();
579 let source = TempDir::new().unwrap();
580 create_complete_oci_image(source.path());
581 let store = Arc::new(ImageStore::new(tmp.path(), 10 * 1024 * 1024).unwrap());
582 store
583 .put("alpine:latest", "sha256:manifestxyz789", source.path())
584 .await
585 .unwrap();
586 let puller = ImagePuller::new(store.clone(), RegistryAuth::anonymous());
587
588 assert!(puller
589 .remove_cached("docker.io/library/alpine:latest")
590 .await
591 .unwrap());
592 assert!(store.get("alpine:latest").await.is_none());
593 }
594
595 #[test]
596 fn test_set_metrics_attaches_to_puller() {
597 let tmp = TempDir::new().unwrap();
598 let store = Arc::new(ImageStore::new(tmp.path(), 10 * 1024 * 1024).unwrap());
599 let metrics = crate::prom::RuntimeMetrics::new();
600 let puller =
602 ImagePuller::new(store, RegistryAuth::anonymous()).set_metrics(metrics.clone());
603 assert!(puller.metrics.is_some());
604 assert_eq!(metrics.image_pull_total.get(), 0);
605 assert_eq!(metrics.image_pull_duration.get_sample_count(), 0);
606 }
607
608 #[test]
609 fn test_cache_reference_candidates_include_short_docker_hub_aliases() {
610 let parsed = ImageReference::parse("docker.io/library/alpine:latest").unwrap();
611 let candidates = cache_reference_candidates("docker.io/library/alpine:latest", &parsed);
612
613 assert_eq!(
614 candidates,
615 vec![
616 "docker.io/library/alpine:latest".to_string(),
617 "alpine:latest".to_string(),
618 "alpine".to_string(),
619 ]
620 );
621 }
622
623 #[test]
624 fn test_digest_matches_exact_and_prefix_queries() {
625 assert!(digest_matches("sha256:abcdef123456", "sha256:abcdef123456"));
626 assert!(digest_matches("sha256:abcdef123456", "sha256:abcdef"));
627 assert!(!digest_matches("sha256:abcdef123456", "sha256:"));
628 assert!(!digest_matches("sha256:abcdef123456", "abcdef"));
629 }
630
631 fn create_complete_oci_image(path: &Path) {
632 std::fs::create_dir_all(path.join("blobs/sha256")).unwrap();
633 std::fs::write(path.join("oci-layout"), r#"{"imageLayoutVersion":"1.0.0"}"#).unwrap();
634
635 let config_content = r#"{
636 "architecture": "amd64",
637 "os": "linux",
638 "config": {
639 "Entrypoint": ["/bin/sh"],
640 "Cmd": ["-c", "true"],
641 "Env": ["PATH=/usr/bin:/bin"],
642 "WorkingDir": "/"
643 },
644 "rootfs": {
645 "type": "layers",
646 "diff_ids": ["sha256:layerdiff"]
647 },
648 "history": []
649 }"#;
650 let config_hash = "configabc123";
651 std::fs::write(path.join("blobs/sha256").join(config_hash), config_content).unwrap();
652
653 let layer_hash = "layerdef456";
654 std::fs::write(path.join("blobs/sha256").join(layer_hash), b"layer").unwrap();
655
656 let manifest_content = format!(
657 r#"{{
658 "schemaVersion": 2,
659 "mediaType": "application/vnd.oci.image.manifest.v1+json",
660 "config": {{
661 "mediaType": "application/vnd.oci.image.config.v1+json",
662 "digest": "sha256:{}",
663 "size": {}
664 }},
665 "layers": [
666 {{
667 "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip",
668 "digest": "sha256:{}",
669 "size": 5
670 }}
671 ]
672 }}"#,
673 config_hash,
674 config_content.len(),
675 layer_hash
676 );
677 let manifest_hash = "manifestxyz789";
678 std::fs::write(
679 path.join("blobs/sha256").join(manifest_hash),
680 &manifest_content,
681 )
682 .unwrap();
683
684 let index_content = format!(
685 r#"{{
686 "schemaVersion": 2,
687 "mediaType": "application/vnd.oci.image.index.v1+json",
688 "manifests": [
689 {{
690 "mediaType": "application/vnd.oci.image.manifest.v1+json",
691 "digest": "sha256:{}",
692 "size": {}
693 }}
694 ]
695 }}"#,
696 manifest_hash,
697 manifest_content.len()
698 );
699 std::fs::write(path.join("index.json"), index_content).unwrap();
700 }
701}