Skip to main content

ImagePuller

Struct ImagePuller 

Source
pub struct ImagePuller { /* private fields */ }
Expand description

OCI image puller with caching

Implementations§

Source§

impl ImagePuller

Source

pub fn new<C: BlobCacheBackend + 'static>(cache: C) -> Self

Create a new image puller with any cache backend.

Pulls will target the process’s runtime platform (with the historical macOS darwin → linux fallback). To pull a specific platform, use ImagePuller::with_platform.

Source

pub fn with_cache(cache: Arc<Box<dyn BlobCacheBackend>>) -> Self

Create a new image puller with boxed cache backend.

Pulls will target the process’s runtime platform (with the historical macOS darwin → linux fallback). To pull a specific platform, use ImagePuller::with_platform.

Source

pub fn with_platform( cache: Arc<Box<dyn BlobCacheBackend>>, target: TargetPlatform, ) -> Self

Create a new image puller targeting a specific OCI platform.

The puller’s internal oci-client will select the manifest whose {os}/{arch} matches target from a multi-platform image index. Unlike ImagePuller::new, no macOS darwin → linux fallback is applied — an explicit target is respected exactly.

Source

pub fn with_concurrency_limit(self, limit: usize) -> Self

Set concurrency limit for blob downloads

Source

pub fn with_s3_cache(self, s3: Arc<Box<dyn BlobCacheBackend>>) -> Self

Attach a SHARED/remote blob cache (typically S3) as the write-through tier probed after the primary cache and before the network. See the s3_cache field. Build one from the environment with crate::s3_cache_from_env.

Source

pub fn with_default_registry(self, registry: impl Into<String>) -> Self

Set the last-resort default registry host for bare/unqualified names (e.g. docker.io). With no default set, a bare name found nowhere in the chain is an error — ZLayer never silently invents docker.io.

Source

pub fn with_source_policy(self, source: SourcePolicy) -> Self

Override the resolution chain order for this puller (per-image policy).

Source

pub async fn from_env_for_runtime( cache: Arc<Box<dyn BlobCacheBackend>>, source: SourcePolicy, ) -> Self

Central runtime-puller constructor: wraps cache and wires the shared S3 tier (ZLAYER_S3_BUCKET) + last-resort default registry (ZLAYER_DEFAULT_REGISTRY) from the environment, plus the per-image source policy. This is the SINGLE place runtimes get the full source chain — they must not re-implement the env wiring. Callers add .with_local_registry(..) afterward when they have one (it is feature-gated, so it stays at the call site).

Source

pub async fn pull_blob( &self, image: &str, digest: &str, auth: &RegistryAuth, ) -> Result<Vec<u8>>

Pull a single blob and cache it

Uses the provided authentication credentials to pull blobs from the registry.

§Errors

Returns an error if the blob cannot be pulled from the registry or cached.

§Panics

Panics if the concurrency semaphore is closed.

Source

pub async fn pull_blob_with_urls( &self, image: &str, digest: &str, auth: &RegistryAuth, urls: &[String], expected_size: Option<i64>, ) -> Result<Vec<u8>>

Pull a blob, with foreign-layer urls[] redirect fallback on 404.

Behaviour matches [pull_blob] for ordinary layers. For descriptors that carry a non-empty urls list (typically Windows base layers with media type application/vnd.docker.image.rootfs.foreign.diff.tar.gzip or the OCI nondistributable layer types served by Microsoft Container Registry), a primary-registry 404 triggers sequential GETs against each URL. Each redirect response is digest-verified (and size-verified when expected_size is provided); the first successful match is cached and returned.

At most the first MAX_FOREIGN_LAYER_REDIRECTS URLs are attempted; any additional URLs are ignored to guard against circular redirect spam.

§Errors

Returns an error if the blob cannot be pulled from the primary registry and every urls[] fallback also fails.

§Panics

Panics if the concurrency semaphore is closed.

Source

pub async fn pull_blob_to_file( &self, image: &str, digest: &str, auth: &RegistryAuth, urls: &[String], expected_size: Option<i64>, staging_dir: &Path, ) -> Result<PathBuf>

Pull a single blob to a file in staging_dir, returning the file path, without ever holding the whole blob in memory.

