microsandbox-image 0.4.6

OCI image pulling, layer extraction, and caching for microsandbox.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! Layer download and blob-cache management.

use std::{
    fs::File,
    io::{self, Read},
    path::{Path, PathBuf},
    time::Instant,
};

use oci_client::client::{BlobResponse, SizedStream};
use sha2::{Digest as Sha2Digest, Sha256};
use tokio::io::AsyncWriteExt;

use crate::{
    digest::Digest,
    error::{ImageError, ImageResult},
    lock::{flock_exclusive_by_fd, flock_unlock, open_lock_file},
    store::GlobalCache,
};

//--------------------------------------------------------------------------------------------------
// Constants
//--------------------------------------------------------------------------------------------------

/// Minimum byte delta between per-layer download progress updates.
const DOWNLOAD_PROGRESS_EMIT_BYTES: u64 = 256 * 1024;

//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------

/// A single OCI layer handle with download state.
pub(crate) struct Layer {
    /// Compressed layer digest (from manifest).
    pub digest: Digest,
    /// Cached paths derived from the global cache.
    tar_path: PathBuf,
    download_lock_path: PathBuf,
    part_path: PathBuf,
}

enum DownloadStart {
    Fresh,
    Resume(u64),
    Complete,
}

//--------------------------------------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------------------------------------

impl Layer {
    /// Create a new layer handle.
    pub fn new(digest: Digest, cache: &GlobalCache) -> Self {
        Self {
            tar_path: cache.tar_path(&digest),
            download_lock_path: cache.download_lock_path(&digest),
            part_path: cache.part_path(&digest),
            digest,
        }
    }

    /// Path to the compressed tarball.
    pub fn tar_path_ref(&self) -> PathBuf {
        self.tar_path.clone()
    }

