microsandbox-rb 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,9 +22,9 @@ use microsandbox::sandbox::{
22
22
  AttachOptionsBuilder, DestroyOptions, DiskImageFormat, EnvVar, ExternalMountRestorePolicy,
23
23
  FlatClone, FsEntry, FsEntryKind, FsMetadata, HostPermissions, HttpDenyResponseFormat,
24
24
  MountBuilder, Patch, PullPolicy, PullProgress, PullProgressHandle, RestartOptions,
25
- RlimitResource, RootDiskBuilder, SandboxBuilder, SandboxHandle, SandboxMetrics,
26
- SandboxModificationBuilder, SandboxModificationPatch, SandboxStatus, SandboxStopResult,
27
- SecretBuilder, SecretModificationPatch, SecretSource, SecurityProfile, StatVirtualization,
25
+ RlimitResource, RootDiskBuilder, SandboxBuilder, SandboxMetrics, SandboxModificationBuilder,
26
+ SandboxModificationPatch, SandboxRecord, SandboxStatus, SandboxStopResult, SecretBuilder,
27
+ SecretModificationPatch, SecretSource, SecurityProfile, StatVirtualization,
28
28
  };
29
29
  use microsandbox::snapshot::SnapshotReference;
30
30
  use microsandbox::LogLevel;
@@ -69,8 +69,7 @@ use crate::stream::{LogStream, MetricsStream};
69
69
  /// `RuntimeNotInstalledError` and must leave the home untouched. A no-op for
70
70
  /// a cloud backend and on the OCI path (the directory then already exists).
