microsandbox 0.6.7

`microsandbox` is the core library for the microsandbox project.
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
//! Disk snapshot creation, inspection, and consumption.
//!
//! A snapshot is a self-describing, content-addressed directory on
//! disk. It captures a stopped sandbox's writable upper layer plus
//! the metadata needed to pin the immutable lower (image). The
//! artifact is the source of truth; the local DB index is just a
//! cache of "snapshots I happen to know about on this machine."
//!
//! See `planning/microsandbox/implementation/snapshot-api-resumable-cloning.md` for the
//! full design. Today snapshots are stopped-sandbox / raw-format only;
//! the manifest schema and DB columns are forward-compatible with
//! qcow2 backing chains landing later.

mod archive;
mod create;
#[doc(hidden)]
pub mod downgrade;
pub(crate) mod migration;
mod store;
mod verify;

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

use std::path::{Path, PathBuf};

use crate::{MicrosandboxError, MicrosandboxResult};

/// A snapshot artifact on disk.
///
/// Returned by [`Snapshot::create`] and [`Snapshot::open`]. The
/// directory at [`path()`](Snapshot::path) holds the canonical
/// `snapshot.json` and the captured upper file.
#[derive(Debug, Clone)]
pub struct Snapshot {
    path: PathBuf,
    digest: String,
    manifest: Manifest,
}

/// Builder for [`SnapshotConfig`].
///
/// Constructed via [`Snapshot::builder`]. The snapshot name is fixed at
/// construction; the source sandbox is set with
/// [`from_sandbox`](Self::from_sandbox) and is required.
pub struct SnapshotBuilder {
    name: String,
    source_sandbox: Option<String>,
    dest_dir: Option<PathBuf>,
    labels: Vec<(String, String)>,
    force: bool,
    record_integrity: bool,
    resumable: bool,
}

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

impl Snapshot {
    /// Start configuring a snapshot named `name`, stored under the
    /// default snapshots directory.
    ///
    /// The source sandbox is required:
    /// `Snapshot::builder("clean").from_sandbox("box").create()`.
    ///
    /// The name is the artifact's human-readable address and directory
    /// basename; the descriptor digest is its identity. By default the
    /// artifact is created in the snapshots store, and
    /// [`dest_dir`](SnapshotBuilder::dest_dir) selects a different parent
    /// directory. Archive movement happens through
    /// [`save`](Self::save)/[`load`](Self::load).
    pub fn builder(name: impl Into<String>) -> SnapshotBuilder {
        SnapshotBuilder {
            name: name.into(),
            source_sandbox: None,
            dest_dir: None,
            labels: Vec::new(),
            force: false,
            record_integrity: false,
            resumable: false,
        }
    }

    /// Create a snapshot artifact from a stopped sandbox.
    ///
    /// Writes `snapshot.json` and the captured `upper.ext4` into the
    /// destination directory atomically (manifest renamed last). On
    /// success, also upserts a row into the local `snapshot_index`
    /// cache; index failures are logged but do not fail the call —
    /// the artifact is the source of truth.
    pub async fn create(config: SnapshotConfig) -> MicrosandboxResult<Self> {
        let backend = crate::backend::default_backend();
        let local = backend.as_local().ok_or_else(snapshots_require_local)?;
        create::create_snapshot(local, config).await
    }

    /// Open an existing snapshot artifact by path or bare name.
    ///
    /// Bare names (no path separator) resolve under the default
    /// snapshots directory; anything else is treated as a path.
    /// This is a fast metadata operation: it verifies the manifest
    /// structure, recomputes the manifest digest, and checks that the
    /// upper file exists with the recorded size. It does not read the
    /// full upper contents.
    pub async fn open(path_or_name: impl AsRef<str>) -> MicrosandboxResult<Self> {
        let backend = crate::backend::default_backend();
        let local = backend.as_local().ok_or_else(snapshots_require_local)?;
        store::open_snapshot(local, path_or_name.as_ref()).await
    }

    /// Verify the state closure bound by this snapshot.
    pub async fn verify(&self) -> MicrosandboxResult<SnapshotVerifyReport> {
        verify::verify_snapshot(self).await
    }

    /// Path to the artifact directory.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Canonical content digest of this snapshot's manifest
    /// (`sha256:hex`). This is the snapshot's identity.
    pub fn digest(&self) -> &str {
        &self.digest
    }

    /// Parsed manifest.
    pub fn manifest(&self) -> &Manifest {
        &self.manifest
    }

    /// Apparent size of a file-state upper layer in bytes.
    pub fn size_bytes(&self) -> Option<u64> {
        self.manifest
            .state
            .as_file()
            .map(|state| state.upper.size_bytes)
    }

    /// Closed state variant carried by the descriptor.
    pub fn state(&self) -> &SnapshotState {
        &self.manifest.state
    }