    /// Download the layer blob to the cache.
    ///
    /// Uses cross-process `flock()` to prevent races. Supports resumption
    /// via partial `.part` files.
    pub async fn download(
        &self,
        client: &oci_client::Client,
        image_ref: &oci_client::Reference,
        expected_size: Option<u64>,
        force: bool,
        progress: Option<&crate::progress::PullProgressSender>,
        layer_index: usize,
    ) -> ImageResult<()> {
        let started_at = Instant::now();
        let tar_path = &self.tar_path;
        let part_path = &self.part_path;

        // Acquire cross-process download lock (non-blocking on async executor).
        let lock_file = open_lock_file(&self.download_lock_path)?;
        {
            use std::os::unix::io::AsRawFd;
            let fd = lock_file.as_raw_fd();
            tokio::task::spawn_blocking(move || flock_exclusive_by_fd(fd))
                .await
                .map_err(|e| ImageError::Io(std::io::Error::other(e)))??;
        }
        let _guard = scopeguard::guard(lock_file, |f| {
            let _ = flock_unlock(&f);
        });

        if force {
            remove_file_if_exists(tar_path)?;
            remove_file_if_exists(part_path)?;
        }

        let digest_display = self.digest.to_string();
        let digest_str: std::sync::Arc<str> = digest_display.as_str().into();

        // Re-check after lock — another process may have completed the download.
        match tokio::fs::metadata(tar_path).await {
            Ok(meta)
                if expected_size.is_some_and(|expected| meta.len() == expected)
                    || (expected_size.is_none() && meta.len() > 0) =>
            {
                if let Some(p) = progress {
                    p.send(crate::progress::PullProgress::LayerDownloadComplete {
                        layer_index,
                        digest: digest_str,
                        downloaded_bytes: expected_size.unwrap_or(0),
                    });
                }
                tracing::debug!(
                    layer_index,
                    digest = %digest_display,
                    elapsed_ms = started_at.elapsed().as_millis(),
                    "layer download reused cached tarball"
                );
                return Ok(());
            }
            Ok(_) | Err(_) => {}
        }

        // Stream the blob to a .part file.
        let expected_hex = self.digest.hex();

        // Run download-start determination (may hash a large .part file) off the executor.
        let part_path_for_start = part_path.clone();
        let expected_hex_owned = expected_hex.to_string();
        let download_start = tokio::task::spawn_blocking(move || {
            determine_download_start(&part_path_for_start, expected_size, &expected_hex_owned)
        })
        .await
        .map_err(|e| ImageError::Io(io::Error::other(e)))??;
        if matches!(download_start, DownloadStart::Complete) {
            tokio::fs::rename(part_path, tar_path)
                .await
                .map_err(|e| ImageError::Cache {
                    path: tar_path.clone(),
                    source: e,
                })?;

            if let Some(p) = progress {
                p.send(crate::progress::PullProgress::LayerDownloadComplete {
                    layer_index,
                    digest: digest_str,
                    downloaded_bytes: expected_size.unwrap_or(0),
                });
            }

            tracing::debug!(
                layer_index,
                digest = %digest_display,
                elapsed_ms = started_at.elapsed().as_millis(),
                "layer download resumed from completed part file"
            );

            return Ok(());
        }

        let (mut stream, mut file, mut downloaded): (SizedStream, tokio::fs::File, u64) =
            match download_start {
                DownloadStart::Fresh => {
                    let stream = client
                        .pull_blob_stream(image_ref, digest_display.as_str())
                        .await?;
                    let file = tokio::fs::OpenOptions::new()
                        .create(true)
                        .truncate(true)
                        .write(true)
                        .open(part_path)
                        .await
                        .map_err(|e| ImageError::Cache {
                            path: part_path.clone(),
                            source: e,
                        })?;
                    (stream, file, 0)
                }
                DownloadStart::Resume(offset) => {
                    let blob = client
                        .pull_blob_stream_partial(image_ref, digest_display.as_str(), offset, None)
                        .await?;

                    match blob {
                        BlobResponse::Partial(stream) => {
                            let file = tokio::fs::OpenOptions::new()
                                .create(true)
                                .append(true)
                                .open(part_path)
                                .await
                                .map_err(|e| ImageError::Cache {
                                    path: part_path.clone(),
                                    source: e,
                                })?;
                            (stream, file, offset)
                        }
                        BlobResponse::Full(stream) => {
                            let file = tokio::fs::OpenOptions::new()
                                .create(true)
                                .truncate(true)
                                .write(true)
                                .open(part_path)
                                .await
                                .map_err(|e| ImageError::Cache {
                                    path: part_path.clone(),
                                    source: e,
                                })?;
                            (stream, file, 0)
                        }
                    }
                }
                DownloadStart::Complete => unreachable!(),
            };
        let mut last_progress_bytes = downloaded;

        // Compute SHA-256 incrementally during download — avoids re-reading
        // the entire blob from disk for post-download verification.
        // For resumed downloads, we must hash the existing bytes first.
        let mut hasher = if downloaded > 0 {
            let part_path = part_path.clone();
            tokio::task::spawn_blocking(move || hash_file_hasher(&part_path))
                .await
                .map_err(|e| ImageError::Io(io::Error::other(e)))??
        } else {
            Sha256::new()
        };

        use futures::StreamExt;
        while let Some(chunk) = stream.next().await {
            let chunk = chunk?;
            hasher.update(&chunk);
            file.write_all(&chunk)
                .await
                .map_err(|e| ImageError::Cache {
                    path: part_path.clone(),
                    source: e,
                })?;
            downloaded += chunk.len() as u64;

            let should_emit_progress = downloaded.saturating_sub(last_progress_bytes)
                >= DOWNLOAD_PROGRESS_EMIT_BYTES
                || expected_size.is_some_and(|total| downloaded >= total);

            if should_emit_progress {
                if let Some(p) = progress {
                    p.send(crate::progress::PullProgress::LayerDownloadProgress {
                        layer_index,
                        digest: digest_str.clone(),
                        downloaded_bytes: downloaded,
                        total_bytes: expected_size,
                    });
                }
                last_progress_bytes = downloaded;
            }
        }
        file.flush().await.map_err(|e| ImageError::Cache {
            path: part_path.clone(),
            source: e,
        })?;
        drop(file);

        // Verify compressed digest from the incremental hash.
        let actual_hash = hex::encode(hasher.finalize());
        if actual_hash != expected_hex {
            let _ = tokio::fs::remove_file(part_path).await;
            return Err(ImageError::DigestMismatch {
                digest: digest_display,
                expected: expected_hex.to_string(),
                actual: actual_hash,
            });
        }

        // Atomic rename .part -> final.
        tokio::fs::rename(part_path, tar_path)
            .await
            .map_err(|e| ImageError::Cache {
                path: tar_path.clone(),
                source: e,
            })?;

        if let Some(p) = progress {
            p.send(crate::progress::PullProgress::LayerDownloadComplete {
                layer_index,
                digest: digest_str,
                downloaded_bytes: downloaded,
            });
        }

        tracing::debug!(
            layer_index,
            digest = %digest_display,
            downloaded_bytes = downloaded,
            elapsed_ms = started_at.elapsed().as_millis(),
            "layer download completed"
        );

        Ok(())
    }
}