Resolution mirrors ImagePuller::pull_blob_with_urls but stays on disk: a file-backed cache hit (BlobCacheBackend::get_path) is hardlinked into the stage; a small inline / in-memory / S3 / local-registry hit is written out; otherwise the blob is streamed from the registry through a [HashingFileWriter] (inline SHA-256 verification) into a .part temp file that is fsynced, verified, atomically renamed into place, and then best-effort ingested into the cache via BlobCacheBackend::put_path.

§Errors

Returns an error if every source (cache tiers, primary registry, and all urls[] foreign-layer fallbacks) fails, or the streamed bytes fail digest / size verification.

§Panics

Panics if the concurrency semaphore is closed.

Source

pub async fn pull_image_to_files( &self, image: &str, auth: &RegistryAuth, staging_dir: &Path, ) -> Result<Vec<(PathBuf, String)>>

Pull every layer of an image to files in staging_dir (default PullPolicy::Newer), streaming each layer so no layer is ever fully held in memory. Returns (layer_file_path, media_type) in apply order.

§Errors

Returns an error if the manifest or any layer cannot be pulled.

Source

pub async fn pull_image_to_files_with_policy( &self, image: &str, auth: &RegistryAuth, staging_dir: &Path, policy: PullPolicy, ) -> Result<Vec<(PathBuf, String)>>

Pull every layer of an image to files honoring an explicit PullPolicy.

§Errors

Returns an error if the manifest or any layer cannot be pulled.

Source

pub async fn remote_manifest_digest( &self, image: &str, auth: &RegistryAuth, ) -> Result<Option<String>>

Fetch the current upstream manifest digest for image from the registry without pulling the manifest body. Uses HEAD /v2/{repo}/manifests/{tag}.

Returns Ok(Some(digest)) when the registry reports a current digest, Ok(None) when the image or tag is not found on the registry, and Err on transport / auth / protocol failures.

This exists so [pull_manifest] can revalidate its cache entry against the live registry state for mutable tags (:latest, :dev, …) without paying for a full manifest download on every pull.

§Errors

Returns an error if the image reference is invalid or the registry returns a transport, auth, or protocol-level failure.

Source

pub async fn pull_manifest( &self, image: &str, auth: &RegistryAuth, ) -> Result<(OciImageManifest, String)>

Pull an image manifest from the registry.

Returns the manifest and its registry-reported digest. Manifests are cached to avoid repeated network requests for the same image reference.

For mutable tags (:latest, :dev, :edge, :main, :master, or missing/empty tags), a cache hit triggers a HEAD revalidation against the upstream registry. If the cached digest still matches, the cached manifest is returned. If the remote digest differs, the cache entry is invalidated and the manifest is refetched. If the revalidation request itself fails (e.g. the registry is unreachable), the stale cached manifest is returned rather than failing the caller — serving stale beats crashing the deploy.

Pinned tags (e.g. :v1.2.3) and digest references (img@sha256:...) are treated as immutable: a cache hit is returned without revalidation.

§Errors

Returns an error if the manifest cannot be pulled or the image reference is invalid.

Source

pub async fn image_os_in_cache_only( &self, image: &str, ) -> Result<Option<OsKind>>

Resolve image’s OCI os field STRICTLY from local stores, with no network call. Returns Ok(None) when the image (its manifest/config) is not present locally — the caller should then probe the next cache or, as a last resort, the network.

§Errors

Returns an error only when a locally-present config blob cannot be read or parsed — never for a plain local miss (that is Ok(None)).

Source

pub async fn cache_local_image_platform( &self, image: &str, os: &str, architecture: &str, ) -> Result<()>

Stamp a locally-built image’s platform (os + architecture) into the blob cache so the no-network dispatch inspection can resolve it.

This is the writer counterpart to Self::image_os_in_cache_only. A native build (e.g. the macOS Seatbelt builder) never goes through a registry, so nothing writes the manifest + config blob that the local-only OS read consumes. Without it a freshly built Mac-native bundle carries no os hint and the composite mis-routes it to the Linux VM. We write a MINIMAL OCI manifest (under manifest_cache_key) pointing at a config blob whose only meaningful fields are os and architecture — the same keyspace and shape a real pull leaves behind — plus the digest and original-ref sidecars. Idempotent: re-stamping overwrites the keys.

§Errors