    /// Get a handle by digest, name, or path from the local index.
    pub async fn get(name_or_digest: &str) -> MicrosandboxResult<SnapshotHandle> {
        let backend = crate::backend::default_backend();
        let local = backend.as_local().ok_or_else(snapshots_require_local)?;
        store::get_handle(local, name_or_digest).await
    }

    /// List indexed snapshots from the local DB cache.
    ///
    /// External-path snapshots booted by full path are not in the
    /// index and won't appear here; use [`list_dir`](Self::list_dir)
    /// to enumerate artifacts on disk directly.
    pub async fn list() -> MicrosandboxResult<Vec<SnapshotHandle>> {
        let backend = crate::backend::default_backend();
        let local = backend.as_local().ok_or_else(snapshots_require_local)?;
        store::list_indexed(local).await
    }

    /// Walk a directory and parse each subdirectory's manifest. Does
    /// not touch the index. Skips entries that don't look like
    /// snapshot artifacts.
    pub async fn list_dir(dir: impl AsRef<Path>) -> MicrosandboxResult<Vec<Snapshot>> {
        let backend = crate::backend::default_backend();
        let local = backend.as_local().ok_or_else(snapshots_require_local)?;
        store::list_dir(local, dir.as_ref()).await
    }

    /// Remove a snapshot artifact (by path or name) and its index row.
    ///
    /// Refuses if the snapshot has indexed children, unless `force`
    /// is set. The artifact directory is deleted on success.
    pub async fn remove(path_or_name: &str, force: bool) -> MicrosandboxResult<()> {
        let backend = crate::backend::default_backend();
        let local = backend.as_local().ok_or_else(snapshots_require_local)?;
        store::remove_snapshot(local, path_or_name, force).await
    }

    /// Rebuild the local index from the artifacts in `dir`. Returns
    /// the number of artifacts indexed.
    pub async fn reindex(dir: impl AsRef<Path>) -> MicrosandboxResult<usize> {
        let backend = crate::backend::default_backend();
        let local = backend.as_local().ok_or_else(snapshots_require_local)?;
        store::reindex_dir(local, dir.as_ref()).await
    }

    /// Bundle a snapshot into a `.tar.zst` archive.
    pub async fn save(
        name_or_path: &str,
        out: &Path,
        opts: archive::SaveOpts,
    ) -> MicrosandboxResult<()> {
        let backend = crate::backend::default_backend();
        let local = backend.as_local().ok_or_else(snapshots_require_local)?;
        archive::save_snapshot(local, name_or_path, out, opts).await
    }

    /// Unpack a snapshot archive (`.tar.zst` or `.tar`) into the
    /// snapshots dir, registering anything found in the index.
    pub async fn load(
        archive_path: &Path,
        dest: Option<&Path>,
    ) -> MicrosandboxResult<SnapshotHandle> {
        let backend = crate::backend::default_backend();
        let local = backend.as_local().ok_or_else(snapshots_require_local)?;
        archive::load_snapshot(local, archive_path, dest).await
    }
}

/// Build an `Unsupported` error for snapshot ops that aren't wired through
/// the cloud trait yet. Snapshots are local-only today.
fn snapshots_require_local() -> MicrosandboxError {
    MicrosandboxError::Unsupported {
        feature: "Snapshot operations".into(),
        available_when: "when cloud snapshots land".into(),
    }
}

/// Lightweight handle backed by an index row.
///
/// Returned by [`Snapshot::list`]. Use [`open`](SnapshotHandle::open)
/// to read the artifact metadata, and [`Snapshot::verify`] for explicit
/// content verification.
#[derive(Debug, Clone)]
pub struct SnapshotHandle {
    pub(crate) digest: String,
    pub(crate) name: Option<String>,
    pub(crate) parent_digest: Option<String>,
    pub(crate) scope: SnapshotScope,
    pub(crate) image_ref: String,
    pub(crate) state_kind: String,
    pub(crate) format: Option<SnapshotFormat>,
    pub(crate) fstype: Option<String>,
    pub(crate) checkpoint_manifest_digest: Option<String>,
    pub(crate) size_bytes: Option<u64>,
    pub(crate) locality: String,
    pub(crate) availability: String,
    pub(crate) migration_state: String,
    pub(crate) migration_error_code: Option<String>,
    pub(crate) created_at: chrono::NaiveDateTime,
    pub(crate) artifact_path: PathBuf,
}

impl SnapshotHandle {
    /// Manifest digest (`sha256:hex`) — canonical identity.
    pub fn digest(&self) -> &str {
        &self.digest
    }

    /// Name alias (None for digest-only entries).
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Parent snapshot's digest, or `None` for a root.
    pub fn parent_digest(&self) -> Option<&str> {
        self.parent_digest.as_deref()
    }

    /// Snapshot payload scope.
    pub fn scope(&self) -> SnapshotScope {
        self.scope
    }

    /// Image reference the snapshot was taken from.
    pub fn image_ref(&self) -> &str {
        &self.image_ref
    }

    /// Stable file/checkpoint state discriminant.
    pub fn state_kind(&self) -> &str {
        &self.state_kind
    }