//--------------------------------------------------------------------------------------------------
// Functions: Helpers
//--------------------------------------------------------------------------------------------------

/// Compute the SHA-256 hex digest of a file.
fn compute_sha256_file(path: &Path) -> ImageResult<String> {
    Ok(hex::encode(hash_file_hasher(path)?.finalize()))
}

fn hash_file_hasher(path: &Path) -> ImageResult<Sha256> {
    let mut file = File::open(path).map_err(|e| ImageError::Cache {
        path: path.to_path_buf(),
        source: e,
    })?;
    let mut hasher = Sha256::new();
    let mut buf = [0u8; 64 * 1024];
    loop {
        let n = file.read(&mut buf).map_err(|e| ImageError::Cache {
            path: path.to_path_buf(),
            source: e,
        })?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    Ok(hasher)
}

fn remove_file_if_exists(path: &Path) -> ImageResult<()> {
    match std::fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(err) => Err(ImageError::Cache {
            path: path.to_path_buf(),
            source: err,
        }),
    }
}

fn determine_download_start(
    part_path: &Path,
    expected_size: Option<u64>,
    expected_hex: &str,
) -> ImageResult<DownloadStart> {
    let part_size = match std::fs::metadata(part_path) {
        Ok(meta) => meta.len(),
        Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(DownloadStart::Fresh),
        Err(err) => {
            return Err(ImageError::Cache {
                path: part_path.to_path_buf(),
                source: err,
            });
        }
    };

    if part_size == 0 {
        return Ok(DownloadStart::Fresh);
    }

    if let Some(expected) = expected_size {
        if part_size > expected {
            let _ = std::fs::remove_file(part_path);
            return Ok(DownloadStart::Fresh);
        }

        if part_size == expected {
            let actual_hash = compute_sha256_file(part_path)?;
            if actual_hash == expected_hex {
                return Ok(DownloadStart::Complete);
            }

            let _ = std::fs::remove_file(part_path);
            return Ok(DownloadStart::Fresh);
        }
    }

    Ok(DownloadStart::Resume(part_size))
}

//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use tempfile::tempdir;

    use super::{DownloadStart, determine_download_start, remove_file_if_exists};

    #[test]
    fn test_determine_download_start_returns_fresh_when_part_missing() {
        let temp = tempdir().unwrap();
        let path = temp.path().join("layer.part");

        let start = determine_download_start(&path, Some(10), "deadbeef").unwrap();

        assert!(matches!(start, DownloadStart::Fresh));
    }

    #[test]
    fn test_determine_download_start_resumes_partial_file() {
        let temp = tempdir().unwrap();
        let path = temp.path().join("layer.part");
        std::fs::write(&path, b"hello").unwrap();

        let start = determine_download_start(&path, Some(10), "deadbeef").unwrap();

        assert!(matches!(start, DownloadStart::Resume(5)));
    }

    #[test]
    fn test_determine_download_start_resets_oversized_part_file() {
        let temp = tempdir().unwrap();
        let path = temp.path().join("layer.part");
        std::fs::write(&path, b"hello world").unwrap();

        let start = determine_download_start(&path, Some(5), "deadbeef").unwrap();

        assert!(matches!(start, DownloadStart::Fresh));
        assert!(!path.exists());
    }

    #[test]
    fn test_determine_download_start_marks_complete_when_hash_matches() {
        let temp = tempdir().unwrap();
        let path = temp.path().join("layer.part");
        std::fs::write(&path, b"hello").unwrap();
        let digest = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";

        let start = determine_download_start(&path, Some(5), digest).unwrap();

        assert!(matches!(start, DownloadStart::Complete));
    }

    #[test]
    fn test_determine_download_start_restarts_when_full_part_hash_mismatches() {
        let temp = tempdir().unwrap();
        let path = temp.path().join("layer.part");
        std::fs::write(&path, b"hello").unwrap();

        let start = determine_download_start(&path, Some(5), "deadbeef").unwrap();

        assert!(matches!(start, DownloadStart::Fresh));
        assert!(!path.exists());
    }

    #[test]
    fn test_remove_file_if_exists_deletes_existing_file() {
        let temp = tempdir().unwrap();
        let path = temp.path().join("layer.tar.gz");
        std::fs::write(&path, b"cached").unwrap();

        remove_file_if_exists(&path).unwrap();

        assert!(!path.exists());
    }

    #[test]
    fn test_remove_file_if_exists_ignores_missing_file() {
        let temp = tempdir().unwrap();
        let path = temp.path().join("missing.tar.gz");

        remove_file_if_exists(&path).unwrap();

        assert!(!path.exists());
    }
}