71
71
  fn prepare_local_sandboxes_dir() -> Result<(), Error> {
72
- crate::backend::ensure_this_process_backend()?;
73
- let backend = microsandbox::default_backend();
72
+ let backend = crate::backend::active_context()?;
74
73
  let Some(local) = backend.as_local() else {
75
74
  return Ok(());
76
75
  };
@@ -160,7 +159,7 @@ impl Sandbox {
160
159
  // `Sandbox::builder` reads the default backend synchronously (it
161
160
  // overlays the local backend's global config), before any `block_on`.
162
161
  crate::backend::ensure_this_process_backend()?;
163
- let mut b = microsandbox::Sandbox::builder(name);
162
+ let mut b = crate::backend::active_context()?.sandboxes().builder(name);
164
163
  // Relative host paths are anchored to the current directory here, once,
165
164
  // before the core persists them (see host_path.rs).
166
165
  let host_paths = HostPaths::for_default_backend()?;
@@ -326,10 +325,10 @@ impl Sandbox {
326
325
  b = b.registry(move |r| rc.apply(r));
327
326
  }
328
327
  if let Some(secs) = conv::opt::<u64>(opts, "max_duration")? {
329
- b = b.max_duration(secs);
328
+ b = b.max_duration(Duration::from_secs(secs));
330
329
  }
331
330
  if let Some(secs) = conv::opt::<u64>(opts, "idle_timeout")? {
332
- b = b.idle_timeout(secs);
331
+ b = b.idle_timeout(Duration::from_secs(secs));
333
332
  }
334
333
  for (host, guest) in conv::opt_port_map(opts, "ports_udp")? {
335
334
  b = b.port_udp(host, guest);
@@ -609,7 +608,10 @@ impl Sandbox {
609
608
  };
610
609
  let name = conv::opt_string(opts, "name")?
611
610
  .ok_or_else(|| error::base_error("restore needs name: (the new sandbox name)"))?;
612
- let mut b = microsandbox::Sandbox::restore_ref(reference).name(name);
611
+ let mut b = crate::backend::active_context()?
612
+ .sandboxes()
613
+ .restore_ref(reference)
614
+ .name(name);
613
615
  if let Some(v) = conv::opt_u8(opts, "cpus")? {
614
616
  b = b.cpus(v);
615
617
  }
@@ -623,10 +625,10 @@ impl Sandbox {
623
625
  b = b.log_level(log_level_from_str(&level)?);
624
626
  }
625
627
  if let Some(secs) = conv::opt::<u64>(opts, "max_duration")? {
626
- b = b.max_duration(secs);
628
+ b = b.max_duration(Duration::from_secs(secs));
627
629
  }
628
630
  if let Some(secs) = conv::opt::<u64>(opts, "idle_timeout")? {
629
- b = b.idle_timeout(secs);
631
+ b = b.idle_timeout(Duration::from_secs(secs));
630
632
  }
631
633
  for (guest, spec) in parse_volumes(opts, host_paths)? {
632
634
  b = b.volume(guest, move |mb| spec.apply(mb));
@@ -667,10 +669,11 @@ impl Sandbox {
667
669
  /// Restart a previously-defined sandbox by name.
668
670
  fn start(name: String, opts: RHash) -> Result<Sandbox, Error> {
669
671
  let detached = conv::opt_bool(opts, "detached")?;
672
+ let sandboxes = crate::backend::active_context()?.sandboxes();
670
673
  let inner = if detached {
671
- block_on(microsandbox::Sandbox::start_detached(&name))?.map_err(error::to_ruby)?
674
+ block_on(sandboxes.start_detached(&name))?.map_err(error::to_ruby)?
672
675
  } else {
673
- block_on(microsandbox::Sandbox::start(&name))?.map_err(error::to_ruby)?
676
+ block_on(sandboxes.start(&name))?.map_err(error::to_ruby)?
674
677
  };
675
678
  Ok(Sandbox::from_inner(inner))
676
679
  }
@@ -678,16 +681,41 @@ impl Sandbox {
678
681
  /// A controllable handle for a sandbox by name (running or not). Carries
679
682
  /// metadata accessors and the full lifecycle surface (see `SbHandle`).
680
683
  fn get(name: String) -> Result<SbHandle, Error> {
681
- let handle = block_on(microsandbox::Sandbox::get(&name))?.map_err(error::to_ruby)?;
684
+ let context = crate::backend::active_context()?;
685
+ let handle =
686
+ block_on(context.sandbox_ops().get(context.clone(), &name))?.map_err(error::to_ruby)?;
682
687
  Ok(SbHandle::from_inner(handle))
683
688
  }
684
689
 
685
- /// Convert one `SandboxPage` into a `{ "sandboxes" => [SbHandle], "next_cursor" => String|nil }`
686
- /// Ruby Hash (v0.6.8 paginated listing contract).
687
- fn page_to_hash(page: microsandbox::sandbox::SandboxPage) -> Result<RHash, Error> {
690
+ /// First page of controllable handles.
691
+ fn list() -> Result<RHash, Error> {
692
+ Self::list_with(ruby().hash_new())
693
+ }
694
+
695
+ /// One page of catalog observations plus its opaque continuation cursor.
696
+ fn list_with(opts: RHash) -> Result<RHash, Error> {
697
+ let context = crate::backend::active_context()?;
698
+ let mut query = microsandbox::SandboxListBuilder::default()
699
+ .labels(conv::opt_string_map(opts, "labels")?);
700
+ if let Some(limit) = conv::opt_u32(opts, "limit")? {
701
+ let max = microsandbox::sandbox::MAX_SANDBOX_LIST_LIMIT;
702
+ if !(1..=max).contains(&limit) {
703
+ return Err(error::to_ruby(
704
+ microsandbox::MicrosandboxError::InvalidConfig(format!(
705
+ "sandbox list limit must be between 1 and {max}"
706
+ )),
707
+ ));
708
+ }
709
+ query = query.limit(limit);
710
+ }
711
+ if let Some(cursor) = conv::opt_string(opts, "cursor")? {
712
+ query = query.cursor(cursor);
713
+ }
714
+ let page = block_on(context.sandbox_ops().list(context.clone(), query))?
715
+ .map_err(error::to_ruby)?;
688
716
  let arr = ruby().ary_new();
689
- for h in page.sandboxes {
690
- arr.push(SbHandle::from_inner(h))?;
717
+ for handle in page.sandboxes {
718
+ arr.push(SbHandle::from_inner(handle))?;
691
719
  }
692
720
  let hash = ruby().hash_new();
693
721
  hash.aset("sandboxes", arr)?;
@@ -695,36 +723,10 @@ impl Sandbox {
695
723
  Ok(hash)
696
724
  }
697
725
 
698
- /// First page of sandboxes (default page size), as a page Hash of
699
- /// controllable handles.
700
- fn list() -> Result<RHash, Error> {
701
- let page = block_on(microsandbox::Sandbox::list())?.map_err(error::to_ruby)?;
702
- Self::page_to_hash(page)
703
- }
704
-
705
- /// One configured page of sandboxes as a page Hash. `opts` carries an
706
- /// optional string→string `labels` map (AND-matched), an optional `limit`
707
- /// (1..=100) and an optional opaque `cursor` from a previous page.
708
- fn list_with(opts: RHash) -> Result<RHash, Error> {
709
- let labels = conv::opt_string_map(opts, "labels")?;
710
- let limit = conv::opt_u32(opts, "limit")?;
711
- let cursor = conv::opt_string(opts, "cursor")?;
712
- let page = block_on(microsandbox::Sandbox::list_with(move |mut b| {
713
- if let Some(limit) = limit {
714
- b = b.limit(limit);
715
- }
716
- if let Some(cursor) = cursor {
717
- b = b.cursor(cursor);
718
- }
719
- b.labels(labels)
720
- }))?
721
- .map_err(error::to_ruby)?;
722
- Self::page_to_hash(page)
723
- }
724
-
725
- /// Remove a (stopped) sandbox by name.
726
+ /// Remove a stopped sandbox by name.
726
727
  fn remove(name: String) -> Result<(), Error> {
727
- block_on(microsandbox::Sandbox::remove(&name))?.map_err(error::to_ruby)
728
+ let sandboxes = crate::backend::active_context()?.sandboxes();
729
+ block_on(sandboxes.remove(&name))?.map_err(error::to_ruby)
728
730
  }
729
731
 
730
732
  //----------------------------------------------------------------------
@@ -885,7 +887,22 @@ impl Sandbox {
885
887
  fn wait_for_status(&self, status: String) -> Result<SbHandle, Error> {
886
888
  let inner = self.inner.get()?;
887
889
  let status = sandbox_status_from_str(&status)?;
888
- let handle = block_on(inner.wait_for_status(status))?.map_err(error::to_ruby)?;
890
+ let handle = block_on(async {
891
+ let context = inner.backend();
892
+ let handle = context
893
+ .sandbox_ops()
894
+ .get(context.clone(), inner.name())
895
+ .await?;
896
+ if handle.id() != inner.id() {
897
+ return Err(microsandbox::MicrosandboxError::SandboxReplaced {
898
+ name: inner.name().to_owned(),
899
+ expected: inner.id().to_string(),
900
+ actual: handle.id().to_string(),
901
+ });
902
+ }
903
+ handle.wait_for_status(status).await
904
+ })?
905
+ .map_err(error::to_ruby)?;
889
906
  Ok(SbHandle::from_inner(handle))
890
907
  }
891
908
 
@@ -905,6 +922,17 @@ impl Sandbox {
905
922
  block_on(inner.destroy_with(options))?.map_err(error::to_ruby)
906
923
  }
907
924
 
925
+ /// Version embedded in the executable selected by the retained context.
926
+ fn local_runtime_version(&self) -> Result<Option<String>, Error> {
927
+ let sandbox = self.inner.get()?;
928
+ let Some(local) = sandbox.context().as_local() else {
929
+ return Ok(None);
930
+ };
931
+ let runtime =
932
+ microsandbox::setup::resolve_runtime(local.config()).map_err(error::to_ruby)?;
933
+ crate::msb_version(runtime.msb_path.to_string_lossy().into_owned())
934
+ }
935
+
908
936
  /// Live status fetched from the backend (a round-trip per call).
909
937
  fn status(&self) -> Result<String, Error> {
910
938
  let inner = self.inner.get()?;
@@ -927,8 +955,7 @@ impl Sandbox {
927
955
  /// detaching a clone disarms the shared handle just the same.
928
956
  fn detach(&self) -> Result<(), Error> {
929
957
  let inner = self.inner.get()?.clone();
930
- block_on(inner.detach())?;
931
- Ok(())
958
+ block_on(inner.detach())?.map_err(error::to_ruby)
932
959
  }
933
960
 
934
961
  /// Latest metrics snapshot as a Hash.
@@ -2951,11 +2978,11 @@ impl PullSession {
2951
2978
  /// a synchronous snapshot read off the handle (no round-trip).
2952
2979
  #[magnus::wrap(class = "Microsandbox::Native::SandboxHandle", free_immediately, size)]
2953
2980
  pub struct SbHandle {
2954
- inner: ForkGuarded<SandboxHandle>,
2981
+ inner: ForkGuarded<SandboxRecord>,
2955
2982
  }
2956
2983
 
2957
2984
  impl SbHandle {
2958
- fn from_inner(inner: SandboxHandle) -> Self {
2985
+ fn from_inner(inner: SandboxRecord) -> Self {
2959
2986
  Self {
2960
2987
  inner: ForkGuarded::new("Microsandbox::SandboxHandle", inner),
2961
2988
  }
@@ -3111,8 +3138,8 @@ impl SbHandle {
3111
3138
  /// with `dest_dir:` for explicit placement.)
3112
3139
  fn snapshot(&self, name: String) -> Result<RHash, Error> {
3113
3140
  let inner = self.inner.get()?;
3114
- let snap = block_on(inner.snapshot(&name))?.map_err(error::to_ruby)?;
3115
- Ok(crate::snapshot::snapshot_to_hash(&snap))
3141
+ let result = block_on(inner.snapshot(&name))?.map_err(error::to_ruby)?;
3142
+ crate::snapshot::snapshot_to_hash(&result.checkpoint)
3116
3143
  }
3117
3144
 
3118
3145
  /// Health-check the guest agent without refreshing the idle timer. A stopped
@@ -3266,6 +3293,10 @@ pub fn define(ruby: &Ruby, native: &RModule) -> Result<(), Error> {
3266
3293
  class.define_method("restart", method!(Sandbox::restart, 1))?;
3267
3294
  class.define_method("destroy", method!(Sandbox::destroy, 1))?;
3268
3295
  class.define_method("status", method!(Sandbox::status, 0))?;
3296
+ class.define_method(
3297
+ "local_runtime_version",
3298
+ method!(Sandbox::local_runtime_version, 0),
3299
+ )?;
3269
3300
  class.define_method("owns_lifecycle", method!(Sandbox::owns_lifecycle, 0))?;
3270
3301
  class.define_method("detach", method!(Sandbox::detach, 0))?;
3271
3302
  class.define_method("metrics", method!(Sandbox::metrics, 0))?;
@@ -15,8 +15,8 @@ use std::path::{Path, PathBuf};
15
15
 
16
16
  use magnus::{function, prelude::*, Error, RArray, RHash, RModule, Ruby};
17
17
  use microsandbox::snapshot::{
18
- GuestFlush, SaveOpts, Snapshot, SnapshotFormat, SnapshotHandle, SnapshotReference,
19
- SnapshotScope, SnapshotVerifyReport, UpperVerifyStatus,
18
+ Checkpoint, GuestFlush, SaveOpts, SnapshotFormat, SnapshotReference, SnapshotScope,
19
+ SnapshotVerifyReport, UpperVerifyStatus,
20
20
  };
21
21
 
22
22
  use crate::conv;
@@ -71,14 +71,17 @@ fn guest_flush_from_str(s: &str) -> Result<GuestFlush, Error> {
71
71
  /// `fstype`/`size_bytes` are nil for checkpoint-state snapshots, and the
72
72
  /// `checkpoint_*` keys are nil for file-state ones — the two state families
73
73
  /// are disjoint by contract.
74
- pub(crate) fn snapshot_to_hash(snap: &Snapshot) -> RHash {
75
- let m = snap.manifest();
76
- let state = snap.state();
74
+ pub(crate) fn snapshot_to_hash(snap: &Checkpoint) -> Result<RHash, Error> {
75
+ let (m, tags) = block_on(async {
76
+ Ok::<_, microsandbox::MicrosandboxError>((snap.manifest().await?, snap.labels().await?))
77
+ })?
78
+ .map_err(error::to_ruby)?;
79
+ let state = &m.state;
77
80
  let file = state.as_file();
78
81
  let checkpoint = state.as_checkpoint();
79
82
  let hash = ruby().hash_new();
80
83
  let _ = hash.aset("digest", snap.digest().to_string());
81
- let _ = hash.aset("id", snap.id().as_str().to_string());
84
+ let _ = hash.aset("id", snap.id().to_string());
82
85
  set_reference(&hash, &snap.reference());
83
86
  // A cloud artifact has no local path (`path()` is `Unsupported` there).
84
87
  let _ = hash.aset(
@@ -87,7 +90,7 @@ pub(crate) fn snapshot_to_hash(snap: &Snapshot) -> RHash {
87
90
  );
88
91
  let _ = hash.aset("size_bytes", snap.size_bytes());
89
92
  let _ = hash.aset("scope", scope_str(m.scope));
90
- let _ = hash.aset("state_kind", state.kind());
93
+ let _ = hash.aset("state_kind", snap.state_kind().as_str());
91
94
  let _ = hash.aset("image_ref", m.image.reference.clone());
92
95
  let _ = hash.aset("image_manifest_digest", m.image.manifest_digest.clone());
93
96
  let _ = hash.aset("format", file.map(|f| format_str(f.disk_format)));
@@ -106,18 +109,20 @@ pub(crate) fn snapshot_to_hash(snap: &Snapshot) -> RHash {
106
109
  let _ = hash.aset("created_at_ms", created_at_ms(&m.capture.created_at));
107
110
  let _ = hash.aset("source_sandbox", m.capture.source_lineage.clone());
108
111
  let labels = ruby().hash_new();
109
- for (k, v) in snap.labels() {
112
+ for (k, v) in tags {
110
113
  let _ = labels.aset(k.as_str(), v.as_str());
111
114
  }
112
115
  let _ = hash.aset("labels", labels);
113
- hash
116
+ Ok(hash)
114
117
  }
115
118
 
116
119
  /// Create a snapshot artifact named `name` from a stopped sandbox. `opts`:
117
120
  /// from_sandbox (required), dest_dir, labels, force, record_integrity,
118
121
  /// full, guest_flush. Returns the full SnapshotInfo Hash.
119
122
  fn create(name: String, opts: RHash) -> Result<RHash, Error> {
120
- let mut b = Snapshot::builder(name);
123
+ let mut b = crate::backend::active_context()?
124
+ .checkpoints()
125
+ .builder(name);
121
126
  match conv::opt_string(opts, "from_sandbox")? {
122
127
  Some(src) => b = b.from_sandbox(src),
123
128
  None => {
@@ -146,7 +151,7 @@ fn create(name: String, opts: RHash) -> Result<RHash, Error> {
146
151
  }
147
152
 
148
153
  let snap = block_on(b.create())?.map_err(error::to_ruby)?;
149
- Ok(snapshot_to_hash(&snap))
154
+ snapshot_to_hash(&snap)
150
155
  }
151
156
 
152
157
  /// Open an existing snapshot artifact by bare name or path. Cheap metadata
@@ -154,17 +159,19 @@ fn create(name: String, opts: RHash) -> Result<RHash, Error> {
154
159
  /// Hash — the only way to inspect an artifact addressed by path (`get`/`list`
155
160
  /// read the local index, which path-addressed artifacts are absent from).
156
161
  fn open(path_or_name: String) -> Result<RHash, Error> {
157
- let snap = block_on(Snapshot::open(&path_or_name))?.map_err(error::to_ruby)?;
158
- Ok(snapshot_to_hash(&snap))
162
+ let checkpoints = crate::backend::active_context()?.checkpoints();
163
+ let snap = block_on(checkpoints.open(&path_or_name))?.map_err(error::to_ruby)?;
164
+ snapshot_to_hash(&snap)
159
165
  }
160
166
 
161
167
  /// Walk `dir` and parse each subdirectory's `snapshot.json` without touching
162
168
  /// the local index — for enumerating external/un-imported snapshot collections.
163
169
  fn list_dir(dir: String) -> Result<RArray, Error> {
164
- let snaps = block_on(Snapshot::list_dir(Path::new(&dir)))?.map_err(error::to_ruby)?;
170
+ let checkpoints = crate::backend::active_context()?.checkpoints();
171
+ let snaps = block_on(checkpoints.list_dir(Path::new(&dir)))?.map_err(error::to_ruby)?;
165
172
  let arr = ruby().ary_new();
166
173
  for snap in &snaps {
167
- arr.push(snapshot_to_hash(snap))?;
174
+ arr.push(snapshot_to_hash(snap)?)?;
168
175
  }
169
176
  Ok(arr)
170
177
  }
@@ -173,29 +180,26 @@ fn list_dir(dir: String) -> Result<RArray, Error> {
173
180
  /// snapshots directory). Returns the number of indexed snapshots — the repair
174
181
  /// for index drift or out-of-band imports that `get`/`list` can't see.
175
182
  fn reindex(dir: Option<String>) -> Result<u64, Error> {
176
- let dir: PathBuf = match dir {
177
- Some(d) => PathBuf::from(d),
178
- None => {
179
- crate::backend::ensure_this_process_backend()?;
180
- microsandbox::default_backend()
181
- .as_local()
182
- .map(|l| l.snapshots_dir())
183
- .unwrap_or_else(|| PathBuf::from("."))
184
- }
185
- };
186
- let n = block_on(Snapshot::reindex(&dir))?.map_err(error::to_ruby)?;
183
+ let checkpoints = crate::backend::active_context()?.checkpoints();
184
+ let n = match dir {
185
+ Some(dir) => block_on(checkpoints.reindex(Path::new(&dir)))?,
186
+ None => block_on(checkpoints.reindex_default())?,
187
+ }
188
+ .map_err(error::to_ruby)?;
187
189
  Ok(n as u64)
188
190
  }
189
191
 
190
192
  /// Metadata for one snapshot by name or digest.
191
193
  fn get(name_or_digest: String) -> Result<RHash, Error> {
192
- let handle = block_on(Snapshot::get(&name_or_digest))?.map_err(error::to_ruby)?;
194
+ let checkpoints = crate::backend::active_context()?.checkpoints();
195
+ let handle = block_on(checkpoints.get(&name_or_digest))?.map_err(error::to_ruby)?;
193
196
  Ok(handle_to_hash(&handle))
194
197
  }
195
198
 
196
199
  /// All snapshots as metadata hashes.
197
200
  fn list() -> Result<RArray, Error> {
198
- let handles = block_on(Snapshot::list())?.map_err(error::to_ruby)?;
201
+ let checkpoints = crate::backend::active_context()?.checkpoints();
202
+ let handles = block_on(checkpoints.list())?.map_err(error::to_ruby)?;
199
203
  let arr = ruby().ary_new();
200
204
  for h in &handles {
201
205
  arr.push(handle_to_hash(h))?;
@@ -205,7 +209,8 @@ fn list() -> Result<RArray, Error> {
205
209
 
206
210
  /// Remove a snapshot artifact by name or path.
207
211
  fn remove(name_or_path: String, force: bool) -> Result<(), Error> {
208
- block_on(Snapshot::remove(&name_or_path, force))?.map_err(error::to_ruby)
212
+ let checkpoints = crate::backend::active_context()?.checkpoints();
213
+ block_on(checkpoints.remove(&name_or_path, force))?.map_err(error::to_ruby)
209
214
  }
210
215
 
211
216
  /// Verify a snapshot's recorded upper-layer integrity. Returns
@@ -217,8 +222,9 @@ fn verify(name_or_path: String) -> Result<RHash, Error> {
217
222
  // Open AND verify in ONE `block_on`, so the opened snapshot never sits in
218
223
  // this frame between two calls (`block_on` returns `Err` when an interrupt
219
224
  // is delivered before it starts; one call leaves no such in-between state).
225
+ let checkpoints = crate::backend::active_context()?.checkpoints();
220
226
  let report = block_on(async move {
221
- let snap = Snapshot::open(&name_or_path).await?;
227
+ let snap = checkpoints.open(&name_or_path).await?;
222
228
  snap.verify().await
223
229
  })?
224
230
  .map_err(error::to_ruby)?;
@@ -234,27 +240,23 @@ fn save(name_or_path: String, out_path: String, opts: RHash) -> Result<(), Error
234
240
  plain_tar: conv::opt_bool(opts, "plain_tar")?,
235
241
  ..Default::default()
236
242
  };
237
- block_on(Snapshot::save(
238
- &name_or_path,
239
- std::path::Path::new(&out_path),
240
- save_opts,
241
- ))?
242
- .map_err(error::to_ruby)
243
+ let checkpoints = crate::backend::active_context()?.checkpoints();
244
+ block_on(checkpoints.save(&name_or_path, std::path::Path::new(&out_path), save_opts))?
245
+ .map_err(error::to_ruby)
243
246
  }
244
247
 
245
248
  /// Unpack a snapshot archive into the snapshots dir. Returns the loaded
246
249
  /// snapshot's metadata hash. `dest` is an optional explicit directory.
247
250
  fn load(archive_path: String, dest: Option<String>) -> Result<RHash, Error> {
248
251
  let dest_path = dest.map(PathBuf::from);
249
- let handle = block_on(Snapshot::load(
250
- std::path::Path::new(&archive_path),
251
- dest_path.as_deref(),
252
- ))?
253
- .map_err(error::to_ruby)?;
252
+ let checkpoints = crate::backend::active_context()?.checkpoints();
253
+ let handle =
254
+ block_on(checkpoints.load(std::path::Path::new(&archive_path), dest_path.as_deref()))?
255
+ .map_err(error::to_ruby)?;
254
256
  Ok(handle_to_hash(&handle))
255
257
  }
256
258
 
257
- fn handle_to_hash(handle: &SnapshotHandle) -> RHash {
259
+ fn handle_to_hash(handle: &Checkpoint) -> RHash {
258
260
  let hash = ruby().hash_new();
259
261
  let _ = hash.aset("digest", handle.digest().to_string());
260
262
  // The stable portable identity: unlike the member `name` alias, it resolves
@@ -264,7 +266,7 @@ fn handle_to_hash(handle: &SnapshotHandle) -> RHash {
264
266
  let _ = hash.aset("name", handle.name().map(str::to_string));
265
267
  let _ = hash.aset("parent_digest", handle.parent_digest().map(str::to_string));
266
268
  let _ = hash.aset("scope", scope_str(handle.scope()));
267
- let _ = hash.aset("state_kind", handle.state_kind().to_string());
269
+ let _ = hash.aset("state_kind", handle.state_kind().as_str());
268
270
  let _ = hash.aset("image_ref", handle.image_ref().to_string());
269
271
  let _ = hash.aset("format", handle.format().map(format_str));
270
272
  let _ = hash.aset("fstype", handle.fstype().map(str::to_string));
@@ -30,8 +30,8 @@ fn diagnose_json(config_json: String, scope_json: String) -> Result<String, Erro
30
30
  fn recover_json(name: String, options_json: String) -> Result<String, Error> {
31
31
  let options: StorageRecoveryOptions = serde_json::from_str(&options_json)
32
32
  .map_err(|e| error::base_error(format!("invalid storage recovery options: {e}")))?;
33
- let recovery = block_on(microsandbox::Sandbox::recover_storage(&name, options))?
34
- .map_err(error::to_ruby)?;
33
+ let sandboxes = crate::backend::active_context()?.sandboxes();
34
+ let recovery = block_on(sandboxes.recover_storage(&name, options))?.map_err(error::to_ruby)?;
35
35
  serde_json::to_string(&recovery)
36
36
  .map_err(|e| error::base_error(format!("cannot encode the storage recovery result: {e}")))
37
37
  }
@@ -7,31 +7,31 @@ use std::path::{Component, Path};
7
7
  use std::sync::Arc;
8
8
 
9
9
  use magnus::{function, method, prelude::*, Error, RArray, RHash, RModule, RString, Ruby};
10
- use microsandbox::volume::VolumeHandle;
11
- use microsandbox::{Backend, MicrosandboxError};
10
+ use microsandbox::{Context, MicrosandboxError, Volume};
12
11
 
13
12
  use crate::conv;
14
13
  use crate::error;
15
14
  use crate::runtime::{block_on, ruby, ForkGuarded};
16
15
  use crate::sandbox::{fs_entry_to_hash, fs_metadata_to_hash};
17
16
 
18
- fn handle_to_hash(h: &VolumeHandle) -> RHash {
17
+ fn handle_to_hash(volume: &Volume) -> RHash {
18
+ let info = volume.observation();
19
19
  let hash = ruby().hash_new();
20
- let _ = hash.aset("name", h.name().to_string());
21
- let _ = hash.aset("kind", h.kind().as_str().to_string());
22
- let _ = hash.aset("default", h.is_default());
23
- let _ = hash.aset("quota_mib", h.quota_mib());
24
- let _ = hash.aset("used_bytes", h.used_bytes());
25
- let _ = hash.aset("capacity_bytes", h.capacity_bytes());
26
- let _ = hash.aset("disk_format", h.disk_format().map(str::to_string));
27
- let _ = hash.aset("disk_fstype", h.disk_fstype().map(str::to_string));
20
+ let _ = hash.aset("name", info.name);
21
+ let _ = hash.aset("kind", info.kind.as_str());
22
+ let _ = hash.aset("default", info.is_default);
23
+ let _ = hash.aset("quota_mib", info.quota_mib);
24
+ let _ = hash.aset("used_bytes", info.used_bytes);
25
+ let _ = hash.aset("capacity_bytes", info.capacity_bytes);
26
+ let _ = hash.aset("disk_format", info.disk_format);
27
+ let _ = hash.aset("disk_fstype", info.disk_fstype);
28
28
  let _ = hash.aset(
29
29
  "created_at_ms",
30
- h.created_at().map(|dt| dt.timestamp_millis()),
30
+ info.created_at.map(|dt| dt.timestamp_millis()),
31
31
  );
32
32
  let labels = ruby().hash_new();
33
- for (k, v) in h.labels().iter() {
34
- let _ = labels.aset(k.clone(), v.clone());
33
+ for (k, v) in info.labels {
34
+ let _ = labels.aset(k, v);
35
35
  }
36
36
  let _ = hash.aset("labels", labels);
37
37
  hash
@@ -39,7 +39,7 @@ fn handle_to_hash(h: &VolumeHandle) -> RHash {
39
39
 
40
40
  /// Create a named volume. `opts`: kind ("dir"|"disk"), size_mib, quota_mib, labels.
41
41
  fn create(name: String, opts: RHash) -> Result<RHash, Error> {
42
- let mut builder = microsandbox::Volume::builder(&name);
42
+ let mut builder = crate::backend::active_context()?.volumes().builder(&name);
43
43
  let kind = conv::opt_string(opts, "kind")?.unwrap_or_else(|| "dir".to_string());
44
44
  let size_mib = conv::opt_u32(opts, "size_mib")?;
45
45
 
@@ -81,19 +81,22 @@ fn create(name: String, opts: RHash) -> Result<RHash, Error> {
81
81
  }
82
82
 
83
83
  fn get(name: String) -> Result<RHash, Error> {
84
- let handle = block_on(microsandbox::Volume::get(&name))?.map_err(error::to_ruby)?;
84
+ let volumes = crate::backend::active_context()?.volumes();
85
+ let handle = block_on(volumes.get(&name))?.map_err(error::to_ruby)?;
85
86
  Ok(handle_to_hash(&handle))
86
87
  }
87
88
 
88
89
  /// The backend's default volume (v0.6.9). Cloud-backend only — the local
89
90
  /// backend rejects it (Unsupported) to avoid accidental host access.
90
91
  fn get_default() -> Result<RHash, Error> {
91
- let handle = block_on(microsandbox::Volume::get_default())?.map_err(error::to_ruby)?;
92
+ let volumes = crate::backend::active_context()?.volumes();
93
+ let handle = block_on(volumes.get_default())?.map_err(error::to_ruby)?;
92
94
  Ok(handle_to_hash(&handle))
93
95
  }
94
96
 
95
97
  fn list() -> Result<RArray, Error> {
96
- let handles = block_on(microsandbox::Volume::list())?.map_err(error::to_ruby)?;
98
+ let volumes = crate::backend::active_context()?.volumes();
99
+ let handles = block_on(volumes.list())?.map_err(error::to_ruby)?;
97
100
  let arr = ruby().ary_new();
98
101
  for h in handles.iter() {
99
102
  arr.push(handle_to_hash(h))?;
@@ -102,7 +105,8 @@ fn list() -> Result<RArray, Error> {
102
105
  }
103
106
 
104
107
  fn remove(name: String) -> Result<(), Error> {
105
- block_on(microsandbox::Volume::remove(&name))?.map_err(error::to_ruby)
108
+ let volumes = crate::backend::active_context()?.volumes();
109
+ block_on(volumes.remove(&name))?.map_err(error::to_ruby)
106
110
  }
107
111
 
108
112
  /// Volume paths are relative to the volume root and never need a `..` segment,
@@ -130,7 +134,7 @@ fn contained(path: &str) -> Result<&str, Error> {
130
134
  pub struct VolumeFs {
131
135
  /// The backend this view is bound to — a clone of the creating process's
132
136
  /// default backend, so it must not cross a fork.
133
- backend: ForkGuarded<Arc<dyn Backend>>,
137
+ backend: ForkGuarded<Arc<dyn Context>>,
134
138
  name: String,
135
139
  }
136
140
 
@@ -140,9 +144,8 @@ impl VolumeFs {
140
144
  /// trait, which yields precise per-operation `Unsupported` errors on
141
145
  /// backends that can't serve it — no local-only downcast needed here.
142
146
  fn for_volume(name: String) -> Result<VolumeFs, Error> {
143
- crate::backend::ensure_this_process_backend()?;
144
147
  Ok(VolumeFs {
145
- backend: ForkGuarded::new("Microsandbox::VolumeFs", microsandbox::default_backend()),
148
+ backend: ForkGuarded::new("Microsandbox::VolumeFs", crate::backend::active_context()?),
146
149
  name,
147
150
  })
148
151
  }
@@ -2348,6 +2348,10 @@ module Microsandbox
2348
2348
  @native.status.to_sym
2349
2349
  end
2350
2350
 
2351
+ # Embedded version of the executable selected by this sandbox's local
2352
+ # context. Returns nil for remote sandboxes or an unversioned executable.
2353
+ def local_runtime_version = @native.local_runtime_version
2354
+
2351
2355
  # @return [Boolean] whether this handle owns the sandbox process lifecycle
2352
2356
  # (i.e. stopping it or dropping the handle terminates the sandbox)
2353
2357
  def owns_lifecycle?
@@ -8,7 +8,7 @@ module Microsandbox
8
8
  # Versioning section of the README for the full gem-to-runtime map. Must equal
9
9
  # the native ext's Cargo crate version (`Native.version`), enforced by
10
10
  # spec/unit/version_spec.rb.
11
- VERSION = "0.18.0"
11
+ VERSION = "0.19.0"
12
12
 
13
13
  # The upstream microsandbox runtime release this gem build embeds — the `tag`
14
14
  # pinned on every upstream git dep in ext/microsandbox/Cargo.toml. The `msb`
@@ -16,5 +16,5 @@ module Microsandbox
16
16
  # sandbox on any other `msb` version. Exposed at runtime as
17
17
  # {Microsandbox.runtime_version}. spec/unit/version_spec.rb asserts it stays in
18
18
  # sync with the Cargo tag so it can't silently drift out of date.
19
- RUNTIME_VERSION = "v0.7.14"
19
+ RUNTIME_VERSION = "v0.8.4"
20
20
  end