    /// On-disk format for file state.
    pub fn format(&self) -> Option<SnapshotFormat> {
        self.format
    }

    /// Filesystem type for file state.
    pub fn fstype(&self) -> Option<&str> {
        self.fstype.as_deref()
    }

    /// Checkpoint manifest digest for checkpoint state.
    pub fn checkpoint_manifest_digest(&self) -> Option<&str> {
        self.checkpoint_manifest_digest.as_deref()
    }

    /// Apparent size of the upper file at index time.
    pub fn size_bytes(&self) -> Option<u64> {
        self.size_bytes
    }

    /// Whether payload state is embedded or provider-linked.
    pub fn locality(&self) -> &str {
        &self.locality
    }

    /// Current local availability projection.
    pub fn availability(&self) -> &str {
        &self.availability
    }

    /// Adjacent-release migration status for this indexed artifact.
    pub fn migration_state(&self) -> &str {
        &self.migration_state
    }

    /// Stable migration failure code when migration is blocked.
    pub fn migration_error_code(&self) -> Option<&str> {
        self.migration_error_code.as_deref()
    }

    /// Snapshot creation time (from manifest).
    pub fn created_at(&self) -> chrono::NaiveDateTime {
        self.created_at
    }

    /// Local artifact directory path.
    pub fn path(&self) -> &Path {
        &self.artifact_path
    }

    /// Open the underlying artifact metadata.
    pub async fn open(&self) -> MicrosandboxResult<Snapshot> {
        Snapshot::open(self.artifact_path.to_string_lossy().as_ref()).await
    }

    /// Remove this snapshot. See [`Snapshot::remove`].
    pub async fn remove(&self, force: bool) -> MicrosandboxResult<()> {
        Snapshot::remove(&self.digest, force).await
    }
}

impl SnapshotBuilder {
    /// Set the source sandbox to snapshot. Required.
    pub fn from_sandbox(mut self, source_sandbox: impl Into<String>) -> Self {
        self.source_sandbox = Some(source_sandbox.into());
        self
    }

    /// Create the artifact under this parent directory instead of the
    /// default snapshots store. The artifact directory is
    /// `dest_dir/<name>`; the name stays the snapshot's identity.
    pub fn dest_dir(mut self, dest_dir: impl Into<PathBuf>) -> Self {
        self.dest_dir = Some(dest_dir.into());
        self
    }

    /// Add a user label.
    pub fn label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.labels.push((key.into(), value.into()));
        self
    }

    /// Overwrite an existing artifact at the destination.
    pub fn force(mut self) -> Self {
        self.force = true;
        self
    }

    /// Retained source-compatibility setter.
    ///
    /// Final schema 1 always computes and records file-state integrity, so
    /// calling this method no longer changes creation behavior.
    pub fn record_integrity(mut self) -> Self {
        self.record_integrity = true;
        self
    }

    /// Request a future resumable snapshot.
    ///
    /// The builder accepts this stable option now, but creation returns
    /// `Unsupported` until VM pause/resume capture is implemented.
    pub fn resumable(mut self) -> Self {
        self.resumable = true;
        self
    }

    /// Build the [`SnapshotConfig`].
    pub fn build(self) -> MicrosandboxResult<SnapshotConfig> {
        let source_sandbox = self.source_sandbox.ok_or_else(|| {
            crate::MicrosandboxError::InvalidConfig(
                "snapshot builder requires a source sandbox; set from_sandbox before create".into(),
            )
        })?;
        Ok(SnapshotConfig {
            name: self.name,
            dest_dir: self.dest_dir,
            source_sandbox,
            labels: self.labels,
            force: self.force,
            record_integrity: self.record_integrity,
            resumable: self.resumable,
        })
    }

    /// Build and execute the snapshot in one step.
    pub async fn create(self) -> MicrosandboxResult<Snapshot> {
        Snapshot::create(self.build()?).await
    }
}

//--------------------------------------------------------------------------------------------------
// Re-Exports
//--------------------------------------------------------------------------------------------------

pub use archive::SaveOpts;
#[cfg(feature = "fuzzing")]
pub use archive::fuzz_unpack_archive;
pub use microsandbox_image::snapshot::{
    CheckpointSnapshotState, DESCRIPTOR_FILENAME, FileSnapshotState, ImageRef, Manifest,
    SnapshotDescriptor, SnapshotFormat, SnapshotScope, SnapshotState, UpperIntegrity, UpperLayer,
};
pub use microsandbox_types::{SnapshotSpec, SnapshotSpec as SnapshotConfig};
pub use verify::{SnapshotVerifyReport, UpperVerifyStatus};

//--------------------------------------------------------------------------------------------------
// Internal — used by submodules
//--------------------------------------------------------------------------------------------------

impl Snapshot {
    pub(crate) fn from_parts(path: PathBuf, digest: String, manifest: Manifest) -> Self {
        Self {
            path,
            digest,
            manifest,
        }
    }
}