Skip to main content

oci_core/workflows/
push.rs

1/// Common utilities for OCI image push workflows.
2/// Provides high-level abstractions for pushing layers, configs, and manifests to registries.
3
4use std::sync::Arc;
5
6use tokio::sync::mpsc;
7
8use crate::core::auth::RegistryAuth;
9use crate::core::blobs::{LayerUploadOptions, LayerUploadPool, LocalLayer, UploadSummary};
10use crate::core::client::Client;
11use crate::core::errors::OciError;
12use crate::core::manifest::OciImageManifest;
13use crate::core::reference::Reference;
14
15/// Encapsulates metadata needed to push a complete OCI image.
16#[derive(Debug, Clone)]
17pub struct PushMetadata {
18    /// Target registry reference
19    pub target_ref: Reference,
20    /// All layers to be pushed
21    pub layers: Vec<LocalLayer>,
22    /// Configuration descriptor
23    pub config: ConfigBlob,
24    /// Image manifest
25    pub manifest: OciImageManifest,
26    /// Optional index for multi-platform images
27    pub index: Option<IndexBlob>,
28}
29
30/// Configuration blob metadata
31#[derive(Debug, Clone)]
32pub struct ConfigBlob {
33    pub digest: String,
34    pub data: Vec<u8>,
35}
36
37/// Index manifest (for multi-architecture support)
38#[derive(Debug, Clone)]
39pub struct IndexBlob {
40    pub media_type: String,
41    pub data: Vec<u8>,
42}
43
44/// Options controlling how a push operation behaves.
45#[derive(Debug, Clone)]
46pub struct PushOptions {
47    /// Layer upload options (chunk size, concurrency, etc.)
48    pub layer_upload_opts: Option<LayerUploadOptions>,
49    /// Whether to skip pre-checking blobs for existence
50    pub skip_blob_check: bool,
51}
52
53impl Default for PushOptions {
54    fn default() -> Self {
55        Self {
56            layer_upload_opts: None,
57            skip_blob_check: false,
58        }
59    }
60}
61
62/// Result of a push operation.
63#[derive(Debug)]
64pub struct PushResult {
65    /// Number of layers uploaded
66    pub layers_uploaded: usize,
67    /// Number of layers skipped (already existed)
68    pub layers_skipped: usize,
69    /// Whether config was uploaded
70    pub config_uploaded: bool,
71    /// Whether index was pushed (if applicable)
72    pub index_pushed: bool,
73}
74
75/// Unified interface for pushing OCI images.
76/// This trait allows implementations to provide their own orchestration
77/// while using common building blocks from the OCI library.
78#[allow(async_fn_in_trait)]
79pub trait OciImagePusher {
80    /// Push the complete image (layers + config + manifest + index)
81    async fn push(&self, metadata: PushMetadata, opts: PushOptions) -> Result<PushResult, OciError>;
82}
83
84/// Common validation for push operations.
85pub fn validate_push_metadata(metadata: &PushMetadata) -> Result<(), OciError> {
86    if metadata.layers.is_empty() {
87        return Err(OciError::PushError("Image must have at least one layer".to_string()));
88    }
89
90    if metadata.config.digest.is_empty() {
91        return Err(OciError::PushError("Config digest is required".to_string()));
92    }
93
94    if metadata.target_ref.repository.is_empty() {
95        return Err(OciError::PushError("Target reference repository is required".to_string()));
96    }
97
98    Ok(())
99}
100
101/// Result of checking and filtering blobs for upload.
102#[derive(Debug)]
103pub struct BlobCheckResult {
104    pub layers_to_upload: Vec<LocalLayer>,
105    pub skipped_count: usize,
106}
107
108/// Check remote registry for blob existence and filter layers.
109/// Returns layers that need to be uploaded.
110pub async fn check_and_filter_layers(
111    client: &Client,
112    target_ref: &Reference,
113    auth: &RegistryAuth,
114    layers: Vec<LocalLayer>,
115) -> Result<BlobCheckResult, OciError> {
116    let mut layers_to_upload = Vec::new();
117    let mut skipped_count = 0;
118
119    for layer in layers {
120        match client.blob_exists(target_ref, &layer.digest, auth).await {
121            Ok(true) => {
122                skipped_count += 1;
123                continue;
124            }
125            Ok(false) => {
126                // Blob doesn't exist, proceed with upload
127            }
128            Err(_err) => {
129                // Unable to check, attempt upload anyway
130            }
131        }
132        layers_to_upload.push(layer);
133    }
134
135    Ok(BlobCheckResult {
136        layers_to_upload,
137        skipped_count,
138    })
139}
140
141/// Check if config blob exists in remote registry.
142pub async fn check_config_exists(
143    client: &Client,
144    target_ref: &Reference,
145    auth: &RegistryAuth,
146    config_digest: &str,
147) -> Result<bool, OciError> {
148    match client.blob_exists(target_ref, config_digest, auth).await {
149        Ok(exists) => Ok(exists),
150        Err(_) => {
151            // If we can't check, assume it doesn't exist and attempt upload
152            Ok(false)
153        }
154    }
155}
156
157/// Upload config blob if it doesn't exist.
158pub async fn upload_config_if_needed(
159    client: &Client,
160    target_ref: &Reference,
161    auth: &RegistryAuth,
162    config_digest: &str,
163    config_bytes: &[u8],
164    config_exists: bool,
165) -> Result<(), OciError> {
166    if !config_exists {
167        client
168            .push_blob(target_ref, auth, config_bytes, config_digest)
169            .await?;
170    }
171    Ok(())
172}
173
174/// Stream layers through the upload pool with concurrent workers.
175pub async fn upload_layers_concurrent(
176    client: &Client,
177    target_ref: &Reference,
178    auth: Arc<RegistryAuth>,
179    layers: Vec<LocalLayer>,
180    options: LayerUploadOptions,
181) -> Result<UploadSummary, OciError> {
182    if layers.is_empty() {
183        return Ok(UploadSummary {
184            uploaded: vec![],
185            skipped: 0,
186        });
187    }
188
189    let (tx, rx) = mpsc::channel::<LocalLayer>(options.concurrency * 2);
190
191    // Spawn upload task
192    let client_clone = client.clone();
193    let target_ref_clone = target_ref.clone();
194    let auth_clone = Arc::clone(&auth);
195    let options_clone = options.clone();
196
197    let upload_task = tokio::task::spawn(async move {
198        let uploader = LayerUploadPool::new(&client_clone, &target_ref_clone, auth_clone, options_clone);
199        uploader.upload_stream(rx).await
200    });
201
202    // Send layers
203    for layer in layers {
204        tx.send(layer).await.map_err(|e| {
205            OciError::Network(format!("Failed to enqueue layer: {}", e))
206        })?;
207    }
208    drop(tx);
209
210    // Wait for upload to complete
211    upload_task
212        .await
213        .map_err(|err| OciError::Network(format!("Upload task failed: {}", err)))?
214}
215
216/// Push manifest bytes to remote registry.
217pub async fn push_manifest_bytes(
218    client: &Client,
219    target_ref: &Reference,
220    auth: &RegistryAuth,
221    manifest_media_type: &str,
222    manifest_bytes: &[u8],
223) -> Result<String, OciError> {
224    client
225        .push_manifest_bytes(target_ref, manifest_media_type, manifest_bytes, auth)
226        .await
227}
228
229/// Optionally push index bytes (for multi-architecture support).
230pub async fn push_index_bytes_if_present(
231    client: &Client,
232    target_ref: &Reference,
233    auth: &RegistryAuth,
234    index_media_type: Option<&str>,
235    index_bytes: Option<&[u8]>,
236) -> Result<(), OciError> {
237    if let (Some(mt), Some(bytes)) = (index_media_type, index_bytes) {
238        client
239            .push_manifest_bytes(target_ref, mt, bytes, auth)
240            .await?;
241    }
242    Ok(())
243}