use crate::cache::BlobCacheBackend;
use crate::error::{RegistryError, Result};
use crate::image_config::{ImageConfig, OciImageConfigRoot};
use crate::wasm::{detect_artifact_type, extract_wasm_info, ArtifactType, WasmArtifactInfo};
use futures_util::stream::{StreamExt, TryStreamExt};
use oci_client::{
client::{ClientConfig, ClientProtocol},
manifest::{ImageIndexEntry, OciImageIndex, OciImageManifest, OciManifest},
secrets::RegistryAuth,
Reference, RegistryOperation,
};
use std::sync::Arc;
use thiserror::Error;
use tokio::sync::Semaphore;
use tracing::instrument;
const LAYER_PULL_CONCURRENCY: usize = 8;
use zlayer_spec::PullPolicy;
const S3_TIER_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
type WarmSlot = tokio::sync::OnceCell<std::result::Result<(OciImageManifest, String), String>>;
type ConfigSlot = tokio::sync::OnceCell<std::result::Result<ImageConfig, String>>;
static PULL_SINGLEFLIGHT: std::sync::OnceLock<
tokio::sync::Mutex<std::collections::HashMap<String, std::sync::Weak<WarmSlot>>>,
> = std::sync::OnceLock::new();
fn pull_singleflight(
) -> &'static tokio::sync::Mutex<std::collections::HashMap<String, std::sync::Weak<WarmSlot>>> {
PULL_SINGLEFLIGHT.get_or_init(|| tokio::sync::Mutex::new(std::collections::HashMap::new()))
}
static CONFIG_SINGLEFLIGHT: std::sync::OnceLock<
tokio::sync::Mutex<std::collections::HashMap<String, std::sync::Weak<ConfigSlot>>>,
> = std::sync::OnceLock::new();
fn config_singleflight(
) -> &'static tokio::sync::Mutex<std::collections::HashMap<String, std::sync::Weak<ConfigSlot>>> {
CONFIG_SINGLEFLIGHT.get_or_init(|| tokio::sync::Mutex::new(std::collections::HashMap::new()))
}
#[cfg(feature = "local")]
use crate::wasm_export::WasmExportResult;
#[must_use]
fn canonical_manifest_ref(image: &str) -> String {
use std::str::FromStr;
match oci_client::Reference::from_str(image) {
Ok(reference) => reference.whole(),
Err(_) => image.to_string(),
}
}
#[must_use]
pub fn manifest_cache_key(image: &str) -> String {
format!("manifest:{}", canonical_manifest_ref(image))
}
#[must_use]
pub fn manifest_digest_cache_key(image: &str) -> String {
format!("manifest:digest-{}", canonical_manifest_ref(image))
}
#[must_use]
pub fn manifest_orig_cache_key(image: &str) -> String {
format!("manifest-orig:{}", canonical_manifest_ref(image))
}
#[derive(Debug, Error)]
pub enum PushError {
#[error("authentication failed for registry {registry}: {reason}")]
AuthenticationFailed {
registry: String,
reason: String,
},
#[error("failed to upload blob {digest}: {reason}")]
BlobUploadFailed {
digest: String,
reason: String,
},
#[error("failed to upload manifest: {reason}")]
ManifestUploadFailed {
reason: String,
},
#[error("network error: {0}")]
NetworkError(String),
#[error("invalid image reference: {reference}")]
InvalidReference {
reference: String,
},
#[error("OCI distribution error: {0}")]
OciError(#[from] oci_client::errors::OciDistributionError),
}
#[derive(Debug, Clone)]
pub struct PushResult {
pub manifest_digest: String,
pub blobs_pushed: Vec<String>,
pub reference: String,
}
#[cfg(feature = "local")]
#[derive(Debug, Clone)]
pub struct ArtifactLayer {
pub data: Vec<u8>,
pub media_type: String,
pub title: Option<String>,
}
#[cfg(feature = "local")]
#[must_use]
pub fn oci_sha256_digest(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(bytes);
format!("sha256:{}", hex::encode(hasher.finalize()))
}
pub(crate) fn go_arch_name() -> &'static str {
match std::env::consts::ARCH {
"x86_64" => "amd64",
"x86" => "amd",
"aarch64" => "arm64",
"powerpc64" => "ppc64le",
other => other,
}
}
pub(crate) fn go_os_name() -> &'static str {
match std::env::consts::OS {
"macos" => "darwin",
other => other,
}
}
fn is_mutable_tag(image: &str) -> bool {
let (without_digest, had_digest) = match image.find('@') {
Some(idx) => (&image[..idx], true),
None => (image, false),
};
if had_digest {
return false;
}
let tag = match without_digest.rfind(':') {
Some(idx) => {
let candidate = &without_digest[idx + 1..];
if candidate.contains('/') {
None
} else {
Some(candidate)
}
}
None => None,
};
match tag {
None | Some("") => true,
Some(t) => matches!(t, "latest" | "dev" | "edge" | "main" | "master"),
}
}
#[cfg(feature = "local")]
fn local_image_ref_candidates(image: &str) -> Vec<(String, String)> {
zlayer_types::image_ref_candidates(image)
}
#[cfg(all(test, feature = "local"))]
mod local_image_ref_candidates_tests {
use super::local_image_ref_candidates;
fn contains(candidates: &[(String, String)], name: &str, reference: &str) -> bool {
candidates.iter().any(|(n, r)| n == name && r == reference)
}
#[test]
fn bare_name_with_tag_produces_library_and_self() {
let c = local_image_ref_candidates("zarcrunner-executor:latest");
assert!(
contains(&c, "zarcrunner-executor", "latest"),
"missing bare candidate in {c:?}",
);
assert!(
contains(&c, "library/zarcrunner-executor", "latest"),
"missing library/ candidate in {c:?}",
);
}
#[test]
fn fully_qualified_docker_hub_strips_prefixes() {
let c = local_image_ref_candidates("docker.io/library/zarcrunner-executor:latest");
assert!(
contains(&c, "docker.io/library/zarcrunner-executor", "latest"),
"missing primary in {c:?}",
);
assert!(
contains(&c, "library/zarcrunner-executor", "latest"),
"missing docker.io-stripped form in {c:?}",
);
assert!(
contains(&c, "zarcrunner-executor", "latest"),
"missing docker.io/library-stripped form in {c:?}",
);
}
#[test]
fn ghcr_keeps_qualified_and_bare_segment_but_no_library_prefix() {
let c = local_image_ref_candidates("ghcr.io/team/svc:1.2");
assert!(
contains(&c, "ghcr.io/team/svc", "1.2"),
"missing primary in {c:?}",
);
assert!(
contains(&c, "svc", "1.2"),
"missing bare last-segment fallback in {c:?}",
);
assert!(
!c.iter().any(|(n, _)| n.starts_with("library/")),
"unexpected library/ prefix in {c:?}",
);
}
#[test]
fn digest_reference_is_preserved() {
let digest = "sha256:0000000000000000000000000000000000000000000000000000000000000000";
let input = format!("foo@{digest}");
let c = local_image_ref_candidates(&input);
assert!(
contains(&c, "foo", digest),
"missing foo@digest candidate in {c:?}",
);
assert!(
contains(&c, "library/foo", digest),
"missing library/foo@digest candidate in {c:?}",
);
for (_, r) in &c {
assert_eq!(r, digest, "non-digest reference leaked into {c:?}");
}
}
#[test]
fn deterministic_input_has_no_duplicates() {
for input in [
"zarcrunner-executor:latest",
"docker.io/library/zarcrunner-executor:latest",
"ghcr.io/team/svc:1.2",
"foo",
"library/foo:1.0",
"foo@sha256:0000000000000000000000000000000000000000000000000000000000000000",
] {
let c = local_image_ref_candidates(input);
let mut sorted: Vec<_> = c.clone();
sorted.sort();
let original_len = sorted.len();
sorted.dedup();
assert_eq!(
original_len,
sorted.len(),
"duplicate candidates produced for {input}: {c:?}",
);
}
}
}
fn build_platform_resolver(
target: Option<zlayer_spec::TargetPlatform>,
) -> impl Fn(&[ImageIndexEntry]) -> Option<String> + Send + Sync + 'static {
let has_target = target.is_some();
let (target_os, target_arch, target_os_version): (String, String, Option<String>) = match target
{
Some(tp) => (
tp.os.as_oci_str().to_string(),
tp.arch.as_oci_str().to_string(),
tp.os_version,
),
None => (go_os_name().to_string(), go_arch_name().to_string(), None),
};
let use_macos_fallback = !has_target && cfg!(target_os = "macos");
move |manifests: &[ImageIndexEntry]| -> Option<String> {
if target_os == "windows" {
if let Some(want_version) = target_os_version.as_deref() {
if let Some(entry) = manifests.iter().find(|entry| {
entry.platform.as_ref().is_some_and(|p| {
p.os == target_os
&& p.architecture == target_arch
&& p.os_version
.as_deref()
.is_some_and(|v| v == want_version || v.starts_with(want_version))
})
}) {
return Some(entry.digest.clone());
}
}
}
if let Some(entry) = manifests.iter().find(|entry| {
entry
.platform
.as_ref()
.is_some_and(|p| p.os == target_os && p.architecture == target_arch)
}) {
return Some(entry.digest.clone());
}
if use_macos_fallback {
return manifests
.iter()
.find(|entry| {
entry
.platform
.as_ref()
.is_some_and(|p| p.os == "linux" && p.architecture == target_arch)
})
.map(|entry| entry.digest.clone());
}
None
}
}
fn parse_image_manifest_only(data: &[u8]) -> Option<OciImageManifest> {
match serde_json::from_slice::<OciManifest>(data).ok()? {
OciManifest::Image(manifest) => Some(manifest),
OciManifest::ImageIndex(_) => None,
}
}
fn build_client_config(target: Option<zlayer_spec::TargetPlatform>) -> ClientConfig {
ClientConfig {
protocol: ClientProtocol::Https,
connect_timeout: Some(std::time::Duration::from_secs(30)),
read_timeout: Some(std::time::Duration::from_secs(300)), platform_resolver: Some(Box::new(build_platform_resolver(target))),
..Default::default()
}
}
pub struct ImagePuller {
client: oci_client::Client,
cache: Arc<Box<dyn BlobCacheBackend>>,
concurrency_limit: Arc<Semaphore>,
network_calls: Arc<std::sync::atomic::AtomicUsize>,
s3_cache: Option<Arc<Box<dyn BlobCacheBackend>>>,
default_registry: Option<String>,
source_policy: zlayer_spec::SourcePolicy,
#[cfg(feature = "local")]
target: Option<zlayer_spec::TargetPlatform>,
#[cfg(feature = "local")]
local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
}
impl ImagePuller {
pub fn new<C: BlobCacheBackend + 'static>(cache: C) -> Self {
let client = oci_client::Client::new(build_client_config(None));
Self {
client,
cache: Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>),
concurrency_limit: Arc::new(Semaphore::new(3)),
network_calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
s3_cache: None,
default_registry: None,
source_policy: zlayer_spec::SourcePolicy::LocalFirst,
#[cfg(feature = "local")]
target: None,
#[cfg(feature = "local")]
local_registry: None,
}
}
#[must_use]
pub fn with_cache(cache: Arc<Box<dyn BlobCacheBackend>>) -> Self {
let client = oci_client::Client::new(build_client_config(None));
Self {
client,
cache,
concurrency_limit: Arc::new(Semaphore::new(3)),
network_calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
s3_cache: None,
default_registry: None,
source_policy: zlayer_spec::SourcePolicy::LocalFirst,
#[cfg(feature = "local")]
target: None,
#[cfg(feature = "local")]
local_registry: None,
}
}
#[must_use]
pub fn with_platform(
cache: Arc<Box<dyn BlobCacheBackend>>,
target: zlayer_spec::TargetPlatform,
) -> Self {
#[cfg(feature = "local")]
let client = oci_client::Client::new(build_client_config(Some(target.clone())));
#[cfg(not(feature = "local"))]
let client = oci_client::Client::new(build_client_config(Some(target)));
Self {
client,
cache,
concurrency_limit: Arc::new(Semaphore::new(3)),
network_calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
s3_cache: None,
default_registry: None,
source_policy: zlayer_spec::SourcePolicy::LocalFirst,
#[cfg(feature = "local")]
target: Some(target),
#[cfg(feature = "local")]
local_registry: None,
}
}
fn note_network_call(&self) {
self.network_calls
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
#[cfg(test)]
fn network_call_count(&self) -> usize {
self.network_calls
.load(std::sync::atomic::Ordering::Relaxed)
}
async fn store_auth(&self, image: &str, auth: &RegistryAuth) -> Result<()> {
let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
registry: "unknown".to_string(),
image: image.to_string(),
})?;
self.client
.store_auth_if_needed(reference.resolve_registry(), auth)
.await;
Ok(())
}
#[must_use]
pub fn with_concurrency_limit(mut self, limit: usize) -> Self {
self.concurrency_limit = Arc::new(Semaphore::new(limit));
self
}
#[must_use]
pub fn with_s3_cache(mut self, s3: Arc<Box<dyn BlobCacheBackend>>) -> Self {
self.s3_cache = Some(s3);
self
}
async fn s3_tier_get(&self, key: &str) -> Option<Vec<u8>> {
let s3 = self.s3_cache.as_ref()?;
match tokio::time::timeout(S3_TIER_READ_TIMEOUT, s3.get(key)).await {
Ok(Ok(data)) => data,
Ok(Err(e)) => {
tracing::debug!(key = %key, error = %e, "S3 tier read failed; treating as cache miss");
None
}
Err(_elapsed) => {
tracing::warn!(
key = %key,
timeout_secs = S3_TIER_READ_TIMEOUT.as_secs(),
"S3 tier read timed out (endpoint unreachable?); treating as cache miss and \
falling through to origin/local"
);
None
}
}
}
#[must_use]
pub fn with_default_registry(mut self, registry: impl Into<String>) -> Self {
let host = registry.into();
self.default_registry = if host.trim().is_empty() {
None
} else {
Some(host)
};
self
}
#[must_use]
pub fn with_source_policy(mut self, source: zlayer_spec::SourcePolicy) -> Self {
self.source_policy = source;
self
}
pub async fn from_env_for_runtime(
cache: Arc<Box<dyn BlobCacheBackend>>,
source: zlayer_spec::SourcePolicy,
) -> Self {
let mut puller = Self::with_cache(cache).with_source_policy(source);
match crate::cache_config::s3_cache_from_env().await {
Ok(Some(s3)) => puller = puller.with_s3_cache(s3),
Ok(None) => {}
Err(e) => {
tracing::warn!(error = %e, "S3 cache tier configured but failed to initialize; continuing without it");
}
}
if let Some(default_registry) = crate::cache_config::default_registry_from_env() {
puller = puller.with_default_registry(default_registry);
}
puller
}
#[cfg(feature = "local")]
#[must_use]
pub fn with_local_registry(
mut self,
registry: std::sync::Arc<crate::local_registry::LocalRegistry>,
) -> Self {
self.local_registry = Some(registry);
self
}
pub async fn pull_blob(
&self,
image: &str,
digest: &str,
auth: &RegistryAuth,
) -> Result<Vec<u8>> {
self.pull_blob_with_urls(image, digest, auth, &[], None)
.await
}
pub async fn pull_blob_with_urls(
&self,
image: &str,
digest: &str,
auth: &RegistryAuth,
urls: &[String],
expected_size: Option<i64>,
) -> Result<Vec<u8>> {
if let Some(data) = self.cache.get(digest).await? {
tracing::debug!(digest = %digest, "blob found in cache");
return Ok(data);
}
if let Some(data) = self.s3_tier_get(digest).await {
tracing::debug!(digest = %digest, "blob found in S3 tier; warming local cache");
let _ = self.cache.put(digest, &data).await;
return Ok(data);
}
#[cfg(feature = "local")]
if let Some(registry) = &self.local_registry {
if let Ok(data) = registry.get_blob(digest).await {
if !data.is_empty() {
tracing::debug!(
digest = %digest,
"blob found in local registry; warming local cache"
);
let _ = self.cache.put(digest, &data).await;
return Ok(data);
}
}
}
self.store_auth(image, auth).await?;
let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
registry: "unknown".to_string(),
image: image.to_string(),
})?;
let _permit = self.concurrency_limit.acquire().await.unwrap();
tracing::debug!(digest = %digest, image = %image, "pulling blob from registry");
let mut buffer = Vec::new();
let primary_result = self.client.pull_blob(&reference, digest, &mut buffer).await;
let buffer = match primary_result {
Ok(()) => buffer,
Err(err) if is_blob_not_found(&err) && !urls.is_empty() => {
tracing::info!(
digest = %digest,
urls_count = urls.len(),
"primary registry missed foreign layer; attempting urls[] redirects"
);
let mut last_err: Option<RegistryError> = None;
let mut recovered: Option<Vec<u8>> = None;
for url in urls.iter().take(MAX_FOREIGN_LAYER_REDIRECTS) {
match fetch_blob_from_url(url, digest, expected_size).await {
Ok(bytes) => {
tracing::info!(url = %url, "foreign layer recovered via redirect");
recovered = Some(bytes);
break;
}
Err(e) => {
tracing::warn!(url = %url, error = %e, "redirect attempt failed");
last_err = Some(e);
}
}
}
if let Some(bytes) = recovered {
bytes
} else {
tracing::error!(
digest = %digest,
image = %image,
"foreign layer redirect fallback exhausted"
);
return Err(last_err.unwrap_or(RegistryError::Oci(err)));
}
}
Err(err) => {
tracing::error!(error = %err, digest = %digest, image = %image, "failed to pull blob from registry");
return Err(RegistryError::Oci(err));
}
};
if buffer.is_empty() {
return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
format!("blob {digest} was empty after pulling from registry"),
)));
}
self.cache.put(digest, &buffer).await?;
if let Some(s3) = &self.s3_cache {
if let Err(e) = s3.put(digest, &buffer).await {
tracing::debug!(digest = %digest, error = %e, "failed to propagate blob to S3 tier");
}
}
tracing::debug!(digest = %digest, size = buffer.len(), "blob cached successfully");
Ok(buffer)
}
#[allow(clippy::too_many_lines)]
pub async fn pull_blob_to_file(
&self,
image: &str,
digest: &str,
auth: &RegistryAuth,
urls: &[String],
expected_size: Option<i64>,
staging_dir: &std::path::Path,
) -> Result<std::path::PathBuf> {
tokio::fs::create_dir_all(staging_dir)
.await
.map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
let dest = staging_dir.join(blob_staging_filename(digest));
if let Some(path) = self.cache.get_path(digest).await? {
tracing::debug!(digest = %digest, "blob found in cache (file-backed); linking into stage");
link_or_copy(&path, &dest).await?;
return Ok(dest);
}
if let Some(data) = self.cache.get(digest).await? {
tracing::debug!(digest = %digest, "blob found in cache (inline); writing into stage");
tokio::fs::write(&dest, &data)
.await
.map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
return Ok(dest);
}
if let Some(data) = self.s3_tier_get(digest).await {
tracing::debug!(digest = %digest, "blob found in S3 tier; staging + warming local cache");
tokio::fs::write(&dest, &data)
.await
.map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
let _ = self.cache.put_path(digest, &dest).await;
return Ok(dest);
}
#[cfg(feature = "local")]
if let Some(registry) = &self.local_registry {
if let Ok(data) = registry.get_blob(digest).await {
if !data.is_empty() {
tracing::debug!(digest = %digest, "blob found in local registry; staging + warming local cache");
tokio::fs::write(&dest, &data)
.await
.map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
let _ = self.cache.put_path(digest, &dest).await;
return Ok(dest);
}
}
}
self.store_auth(image, auth).await?;
let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
registry: "unknown".to_string(),
image: image.to_string(),
})?;
let _permit = self.concurrency_limit.acquire().await.unwrap();
tracing::debug!(digest = %digest, image = %image, "streaming blob from registry to file");
let seq = BLOB_PART_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let tmp = staging_dir.join(format!(
"{}.part.{}.{}",
blob_staging_filename(digest),
std::process::id(),
seq
));
let make_writer = || async {
let file = tokio::fs::File::create(&tmp)
.await
.map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
Ok::<_, RegistryError>(HashingFileWriter::new(file))
};
let mut writer = make_writer().await?;
let primary = self.client.pull_blob(&reference, digest, &mut writer).await;
let final_writer = match primary {
Ok(()) => writer,
Err(err) if is_blob_not_found(&err) && !urls.is_empty() => {
tracing::info!(
digest = %digest,
urls_count = urls.len(),
"primary registry missed foreign layer; streaming urls[] redirects"
);
drop(writer);
let mut recovered: Option<HashingFileWriter> = None;
let mut last_err: Option<RegistryError> = None;
for url in urls.iter().take(MAX_FOREIGN_LAYER_REDIRECTS) {
let mut w = make_writer().await?;
match fetch_blob_from_url_to_writer(url, expected_size, &mut w).await {
Ok(()) => {
tracing::info!(url = %url, "foreign layer recovered via redirect");
recovered = Some(w);
break;
}
Err(e) => {
tracing::warn!(url = %url, error = %e, "redirect attempt failed");
last_err = Some(e);
}
}
}
if let Some(w) = recovered {
w
} else {
let _ = tokio::fs::remove_file(&tmp).await;
tracing::error!(digest = %digest, image = %image, "foreign layer redirect fallback exhausted");
return Err(last_err.unwrap_or(RegistryError::Oci(err)));
}
}
Err(err) => {
let _ = tokio::fs::remove_file(&tmp).await;
tracing::error!(error = %err, digest = %digest, image = %image, "failed to stream blob from registry");
return Err(RegistryError::Oci(err));
}
};
let (actual_digest, written) = final_writer.finalize().await?;
if written == 0 {
let _ = tokio::fs::remove_file(&tmp).await;
return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
format!("blob {digest} was empty after pulling from registry"),
)));
}
if !actual_digest.eq_ignore_ascii_case(digest) {
let _ = tokio::fs::remove_file(&tmp).await;
return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
format!("digest mismatch: expected {digest}, got {actual_digest}"),
)));
}
if let Some(expected) = expected_size {
if let Ok(expected_u) = u64::try_from(expected) {
if written != expected_u {
let _ = tokio::fs::remove_file(&tmp).await;
return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
format!(
"blob {digest}: size mismatch (expected {expected}, got {written})"
),
)));
}
}
}
tokio::fs::rename(&tmp, &dest)
.await
.map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
if let Err(e) = self.cache.put_path(digest, &dest).await {
tracing::debug!(digest = %digest, error = %e, "failed to ingest streamed blob into cache");
}
if let Some(s3) = &self.s3_cache {
if let Err(e) = s3.put_path(digest, &dest).await {
tracing::debug!(digest = %digest, error = %e, "failed to propagate blob to S3 tier");
}
}
tracing::debug!(digest = %digest, size = written, "blob streamed to file successfully");
Ok(dest)
}
pub async fn pull_image_to_files(
&self,
image: &str,
auth: &RegistryAuth,
staging_dir: &std::path::Path,
) -> Result<Vec<(std::path::PathBuf, String)>> {
self.pull_image_to_files_inner(image, auth, staging_dir, PullPolicy::Newer)
.await
}
pub async fn pull_image_to_files_with_policy(
&self,
image: &str,
auth: &RegistryAuth,
staging_dir: &std::path::Path,
policy: PullPolicy,
) -> Result<Vec<(std::path::PathBuf, String)>> {
self.pull_image_to_files_inner(image, auth, staging_dir, policy)
.await
}
fn pull_singleflight_key(&self, image: &str, policy: PullPolicy) -> String {
let cache_id = Arc::as_ptr(&self.cache) as usize;
format!(
"{cache_id:x}|{:?}|{:?}|{}",
policy,
self.source_policy,
canonical_manifest_ref(image),
)
}
async fn pull_image_to_files_inner(
&self,
image: &str,
auth: &RegistryAuth,
staging_dir: &std::path::Path,
policy: PullPolicy,
) -> Result<Vec<(std::path::PathBuf, String)>> {
let key = self.pull_singleflight_key(image, policy);
let (slot, is_leader) = {
let mut map = pull_singleflight().lock().await;
if let Some(existing) = map.get(&key).and_then(std::sync::Weak::upgrade) {
(existing, false)
} else {
let fresh: Arc<WarmSlot> = Arc::new(tokio::sync::OnceCell::new());
map.insert(key.clone(), Arc::downgrade(&fresh));
(fresh, true)
}
};
let mut leader_layers: Option<Result<Vec<(std::path::PathBuf, String)>>> = None;
let shared = slot
.get_or_init(|| async {
match self.pull_manifest_inner(image, auth, policy).await {
Ok((manifest, digest)) => {
leader_layers = Some(
self.materialize_layers_to_files(image, auth, staging_dir, &manifest)
.await,
);
Ok((manifest, digest))
}
Err(e) => Err(e.to_string()),
}
})
.await;
if is_leader {
pull_singleflight().lock().await.remove(&key);
}
if let Some(result) = leader_layers {
return result;
}
match shared {
Ok((manifest, _digest)) => {
self.materialize_layers_to_files(image, auth, staging_dir, manifest)
.await
}
Err(msg) => {
Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
format!("image warm failed for {image}: {msg}"),
)))
}
}
}
async fn materialize_layers_to_files(
&self,
image: &str,
auth: &RegistryAuth,
staging_dir: &std::path::Path,
manifest: &OciImageManifest,
) -> Result<Vec<(std::path::PathBuf, String)>> {
tracing::info!(
image = %image,
layer_count = manifest.layers.len(),
"pulling image layers (streamed to files)"
);
let layer_inputs: Vec<(usize, String, String, Vec<String>, i64)> = manifest
.layers
.iter()
.enumerate()
.map(|(i, l)| {
(
i,
l.digest.clone(),
l.media_type.clone(),
l.urls.clone().unwrap_or_default(),
l.size,
)
})
.collect();
let layers: Vec<(std::path::PathBuf, String)> =
futures_util::stream::iter(layer_inputs.into_iter().map(
|(i, digest, media_type, urls, size)| async move {
tracing::debug!(
layer = i,
digest = %digest,
media_type = %media_type,
size,
"streaming layer to file"
);
let path = self
.pull_blob_to_file(image, &digest, auth, &urls, Some(size), staging_dir)
.await?;
Ok::<(std::path::PathBuf, String), RegistryError>((path, media_type))
},
))
.buffered(LAYER_PULL_CONCURRENCY)
.try_collect()
.await?;
tracing::info!(image = %image, layers_pulled = layers.len(), "image pull complete (streamed)");
Ok(layers)
}
pub async fn remote_manifest_digest(
&self,
image: &str,
auth: &RegistryAuth,
) -> Result<Option<String>> {
let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
registry: "unknown".to_string(),
image: image.to_string(),
})?;
self.note_network_call();
match self.client.fetch_manifest_digest(&reference, auth).await {
Ok(digest) => Ok(Some(digest)),
Err(oci_client::errors::OciDistributionError::ImageManifestNotFoundError(_)) => {
tracing::debug!(image = %image, "remote manifest not found");
Ok(None)
}
Err(e) => {
tracing::warn!(error = %e, image = %image, "failed to fetch remote manifest digest");
Err(RegistryError::Oci(e))
}
}
}
async fn try_cached_manifest(
&self,
image: &str,
auth: &RegistryAuth,
cache_key: &str,
digest_key: &str,
policy: PullPolicy,
) -> Option<(OciImageManifest, String)> {
let data = self.cache.get(cache_key).await.ok().flatten()?;
let manifest = parse_image_manifest_only(&data)?;
let cached_digest = self
.cache
.get(digest_key)
.await
.ok()
.flatten()
.and_then(|bytes| String::from_utf8(bytes).ok());
if matches!(policy, PullPolicy::IfNotPresent | PullPolicy::Never) {
let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
tracing::debug!(image = %image, "manifest cache hit (IfNotPresent/Never, no revalidation)");
return Some((manifest, digest));
}
if !is_mutable_tag(image) {
let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
tracing::debug!(image = %image, "manifest cache hit (pinned ref)");
return Some((manifest, digest));
}
match self.remote_manifest_digest(image, auth).await {
Ok(Some(remote_digest)) => {
if let Some(cached) = cached_digest.as_deref() {
if cached == remote_digest {
tracing::debug!(image = %image, "manifest cache hit (revalidated)");
return Some((manifest, remote_digest));
}
tracing::info!(
image = %image,
cached = %cached,
remote = %remote_digest,
"cached manifest is stale, refetching"
);
} else {
tracing::info!(
image = %image,
remote = %remote_digest,
"cached manifest has no stored digest, refetching"
);
}
if let Err(e) = self.cache.delete(cache_key).await {
tracing::warn!(
image = %image,
error = %e,
"failed to delete stale manifest cache entry"
);
}
if let Err(e) = self.cache.delete(digest_key).await {
tracing::warn!(
image = %image,
error = %e,
"failed to delete stale manifest digest cache entry"
);
}
None
}
Ok(None) => {
tracing::warn!(image = %image, "remote manifest not found, using stale cache");
let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
Some((manifest, digest))
}
Err(e) => {
tracing::warn!(
image = %image,
error = %e,
"manifest revalidation failed, using stale cache"
);
let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
Some((manifest, digest))
}
}
}
#[cfg(feature = "local")]
async fn resolve_stored_manifest(
&self,
registry: &crate::local_registry::LocalRegistry,
name: &str,
data: &[u8],
) -> Option<(OciImageManifest, String)> {
match serde_json::from_slice::<OciManifest>(data).ok()? {
OciManifest::Image(manifest) => Some((manifest, crate::cache::compute_digest(data))),
OciManifest::ImageIndex(index) => {
let resolver = build_platform_resolver(self.target.clone());
let selected = resolver(&index.manifests)?;
let sub = registry.get_manifest(name, &selected).await.ok()?;
let manifest = serde_json::from_slice::<OciImageManifest>(&sub).ok()?;
tracing::debug!(
name = %name,
index_digest = %crate::cache::compute_digest(data),
selected = %selected,
"resolved stored OCI image index to its platform-specific manifest",
);
Some((manifest, crate::cache::compute_digest(&sub)))
}
}
}
#[cfg(feature = "local")]
async fn try_local_registry(&self, image: &str) -> Option<(OciImageManifest, String)> {
let registry = self.local_registry.as_ref()?;
let candidates = local_image_ref_candidates(image);
let primary = candidates.first().map(|(n, _)| n.clone());
for (name, reference) in candidates {
if let Ok(data) = registry.get_manifest(&name, &reference).await {
if let Some((manifest, digest)) =
self.resolve_stored_manifest(registry, &name, &data).await
{
if primary.as_deref() == Some(name.as_str()) {
tracing::debug!(
image = %image,
digest = %digest,
"manifest found in local registry",
);
} else {
tracing::debug!(
image = %image,
matched_name = %name,
digest = %digest,
"manifest found in local registry via name-form fallback",
);
}
return Some((manifest, digest));
}
tracing::warn!(
image = %image,
candidate = %name,
"local registry manifest parse/resolve failed",
);
}
}
if zlayer_types::image_str_is_unqualified(image) {
if let Some((want_name, want_ref)) =
local_image_ref_candidates(image).into_iter().next()
{
let want_leaf = want_name
.rsplit('/')
.next()
.unwrap_or(&want_name)
.to_string();
if let Ok(stored) = registry.list_images().await {
for s in stored {
let s_leaf = s.rsplit('/').next().unwrap_or(&s);
if s_leaf != want_leaf {
continue;
}
if let Ok(data) = registry.get_manifest(&s, &want_ref).await {
if let Some((manifest, digest)) =
self.resolve_stored_manifest(registry, &s, &data).await
{
tracing::debug!(
image = %image,
matched_name = %s,
reference = %want_ref,
digest = %digest,
"manifest found in local registry via unqualified suffix-match",
);
return Some((manifest, digest));
}
}
}
}
}
}
None
}
pub async fn pull_manifest(
&self,
image: &str,
auth: &RegistryAuth,
) -> Result<(OciImageManifest, String)> {
self.pull_manifest_inner(image, auth, PullPolicy::Newer)
.await
}
async fn pull_manifest_inner(
&self,
image: &str,
auth: &RegistryAuth,
policy: PullPolicy,
) -> Result<(OciImageManifest, String)> {
use zlayer_spec::SourcePolicy;
let cache_key = manifest_cache_key(image);
let digest_key = manifest_digest_cache_key(image);
let source = self.source_policy;
let use_local = !matches!(source, SourcePolicy::RemoteOnly);
let use_s3 = matches!(source, SourcePolicy::LocalFirst | SourcePolicy::S3First);
let use_origin = !matches!(source, SourcePolicy::LocalOnly);
#[cfg(feature = "local")]
if use_local {
if let Some((manifest, digest)) = self.try_local_registry(image).await {
self.warm_local_cache(image, &cache_key, &digest_key, &manifest, &digest)
.await;
let revalidate = use_origin
&& !matches!(policy, PullPolicy::IfNotPresent | PullPolicy::Never)
&& is_mutable_tag(image);
if !revalidate {
return Ok((manifest, digest));
}
match self.remote_manifest_digest(image, auth).await {
Ok(Some(remote_digest)) if remote_digest != digest => {
tracing::info!(
image = %image,
local = %digest,
remote = %remote_digest,
"remote has newer manifest, pulling fresh"
);
}
Ok(Some(_) | None) => return Ok((manifest, digest)),
Err(e) => {
tracing::warn!(image = %image, error = %e, "remote check failed, using local manifest");
return Ok((manifest, digest));
}
}
return self
.pull_from_origin(image, auth, &cache_key, &digest_key)
.await;
}
}
if use_local {
if matches!(source, SourcePolicy::S3First) {
if let Some(hit) = self
.try_s3_manifest(image, auth, &cache_key, &digest_key, policy)
.await
{
return Ok(hit);
}
if let Some(hit) = self
.try_cached_manifest(image, auth, &cache_key, &digest_key, policy)
.await
{
return Ok(hit);
}
} else {
if let Some(hit) = self
.try_cached_manifest(image, auth, &cache_key, &digest_key, policy)
.await
{
return Ok(hit);
}
if use_s3 {
if let Some(hit) = self
.try_s3_manifest(image, auth, &cache_key, &digest_key, policy)
.await
{
return Ok(hit);
}
}
}
}
if !use_origin {
return Err(RegistryError::NotFound {
registry: "local".to_string(),
image: format!(
"{image} (source_policy=local_only: not present in any local source \
and remote resolution is disabled for this image)"
),
});
}
self.pull_from_origin(image, auth, &cache_key, &digest_key)
.await
}
async fn pull_from_origin(
&self,
image: &str,
auth: &RegistryAuth,
cache_key: &str,
digest_key: &str,
) -> Result<(OciImageManifest, String)> {
let pull_ref: Reference = if zlayer_types::image_str_is_unqualified(image) {
let Some(default) = self.default_registry.as_deref() else {
tracing::error!(
image = %image,
missing_config = "ZLAYER_DEFAULT_REGISTRY",
"cannot resolve unqualified image: no default registry is configured. Set \
ZLAYER_DEFAULT_REGISTRY (or run `zlayer login --default <host>`) to pick the \
registry bare names resolve against, push a fully-qualified ref (e.g. \
registry.example.com/{image}), or `zlayer build` it locally"
);
return Err(RegistryError::NotFound {
registry: "local".to_string(),
image: format!(
"{image} (unqualified image not found locally and no default registry is \
configured: set ZLAYER_DEFAULT_REGISTRY or run `zlayer login --default \
<host>` to choose the registry bare names resolve against, use a full \
registry URL such as registry.example.com/{image} for a remote pull, or \
run `zlayer build` to produce it locally — ZLayer never silently pulls \
bare names from a public registry)"
),
});
};
let qualified = format!("{}/{}", default.trim_end_matches('/'), image);
tracing::info!(
image = %image,
default_registry = %default,
qualified = %qualified,
"bare name resolved nowhere; using configured last-resort default registry"
);
qualified.parse().map_err(|_| RegistryError::NotFound {
registry: default.to_string(),
image: qualified.clone(),
})?
} else {
image.parse().map_err(|_| RegistryError::NotFound {
registry: "unknown".to_string(),
image: image.to_string(),
})?
};
tracing::info!(image = %image, reference = %pull_ref, "pulling manifest from registry");
self.note_network_call();
match self.client.pull_image_manifest(&pull_ref, auth).await {
Ok((manifest, digest)) => {
tracing::debug!(
image = %image,
digest = %digest,
layers = manifest.layers.len(),
"manifest pulled successfully"
);
self.propagate_manifest_down(image, cache_key, digest_key, &manifest, &digest)
.await;
Ok((manifest, digest))
}
Err(remote_err) => {
#[cfg(feature = "local")]
if let Some((manifest, digest)) = self.try_local_registry(image).await {
tracing::warn!(
image = %image,
error = %remote_err,
"remote pull failed, falling back to local registry"
);
return Ok((manifest, digest));
}
tracing::error!(error = %remote_err, image = %image, "failed to pull manifest");
Err(RegistryError::Oci(remote_err))
}
}
}
async fn record_original_ref(&self, image: &str) {
let _ = self
.cache
.put(&manifest_orig_cache_key(image), image.as_bytes())
.await;
}
async fn warm_local_cache(
&self,
image: &str,
cache_key: &str,
digest_key: &str,
manifest: &OciImageManifest,
digest: &str,
) {
if let Ok(bytes) = serde_json::to_vec(manifest) {
let _ = self.cache.put(cache_key, &bytes).await;
let _ = self.cache.put(digest_key, digest.as_bytes()).await;
}
self.record_original_ref(image).await;
}
async fn propagate_manifest_down(
&self,
image: &str,
cache_key: &str,
digest_key: &str,
manifest: &OciImageManifest,
digest: &str,
) {
let Ok(bytes) = serde_json::to_vec(manifest) else {
return;
};
let prev_digest = self
.cache
.get(digest_key)
.await
.ok()
.flatten()
.and_then(|b| String::from_utf8(b).ok());
let tag_moved = matches!(prev_digest, Some(prev) if prev != digest);
let _ = self.cache.put(cache_key, &bytes).await;
let _ = self.cache.put(digest_key, digest.as_bytes()).await;
self.record_original_ref(image).await;
if let Some(s3) = &self.s3_cache {
if let Err(e) = s3.put(cache_key, &bytes).await {
tracing::debug!(error = %e, "failed to propagate manifest body to S3 tier");
}
if let Err(e) = s3.put(digest_key, digest.as_bytes()).await {
tracing::debug!(error = %e, "failed to propagate manifest digest to S3 tier");
}
}
if tag_moved {
match crate::prune::prune_dangling_blobs(self.cache.as_ref().as_ref()).await {
Ok((deleted, reclaimed)) if !deleted.is_empty() => {
tracing::info!(
image = %image,
superseded = deleted.len(),
reclaimed_bytes = reclaimed,
"reclaimed layers from a superseded manifest after tag update"
);
}
Ok(_) => {}
Err(e) => {
tracing::debug!(image = %image, error = %e, "post-tag-update blob prune failed");
}
}
}
}
async fn try_s3_manifest(
&self,
image: &str,
auth: &RegistryAuth,
cache_key: &str,
digest_key: &str,
policy: PullPolicy,
) -> Option<(OciImageManifest, String)> {
self.s3_cache.as_ref()?;
let data = self.s3_tier_get(cache_key).await?;
let manifest = parse_image_manifest_only(&data)?;
let cached_digest = self
.s3_tier_get(digest_key)
.await
.and_then(|b| String::from_utf8(b).ok());
if matches!(policy, PullPolicy::IfNotPresent | PullPolicy::Never) || !is_mutable_tag(image)
{
let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
self.warm_local_cache(image, cache_key, digest_key, &manifest, &digest)
.await;
tracing::debug!(image = %image, "manifest S3 tier hit");
return Some((manifest, digest));
}
match self.remote_manifest_digest(image, auth).await {
Ok(Some(remote_digest)) if cached_digest.as_deref() == Some(remote_digest.as_str()) => {
self.warm_local_cache(image, cache_key, digest_key, &manifest, &remote_digest)
.await;
tracing::debug!(image = %image, "manifest S3 tier hit (revalidated)");
Some((manifest, remote_digest))
}
Ok(Some(_)) => {
tracing::info!(image = %image, "S3 manifest stale vs origin, refetching");
None
}
Ok(None) | Err(_) => {
let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
self.warm_local_cache(image, cache_key, digest_key, &manifest, &digest)
.await;
tracing::warn!(image = %image, "S3 manifest revalidation unavailable, serving S3 copy");
Some((manifest, digest))
}
}
}
async fn resolve_manifest_local_only(&self, image: &str) -> Option<(OciImageManifest, String)> {
let cache_key = manifest_cache_key(image);
let digest_key = manifest_digest_cache_key(image);
if let Some(hit) = self
.try_cached_manifest(
image,
&RegistryAuth::Anonymous,
&cache_key,
&digest_key,
PullPolicy::IfNotPresent,
)
.await
{
return Some(hit);
}
#[cfg(feature = "local")]
if let Some((manifest, digest)) = self.try_local_registry(image).await {
if let Ok(bytes) = serde_json::to_vec(&manifest) {
let _ = self.cache.put(&cache_key, &bytes).await;
let _ = self.cache.put(&digest_key, digest.as_bytes()).await;
}
return Some((manifest, digest));
}
None
}
pub async fn image_os_in_cache_only(&self, image: &str) -> Result<Option<zlayer_spec::OsKind>> {
let Some((manifest, _digest)) = self.resolve_manifest_local_only(image).await else {
return Ok(None);
};
let config_digest = &manifest.config.digest;
let Some(config_blob) = self.cache.get(config_digest).await.ok().flatten() else {
return Ok(None);
};
let config_root: OciImageConfigRoot =
serde_json::from_slice(&config_blob).map_err(|e| {
tracing::error!(
error = %e,
image = %image,
config_digest = %config_digest,
"failed to parse cached image config JSON for OS inspection"
);
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"failed to parse image config for {image}: {e}"
)))
})?;
Ok(config_root
.os
.as_deref()
.and_then(zlayer_spec::OsKind::from_oci_str))
}
pub async fn cache_local_image_platform(
&self,
image: &str,
os: &str,
architecture: &str,
) -> Result<()> {
let config_json = serde_json::json!({
"architecture": architecture,
"os": os,
"config": {},
});
let config_bytes = serde_json::to_vec(&config_json).map_err(|e| {
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"failed to serialize local image config for {image}: {e}"
)))
})?;
let config_digest = crate::cache::compute_digest(&config_bytes);
self.cache.put(&config_digest, &config_bytes).await?;
let manifest = OciImageManifest {
schema_version: 2,
media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
artifact_type: None,
config: oci_client::manifest::OciDescriptor {
media_type: "application/vnd.oci.image.config.v1+json".to_string(),
digest: config_digest.clone(),
size: i64::try_from(config_bytes.len()).unwrap_or(0),
urls: None,
annotations: None,
},
layers: vec![],
annotations: None,
subject: None,
};
let manifest_bytes = serde_json::to_vec(&manifest).map_err(|e| {
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"failed to serialize local image manifest for {image}: {e}"
)))
})?;
let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
self.cache
.put(&manifest_cache_key(image), &manifest_bytes)
.await?;
self.cache
.put(
&manifest_digest_cache_key(image),
manifest_digest.as_bytes(),
)
.await?;
self.record_original_ref(image).await;
Ok(())
}
pub async fn image_runtime_marker_in_cache_only(&self, image: &str) -> Result<Option<String>> {
let Some((manifest, _digest)) = self.resolve_manifest_local_only(image).await else {
return Ok(None);
};
Ok(manifest
.annotations
.as_ref()
.and_then(|a| a.get(crate::ZLAYER_RUNTIME_ANNOTATION).cloned()))
}
pub async fn image_isolation_marker_in_cache_only(
&self,
image: &str,
) -> Result<Option<String>> {
let Some((manifest, _digest)) = self.resolve_manifest_local_only(image).await else {
return Ok(None);
};
let config_digest = &manifest.config.digest;
let Some(config_blob) = self.cache.get(config_digest).await.ok().flatten() else {
return Ok(None);
};
let config_root: OciImageConfigRoot =
serde_json::from_slice(&config_blob).map_err(|e| {
tracing::error!(
error = %e,
image = %image,
config_digest = %config_digest,
"failed to parse cached image config JSON for isolation inspection"
);
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"failed to parse image config for {image}: {e}"
)))
})?;
Ok(config_root
.config
.and_then(|c| c.labels)
.and_then(|l| l.get(crate::ZLAYER_ISOLATION_ANNOTATION).cloned()))
}
pub async fn pull_manifest_with_policy(
&self,
image: &str,
auth: &RegistryAuth,
policy: PullPolicy,
) -> Result<(OciImageManifest, String)> {
let force_refresh = matches!(policy, PullPolicy::Always);
if force_refresh {
let cache_key = manifest_cache_key(image);
let digest_key = manifest_digest_cache_key(image);
if let Err(e) = self.cache.delete(&cache_key).await {
tracing::warn!(
image = %image,
error = %e,
"failed to invalidate manifest cache for force refresh"
);
}
if let Err(e) = self.cache.delete(&digest_key).await {
tracing::warn!(
image = %image,
error = %e,
"failed to invalidate manifest digest cache for force refresh"
);
}
}
self.pull_manifest_inner(image, auth, policy).await
}
pub async fn pull_image_config(&self, image: &str, auth: &RegistryAuth) -> Result<ImageConfig> {
self.pull_image_config_inner(image, auth, PullPolicy::Newer)
.await
}
async fn pull_image_config_inner(
&self,
image: &str,
auth: &RegistryAuth,
policy: PullPolicy,
) -> Result<ImageConfig> {
let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
let config_digest = &manifest.config.digest;
tracing::debug!(
image = %image,
config_digest = %config_digest,
config_media_type = %manifest.config.media_type,
"fetching image config blob"
);
let config_blob = self.pull_blob(image, config_digest, auth).await?;
let config_root: OciImageConfigRoot =
serde_json::from_slice(&config_blob).map_err(|e| {
tracing::error!(
error = %e,
image = %image,
config_digest = %config_digest,
"failed to parse image config JSON"
);
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"failed to parse image config for {image}: {e}"
)))
})?;
let config = config_root.config.unwrap_or_default();
tracing::info!(
image = %image,
has_entrypoint = config.entrypoint.is_some(),
has_cmd = config.cmd.is_some(),
has_working_dir = config.working_dir.is_some(),
has_user = config.user.is_some(),
env_count = config.env.as_ref().map_or(0, std::vec::Vec::len),
"image config parsed successfully"
);
Ok(config)
}
pub async fn pull_image_config_with_policy(
&self,
image: &str,
auth: &RegistryAuth,
policy: PullPolicy,
) -> Result<ImageConfig> {
let force_refresh = matches!(policy, PullPolicy::Always);
if force_refresh {
let cache_key = manifest_cache_key(image);
let digest_key = manifest_digest_cache_key(image);
if let Err(e) = self.cache.delete(&cache_key).await {
tracing::warn!(
image = %image,
error = %e,
"failed to invalidate manifest cache for force refresh"
);
}
if let Err(e) = self.cache.delete(&digest_key).await {
tracing::warn!(
image = %image,
error = %e,
"failed to invalidate manifest digest cache for force refresh"
);
}
}
let key = self.pull_singleflight_key(image, policy);
let (slot, is_leader) = {
let mut map = config_singleflight().lock().await;
if let Some(existing) = map.get(&key).and_then(std::sync::Weak::upgrade) {
(existing, false)
} else {
let fresh: Arc<ConfigSlot> = Arc::new(tokio::sync::OnceCell::new());
map.insert(key.clone(), Arc::downgrade(&fresh));
(fresh, true)
}
};
let outcome = slot
.get_or_init(|| async {
self.pull_image_config_inner(image, auth, policy)
.await
.map_err(|e| e.to_string())
})
.await
.clone();
if is_leader {
config_singleflight().lock().await.remove(&key);
}
outcome.map_err(|msg| {
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"image config fetch failed for {image}: {msg}"
)))
})
}
pub async fn image_os(
&self,
image: &str,
auth: &RegistryAuth,
) -> Result<Option<zlayer_spec::OsKind>> {
self.image_os_with_policy(image, auth, PullPolicy::Newer)
.await
}
pub async fn image_os_with_policy(
&self,
image: &str,
auth: &RegistryAuth,
policy: PullPolicy,
) -> Result<Option<zlayer_spec::OsKind>> {
let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
let config_digest = &manifest.config.digest;
let config_blob = self.pull_blob(image, config_digest, auth).await?;
let config_root: OciImageConfigRoot =
serde_json::from_slice(&config_blob).map_err(|e| {
tracing::error!(
error = %e,
image = %image,
config_digest = %config_digest,
"failed to parse image config JSON for OS inspection"
);
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"failed to parse image config for {image}: {e}"
)))
})?;
Ok(config_root
.os
.as_deref()
.and_then(zlayer_spec::OsKind::from_oci_str))
}
pub async fn image_runtime_marker(
&self,
image: &str,
auth: &RegistryAuth,
) -> Result<Option<String>> {
self.image_runtime_marker_with_policy(image, auth, PullPolicy::Newer)
.await
}
pub async fn image_runtime_marker_with_policy(
&self,
image: &str,
auth: &RegistryAuth,
policy: PullPolicy,
) -> Result<Option<String>> {
let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
Ok(manifest
.annotations
.as_ref()
.and_then(|a| a.get(crate::ZLAYER_RUNTIME_ANNOTATION).cloned()))
}
pub async fn image_isolation_marker_with_policy(
&self,
image: &str,
auth: &RegistryAuth,
policy: PullPolicy,
) -> Result<Option<String>> {
let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
let config_digest = &manifest.config.digest;
let config_blob = self.pull_blob(image, config_digest, auth).await?;
let config_root: OciImageConfigRoot =
serde_json::from_slice(&config_blob).map_err(|e| {
tracing::error!(
error = %e,
image = %image,
config_digest = %config_digest,
"failed to parse image config JSON for isolation inspection"
);
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"failed to parse image config for {image}: {e}"
)))
})?;
Ok(config_root
.config
.and_then(|c| c.labels)
.and_then(|l| l.get(crate::ZLAYER_ISOLATION_ANNOTATION).cloned()))
}
pub async fn image_os_version(
&self,
image: &str,
auth: &RegistryAuth,
) -> Result<Option<String>> {
let (manifest, _digest) = self.pull_manifest(image, auth).await?;
let config_digest = &manifest.config.digest;
let config_blob = self.pull_blob(image, config_digest, auth).await?;
let config_root: OciImageConfigRoot =
serde_json::from_slice(&config_blob).map_err(|e| {
tracing::error!(
error = %e,
image = %image,
config_digest = %config_digest,
"failed to parse image config JSON for os.version inspection"
);
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"failed to parse image config for {image}: {e}"
)))
})?;
Ok(config_root.os_version)
}
pub async fn detect_artifact_type(
&self,
image: &str,
auth: &RegistryAuth,
) -> Result<(ArtifactType, OciImageManifest, String)> {
let (manifest, digest) = self.pull_manifest(image, auth).await?;
let artifact_type = detect_artifact_type(&manifest);
tracing::info!(
image = %image,
artifact_type = %artifact_type,
"detected artifact type"
);
Ok((artifact_type, manifest, digest))
}
pub async fn get_wasm_info(
&self,
image: &str,
auth: &RegistryAuth,
) -> Result<Option<WasmArtifactInfo>> {
let (manifest, _digest) = self.pull_manifest(image, auth).await?;
Ok(extract_wasm_info(&manifest))
}
pub async fn pull_wasm(
&self,
image: &str,
auth: &RegistryAuth,
) -> Result<(Vec<u8>, WasmArtifactInfo)> {
let (manifest, _digest) = self.pull_manifest(image, auth).await?;
let wasm_info = extract_wasm_info(&manifest).ok_or_else(|| RegistryError::NotFound {
registry: "unknown".to_string(),
image: format!("{image} (not a WASM artifact)"),
})?;
let wasm_digest =
wasm_info
.wasm_layer_digest
.as_ref()
.ok_or_else(|| RegistryError::NotFound {
registry: "unknown".to_string(),
image: format!("{image} (no WASM layer found)"),
})?;
tracing::info!(
image = %image,
wasi_version = %wasm_info.wasi_version,
wasm_digest = %wasm_digest,
"pulling WASM binary"
);
let wasm_bytes = self.pull_blob(image, wasm_digest, auth).await?;
tracing::info!(
image = %image,
wasm_size = wasm_bytes.len(),
"WASM binary pulled successfully"
);
Ok((wasm_bytes, wasm_info))
}
pub async fn pull_image(
&self,
image: &str,
auth: &RegistryAuth,
) -> Result<Vec<(Vec<u8>, String)>> {
self.pull_image_inner(image, auth, PullPolicy::Newer).await
}
async fn pull_image_inner(
&self,
image: &str,
auth: &RegistryAuth,
policy: PullPolicy,
) -> Result<Vec<(Vec<u8>, String)>> {
let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
tracing::info!(
image = %image,
layer_count = manifest.layers.len(),
"pulling image layers"
);
let layer_inputs: Vec<(usize, String, String, Vec<String>, i64)> = manifest
.layers
.iter()
.enumerate()
.map(|(i, l)| {
(
i,
l.digest.clone(),
l.media_type.clone(),
l.urls.clone().unwrap_or_default(),
l.size,
)
})
.collect();
let layers: Vec<(Vec<u8>, String)> =
futures_util::stream::iter(layer_inputs.into_iter().map(
|(i, digest, media_type, urls, size)| async move {
tracing::debug!(
layer = i,
digest = %digest,
media_type = %media_type,
size,
"pulling layer"
);
let data = self
.pull_blob_with_urls(image, &digest, auth, &urls, Some(size))
.await?;
if data.is_empty() {
return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
format!("layer {i} ({digest}) is empty after pull"),
)));
}
Ok::<(Vec<u8>, String), RegistryError>((data, media_type))
},
))
.buffered(LAYER_PULL_CONCURRENCY)
.try_collect()
.await?;
tracing::info!(
image = %image,
layers_pulled = layers.len(),
"image pull complete"
);
Ok(layers)
}
pub async fn pull_image_with_policy(
&self,
image: &str,
auth: &RegistryAuth,
policy: PullPolicy,
) -> Result<Vec<(Vec<u8>, String)>> {
let force_refresh = matches!(policy, PullPolicy::Always);
if force_refresh {
let cache_key = manifest_cache_key(image);
let digest_key = manifest_digest_cache_key(image);
if let Err(e) = self.cache.delete(&cache_key).await {
tracing::warn!(
image = %image,
error = %e,
"failed to invalidate manifest cache for force refresh"
);
}
if let Err(e) = self.cache.delete(&digest_key).await {
tracing::warn!(
image = %image,
error = %e,
"failed to invalidate manifest digest cache for force refresh"
);
}
}
self.pull_image_inner(image, auth, policy).await
}
#[instrument(
name = "push_blob",
skip(self, data, auth, _media_type),
fields(
reference = %reference,
digest = %digest,
size = data.len(),
)
)]
pub async fn push_blob(
&self,
reference: &str,
digest: &str,
data: &[u8],
_media_type: &str,
auth: &RegistryAuth,
) -> std::result::Result<(), PushError> {
let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
reference: reference.to_string(),
})?;
tracing::debug!(
reference = %reference,
digest = %digest,
size = data.len(),
"pushing blob to registry"
);
self.client
.auth(&image_ref, auth, RegistryOperation::Push)
.await
.map_err(|e| PushError::AuthenticationFailed {
registry: image_ref.resolve_registry().to_string(),
reason: e.to_string(),
})?;
self.client
.push_blob(&image_ref, data, digest)
.await
.map_err(|e| PushError::BlobUploadFailed {
digest: digest.to_string(),
reason: e.to_string(),
})?;
tracing::info!(
reference = %reference,
digest = %digest,
size = data.len(),
"blob pushed successfully"
);
Ok(())
}
#[instrument(
name = "push_manifest_to_registry",
skip(self, manifest, auth),
fields(
reference = %reference,
layers = manifest.layers.len(),
)
)]
pub async fn push_manifest_to_registry(
&self,
reference: &str,
manifest: &OciImageManifest,
auth: &RegistryAuth,
) -> std::result::Result<String, PushError> {
let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
reference: reference.to_string(),
})?;
tracing::debug!(
reference = %reference,
layers = manifest.layers.len(),
config_digest = %manifest.config.digest,
"pushing manifest to registry"
);
self.client
.auth(&image_ref, auth, RegistryOperation::Push)
.await
.map_err(|e| PushError::AuthenticationFailed {
registry: image_ref.resolve_registry().to_string(),
reason: e.to_string(),
})?;
let manifest_url = self
.client
.push_manifest(&image_ref, &OciManifest::Image(manifest.clone()))
.await
.map_err(|e| PushError::ManifestUploadFailed {
reason: e.to_string(),
})?;
let digest = if let Some(digest_start) = manifest_url.rfind('@') {
manifest_url[digest_start + 1..].to_string()
} else {
let manifest_json =
serde_json::to_vec(manifest).map_err(|e| PushError::ManifestUploadFailed {
reason: format!("failed to serialize manifest: {e}"),
})?;
crate::cache::compute_digest(&manifest_json)
};
tracing::info!(
reference = %reference,
digest = %digest,
manifest_url = %manifest_url,
"manifest pushed successfully"
);
Ok(digest)
}
#[instrument(
name = "push_image_index_to_registry",
skip(self, index, auth),
fields(
reference = %reference,
manifests = index.manifests.len(),
)
)]
pub async fn push_image_index_to_registry(
&self,
reference: &str,
index: &OciImageIndex,
auth: &RegistryAuth,
) -> std::result::Result<String, PushError> {
let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
reference: reference.to_string(),
})?;
tracing::debug!(
reference = %reference,
manifests = index.manifests.len(),
"pushing image index to registry"
);
self.client
.auth(&image_ref, auth, RegistryOperation::Push)
.await
.map_err(|e| PushError::AuthenticationFailed {
registry: image_ref.resolve_registry().to_string(),
reason: e.to_string(),
})?;
let manifest_url = self
.client
.push_manifest(&image_ref, &OciManifest::ImageIndex(index.clone()))
.await
.map_err(|e| PushError::ManifestUploadFailed {
reason: e.to_string(),
})?;
let digest = if let Some(digest_start) = manifest_url.rfind('@') {
manifest_url[digest_start + 1..].to_string()
} else {
let index_json =
serde_json::to_vec(index).map_err(|e| PushError::ManifestUploadFailed {
reason: format!("failed to serialize image index: {e}"),
})?;
crate::cache::compute_digest(&index_json)
};
tracing::info!(
reference = %reference,
digest = %digest,
"image index pushed successfully"
);
Ok(digest)
}
#[instrument(
name = "push_manifest_blob",
skip(self, manifest_bytes, auth),
fields(
reference = %reference,
content_type = %content_type,
size = manifest_bytes.len(),
)
)]
pub async fn push_manifest_blob(
&self,
reference: &str,
manifest_bytes: Vec<u8>,
content_type: &str,
auth: &RegistryAuth,
) -> std::result::Result<String, PushError> {
let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
reference: reference.to_string(),
})?;
let header_value =
content_type
.parse()
.map_err(|e: reqwest::header::InvalidHeaderValue| {
PushError::ManifestUploadFailed {
reason: format!("invalid Content-Type {content_type:?}: {e}"),
}
})?;
self.client
.auth(&image_ref, auth, RegistryOperation::Push)
.await
.map_err(|e| PushError::AuthenticationFailed {
registry: image_ref.resolve_registry().to_string(),
reason: e.to_string(),
})?;
let manifest_url = self
.client
.push_manifest_raw(&image_ref, manifest_bytes.clone(), header_value)
.await
.map_err(|e| PushError::ManifestUploadFailed {
reason: e.to_string(),
})?;
let digest = if let Some(digest_start) = manifest_url.rfind('@') {
manifest_url[digest_start + 1..].to_string()
} else {
crate::cache::compute_digest(&manifest_bytes)
};
tracing::info!(
reference = %reference,
digest = %digest,
"manifest blob pushed successfully"
);
Ok(digest)
}
#[cfg(feature = "local")]
#[allow(clippy::too_many_lines)]
#[instrument(
name = "push_wasm",
skip(self, export_result, auth),
fields(
reference = %reference,
wasm_size = export_result.wasm_size,
wasi_version = %export_result.wasi_version,
)
)]
pub async fn push_wasm(
&self,
reference: &str,
export_result: &WasmExportResult,
auth: &RegistryAuth,
) -> std::result::Result<PushResult, PushError> {
use crate::wasm::{WASM_CONFIG_MEDIA_TYPE_V0, WASM_LAYER_MEDIA_TYPE_GENERIC};
let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
reference: reference.to_string(),
})?;
tracing::info!(
reference = %reference,
wasm_size = export_result.wasm_size,
wasi_version = %export_result.wasi_version,
artifact_type = %export_result.artifact_type,
"pushing WASM artifact to registry"
);
self.client
.auth(&image_ref, auth, RegistryOperation::Push)
.await
.map_err(|e| PushError::AuthenticationFailed {
registry: image_ref.resolve_registry().to_string(),
reason: e.to_string(),
})?;
let mut blobs_pushed = Vec::new();
tracing::debug!(
digest = %export_result.config_digest,
size = export_result.config_size,
"pushing config blob"
);
self.client
.push_blob(
&image_ref,
&export_result.config_blob,
&export_result.config_digest,
)
.await
.map_err(|e| PushError::BlobUploadFailed {
digest: export_result.config_digest.clone(),
reason: e.to_string(),
})?;
blobs_pushed.push(export_result.config_digest.clone());
tracing::debug!(
digest = %export_result.wasm_layer_digest,
size = export_result.wasm_size,
"pushing WASM layer blob"
);
self.client
.push_blob(
&image_ref,
&export_result.wasm_binary,
&export_result.wasm_layer_digest,
)
.await
.map_err(|e| PushError::BlobUploadFailed {
digest: export_result.wasm_layer_digest.clone(),
reason: e.to_string(),
})?;
blobs_pushed.push(export_result.wasm_layer_digest.clone());
#[allow(clippy::cast_possible_wrap)]
let manifest = OciImageManifest {
schema_version: 2,
media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
artifact_type: Some(export_result.artifact_type.clone()),
config: oci_client::manifest::OciDescriptor {
media_type: WASM_CONFIG_MEDIA_TYPE_V0.to_string(),
digest: export_result.config_digest.clone(),
size: export_result.config_size as i64,
urls: None,
annotations: None,
},
layers: vec![oci_client::manifest::OciDescriptor {
media_type: WASM_LAYER_MEDIA_TYPE_GENERIC.to_string(),
digest: export_result.wasm_layer_digest.clone(),
size: export_result.wasm_size as i64,
urls: None,
annotations: None,
}],
annotations: None,
subject: None,
};
tracing::debug!(
config_digest = %export_result.config_digest,
wasm_digest = %export_result.wasm_layer_digest,
"pushing manifest"
);
let manifest_url = self
.client
.push_manifest(&image_ref, &OciManifest::Image(manifest))
.await
.map_err(|e| PushError::ManifestUploadFailed {
reason: e.to_string(),
})?;
let manifest_digest = if let Some(digest_start) = manifest_url.rfind('@') {
manifest_url[digest_start + 1..].to_string()
} else {
export_result.manifest_digest.clone()
};
tracing::info!(
reference = %reference,
manifest_digest = %manifest_digest,
blobs_pushed = blobs_pushed.len(),
"WASM artifact pushed successfully"
);
Ok(PushResult {
manifest_digest,
blobs_pushed,
reference: reference.to_string(),
})
}
#[cfg(feature = "local")]
#[allow(clippy::too_many_arguments)]
#[instrument(name = "push_artifact", skip(self, config_blob, layers, annotations, auth), fields(reference = %reference, artifact_type = %artifact_type, layers = layers.len()))]
pub async fn push_artifact(
&self,
reference: &str,
artifact_type: &str,
config_media_type: &str,
config_blob: &[u8],
layers: &[ArtifactLayer],
annotations: std::collections::BTreeMap<String, String>,
auth: &RegistryAuth,
) -> std::result::Result<PushResult, PushError> {
let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
reference: reference.to_string(),
})?;
self.client
.auth(&image_ref, auth, RegistryOperation::Push)
.await
.map_err(|e| PushError::AuthenticationFailed {
registry: image_ref.resolve_registry().to_string(),
reason: e.to_string(),
})?;
let mut blobs_pushed = Vec::new();
let config_digest = oci_sha256_digest(config_blob);
self.client
.push_blob(&image_ref, config_blob, &config_digest)
.await
.map_err(|e| PushError::BlobUploadFailed {
digest: config_digest.clone(),
reason: e.to_string(),
})?;
blobs_pushed.push(config_digest.clone());
let mut layer_descriptors = Vec::with_capacity(layers.len());
for layer in layers {
let digest = oci_sha256_digest(&layer.data);
tracing::debug!(
digest = %digest,
size = layer.data.len(),
media_type = %layer.media_type,
"pushing artifact layer blob"
);
self.client
.push_blob(&image_ref, &layer.data, &digest)
.await
.map_err(|e| PushError::BlobUploadFailed {
digest: digest.clone(),
reason: e.to_string(),
})?;
blobs_pushed.push(digest.clone());
let layer_annotations = layer.title.as_ref().map(|title| {
let mut m = std::collections::BTreeMap::new();
m.insert("org.opencontainers.image.title".to_string(), title.clone());
m
});
#[allow(clippy::cast_possible_wrap)]
layer_descriptors.push(oci_client::manifest::OciDescriptor {
media_type: layer.media_type.clone(),
digest,
size: layer.data.len() as i64,
urls: None,
annotations: layer_annotations,
});
}
let manifest_annotations = if annotations.is_empty() {
None
} else {
Some(annotations)
};
#[allow(clippy::cast_possible_wrap)]
let manifest = OciImageManifest {
schema_version: 2,
media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
artifact_type: Some(artifact_type.to_string()),
config: oci_client::manifest::OciDescriptor {
media_type: config_media_type.to_string(),
digest: config_digest.clone(),
size: config_blob.len() as i64,
urls: None,
annotations: None,
},
layers: layer_descriptors,
annotations: manifest_annotations,
subject: None,
};
let manifest_url = self
.client
.push_manifest(&image_ref, &OciManifest::Image(manifest))
.await
.map_err(|e| PushError::ManifestUploadFailed {
reason: e.to_string(),
})?;
let manifest_digest = manifest_url
.rfind('@')
.map(|i| manifest_url[i + 1..].to_string())
.unwrap_or(manifest_url);
tracing::info!(
reference = %reference,
manifest_digest = %manifest_digest,
blobs_pushed = blobs_pushed.len(),
"OCI artifact pushed successfully"
);
Ok(PushResult {
manifest_digest,
blobs_pushed,
reference: reference.to_string(),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Image {
pub registry: String,
pub repository: String,
pub tag: String,
}
impl std::fmt::Display for Image {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}/{}:{}", self.registry, self.repository, self.tag)
}
}
const MAX_FOREIGN_LAYER_REDIRECTS: usize = 5;
fn is_blob_not_found(err: &oci_client::errors::OciDistributionError) -> bool {
use oci_client::errors::{OciDistributionError, OciErrorCode};
match err {
OciDistributionError::ImageManifestNotFoundError(_) => true,
OciDistributionError::ServerError { code, .. } => *code == 404,
OciDistributionError::RegistryError { envelope, .. } => envelope.errors.iter().any(|e| {
matches!(
e.code,
OciErrorCode::BlobUnknown
| OciErrorCode::ManifestBlobUnknown
| OciErrorCode::ManifestUnknown
| OciErrorCode::NotFound
| OciErrorCode::NameUnknown
)
}),
OciDistributionError::RequestError(req_err) => {
req_err.status() == Some(reqwest::StatusCode::NOT_FOUND)
}
_ => false,
}
}
pub async fn fetch_from_url(
url: &str,
auth: Option<(&str, &str)>,
context: &str,
) -> Result<Vec<u8>> {
let client = reqwest::Client::builder().build().map_err(|e| {
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"failed to build HTTP client for {context} {url}: {e}"
)))
})?;
let mut req = client.get(url);
if let Some((user, pw)) = auth {
req = req.basic_auth(user, Some(pw));
}
let response = req.send().await.map_err(|e| {
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"{context} GET {url} failed: {e}"
)))
})?;
if !response.status().is_success() {
return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
format!("{context} {url} returned HTTP {}", response.status()),
)));
}
let bytes = response.bytes().await.map_err(|e| {
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"failed to read {context} body from {url}: {e}"
)))
})?;
Ok(bytes.to_vec())
}
async fn fetch_blob_from_url(
url: &str,
expected_digest: &str,
expected_size: Option<i64>,
) -> Result<Vec<u8>> {
use sha2::{Digest, Sha256};
let bytes = fetch_from_url(url, None, "foreign-layer redirect").await?;
if bytes.is_empty() {
return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
format!("foreign-layer redirect {url} returned empty body"),
)));
}
if let Some(expected) = expected_size {
if let Ok(expected_u) = u64::try_from(expected) {
if bytes.len() as u64 != expected_u {
return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
format!(
"foreign-layer redirect {url}: size mismatch (expected {expected}, got {})",
bytes.len()
),
)));
}
}
}
let mut hasher = Sha256::new();
hasher.update(&bytes);
let actual = hex::encode(hasher.finalize());
let expected = expected_digest
.strip_prefix("sha256:")
.unwrap_or(expected_digest);
if !actual.eq_ignore_ascii_case(expected) {
return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
format!(
"foreign-layer redirect {url}: digest mismatch (expected {expected_digest}, got sha256:{actual})"
),
)));
}
Ok(bytes)
}
static BLOB_PART_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
fn blob_staging_filename(digest: &str) -> String {
digest.replace([':', '/'], "_")
}
async fn link_or_copy(src: &std::path::Path, dest: &std::path::Path) -> Result<()> {
let _ = tokio::fs::remove_file(dest).await;
if tokio::fs::hard_link(src, dest).await.is_ok() {
return Ok(());
}
tokio::fs::copy(src, dest)
.await
.map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
Ok(())
}
struct HashingFileWriter {
file: tokio::fs::File,
hasher: sha2::Sha256,
written: u64,
}
impl HashingFileWriter {
fn new(file: tokio::fs::File) -> Self {
use sha2::Digest;
Self {
file,
hasher: sha2::Sha256::new(),
written: 0,
}
}
async fn finalize(mut self) -> Result<(String, u64)> {
use sha2::Digest;
use tokio::io::AsyncWriteExt as _;
self.file
.flush()
.await
.map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
self.file
.sync_all()
.await
.map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
let digest = format!("sha256:{}", hex::encode(self.hasher.finalize()));
Ok((digest, self.written))
}
}
impl tokio::io::AsyncWrite for HashingFileWriter {
fn poll_write(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
use sha2::Digest;
let me = self.get_mut();
match std::pin::Pin::new(&mut me.file).poll_write(cx, buf) {
std::task::Poll::Ready(Ok(n)) => {
me.hasher.update(&buf[..n]);
me.written += n as u64;
std::task::Poll::Ready(Ok(n))
}
other => other,
}
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
let me = self.get_mut();
std::pin::Pin::new(&mut me.file).poll_flush(cx)
}
fn poll_shutdown(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
let me = self.get_mut();
std::pin::Pin::new(&mut me.file).poll_shutdown(cx)
}
}
async fn fetch_blob_from_url_to_writer(
url: &str,
expected_size: Option<i64>,
writer: &mut HashingFileWriter,
) -> Result<()> {
use tokio::io::AsyncWriteExt as _;
let client = reqwest::Client::builder().build().map_err(|e| {
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"failed to build HTTP client for foreign-layer redirect {url}: {e}"
)))
})?;
let mut response = client.get(url).send().await.map_err(|e| {
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"foreign-layer redirect GET {url} failed: {e}"
)))
})?;
if !response.status().is_success() {
return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
format!(
"foreign-layer redirect {url} returned HTTP {}",
response.status()
),
)));
}
while let Some(chunk) = response.chunk().await.map_err(|e| {
RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
"failed to read foreign-layer body from {url}: {e}"
)))
})? {
writer
.write_all(&chunk)
.await
.map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
}
if let Some(expected) = expected_size {
if let Ok(expected_u) = u64::try_from(expected) {
if writer.written != expected_u {
return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
format!(
"foreign-layer redirect {url}: size mismatch (expected {expected}, got {})",
writer.written
),
)));
}
}
}
Ok(())
}
pub async fn fetch_archive_from_url(url: &str, auth: Option<(&str, &str)>) -> Result<Vec<u8>> {
let bytes = fetch_from_url(url, auth, "archive fetch").await?;
if bytes.is_empty() {
return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
format!("archive fetch {url} returned empty body"),
)));
}
Ok(bytes)
}
#[must_use]
pub fn spec_auth_to_oci(auth: Option<&zlayer_spec::RegistryAuth>) -> RegistryAuth {
let Some(a) = auth else {
return RegistryAuth::Anonymous;
};
match a.auth_type {
zlayer_spec::RegistryAuthType::Basic | zlayer_spec::RegistryAuthType::Token => {
RegistryAuth::Basic(a.username.clone(), a.password.clone())
}
}
}
#[cfg(feature = "local")]
fn inspection_puller(
cache: Arc<Box<dyn BlobCacheBackend>>,
local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
) -> ImagePuller {
let puller = ImagePuller::with_cache(cache);
match local_registry {
Some(reg) => puller.with_local_registry(reg),
None => puller,
}
}
pub async fn fetch_image_os(
image: &str,
auth: Option<&zlayer_spec::RegistryAuth>,
) -> Result<Option<zlayer_spec::OsKind>> {
let cache = crate::cache::BlobCache::new()?;
let puller = ImagePuller::new(cache);
let oci_auth = spec_auth_to_oci(auth);
puller
.image_os_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
.await
}
#[cfg(feature = "local")]
pub async fn fetch_image_os_in_cache(
image: &str,
auth: Option<&zlayer_spec::RegistryAuth>,
cache: Arc<Box<dyn BlobCacheBackend>>,
local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
) -> Result<Option<zlayer_spec::OsKind>> {
let puller = inspection_puller(cache, local_registry);
let oci_auth = spec_auth_to_oci(auth);
puller
.image_os_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
.await
}
pub async fn fetch_image_runtime_marker(
image: &str,
auth: Option<&zlayer_spec::RegistryAuth>,
) -> Result<Option<String>> {
let cache = crate::cache::BlobCache::new()?;
let puller = ImagePuller::new(cache);
let oci_auth = spec_auth_to_oci(auth);
puller
.image_runtime_marker_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
.await
}
#[cfg(feature = "local")]
pub async fn fetch_image_runtime_marker_in_cache(
image: &str,
auth: Option<&zlayer_spec::RegistryAuth>,
cache: Arc<Box<dyn BlobCacheBackend>>,
local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
) -> Result<Option<String>> {
let puller = inspection_puller(cache, local_registry);
let oci_auth = spec_auth_to_oci(auth);
puller
.image_runtime_marker_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
.await
}
#[cfg(feature = "local")]
pub async fn fetch_image_os_in_cache_only(
image: &str,
cache: Arc<Box<dyn BlobCacheBackend>>,
local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
) -> Result<Option<zlayer_spec::OsKind>> {
let puller = inspection_puller(cache, local_registry);
puller.image_os_in_cache_only(image).await
}
#[cfg(feature = "local")]
pub async fn fetch_image_runtime_marker_in_cache_only(
image: &str,
cache: Arc<Box<dyn BlobCacheBackend>>,
local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
) -> Result<Option<String>> {
let puller = inspection_puller(cache, local_registry);
puller.image_runtime_marker_in_cache_only(image).await
}
pub async fn fetch_image_isolation_marker(
image: &str,
auth: Option<&zlayer_spec::RegistryAuth>,
) -> Result<Option<String>> {
let cache = crate::cache::BlobCache::new()?;
let puller = ImagePuller::new(cache);
let oci_auth = spec_auth_to_oci(auth);
puller
.image_isolation_marker_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
.await
}
#[cfg(feature = "local")]
pub async fn fetch_image_isolation_marker_in_cache(
image: &str,
auth: Option<&zlayer_spec::RegistryAuth>,
cache: Arc<Box<dyn BlobCacheBackend>>,
local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
) -> Result<Option<String>> {
let puller = inspection_puller(cache, local_registry);
let oci_auth = spec_auth_to_oci(auth);
puller
.image_isolation_marker_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
.await
}
#[cfg(feature = "local")]
pub async fn fetch_image_isolation_marker_in_cache_only(
image: &str,
cache: Arc<Box<dyn BlobCacheBackend>>,
local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
) -> Result<Option<String>> {
let puller = inspection_puller(cache, local_registry);
puller.image_isolation_marker_in_cache_only(image).await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_image_display() {
let image = Image {
registry: "docker.io".to_string(),
repository: "library/nginx".to_string(),
tag: "latest".to_string(),
};
assert_eq!(image.to_string(), "docker.io/library/nginx:latest");
}
#[test]
fn test_image_display_ghcr() {
let image = Image {
registry: "ghcr.io".to_string(),
repository: "myorg/myrepo".to_string(),
tag: "v1.2.3".to_string(),
};
assert_eq!(image.to_string(), "ghcr.io/myorg/myrepo:v1.2.3");
}
#[test]
fn test_image_display_with_nested_repo() {
let image = Image {
registry: "gcr.io".to_string(),
repository: "project/subdir/image".to_string(),
tag: "sha-abc123".to_string(),
};
assert_eq!(image.to_string(), "gcr.io/project/subdir/image:sha-abc123");
}
#[test]
fn test_image_clone() {
let image = Image {
registry: "docker.io".to_string(),
repository: "library/nginx".to_string(),
tag: "latest".to_string(),
};
let cloned = image.clone();
assert_eq!(image, cloned);
assert_eq!(cloned.registry, "docker.io");
assert_eq!(cloned.repository, "library/nginx");
assert_eq!(cloned.tag, "latest");
}
#[test]
fn test_image_equality() {
let image1 = Image {
registry: "docker.io".to_string(),
repository: "library/nginx".to_string(),
tag: "latest".to_string(),
};
let image2 = Image {
registry: "docker.io".to_string(),
repository: "library/nginx".to_string(),
tag: "latest".to_string(),
};
let image3 = Image {
registry: "ghcr.io".to_string(),
repository: "library/nginx".to_string(),
tag: "latest".to_string(),
};
assert_eq!(image1, image2);
assert_ne!(image1, image3);
}
#[test]
fn test_image_debug() {
let image = Image {
registry: "docker.io".to_string(),
repository: "test".to_string(),
tag: "v1".to_string(),
};
let debug_str = format!("{image:?}");
assert!(debug_str.contains("Image"));
assert!(debug_str.contains("docker.io"));
assert!(debug_str.contains("test"));
assert!(debug_str.contains("v1"));
}
#[test]
fn test_push_error_display_authentication_failed() {
let err = PushError::AuthenticationFailed {
registry: "ghcr.io".to_string(),
reason: "invalid token".to_string(),
};
assert_eq!(
err.to_string(),
"authentication failed for registry ghcr.io: invalid token"
);
}
#[test]
fn test_push_error_display_authentication_failed_empty_reason() {
let err = PushError::AuthenticationFailed {
registry: "docker.io".to_string(),
reason: String::new(),
};
assert_eq!(
err.to_string(),
"authentication failed for registry docker.io: "
);
}
#[test]
fn test_push_error_display_authentication_failed_long_reason() {
let long_reason = "a]".repeat(100);
let err = PushError::AuthenticationFailed {
registry: "ghcr.io".to_string(),
reason: long_reason.clone(),
};
assert!(err.to_string().contains(&long_reason));
}
#[test]
fn test_push_error_display_blob_upload_failed() {
let err = PushError::BlobUploadFailed {
digest: "sha256:abc123".to_string(),
reason: "connection reset".to_string(),
};
assert_eq!(
err.to_string(),
"failed to upload blob sha256:abc123: connection reset"
);
}
#[test]
fn test_push_error_display_blob_upload_failed_with_full_digest() {
let digest =
"sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".to_string();
let err = PushError::BlobUploadFailed {
digest: digest.clone(),
reason: "timeout".to_string(),
};
assert!(err.to_string().contains(&digest));
assert!(err.to_string().contains("timeout"));
}
#[test]
fn test_push_error_display_manifest_upload_failed() {
let err = PushError::ManifestUploadFailed {
reason: "invalid manifest".to_string(),
};
assert_eq!(
err.to_string(),
"failed to upload manifest: invalid manifest"
);
}
#[test]
fn test_push_error_display_manifest_upload_failed_json_error() {
let err = PushError::ManifestUploadFailed {
reason: "invalid JSON: unexpected token at position 42".to_string(),
};
assert!(err.to_string().contains("invalid JSON"));
assert!(err.to_string().contains("position 42"));
}
#[test]
fn test_push_error_display_network_error() {
let err = PushError::NetworkError("timeout".to_string());
assert_eq!(err.to_string(), "network error: timeout");
}
#[test]
fn test_push_error_display_network_error_connection_refused() {
let err = PushError::NetworkError("connection refused: 127.0.0.1:5000".to_string());
assert_eq!(
err.to_string(),
"network error: connection refused: 127.0.0.1:5000"
);
}
#[test]
fn test_push_error_display_network_error_dns() {
let err =
PushError::NetworkError("DNS resolution failed for registry.example.com".to_string());
assert!(err.to_string().contains("DNS resolution failed"));
}
#[test]
fn test_push_error_display_invalid_reference() {
let err = PushError::InvalidReference {
reference: "invalid::ref".to_string(),
};
assert_eq!(err.to_string(), "invalid image reference: invalid::ref");
}
#[test]
fn test_push_error_display_invalid_reference_empty() {
let err = PushError::InvalidReference {
reference: String::new(),
};
assert_eq!(err.to_string(), "invalid image reference: ");
}
#[test]
fn test_push_error_display_invalid_reference_special_chars() {
let err = PushError::InvalidReference {
reference: "ghcr.io/test/image:tag@sha256:abc".to_string(),
};
assert!(err
.to_string()
.contains("ghcr.io/test/image:tag@sha256:abc"));
}
#[test]
fn test_push_error_debug_authentication_failed() {
let err = PushError::AuthenticationFailed {
registry: "ghcr.io".to_string(),
reason: "invalid token".to_string(),
};
let debug_str = format!("{err:?}");
assert!(debug_str.contains("AuthenticationFailed"));
assert!(debug_str.contains("ghcr.io"));
assert!(debug_str.contains("invalid token"));
}
#[test]
fn test_push_error_debug_blob_upload_failed() {
let err = PushError::BlobUploadFailed {
digest: "sha256:abc123".to_string(),
reason: "network error".to_string(),
};
let debug_str = format!("{err:?}");
assert!(debug_str.contains("BlobUploadFailed"));
assert!(debug_str.contains("sha256:abc123"));
assert!(debug_str.contains("network error"));
}
#[test]
fn test_push_error_debug_manifest_upload_failed() {
let err = PushError::ManifestUploadFailed {
reason: "schema validation failed".to_string(),
};
let debug_str = format!("{err:?}");
assert!(debug_str.contains("ManifestUploadFailed"));
assert!(debug_str.contains("schema validation failed"));
}
#[test]
fn test_push_error_debug_network_error() {
let err = PushError::NetworkError("connection timed out".to_string());
let debug_str = format!("{err:?}");
assert!(debug_str.contains("NetworkError"));
assert!(debug_str.contains("connection timed out"));
}
#[test]
fn test_push_error_debug_invalid_reference() {
let err = PushError::InvalidReference {
reference: "bad-ref".to_string(),
};
let debug_str = format!("{err:?}");
assert!(debug_str.contains("InvalidReference"));
assert!(debug_str.contains("bad-ref"));
}
#[test]
fn test_push_error_debug_oci_error() {
let oci_err =
oci_client::errors::OciDistributionError::GenericError(Some("test error".to_string()));
let err = PushError::OciError(oci_err);
let debug_str = format!("{err:?}");
assert!(debug_str.contains("OciError"));
}
#[test]
fn test_push_error_from_oci_generic_error() {
let oci_err = oci_client::errors::OciDistributionError::GenericError(Some(
"generic error message".to_string(),
));
let push_err: PushError = oci_err.into();
match push_err {
PushError::OciError(inner) => {
assert!(inner.to_string().contains("generic error message"));
}
_ => panic!("Expected OciError variant"),
}
}
#[test]
fn test_push_error_from_oci_config_conversion_error() {
let oci_err = oci_client::errors::OciDistributionError::ConfigConversionError(
"config conversion failed".to_string(),
);
let push_err: PushError = oci_err.into();
match push_err {
PushError::OciError(inner) => {
assert!(inner.to_string().contains("config conversion"));
}
_ => panic!("Expected OciError variant"),
}
}
#[test]
fn test_push_error_from_oci_manifest_parsing_error() {
let oci_err = oci_client::errors::OciDistributionError::ManifestParsingError(
"invalid manifest JSON".to_string(),
);
let push_err: PushError = oci_err.into();
match push_err {
PushError::OciError(inner) => {
assert!(
inner.to_string().contains("manifest") || inner.to_string().contains("JSON")
);
}
_ => panic!("Expected OciError variant"),
}
}
#[test]
fn test_push_error_from_oci_image_manifest_not_found() {
let oci_err = oci_client::errors::OciDistributionError::ImageManifestNotFoundError(
"image:tag".to_string(),
);
let push_err: PushError = oci_err.into();
match push_err {
PushError::OciError(inner) => {
assert!(inner.to_string().contains("image:tag"));
}
_ => panic!("Expected OciError variant"),
}
}
#[test]
fn test_push_error_from_oci_url_parse_error() {
let oci_err =
oci_client::errors::OciDistributionError::UrlParseError("invalid URL".to_string());
let push_err: PushError = oci_err.into();
match push_err {
PushError::OciError(inner) => {
assert!(inner.to_string().contains("URL"));
}
_ => panic!("Expected OciError variant"),
}
}
#[test]
fn test_push_error_from_oci_unsupported_schema_version() {
let oci_err = oci_client::errors::OciDistributionError::UnsupportedSchemaVersionError(99);
let push_err: PushError = oci_err.into();
match push_err {
PushError::OciError(inner) => {
let _ = inner.to_string();
}
_ => panic!("Expected OciError variant"),
}
}
#[test]
fn test_push_error_from_oci_unsupported_media_type() {
let oci_err = oci_client::errors::OciDistributionError::UnsupportedMediaTypeError(
"application/unknown".to_string(),
);
let push_err: PushError = oci_err.into();
match push_err {
PushError::OciError(inner) => {
assert!(inner.to_string().contains("application/unknown"));
}
_ => panic!("Expected OciError variant"),
}
}
#[test]
fn test_push_error_oci_error_display() {
let oci_err = oci_client::errors::OciDistributionError::GenericError(Some(
"version mismatch".to_string(),
));
let push_err = PushError::OciError(oci_err);
assert!(push_err.to_string().contains("OCI distribution error"));
}
#[test]
fn test_push_error_from_oci_spec_violation() {
let oci_err = oci_client::errors::OciDistributionError::SpecViolationError(
"OCI spec violation".to_string(),
);
let push_err: PushError = oci_err.into();
match push_err {
PushError::OciError(inner) => {
assert!(
inner.to_string().contains("spec") || inner.to_string().contains("violation")
);
}
_ => panic!("Expected OciError variant"),
}
}
#[test]
fn test_push_error_from_oci_versioned_parsing_error() {
let oci_err = oci_client::errors::OciDistributionError::VersionedParsingError(
"failed to parse versioned content".to_string(),
);
let push_err: PushError = oci_err.into();
match push_err {
PushError::OciError(inner) => {
let _ = inner.to_string();
}
_ => panic!("Expected OciError variant"),
}
}
#[test]
fn test_push_error_from_oci_registry_token_decode() {
let oci_err = oci_client::errors::OciDistributionError::RegistryTokenDecodeError(
"invalid token format".to_string(),
);
let push_err: PushError = oci_err.into();
match push_err {
PushError::OciError(inner) => {
assert!(inner.to_string().contains("token"));
}
_ => panic!("Expected OciError variant"),
}
}
#[test]
fn test_push_error_from_oci_incompatible_layer_media_type() {
let oci_err = oci_client::errors::OciDistributionError::IncompatibleLayerMediaTypeError(
"application/vnd.incompatible".to_string(),
);
let push_err: PushError = oci_err.into();
match push_err {
PushError::OciError(inner) => {
assert!(
inner.to_string().contains("incompatible")
|| inner.to_string().contains("layer")
);
}
_ => panic!("Expected OciError variant"),
}
}
#[test]
fn test_push_result_creation_all_fields() {
let result = PushResult {
manifest_digest: "sha256:abc123".to_string(),
blobs_pushed: vec!["sha256:def456".to_string(), "sha256:ghi789".to_string()],
reference: "ghcr.io/test/image:v1.0".to_string(),
};
assert_eq!(result.manifest_digest, "sha256:abc123");
assert_eq!(result.blobs_pushed.len(), 2);
assert_eq!(result.blobs_pushed[0], "sha256:def456");
assert_eq!(result.blobs_pushed[1], "sha256:ghi789");
assert_eq!(result.reference, "ghcr.io/test/image:v1.0");
}
#[test]
fn test_push_result_creation_empty_blobs() {
let result = PushResult {
manifest_digest: "sha256:empty".to_string(),
blobs_pushed: vec![],
reference: "docker.io/test:latest".to_string(),
};
assert!(result.blobs_pushed.is_empty());
assert_eq!(result.manifest_digest, "sha256:empty");
}
#[test]
fn test_push_result_creation_single_blob() {
let result = PushResult {
manifest_digest: "sha256:single".to_string(),
blobs_pushed: vec!["sha256:only_one".to_string()],
reference: "registry.example.com/repo:tag".to_string(),
};
assert_eq!(result.blobs_pushed.len(), 1);
}
#[test]
fn test_push_result_creation_many_blobs() {
let blobs: Vec<String> = (0..100).map(|i| format!("sha256:blob{i:03}")).collect();
let result = PushResult {
manifest_digest: "sha256:many".to_string(),
blobs_pushed: blobs,
reference: "test/image:v1".to_string(),
};
assert_eq!(result.blobs_pushed.len(), 100);
assert_eq!(result.blobs_pushed[0], "sha256:blob000");
assert_eq!(result.blobs_pushed[99], "sha256:blob099");
}
#[test]
fn test_push_result_clone() {
let result = PushResult {
manifest_digest: "sha256:abc".to_string(),
blobs_pushed: vec!["sha256:def".to_string()],
reference: "test:v1".to_string(),
};
let cloned = result.clone();
assert_eq!(result.manifest_digest, cloned.manifest_digest);
assert_eq!(result.blobs_pushed, cloned.blobs_pushed);
assert_eq!(result.reference, cloned.reference);
}
#[test]
fn test_push_result_clone_independence() {
let result = PushResult {
manifest_digest: "sha256:original".to_string(),
blobs_pushed: vec!["sha256:blob1".to_string()],
reference: "original:v1".to_string(),
};
let mut cloned = result.clone();
cloned.manifest_digest = "sha256:modified".to_string();
cloned.blobs_pushed.push("sha256:blob2".to_string());
assert_eq!(result.manifest_digest, "sha256:original");
assert_eq!(result.blobs_pushed.len(), 1);
assert_eq!(cloned.manifest_digest, "sha256:modified");
assert_eq!(cloned.blobs_pushed.len(), 2);
}
#[test]
fn test_push_result_debug() {
let result = PushResult {
manifest_digest: "sha256:test".to_string(),
blobs_pushed: vec!["sha256:blob1".to_string(), "sha256:blob2".to_string()],
reference: "ghcr.io/org/repo:tag".to_string(),
};
let debug_str = format!("{result:?}");
assert!(debug_str.contains("PushResult"));
assert!(debug_str.contains("sha256:test"));
assert!(debug_str.contains("sha256:blob1"));
assert!(debug_str.contains("sha256:blob2"));
assert!(debug_str.contains("ghcr.io/org/repo:tag"));
}
#[test]
fn test_push_result_with_full_sha256_digest() {
let full_digest = "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
let result = PushResult {
manifest_digest: full_digest.to_string(),
blobs_pushed: vec![full_digest.to_string()],
reference: "test:latest".to_string(),
};
assert_eq!(result.manifest_digest.len(), 71); }
#[test]
fn test_valid_reference_parsing_docker_hub() {
let reference = "docker.io/library/nginx:latest";
let parsed: Result<Reference, _> = reference.parse();
assert!(parsed.is_ok());
}
#[test]
fn test_valid_reference_parsing_ghcr() {
let reference = "ghcr.io/myorg/myrepo:v1.0.0";
let parsed: Result<Reference, _> = reference.parse();
assert!(parsed.is_ok());
}
#[test]
fn test_valid_reference_parsing_with_digest() {
let reference = "ghcr.io/test/image@sha256:abc123def456789012345678901234567890123456789012345678901234";
let parsed: Result<Reference, _> = reference.parse();
let _ = parsed;
}
#[test]
fn test_valid_reference_parsing_nested_repo() {
let reference = "gcr.io/project-id/subdir/image:tag";
let parsed: Result<Reference, _> = reference.parse();
assert!(parsed.is_ok());
}
#[test]
fn test_invalid_reference_empty() {
let reference = "";
let parsed: Result<Reference, _> = reference.parse();
assert!(parsed.is_err());
}
#[test]
fn test_invalid_reference_double_colon() {
let reference = "invalid::reference";
let parsed: Result<Reference, _> = reference.parse();
assert!(parsed.is_err());
}
#[test]
fn test_push_error_authentication_failed_construction() {
let err = PushError::AuthenticationFailed {
registry: "test.registry.io".to_string(),
reason: "credentials expired".to_string(),
};
let display = err.to_string();
assert!(display.contains("test.registry.io"));
assert!(display.contains("credentials expired"));
}
#[test]
fn test_push_error_blob_upload_failed_construction() {
let digest = "sha256:1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
let err = PushError::BlobUploadFailed {
digest: digest.to_string(),
reason: "server returned 500".to_string(),
};
let display = err.to_string();
assert!(display.contains(digest));
assert!(display.contains("server returned 500"));
}
#[test]
fn test_push_error_manifest_upload_failed_construction() {
let err = PushError::ManifestUploadFailed {
reason: "manifest already exists with different content".to_string(),
};
let display = err.to_string();
assert!(display.contains("manifest already exists"));
}
#[test]
fn test_push_error_network_error_construction() {
let err = PushError::NetworkError("TLS handshake failed".to_string());
let display = err.to_string();
assert!(display.contains("TLS handshake failed"));
}
#[test]
fn test_push_error_invalid_reference_construction() {
let err = PushError::InvalidReference {
reference: "not/a/valid/reference!!!".to_string(),
};
let display = err.to_string();
assert!(display.contains("not/a/valid/reference!!!"));
}
#[test]
fn test_push_error_is_authentication_failed() {
let err = PushError::AuthenticationFailed {
registry: "test".to_string(),
reason: "test".to_string(),
};
assert!(matches!(err, PushError::AuthenticationFailed { .. }));
assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
assert!(!matches!(err, PushError::NetworkError(_)));
assert!(!matches!(err, PushError::InvalidReference { .. }));
assert!(!matches!(err, PushError::OciError(_)));
}
#[test]
fn test_push_error_is_blob_upload_failed() {
let err = PushError::BlobUploadFailed {
digest: "test".to_string(),
reason: "test".to_string(),
};
assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
assert!(matches!(err, PushError::BlobUploadFailed { .. }));
assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
assert!(!matches!(err, PushError::NetworkError(_)));
assert!(!matches!(err, PushError::InvalidReference { .. }));
assert!(!matches!(err, PushError::OciError(_)));
}
#[test]
fn test_push_error_is_manifest_upload_failed() {
let err = PushError::ManifestUploadFailed {
reason: "test".to_string(),
};
assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
assert!(matches!(err, PushError::ManifestUploadFailed { .. }));
assert!(!matches!(err, PushError::NetworkError(_)));
assert!(!matches!(err, PushError::InvalidReference { .. }));
assert!(!matches!(err, PushError::OciError(_)));
}
#[test]
fn test_push_error_is_network_error() {
let err = PushError::NetworkError("test".to_string());
assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
assert!(matches!(err, PushError::NetworkError(_)));
assert!(!matches!(err, PushError::InvalidReference { .. }));
assert!(!matches!(err, PushError::OciError(_)));
}
#[test]
fn test_push_error_is_invalid_reference() {
let err = PushError::InvalidReference {
reference: "test".to_string(),
};
assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
assert!(!matches!(err, PushError::NetworkError(_)));
assert!(matches!(err, PushError::InvalidReference { .. }));
assert!(!matches!(err, PushError::OciError(_)));
}
#[test]
fn test_push_error_is_oci_error() {
let oci_err =
oci_client::errors::OciDistributionError::GenericError(Some("test".to_string()));
let err = PushError::OciError(oci_err);
assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
assert!(!matches!(err, PushError::NetworkError(_)));
assert!(!matches!(err, PushError::InvalidReference { .. }));
assert!(matches!(err, PushError::OciError(_)));
}
#[test]
fn test_push_error_implements_error_trait() {
let err = PushError::NetworkError("test".to_string());
let _: &dyn std::error::Error = &err;
}
#[test]
fn test_push_error_source_for_oci_error() {
use std::error::Error;
let oci_err =
oci_client::errors::OciDistributionError::GenericError(Some("test".to_string()));
let err = PushError::OciError(oci_err);
let source = err.source();
assert!(source.is_some());
}
#[test]
fn test_push_error_source_for_other_variants() {
use std::error::Error;
let err1 = PushError::AuthenticationFailed {
registry: "test".to_string(),
reason: "test".to_string(),
};
assert!(err1.source().is_none());
let err2 = PushError::BlobUploadFailed {
digest: "test".to_string(),
reason: "test".to_string(),
};
assert!(err2.source().is_none());
let err3 = PushError::ManifestUploadFailed {
reason: "test".to_string(),
};
assert!(err3.source().is_none());
let err4 = PushError::NetworkError("test".to_string());
assert!(err4.source().is_none());
let err5 = PushError::InvalidReference {
reference: "test".to_string(),
};
assert!(err5.source().is_none());
}
#[test]
fn test_image_puller_creation_with_blob_cache() {
let cache = crate::cache::BlobCache::new().unwrap();
let puller = ImagePuller::new(cache);
let _ = puller;
}
#[test]
fn test_image_puller_with_concurrency_limit() {
let cache = crate::cache::BlobCache::new().unwrap();
let puller = ImagePuller::new(cache).with_concurrency_limit(5);
let _ = puller;
}
#[test]
fn test_image_puller_with_concurrency_limit_one() {
let cache = crate::cache::BlobCache::new().unwrap();
let puller = ImagePuller::new(cache).with_concurrency_limit(1);
let _ = puller;
}
#[test]
fn test_image_puller_with_shared_cache() {
let cache = crate::cache::BlobCache::new().unwrap();
let shared: Arc<Box<dyn BlobCacheBackend>> = Arc::new(Box::new(cache));
let puller = ImagePuller::with_cache(shared);
let _ = puller;
}
#[tokio::test]
async fn test_push_blob_invalid_reference_returns_error() {
let cache = crate::cache::BlobCache::new().unwrap();
let puller = ImagePuller::new(cache);
let result = puller
.push_blob(
"invalid::reference",
"sha256:test",
b"test data",
"application/octet-stream",
&RegistryAuth::Anonymous,
)
.await;
assert!(result.is_err());
match result {
Err(PushError::InvalidReference { reference }) => {
assert_eq!(reference, "invalid::reference");
}
other => panic!("Expected InvalidReference error, got {other:?}"),
}
}
#[tokio::test]
async fn test_push_blob_empty_reference_returns_error() {
let cache = crate::cache::BlobCache::new().unwrap();
let puller = ImagePuller::new(cache);
let result = puller
.push_blob(
"",
"sha256:test",
b"test data",
"application/octet-stream",
&RegistryAuth::Anonymous,
)
.await;
assert!(result.is_err());
match result {
Err(PushError::InvalidReference { reference }) => {
assert!(reference.is_empty());
}
other => panic!("Expected InvalidReference error, got {other:?}"),
}
}
#[tokio::test]
async fn test_push_manifest_invalid_reference_returns_error() {
let cache = crate::cache::BlobCache::new().unwrap();
let puller = ImagePuller::new(cache);
let manifest = oci_client::manifest::OciImageManifest::default();
let result = puller
.push_manifest_to_registry("invalid::reference", &manifest, &RegistryAuth::Anonymous)
.await;
assert!(result.is_err());
match result {
Err(PushError::InvalidReference { reference }) => {
assert_eq!(reference, "invalid::reference");
}
other => panic!("Expected InvalidReference error, got {other:?}"),
}
}
#[tokio::test]
async fn test_push_manifest_empty_reference_returns_error() {
let cache = crate::cache::BlobCache::new().unwrap();
let puller = ImagePuller::new(cache);
let manifest = oci_client::manifest::OciImageManifest::default();
let result = puller
.push_manifest_to_registry("", &manifest, &RegistryAuth::Anonymous)
.await;
assert!(result.is_err());
match result {
Err(PushError::InvalidReference { reference }) => {
assert!(reference.is_empty());
}
other => panic!("Expected InvalidReference error, got {other:?}"),
}
}
#[cfg(feature = "local")]
#[tokio::test]
async fn test_push_wasm_invalid_reference_returns_error() {
use crate::wasm::WasiVersion;
use crate::wasm_export::WasmExportResult;
let cache = crate::cache::BlobCache::new().unwrap();
let puller = ImagePuller::new(cache);
let export_result = WasmExportResult {
manifest_digest: "sha256:test".to_string(),
manifest_size: 100,
wasm_layer_digest: "sha256:wasm".to_string(),
wasm_size: 1000,
config_digest: "sha256:config".to_string(),
config_size: 2,
wasi_version: WasiVersion::Preview1,
artifact_type: "application/vnd.wasm.module.v1+wasm".to_string(),
manifest_json: b"{}".to_vec(),
config_blob: b"{}".to_vec(),
wasm_binary: vec![0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00],
};
let result = puller
.push_wasm(
"invalid::reference",
&export_result,
&RegistryAuth::Anonymous,
)
.await;
assert!(result.is_err());
match result {
Err(PushError::InvalidReference { reference }) => {
assert_eq!(reference, "invalid::reference");
}
other => panic!("Expected InvalidReference error, got {other:?}"),
}
}
#[cfg(feature = "local")]
#[tokio::test]
async fn test_push_wasm_empty_reference_returns_error() {
use crate::wasm::WasiVersion;
use crate::wasm_export::WasmExportResult;
let cache = crate::cache::BlobCache::new().unwrap();
let puller = ImagePuller::new(cache);
let export_result = WasmExportResult {
manifest_digest: "sha256:test".to_string(),
manifest_size: 100,
wasm_layer_digest: "sha256:wasm".to_string(),
wasm_size: 1000,
config_digest: "sha256:config".to_string(),
config_size: 2,
wasi_version: WasiVersion::Preview2,
artifact_type: "application/vnd.wasm.component.v1+wasm".to_string(),
manifest_json: b"{}".to_vec(),
config_blob: b"{}".to_vec(),
wasm_binary: vec![0x00, 0x61, 0x73, 0x6d, 0x0d, 0x00, 0x01, 0x00],
};
let result = puller
.push_wasm("", &export_result, &RegistryAuth::Anonymous)
.await;
assert!(result.is_err());
match result {
Err(PushError::InvalidReference { reference }) => {
assert!(reference.is_empty());
}
other => panic!("Expected InvalidReference error, got {other:?}"),
}
}
#[cfg(feature = "local")]
#[test]
fn test_wasm_export_result_debug_formatting() {
use crate::wasm::WasiVersion;
use crate::wasm_export::WasmExportResult;
let result = WasmExportResult {
manifest_digest: "sha256:manifest".to_string(),
manifest_size: 500,
wasm_layer_digest: "sha256:layer".to_string(),
wasm_size: 10000,
config_digest: "sha256:cfg".to_string(),
config_size: 2,
wasi_version: WasiVersion::Preview2,
artifact_type: "application/vnd.wasm.component.v1+wasm".to_string(),
manifest_json: vec![],
config_blob: vec![],
wasm_binary: vec![],
};
let debug_str = format!("{result:?}");
assert!(debug_str.contains("WasmExportResult"));
assert!(debug_str.contains("sha256:manifest"));
assert!(debug_str.contains("sha256:layer"));
assert!(debug_str.contains("Preview2"));
}
#[cfg(feature = "local")]
#[test]
fn test_wasm_export_result_clone_independence() {
use crate::wasm::WasiVersion;
use crate::wasm_export::WasmExportResult;
let result = WasmExportResult {
manifest_digest: "sha256:original".to_string(),
manifest_size: 100,
wasm_layer_digest: "sha256:wasm".to_string(),
wasm_size: 1000,
config_digest: "sha256:config".to_string(),
config_size: 2,
wasi_version: WasiVersion::Preview1,
artifact_type: "application/vnd.wasm.module.v1+wasm".to_string(),
manifest_json: b"{}".to_vec(),
config_blob: b"{}".to_vec(),
wasm_binary: vec![0x00, 0x61, 0x73, 0x6d],
};
let mut cloned = result.clone();
cloned.manifest_digest = "sha256:modified".to_string();
assert_eq!(result.manifest_digest, "sha256:original");
assert_eq!(cloned.manifest_digest, "sha256:modified");
}
#[cfg(feature = "local")]
#[test]
fn test_wasm_export_result_all_fields_populated() {
use crate::wasm::WasiVersion;
use crate::wasm_export::WasmExportResult;
let wasm_binary = vec![0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
let config_blob = b"{}".to_vec();
let manifest_json = b"{\"schemaVersion\": 2}".to_vec();
let result = WasmExportResult {
manifest_digest: "sha256:abc".to_string(),
manifest_size: manifest_json.len() as u64,
wasm_layer_digest: "sha256:def".to_string(),
wasm_size: wasm_binary.len() as u64,
config_digest: "sha256:ghi".to_string(),
config_size: config_blob.len() as u64,
wasi_version: WasiVersion::Preview1,
artifact_type: "application/vnd.wasm.module.v1+wasm".to_string(),
manifest_json: manifest_json.clone(),
config_blob: config_blob.clone(),
wasm_binary: wasm_binary.clone(),
};
assert!(result.manifest_digest.starts_with("sha256:"));
assert_eq!(result.manifest_size, manifest_json.len() as u64);
assert!(result.wasm_layer_digest.starts_with("sha256:"));
assert_eq!(result.wasm_size, wasm_binary.len() as u64);
assert!(result.config_digest.starts_with("sha256:"));
assert_eq!(result.config_size, config_blob.len() as u64);
assert_eq!(result.wasi_version, WasiVersion::Preview1);
assert!(result.artifact_type.contains("wasm"));
assert!(!result.manifest_json.is_empty());
assert!(!result.config_blob.is_empty());
assert!(!result.wasm_binary.is_empty());
}
#[test]
fn test_push_flow_documentation_blob_before_manifest() {
}
#[test]
fn test_push_flow_documentation_authentication_order() {
}
#[test]
fn test_push_result_blobs_pushed_order() {
let result = PushResult {
manifest_digest: "sha256:manifest".to_string(),
blobs_pushed: vec!["sha256:config".to_string(), "sha256:wasm_layer".to_string()],
reference: "test:v1".to_string(),
};
assert_eq!(result.blobs_pushed.len(), 2);
assert!(result.blobs_pushed[0].contains("config"));
assert!(result.blobs_pushed[1].contains("layer"));
}
#[test]
fn is_mutable_tag_recognises_no_tag() {
assert!(is_mutable_tag("nginx"));
assert!(is_mutable_tag("zachhandley/zlayer-manager"));
assert!(is_mutable_tag("registry.example.com:5000/img"));
}
#[test]
fn is_mutable_tag_recognises_empty_tag() {
assert!(is_mutable_tag("nginx:"));
}
#[test]
fn is_mutable_tag_recognises_known_mutable_tags() {
assert!(is_mutable_tag("nginx:latest"));
assert!(is_mutable_tag("nginx:dev"));
assert!(is_mutable_tag("nginx:edge"));
assert!(is_mutable_tag("nginx:main"));
assert!(is_mutable_tag("nginx:master"));
assert!(is_mutable_tag("zachhandley/zlayer-manager:latest"));
assert!(is_mutable_tag("registry.example.com:5000/img:latest"));
}
#[test]
fn is_mutable_tag_rejects_pinned_tags() {
assert!(!is_mutable_tag("nginx:1.25"));
assert!(!is_mutable_tag("nginx:1.25.3"));
assert!(!is_mutable_tag("zachhandley/zlayer-manager:v0.10.70"));
assert!(!is_mutable_tag("registry.example.com:5000/img:v1"));
}
#[test]
fn is_mutable_tag_rejects_digest_refs() {
assert!(!is_mutable_tag(
"img@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
));
assert!(!is_mutable_tag(
"nginx:latest@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
));
assert!(!is_mutable_tag(
"registry.example.com:5000/img@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
));
}
#[test]
fn is_blob_not_found_detects_404_server_error() {
use oci_client::errors::OciDistributionError;
let err = OciDistributionError::ServerError {
code: 404,
url: "https://example.com/v2/foo/blobs/sha256:abc".to_string(),
message: "not found".to_string(),
};
assert!(is_blob_not_found(&err));
}
#[test]
fn is_blob_not_found_detects_manifest_not_found() {
use oci_client::errors::OciDistributionError;
let err = OciDistributionError::ImageManifestNotFoundError("foo".to_string());
assert!(is_blob_not_found(&err));
}
#[test]
fn is_blob_not_found_detects_blob_unknown_registry_error() {
use oci_client::errors::{OciDistributionError, OciEnvelope, OciError, OciErrorCode};
let envelope = OciEnvelope {
errors: vec![OciError {
code: OciErrorCode::BlobUnknown,
message: "blob gone".to_string(),
detail: serde_json::Value::Null,
}],
};
let err = OciDistributionError::RegistryError {
envelope,
url: "https://example.com/v2/foo/blobs/sha256:abc".to_string(),
};
assert!(is_blob_not_found(&err));
}
#[test]
fn is_blob_not_found_rejects_non_404_server_error() {
use oci_client::errors::OciDistributionError;
let err = OciDistributionError::ServerError {
code: 500,
url: "https://example.com/v2/foo/blobs/sha256:abc".to_string(),
message: "boom".to_string(),
};
assert!(!is_blob_not_found(&err));
}
#[test]
fn is_blob_not_found_rejects_auth_failure() {
use oci_client::errors::OciDistributionError;
let err = OciDistributionError::AuthenticationFailure("bad creds".to_string());
assert!(!is_blob_not_found(&err));
}
#[test]
fn max_foreign_layer_redirects_is_capped() {
assert_eq!(MAX_FOREIGN_LAYER_REDIRECTS, 5);
}
#[tokio::test]
async fn fetch_blob_from_url_rejects_invalid_url() {
let result = fetch_blob_from_url(
"not-a-url",
"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
None,
)
.await;
assert!(result.is_err());
}
#[tokio::test]
async fn fetch_archive_from_url_rejects_invalid_url() {
let result = fetch_archive_from_url("not-a-url", None).await;
assert!(result.is_err());
}
#[tokio::test]
async fn fetch_archive_from_url_rejects_unreachable_host() {
let result = fetch_archive_from_url("http://127.0.0.1:1/archive.tar", None).await;
assert!(result.is_err());
}
#[tokio::test]
async fn fetch_archive_from_url_accepts_basic_auth_without_panic() {
let result =
fetch_archive_from_url("http://127.0.0.1:1/archive.tar", Some(("user", "password")))
.await;
assert!(result.is_err());
}
#[tokio::test]
async fn fetch_from_url_surfaces_context_in_error() {
let result = fetch_from_url("http://127.0.0.1:1/thing", None, "test-context").await;
let Err(err) = result else {
panic!("expected connect-refused error");
};
let msg = err.to_string();
assert!(
msg.contains("test-context"),
"error should include context label, got: {msg}"
);
}
#[tokio::test]
async fn fetch_blob_from_url_rejects_unreachable_host() {
let result = fetch_blob_from_url(
"http://127.0.0.1:1/foo",
"sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
None,
)
.await;
assert!(result.is_err());
}
#[test]
fn parse_image_manifest_only_rejects_index() {
let index_json = br#"{"schemaVersion":2,"mediaType":"application/vnd.oci.image.index.v1+json","manifests":[]}"#;
assert!(parse_image_manifest_only(index_json).is_none());
}
#[test]
fn parse_image_manifest_only_accepts_image_manifest() {
let image_json = br#"{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","config":{"mediaType":"application/vnd.oci.image.config.v1+json","digest":"sha256:cfg","size":1},"layers":[]}"#;
assert!(parse_image_manifest_only(image_json).is_some());
}
#[cfg(feature = "local")]
#[tokio::test]
async fn resolve_stored_manifest_follows_local_index() {
let tmp = tempfile::TempDir::new().unwrap();
let registry = std::sync::Arc::new(
crate::local_registry::LocalRegistry::new(tmp.path().to_path_buf())
.await
.unwrap(),
);
let image_json = br#"{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","config":{"mediaType":"application/vnd.oci.image.config.v1+json","digest":"sha256:cfg","size":1},"layers":[]}"#;
let sub_digest = registry
.put_manifest("test/img", "sha256:ignored", image_json)
.await
.unwrap();
let index = OciImageIndex {
schema_version: 2,
media_type: Some("application/vnd.oci.image.index.v1+json".to_string()),
manifests: vec![mk_entry(go_os_name(), go_arch_name(), None, &sub_digest)],
artifact_type: None,
annotations: None,
};
let index_bytes = serde_json::to_vec(&index).unwrap();
let cache: Arc<Box<dyn BlobCacheBackend>> =
Arc::new(Box::new(crate::cache::BlobCache::new().unwrap()));
let puller = ImagePuller::with_cache(cache).with_local_registry(registry.clone());
let (_manifest, digest) = puller
.resolve_stored_manifest(®istry, "test/img", &index_bytes)
.await
.expect("index should resolve to the host-platform manifest");
assert_eq!(digest, sub_digest);
let (_m2, d2) = puller
.resolve_stored_manifest(®istry, "test/img", image_json)
.await
.expect("plain image manifest should resolve as-is");
assert_eq!(d2, sub_digest);
}
fn mk_entry(os: &str, arch: &str, os_version: Option<&str>, digest: &str) -> ImageIndexEntry {
ImageIndexEntry {
media_type: "application/vnd.oci.image.manifest.v1+json".to_string(),
digest: digest.to_string(),
size: 0,
platform: Some(oci_client::manifest::Platform {
architecture: arch.to_string(),
os: os.to_string(),
os_version: os_version.map(str::to_string),
os_features: None,
variant: None,
features: None,
}),
annotations: None,
}
}
#[test]
fn platform_resolver_windows_os_version_prefers_prefix_match() {
use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
let manifests = vec![
mk_entry(
"windows",
"amd64",
Some("10.0.20348.2113"),
"sha256:server2022",
),
mk_entry(
"windows",
"amd64",
Some("10.0.26100.1742"),
"sha256:server2025",
),
];
let target =
TargetPlatform::new(OsKind::Windows, ArchKind::Amd64).with_os_version("10.0.26100");
let resolver = build_platform_resolver(Some(target));
assert_eq!(resolver(&manifests).as_deref(), Some("sha256:server2025"));
}
#[test]
fn platform_resolver_windows_os_version_exact_match() {
use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
let manifests = vec![
mk_entry(
"windows",
"amd64",
Some("10.0.20348.2113"),
"sha256:server2022",
),
mk_entry(
"windows",
"amd64",
Some("10.0.26100.1742"),
"sha256:server2025",
),
];
let target = TargetPlatform::new(OsKind::Windows, ArchKind::Amd64)
.with_os_version("10.0.26100.1742");
let resolver = build_platform_resolver(Some(target));
assert_eq!(resolver(&manifests).as_deref(), Some("sha256:server2025"));
}
#[test]
fn platform_resolver_windows_no_os_version_falls_back_to_first_match() {
use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
let manifests = vec![
mk_entry("windows", "amd64", Some("10.0.20348.2113"), "sha256:first"),
mk_entry("windows", "amd64", Some("10.0.26100.1742"), "sha256:second"),
];
let target = TargetPlatform::new(OsKind::Windows, ArchKind::Amd64);
let resolver = build_platform_resolver(Some(target));
assert_eq!(resolver(&manifests).as_deref(), Some("sha256:first"));
}
#[test]
fn platform_resolver_windows_os_version_falls_back_when_no_version_match() {
use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
let manifests = vec![mk_entry(
"windows",
"amd64",
Some("10.0.20348.2113"),
"sha256:only",
)];
let target =
TargetPlatform::new(OsKind::Windows, ArchKind::Amd64).with_os_version("10.0.26100");
let resolver = build_platform_resolver(Some(target));
assert_eq!(resolver(&manifests).as_deref(), Some("sha256:only"));
}
#[test]
fn platform_resolver_non_windows_ignores_os_version() {
use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
let manifests = vec![mk_entry("linux", "amd64", None, "sha256:linux")];
let target =
TargetPlatform::new(OsKind::Linux, ArchKind::Amd64).with_os_version("ignored.on.linux");
let resolver = build_platform_resolver(Some(target));
assert_eq!(resolver(&manifests).as_deref(), Some("sha256:linux"));
}
#[test]
fn manifest_cache_key_is_stable() {
assert_eq!(
manifest_cache_key("alpine:latest"),
"manifest:docker.io/library/alpine:latest"
);
assert_eq!(
manifest_cache_key("docker.io/library/alpine:latest"),
"manifest:docker.io/library/alpine:latest"
);
assert_eq!(manifest_cache_key(""), "manifest:");
}
#[test]
fn manifest_cache_key_normalizes_bare_and_qualified_to_same_key() {
assert_eq!(
manifest_cache_key("alpine:latest"),
manifest_cache_key("docker.io/library/alpine:latest"),
);
assert_eq!(
manifest_digest_cache_key("alpine:latest"),
manifest_digest_cache_key("docker.io/library/alpine:latest"),
);
}
#[test]
fn manifest_digest_cache_key_is_stable() {
assert_eq!(
manifest_digest_cache_key("alpine:latest"),
"manifest:digest-docker.io/library/alpine:latest"
);
}
#[test]
fn manifest_and_digest_keys_never_collide() {
for image in [
"alpine",
"alpine:latest",
"library/redis:7",
"ghcr.io/x/y:tag",
] {
let body = manifest_cache_key(image);
let digest = manifest_digest_cache_key(image);
assert_ne!(body, digest, "cache-key collision for {image}");
assert!(body.starts_with("manifest:"), "manifest key shape: {body}");
assert!(
digest.starts_with("manifest:digest-"),
"digest key shape: {digest}"
);
}
}
fn seed_cache_with_os(
image: &str,
os: &str,
runtime_marker: Option<&str>,
) -> Arc<Box<dyn BlobCacheBackend>> {
let cache = crate::cache::BlobCache::new().unwrap();
let config_json = serde_json::json!({
"architecture": "arm64",
"os": os,
"config": {},
});
let config_bytes = serde_json::to_vec(&config_json).unwrap();
let config_digest = crate::cache::compute_digest(&config_bytes);
cache.put(&config_digest, &config_bytes).unwrap();
let annotations = runtime_marker.map(|m| {
let mut a = std::collections::BTreeMap::new();
a.insert(crate::ZLAYER_RUNTIME_ANNOTATION.to_string(), m.to_string());
a
});
let manifest = OciImageManifest {
schema_version: 2,
media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
artifact_type: None,
config: oci_client::manifest::OciDescriptor {
media_type: "application/vnd.oci.image.config.v1+json".to_string(),
digest: config_digest.clone(),
size: i64::try_from(config_bytes.len()).unwrap(),
urls: None,
annotations: None,
},
layers: vec![],
annotations,
subject: None,
};
let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
cache
.put(&manifest_cache_key(image), &manifest_bytes)
.unwrap();
cache
.put(
&manifest_digest_cache_key(image),
manifest_digest.as_bytes(),
)
.unwrap();
Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>)
}
struct CountingCache {
inner: crate::cache::BlobCache,
watch_key: String,
in_flight: std::sync::atomic::AtomicUsize,
max_in_flight: std::sync::atomic::AtomicUsize,
delay: std::time::Duration,
}
impl CountingCache {
fn new(inner: crate::cache::BlobCache, watch_key: String) -> Arc<Self> {
Arc::new(Self {
inner,
watch_key,
in_flight: std::sync::atomic::AtomicUsize::new(0),
max_in_flight: std::sync::atomic::AtomicUsize::new(0),
delay: std::time::Duration::from_millis(50),
})
}
fn max_concurrent(&self) -> usize {
self.max_in_flight.load(std::sync::atomic::Ordering::SeqCst)
}
}
#[async_trait::async_trait]
impl BlobCacheBackend for CountingCache {
async fn get(
&self,
digest: &str,
) -> std::result::Result<Option<Vec<u8>>, crate::error::CacheError> {
if digest == self.watch_key {
let now = self
.in_flight
.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
+ 1;
self.max_in_flight
.fetch_max(now, std::sync::atomic::Ordering::SeqCst);
tokio::time::sleep(self.delay).await;
let out = self.inner.get(digest);
self.in_flight
.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
out
} else {
self.inner.get(digest)
}
}
async fn put(
&self,
digest: &str,
data: &[u8],
) -> std::result::Result<(), crate::error::CacheError> {
self.inner.put(digest, data)
}
async fn contains(
&self,
digest: &str,
) -> std::result::Result<bool, crate::error::CacheError> {
self.inner.contains(digest)
}
async fn delete(&self, digest: &str) -> std::result::Result<(), crate::error::CacheError> {
self.inner.delete(digest)
}
}
fn counting_cache_for(image: &str) -> Arc<CountingCache> {
let inner = crate::cache::BlobCache::new().unwrap();
let config_json =
serde_json::json!({ "architecture": "arm64", "os": "linux", "config": {} });
let config_bytes = serde_json::to_vec(&config_json).unwrap();
let config_digest = crate::cache::compute_digest(&config_bytes);
inner.put(&config_digest, &config_bytes).unwrap();
let manifest = OciImageManifest {
schema_version: 2,
media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
artifact_type: None,
config: oci_client::manifest::OciDescriptor {
media_type: "application/vnd.oci.image.config.v1+json".to_string(),
digest: config_digest.clone(),
size: i64::try_from(config_bytes.len()).unwrap(),
urls: None,
annotations: None,
},
layers: vec![],
annotations: None,
subject: None,
};
let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
inner
.put(&manifest_cache_key(image), &manifest_bytes)
.unwrap();
inner
.put(
&manifest_digest_cache_key(image),
manifest_digest.as_bytes(),
)
.unwrap();
CountingCache::new(inner, manifest_cache_key(image))
}
#[tokio::test]
async fn pull_image_to_files_single_flights_concurrent_pulls_of_same_ref() {
let image = "registry.example.com/team/executor@sha256:\
1111111111111111111111111111111111111111111111111111111111111111";
let counting = counting_cache_for(image);
let cache: Arc<Box<dyn BlobCacheBackend>> =
Arc::new(Box::new(CountingCacheHandle(counting.clone())) as Box<dyn BlobCacheBackend>);
let puller = Arc::new(ImagePuller::with_cache(cache));
let tmp = tempfile::tempdir().unwrap();
let n = 10usize;
let mut set = tokio::task::JoinSet::new();
for i in 0..n {
let puller = puller.clone();
let image = image.to_string();
let stage = tmp.path().join(format!("stage-{i}"));
set.spawn(async move {
puller
.pull_image_to_files_with_policy(
&image,
&RegistryAuth::Anonymous,
&stage,
PullPolicy::IfNotPresent,
)
.await
});
}
let mut ok = 0usize;
while let Some(joined) = set.join_next().await {
let layers = joined
.expect("task must not panic")
.expect("pull must succeed");
assert!(
layers.is_empty(),
"zero-layer manifest yields zero layer files"
);
ok += 1;
}
assert_eq!(ok, n, "every concurrent caller must complete");
assert_eq!(
counting.max_concurrent(),
1,
"single-flight must collapse the {n} concurrent pulls onto ONE in-flight \
manifest fetch (the leader); followers block until it completes",
);
}
#[tokio::test]
async fn pull_image_config_single_flights_concurrent_fetches_of_same_ref() {
let image = "registry.example.com/team/cfg@sha256:\
2222222222222222222222222222222222222222222222222222222222222222";
let inner = crate::cache::BlobCache::new().unwrap();
let config_json =
serde_json::json!({ "architecture": "arm64", "os": "linux", "config": {} });
let config_bytes = serde_json::to_vec(&config_json).unwrap();
let config_digest = crate::cache::compute_digest(&config_bytes);
inner.put(&config_digest, &config_bytes).unwrap();
let manifest = OciImageManifest {
schema_version: 2,
media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
artifact_type: None,
config: oci_client::manifest::OciDescriptor {
media_type: "application/vnd.oci.image.config.v1+json".to_string(),
digest: config_digest.clone(),
size: i64::try_from(config_bytes.len()).unwrap(),
urls: None,
annotations: None,
},
layers: vec![],
annotations: None,
subject: None,
};
let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
inner
.put(&manifest_cache_key(image), &manifest_bytes)
.unwrap();
inner
.put(
&manifest_digest_cache_key(image),
manifest_digest.as_bytes(),
)
.unwrap();
let counting = CountingCache::new(inner, config_digest.clone());
let cache: Arc<Box<dyn BlobCacheBackend>> =
Arc::new(Box::new(CountingCacheHandle(counting.clone())) as Box<dyn BlobCacheBackend>);
let puller = Arc::new(ImagePuller::with_cache(cache));
let n = 10usize;
let mut set = tokio::task::JoinSet::new();
for _ in 0..n {
let puller = puller.clone();
let image = image.to_string();
set.spawn(async move {
puller
.pull_image_config_with_policy(
&image,
&RegistryAuth::Anonymous,
PullPolicy::IfNotPresent,
)
.await
});
}
let mut ok = 0usize;
while let Some(joined) = set.join_next().await {
joined
.expect("task must not panic")
.expect("config fetch must succeed");
ok += 1;
}
assert_eq!(ok, n);
assert_eq!(
counting.max_concurrent(),
1,
"single-flight must collapse the {n} concurrent config fetches onto ONE \
in-flight config-blob read",
);
}
#[tokio::test]
async fn pull_image_to_files_does_not_false_share_across_refs() {
let image_a = "registry.example.com/team/a@sha256:\
3333333333333333333333333333333333333333333333333333333333333333";
let image_b = "registry.example.com/team/b@sha256:\
4444444444444444444444444444444444444444444444444444444444444444";
let counting_a = counting_cache_for(image_a);
let counting_b = counting_cache_for(image_b);
let puller_a = Arc::new(ImagePuller::with_cache(Arc::new(
Box::new(CountingCacheHandle(counting_a.clone())) as Box<dyn BlobCacheBackend>,
)));
let puller_b = Arc::new(ImagePuller::with_cache(Arc::new(
Box::new(CountingCacheHandle(counting_b.clone())) as Box<dyn BlobCacheBackend>,
)));
let tmp = tempfile::tempdir().unwrap();
let stage_a = tmp.path().join("a");
let stage_b = tmp.path().join("b");
let (ra, rb) = tokio::join!(
puller_a.pull_image_to_files_with_policy(
image_a,
&RegistryAuth::Anonymous,
&stage_a,
PullPolicy::IfNotPresent,
),
puller_b.pull_image_to_files_with_policy(
image_b,
&RegistryAuth::Anonymous,
&stage_b,
PullPolicy::IfNotPresent,
),
);
assert!(ra.expect("ref A pull must succeed").is_empty());
assert!(rb.expect("ref B pull must succeed").is_empty());
assert_eq!(counting_a.max_concurrent(), 1);
assert_eq!(counting_b.max_concurrent(), 1);
}
struct CountingCacheHandle(Arc<CountingCache>);
#[async_trait::async_trait]
impl BlobCacheBackend for CountingCacheHandle {
async fn get(
&self,
digest: &str,
) -> std::result::Result<Option<Vec<u8>>, crate::error::CacheError> {
self.0.get(digest).await
}
async fn put(
&self,
digest: &str,
data: &[u8],
) -> std::result::Result<(), crate::error::CacheError> {
self.0.put(digest, data).await
}
async fn contains(
&self,
digest: &str,
) -> std::result::Result<bool, crate::error::CacheError> {
self.0.contains(digest).await
}
async fn delete(&self, digest: &str) -> std::result::Result<(), crate::error::CacheError> {
self.0.delete(digest).await
}
}
#[tokio::test]
async fn image_os_with_policy_resolves_linux_from_local_cache_no_network() {
let image = "docker.io/library/alpine:latest";
let cache = seed_cache_with_os(image, "linux", None);
let puller = ImagePuller::with_cache(cache);
let os = puller
.image_os_with_policy(image, &RegistryAuth::Anonymous, PullPolicy::IfNotPresent)
.await
.expect("local-first OS inspection must not error");
assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
}
#[cfg(feature = "local")]
#[tokio::test]
async fn fetch_image_os_in_cache_resolves_linux_no_network() {
let image = "docker.io/library/alpine:latest";
let cache = seed_cache_with_os(image, "linux", None);
let os = fetch_image_os_in_cache(image, None, cache, None)
.await
.expect("local-first OS inspection must not error");
assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
}
#[cfg(feature = "local")]
#[tokio::test]
async fn fetch_image_runtime_marker_in_cache_resolves_marker_no_network() {
let image = "ghcr.io/example/vz-base:1.0";
let cache = seed_cache_with_os(image, "linux", Some("vz"));
let marker = fetch_image_runtime_marker_in_cache(image, None, cache, None)
.await
.expect("local-first marker inspection must not error");
assert_eq!(marker.as_deref(), Some("vz"));
}
#[tokio::test]
async fn bare_ref_resolves_from_cache_seeded_under_qualified_ref() {
let cache = seed_cache_with_os("docker.io/library/alpine:latest", "linux", None);
let puller = ImagePuller::with_cache(cache);
let os = puller
.image_os_in_cache_only("alpine:latest")
.await
.expect("bare-ref local inspection must not error");
assert_eq!(
os,
Some(zlayer_spec::OsKind::Linux),
"bare `alpine:latest` must resolve from a cache seeded under the qualified ref",
);
}
#[cfg(feature = "local")]
#[tokio::test]
async fn fetch_image_os_in_cache_only_bare_ref_no_network() {
let cache = seed_cache_with_os("docker.io/library/alpine:latest", "linux", None);
let os = fetch_image_os_in_cache_only("alpine:latest", cache, None)
.await
.expect("local-only inspection must not error");
assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
}
#[tokio::test]
async fn image_os_in_cache_only_no_network_when_manifest_and_config_present() {
let image = "docker.io/library/alpine:latest";
let cache = seed_cache_with_os(image, "linux", None);
let puller = ImagePuller::with_cache(cache);
let os = puller
.image_os_in_cache_only(image)
.await
.expect("cached manifest+config must resolve OS with no network");
assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
}
#[tokio::test]
async fn cache_local_image_platform_round_trips_darwin() {
let image = "ghcr.io/owner/seatbelt-app:latest";
let cache: Arc<Box<dyn BlobCacheBackend>> =
Arc::new(Box::new(crate::cache::BlobCache::new().unwrap()));
let puller = ImagePuller::with_cache(cache);
assert_eq!(
puller.image_os_in_cache_only(image).await.unwrap(),
None,
"no stamp yet must be a clean local miss"
);
puller
.cache_local_image_platform(image, "darwin", "arm64")
.await
.expect("stamping a local image's platform must succeed");
let os = puller
.image_os_in_cache_only(image)
.await
.expect("stamped manifest+config must resolve OS with no network");
assert_eq!(os, Some(zlayer_spec::OsKind::Macos));
}
#[tokio::test]
async fn image_os_in_cache_only_returns_none_on_clean_local_miss() {
let cache: Arc<Box<dyn BlobCacheBackend>> = Arc::new(Box::new(
crate::cache::BlobCache::new().unwrap(),
)
as Box<dyn BlobCacheBackend>);
let puller = ImagePuller::with_cache(cache);
let os = puller
.image_os_in_cache_only("docker.io/library/absent:latest")
.await
.expect("a local miss must be Ok(None), never an error");
assert_eq!(os, None);
assert_eq!(
puller.network_call_count(),
0,
"image_os_in_cache_only must never issue a network call, even on a local miss",
);
}
#[tokio::test]
async fn image_os_in_cache_only_bare_ref_issues_zero_network_calls() {
let cache = seed_cache_with_os("docker.io/library/alpine:latest", "linux", None);
let puller = ImagePuller::with_cache(cache);
let os = puller
.image_os_in_cache_only("alpine:latest")
.await
.expect("bare-ref local inspection must not error");
assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
assert_eq!(
puller.network_call_count(),
0,
"a cached image's OS must resolve with ZERO network calls (no Docker Hub re-inspect)",
);
}
#[tokio::test]
async fn image_runtime_marker_in_cache_only_bare_ref_zero_network() {
let cache = seed_cache_with_os("docker.io/library/alpine:latest", "linux", Some("vz"));
let puller = ImagePuller::with_cache(cache);
let marker = puller
.image_runtime_marker_in_cache_only("alpine:latest")
.await
.expect("bare-ref marker inspection must not error");
assert_eq!(marker.as_deref(), Some("vz"));
assert_eq!(
puller.network_call_count(),
0,
"runtime-marker inspection must resolve from cache with ZERO network calls",
);
}
fn seed_cache_with_isolation(image: &str, isolation: &str) -> Arc<Box<dyn BlobCacheBackend>> {
let cache = crate::cache::BlobCache::new().unwrap();
let config_json = serde_json::json!({
"architecture": "arm64",
"os": "linux",
"config": { "Labels": { crate::ZLAYER_ISOLATION_ANNOTATION: isolation } },
});
let config_bytes = serde_json::to_vec(&config_json).unwrap();
let config_digest = crate::cache::compute_digest(&config_bytes);
cache.put(&config_digest, &config_bytes).unwrap();
let manifest = OciImageManifest {
schema_version: 2,
media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
artifact_type: None,
config: oci_client::manifest::OciDescriptor {
media_type: "application/vnd.oci.image.config.v1+json".to_string(),
digest: config_digest.clone(),
size: i64::try_from(config_bytes.len()).unwrap(),
urls: None,
annotations: None,
},
layers: vec![],
annotations: None,
subject: None,
};
let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
cache
.put(&manifest_cache_key(image), &manifest_bytes)
.unwrap();
cache
.put(
&manifest_digest_cache_key(image),
manifest_digest.as_bytes(),
)
.unwrap();
Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>)
}
#[tokio::test]
async fn image_isolation_marker_in_cache_only_reads_config_label_zero_network() {
let image = "docker.io/library/alpine:latest";
let cache = seed_cache_with_isolation(image, "vz-linux");
let puller = ImagePuller::with_cache(cache);
let iso = puller
.image_isolation_marker_in_cache_only("alpine:latest")
.await
.expect("isolation-label inspection must not error");
assert_eq!(iso.as_deref(), Some("vz-linux"));
assert_eq!(
puller.network_call_count(),
0,
"isolation inspection must resolve from cache with ZERO network calls",
);
}
#[tokio::test]
async fn image_isolation_marker_in_cache_only_none_when_label_absent() {
let image = "docker.io/library/alpine:latest";
let cache = seed_cache_with_os(image, "linux", None);
let puller = ImagePuller::with_cache(cache);
let iso = puller
.image_isolation_marker_in_cache_only(image)
.await
.expect("missing isolation label must be Ok(None), never an error");
assert_eq!(iso, None);
}
#[tokio::test]
async fn manifest_cache_key_collides_bare_qualified_and_literal() {
assert_eq!(
manifest_cache_key("alpine:latest"),
"manifest:docker.io/library/alpine:latest",
);
assert_eq!(
manifest_cache_key("docker.io/library/alpine:latest"),
"manifest:docker.io/library/alpine:latest",
);
assert_eq!(
manifest_cache_key("alpine:latest"),
manifest_cache_key("docker.io/library/alpine:latest"),
);
}
struct BrokenS3;
use crate::error::CacheError;
#[async_trait::async_trait]
impl BlobCacheBackend for BrokenS3 {
async fn get(&self, _digest: &str) -> std::result::Result<Option<Vec<u8>>, CacheError> {
Err(CacheError::Database(
"simulated S3 endpoint unreachable".to_string(),
))
}
async fn put(&self, _digest: &str, _data: &[u8]) -> std::result::Result<(), CacheError> {
Err(CacheError::Database(
"simulated S3 endpoint unreachable".to_string(),
))
}
async fn contains(&self, _digest: &str) -> std::result::Result<bool, CacheError> {
Err(CacheError::Database(
"simulated S3 endpoint unreachable".to_string(),
))
}
}
fn broken_s3() -> Arc<Box<dyn BlobCacheBackend>> {
Arc::new(Box::new(BrokenS3) as Box<dyn BlobCacheBackend>)
}
#[tokio::test]
async fn s3_tier_get_treats_error_as_miss() {
let puller = ImagePuller::with_cache(seed_cache_with_os(
"docker.io/library/alpine:latest",
"linux",
None,
))
.with_s3_cache(broken_s3());
assert!(
puller.s3_tier_get("any-key").await.is_none(),
"an erroring S3 tier must degrade to a cache MISS, not surface the error",
);
}
#[tokio::test]
async fn unreachable_s3_does_not_break_local_cache_hit() {
let image = "ghcr.io/example/app:1.2.3";
let puller = ImagePuller::with_cache(seed_cache_with_os(image, "linux", None))
.with_s3_cache(broken_s3());
let (_manifest, _digest) = puller
.pull_manifest_inner(image, &RegistryAuth::Anonymous, PullPolicy::IfNotPresent)
.await
.expect("a local cache hit must survive an unreachable S3 tier");
}
#[tokio::test]
async fn unreachable_s3_falls_through_to_origin_not_a_hard_s3_error() {
let image = "registry.invalid.example.test/example/app:1.0.0";
let empty_cache: Arc<Box<dyn BlobCacheBackend>> = Arc::new(Box::new(
crate::cache::BlobCache::new().unwrap(),
)
as Box<dyn BlobCacheBackend>);
let puller = ImagePuller::with_cache(empty_cache).with_s3_cache(broken_s3());
let err = puller
.pull_manifest_inner(image, &RegistryAuth::Anonymous, PullPolicy::Newer)
.await
.expect_err("an unreachable origin should error (no network in test env)");
match err {
RegistryError::NotFound { .. } | RegistryError::Oci(_) => {}
other => panic!("expected an origin-class error after S3 fell through, got: {other:?}"),
}
}
}