Returns an error if the manifest or config blob cannot be serialized, or if a cache write fails.

Source

pub async fn image_runtime_marker_in_cache_only( &self, image: &str, ) -> Result<Option<String>>

Resolve image’s com.zlayer.runtime manifest annotation STRICTLY from local stores, with no network call. Ok(None) on a local miss (or when the annotation is absent).

§Errors

Currently infallible in practice; the Result mirrors ImagePuller::image_os_in_cache_only for a uniform caller contract.

Source

pub async fn image_isolation_marker_in_cache_only( &self, image: &str, ) -> Result<Option<String>>

Resolve image’s crate::ZLAYER_ISOLATION_ANNOTATION (com.zlayer.isolation) image-declared isolation default STRICTLY from local stores, with no network call. Ok(None) on a local miss (or when the label is absent).

Unlike Self::image_runtime_marker_in_cache_only (a manifest annotation), the isolation default is an image config label, so this reads the cached CONFIG blob’s config.Labels — mirroring Self::image_os_in_cache_only, which reads the same blob’s os field.

§Errors

Returns an error only when a locally-present config blob cannot be parsed — never for a plain local miss (that is Ok(None)).

Source

pub async fn pull_manifest_with_policy( &self, image: &str, auth: &RegistryAuth, policy: PullPolicy, ) -> Result<(OciImageManifest, String)>

Pull an image manifest, honoring the requested PullPolicy.

PullPolicy::Always invalidates any cached manifest entry before the fetch, guaranteeing a fresh round-trip to the registry. PullPolicy::Newer preserves the legacy revalidate-mutable-tag behavior. PullPolicy::IfNotPresent and PullPolicy::Never trust the blob cache / local registry and skip the remote HEAD revalidation that would otherwise fail for locally-built images sitting behind a 401.

§Errors

Returns an error if the manifest cannot be pulled or the image reference is invalid.

Source

pub async fn pull_image_config( &self, image: &str, auth: &RegistryAuth, ) -> Result<ImageConfig>

Pull and parse the image configuration from the registry.

This fetches the manifest, extracts the config blob digest, pulls the config blob, and parses it to extract container runtime defaults like Entrypoint, Cmd, WorkingDir, Env, and User.

§Arguments
  • image - Image reference (e.g., “docker.io/library/nginx:latest”)
  • auth - Registry authentication credentials
§Returns

Returns the parsed ImageConfig containing the container runtime defaults. If the image config blob has no config section, returns a default (empty) ImageConfig.

§Errors

Returns an error if the manifest or config blob cannot be fetched, or if the config blob cannot be parsed as valid JSON.

Source

pub async fn pull_image_config_with_policy( &self, image: &str, auth: &RegistryAuth, policy: PullPolicy, ) -> Result<ImageConfig>

Pull and parse the image configuration, honoring the requested PullPolicy.

PullPolicy::Always invalidates the cached manifest entry before fetching. The config blob itself is content-addressed by digest, so it does not need explicit invalidation — once the refreshed manifest points at a new config digest, the existing blob-cache lookup will naturally miss and refetch. PullPolicy::IfNotPresent and PullPolicy::Never skip remote revalidation entirely when a manifest is already cached.

§Errors

Returns an error if the manifest or config blob cannot be fetched, or if the config blob cannot be parsed as valid JSON.

Source

pub async fn image_os( &self, image: &str, auth: &RegistryAuth, ) -> Result<Option<OsKind>>

Fetch the operating system targeted by image from its OCI config blob.

Reads the top-level os field (OCI-canonical lowercase, e.g. "linux" / "windows" / "darwin") from the image config and converts it via zlayer_spec::OsKind::from_oci_str. Multi-platform indexes are resolved by the puller’s configured platform_resolver (set at construction time), so the answer reflects the manifest that would actually be pulled for this host.

Returns:

  • Ok(Some(os)) when the config blob carries a recognized OS.
  • Ok(None) when the os field is absent or holds an unknown value — the caller should treat this as “fall through to a platform-agnostic default” rather than an error.
§Errors

Returns an error if the manifest or config blob cannot be fetched, or if the config blob cannot be parsed as valid JSON.

Source

pub async fn image_os_with_policy( &self, image: &str, auth: &RegistryAuth, policy: PullPolicy, ) -> Result<Option<OsKind>>

Like ImagePuller::image_os but honoring an explicit PullPolicy.

The composite runtime’s OS dispatch path drives this with PullPolicy::IfNotPresent so that a locally-cached image (its config blob already in the persistent blob cache / local registry) is inspected WITHOUT any network round-trip. This is what keeps a Linux image routing to the VZ-Linux runtime under a Docker Hub rate-limit: the OS comes from the local store the pull already wrote, never a re-inspection over the wire. IfNotPresent/Never cause [pull_manifest_inner] to trust the cache without the mutable-tag HEAD revalidation that Newer would do.

§Errors

Returns an error if the manifest or config blob cannot be fetched, or if the config blob cannot be parsed as valid JSON.

Source

pub async fn image_runtime_marker( &self, image: &str, auth: &RegistryAuth, ) -> Result<Option<String>>

Read the crate::ZLAYER_RUNTIME_ANNOTATION manifest annotation, used by the agent’s composite runtime to auto-detect runtime-specific bundles (e.g. a macOS VZ base bundle published by zlayer vz build-base, which stamps com.zlayer.runtime=vz). Returns Ok(None) for ordinary images.

§Errors

Returns an error if the manifest cannot be fetched or parsed.

Source

pub async fn image_runtime_marker_with_policy( &self, image: &str, auth: &RegistryAuth, policy: PullPolicy, ) -> Result<Option<String>>

Like ImagePuller::image_runtime_marker but honoring an explicit PullPolicy. The composite runtime drives this with PullPolicy::IfNotPresent so the com.zlayer.runtime marker resolves from the already-pulled local manifest without a network re-fetch.

§Errors

Returns an error if the manifest cannot be fetched or parsed.

Source

pub async fn image_isolation_marker_with_policy( &self, image: &str, auth: &RegistryAuth, policy: PullPolicy, ) -> Result<Option<String>>

Read the crate::ZLAYER_ISOLATION_ANNOTATION image-declared isolation default (com.zlayer.isolation) from image’s OCI config blob, honoring an explicit PullPolicy. Mirrors Self::image_os_with_policy: the composite runtime drives this with PullPolicy::IfNotPresent so the label resolves from the already-pulled local config blob without a network re-fetch. Returns Ok(None) for images that declare no default.

§Errors

Returns an error if the manifest or config blob cannot be fetched, or if the config blob cannot be parsed.

Source

pub async fn image_os_version( &self, image: &str, auth: &RegistryAuth, ) -> Result<Option<String>>

Fetch the os.version string carried by image’s OCI config blob.

For Windows images this corresponds to the host build identifier (e.g. "10.0.20348.2031") recorded by the image builder, and is the value the HCS runtime needs to auto-resolve process vs. Hyper-V isolation against the running host’s build. Most Linux images do not record this field.

Returns:

  • Ok(Some(version)) when the config blob carries an os.version.
  • Ok(None) when the field is absent — callers should treat this as “no builder-asserted version, fall through to a runtime default” rather than an error.
§Errors

Returns an error if the manifest or config blob cannot be fetched, or if the config blob cannot be parsed as valid JSON.

Source

pub async fn detect_artifact_type( &self, image: &str, auth: &RegistryAuth, ) -> Result<(ArtifactType, OciImageManifest, String)>

Detect the artifact type of an image from its manifest

This method pulls the manifest and determines whether the image is a traditional container image or a WASM artifact.

§Arguments
  • image - Image reference (e.g., “ghcr.io/myorg/mymodule:v1.0”)
  • auth - Registry authentication credentials
§Returns

Returns the detected ArtifactType along with the manifest and digest.

§Errors

Returns an error if the manifest cannot be pulled.

Source

pub async fn get_wasm_info( &self, image: &str, auth: &RegistryAuth, ) -> Result<Option<WasmArtifactInfo>>

Extract WASM artifact information from an image

This method pulls the manifest and extracts detailed information about a WASM artifact, including WASI version, layer digest, and module name.

§Arguments
  • image - Image reference (e.g., “ghcr.io/myorg/mymodule:v1.0”)
  • auth - Registry authentication credentials
§Returns

Returns Some(WasmArtifactInfo) if this is a WASM artifact, None otherwise.

§Errors

Returns an error if the manifest cannot be pulled.

Source

pub async fn pull_wasm( &self, image: &str, auth: &RegistryAuth, ) -> Result<(Vec<u8>, WasmArtifactInfo)>

Pull a WASM binary from an image

This method pulls the manifest, verifies it’s a WASM artifact, and returns the raw WASM binary bytes.

§Arguments
  • image - Image reference (e.g., “ghcr.io/myorg/mymodule:v1.0”)
  • auth - Registry authentication credentials
§Returns

Returns the WASM binary bytes if this is a WASM artifact.

§Errors

Returns an error if this is not a WASM artifact or if the WASM layer cannot be found.

Source

pub async fn pull_image( &self, image: &str, auth: &RegistryAuth, ) -> Result<Vec<(Vec<u8>, String)>>

Pull a complete image (manifest + all layers)

Returns a vector of (layer_data, media_type) tuples in order (base layer first).

§Errors

Returns an error if the manifest or any layer cannot be pulled.

Source

pub async fn pull_image_with_policy( &self, image: &str, auth: &RegistryAuth, policy: PullPolicy, ) -> Result<Vec<(Vec<u8>, String)>>

Pull a complete image, honoring the requested PullPolicy.

PullPolicy::Always invalidates the cached manifest entry before fetching. Layer blobs are content-addressed by digest, so they do not need explicit invalidation — once the refreshed manifest points at new layer digests, the existing blob-cache lookups will naturally miss and refetch the new layers. Shared layer blobs remain valid cache hits. PullPolicy::IfNotPresent and PullPolicy::Never trust the cache / local registry without revalidating mutable tags against the remote.

§Errors

Returns an error if the manifest or any layer cannot be pulled.

Source

pub async fn push_blob( &self, reference: &str, digest: &str, data: &[u8], _media_type: &str, auth: &RegistryAuth, ) -> Result<(), PushError>

Push a blob to a remote registry

Uploads a blob (layer or config) to the specified registry. The blob is identified by its digest and will be stored at the repository specified in the reference.

§Arguments
  • reference - Image reference (e.g., “ghcr.io/myorg/mymodule:v1.0”)
  • digest - Content digest of the blob (e.g., “sha256:abc123…”)
  • data - Raw blob data to upload
  • _media_type - MIME type of the blob content (reserved for future use)
  • auth - Registry authentication credentials
§Errors

Returns an error if:

  • The reference is invalid
  • Authentication fails
  • The blob upload fails
Source

pub async fn push_manifest_to_registry( &self, reference: &str, manifest: &OciImageManifest, auth: &RegistryAuth, ) -> Result<String, PushError>

Push a manifest to a remote registry

Uploads an OCI image manifest to the specified registry. The manifest should reference blobs that have already been uploaded.

§Arguments
  • reference - Image reference (e.g., “ghcr.io/myorg/mymodule:v1.0”)
  • manifest - OCI image manifest to upload
  • auth - Registry authentication credentials
§Returns

Returns the manifest digest on success.

§Errors

Returns an error if:

  • The reference is invalid
  • Authentication fails
  • The manifest upload fails
Source

pub async fn push_image_index_to_registry( &self, reference: &str, index: &OciImageIndex, auth: &RegistryAuth, ) -> Result<String, PushError>

Push an OCI image index (manifest list) to a remote registry.

Used for multi-platform images where each platform has its own manifest and the index ties them together.

§Errors

Returns an error if the reference is invalid, authentication fails, or the index upload fails.

Source

pub async fn push_manifest_blob( &self, reference: &str, manifest_bytes: Vec<u8>, content_type: &str, auth: &RegistryAuth, ) -> Result<String, PushError>

Push a pre-serialised manifest blob verbatim to a remote registry.

Unlike Self::push_manifest_to_registry, which round-trips through OciImageManifest and so re-serialises the JSON (potentially losing byte-level fidelity with the locally-computed digest), this PUTs the exact bytes the caller already computed a sha256 over. This matters for Windows WCOW manifests where the layer descriptors carry foreign urls[] arrays that must round-trip unmodified so Windows daemons recognise the layers as foreign and skip download.

The content_type is sent verbatim as the Content-Type header; for a Docker manifest pass "application/vnd.docker.distribution.manifest.v2+json", for an OCI image manifest pass "application/vnd.oci.image.manifest.v1+json".

§Errors

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more