microsandbox-rb 0.17.4 → 0.18.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.
@@ -1,21 +1,22 @@
1
1
  //! Snapshot management: `Microsandbox::Native::Snapshot`.
2
2
  //!
3
3
  //! Snapshots capture a stopped sandbox's disk state into a portable artifact
4
- //! that a later `Sandbox.create(from_snapshot:)` can boot from. Exposed as
4
+ //! that a later `Sandbox.restore` can boot from. Exposed as
5
5
  //! singleton functions returning plain Hashes/Arrays (shaped into value objects
6
6
  //! by the Ruby layer) — there is no long-lived handle to own.
7
7
  //!
8
- //! v0.6.7 descriptor contract: an artifact is identified by its own `name`
9
- //! (`Snapshot::builder(name).from_sandbox(src)`), lives at `dest_dir/<name>`,
10
- //! and its descriptor file is `snapshot.json`. `manifest.json` artifacts from
11
- //! v0.6.6 are auto-migrated by the core on first backend connect.
8
+ //! v0.7 descriptor contract: an artifact is named by the caller
9
+ //! (`Snapshot::builder(name).from_sandbox(src)`) but carries its own stable
10
+ //! `snapshot_id`, and the core decides where it lives (the artifact path is no
11
+ //! longer `dest_dir/<name>`; read it back from `path`). Older artifacts are
12
+ //! migrated by the core on first backend connect.
12
13
 
13
14
  use std::path::{Path, PathBuf};
14
15
 
15
16
  use magnus::{function, prelude::*, Error, RArray, RHash, RModule, Ruby};
16
17
  use microsandbox::snapshot::{
17
- SaveOpts, Snapshot, SnapshotFormat, SnapshotHandle, SnapshotScope, SnapshotVerifyReport,
18
- UpperVerifyStatus,
18
+ GuestFlush, SaveOpts, Snapshot, SnapshotFormat, SnapshotHandle, SnapshotReference,
19
+ SnapshotScope, SnapshotVerifyReport, UpperVerifyStatus,
19
20
  };
20
21
 
21
22
  use crate::conv;
@@ -32,7 +33,7 @@ fn format_str(format: SnapshotFormat) -> &'static str {
32
33
  fn scope_str(scope: SnapshotScope) -> &'static str {
33
34
  match scope {
34
35
  SnapshotScope::Disk => "disk",
35
- SnapshotScope::Resumable => "resumable",
36
+ SnapshotScope::Full => "full",
36
37
  }
37
38
  }
38
39
 
@@ -43,6 +44,26 @@ fn created_at_ms(rfc3339: &str) -> Option<i64> {
43
44
  .map(|dt| dt.timestamp_millis())
44
45
  }
45
46
 
47
+ /// The backend-neutral reference `Sandbox.restore` takes back: its value and
48
+ /// how the backend reads it ("auto", "id" or "path"; a local artifact is
49
+ /// referenced by its absolute path).
50
+ fn set_reference(hash: &RHash, reference: &SnapshotReference) {
51
+ let _ = hash.aset("reference", reference.value().to_string());
52
+ let _ = hash.aset("reference_kind", reference.kind());
53
+ }
54
+
55
+ /// Parse `guest_flush:` (`auto`/`required`/`skip`).
56
+ fn guest_flush_from_str(s: &str) -> Result<GuestFlush, Error> {
57
+ match s {
58
+ "auto" => Ok(GuestFlush::Auto),
59
+ "required" => Ok(GuestFlush::Required),
60
+ "skip" => Ok(GuestFlush::Skip),
61
+ other => Err(error::base_error(format!(
62
+ "unknown guest_flush {other:?} (expected auto/required/skip)"
63
+ ))),
64
+ }
65
+ }
66
+
46
67
  /// Convert a fully-opened `Snapshot` into the `SnapshotInfo` Hash. Unlike a
47
68
  /// `SnapshotHandle` (a lightweight index row), an opened snapshot carries the
48
69
  /// full descriptor, so this is the richest shape — `create`/`open`/`list_dir`
@@ -57,24 +78,35 @@ pub(crate) fn snapshot_to_hash(snap: &Snapshot) -> RHash {
57
78
  let checkpoint = state.as_checkpoint();
58
79
  let hash = ruby().hash_new();
59
80
  let _ = hash.aset("digest", snap.digest().to_string());
60
- let _ = hash.aset("path", snap.path().to_string_lossy().into_owned());
81
+ let _ = hash.aset("id", snap.id().as_str().to_string());
82
+ set_reference(&hash, &snap.reference());
83
+ // A cloud artifact has no local path (`path()` is `Unsupported` there).
84
+ let _ = hash.aset(
85
+ "path",
86
+ snap.path().ok().map(|p| p.to_string_lossy().into_owned()),
87
+ );
61
88
  let _ = hash.aset("size_bytes", snap.size_bytes());
62
89
  let _ = hash.aset("scope", scope_str(m.scope));
63
90
  let _ = hash.aset("state_kind", state.kind());
64
91
  let _ = hash.aset("image_ref", m.image.reference.clone());
65
92
  let _ = hash.aset("image_manifest_digest", m.image.manifest_digest.clone());
66
- let _ = hash.aset("format", file.map(|f| format_str(f.format)));
67
- let _ = hash.aset("fstype", file.map(|f| f.fstype.clone()));
93
+ let _ = hash.aset("format", file.map(|f| format_str(f.disk_format)));
94
+ let _ = hash.aset("fstype", file.map(|f| f.filesystem.clone()));
68
95
  let _ = hash.aset("checkpoint_id", checkpoint.map(|c| c.checkpoint_id.clone()));
69
96
  let _ = hash.aset(
70
97
  "checkpoint_manifest_digest",
71
- checkpoint.map(|c| c.manifest.clone()),
98
+ checkpoint.map(|c| c.checkpoint_root.clone()),
99
+ );
100
+ // v0.7 descriptors link their parent by stable id, not by digest.
101
+ let _ = hash.aset("parent_digest", None::<String>);
102
+ let _ = hash.aset(
103
+ "parent_id",
104
+ m.parent.as_ref().map(|p| p.as_str().to_string()),
72
105
  );
73
- let _ = hash.aset("parent_digest", m.parent.clone());
74
- let _ = hash.aset("created_at_ms", created_at_ms(&m.created_at));
75
- let _ = hash.aset("source_sandbox", m.source_sandbox.clone());
106
+ let _ = hash.aset("created_at_ms", created_at_ms(&m.capture.created_at));
107
+ let _ = hash.aset("source_sandbox", m.capture.source_lineage.clone());
76
108
  let labels = ruby().hash_new();
77
- for (k, v) in &m.labels {
109
+ for (k, v) in snap.labels() {
78
110
  let _ = labels.aset(k.as_str(), v.as_str());
79
111
  }
80
112
  let _ = hash.aset("labels", labels);
@@ -83,7 +115,7 @@ pub(crate) fn snapshot_to_hash(snap: &Snapshot) -> RHash {
83
115
 
84
116
  /// Create a snapshot artifact named `name` from a stopped sandbox. `opts`:
85
117
  /// from_sandbox (required), dest_dir, labels, force, record_integrity,
86
- /// resumable. Returns the full SnapshotInfo Hash.
118
+ /// full, guest_flush. Returns the full SnapshotInfo Hash.
87
119
  fn create(name: String, opts: RHash) -> Result<RHash, Error> {
88
120
  let mut b = Snapshot::builder(name);
89
121
  match conv::opt_string(opts, "from_sandbox")? {
@@ -106,8 +138,11 @@ fn create(name: String, opts: RHash) -> Result<RHash, Error> {
106
138
  if conv::opt_bool(opts, "record_integrity")? {
107
139
  b = b.record_integrity();
108
140
  }
109
- if conv::opt_bool(opts, "resumable")? {
110
- b = b.resumable();
141
+ if conv::opt_bool(opts, "full")? {
142
+ b = b.full();
143
+ }
144
+ if let Some(policy) = conv::opt_string(opts, "guest_flush")? {
145
+ b = b.guest_flush(guest_flush_from_str(&policy)?);
111
146
  }
112
147
 
113
148
  let snap = block_on(b.create())?.map_err(error::to_ruby)?;
@@ -197,6 +232,7 @@ fn save(name_or_path: String, out_path: String, opts: RHash) -> Result<(), Error
197
232
  with_parents: conv::opt_bool(opts, "with_parents")?,
198
233
  with_image: conv::opt_bool(opts, "with_image")?,
199
234
  plain_tar: conv::opt_bool(opts, "plain_tar")?,
235
+ ..Default::default()
200
236
  };
201
237
  block_on(Snapshot::save(
202
238
  &name_or_path,
@@ -221,6 +257,10 @@ fn load(archive_path: String, dest: Option<String>) -> Result<RHash, Error> {
221
257
  fn handle_to_hash(handle: &SnapshotHandle) -> RHash {
222
258
  let hash = ruby().hash_new();
223
259
  let _ = hash.aset("digest", handle.digest().to_string());
260
+ // The stable portable identity: unlike the member `name` alias, it resolves
261
+ // as a selector on its own (a bare name only selects a group head in v0.7).
262
+ let _ = hash.aset("id", handle.id().to_string());
263
+ set_reference(&hash, &handle.reference());
224
264
  let _ = hash.aset("name", handle.name().map(str::to_string));
225
265
  let _ = hash.aset("parent_digest", handle.parent_digest().map(str::to_string));
226
266
  let _ = hash.aset("scope", scope_str(handle.scope()));
@@ -240,7 +280,10 @@ fn handle_to_hash(handle: &SnapshotHandle) -> RHash {
240
280
  "migration_error_code",
241
281
  handle.migration_error_code().map(str::to_string),
242
282
  );
243
- let _ = hash.aset("path", handle.path().to_string_lossy().into_owned());
283
+ let _ = hash.aset(
284
+ "path",
285
+ handle.path().ok().map(|p| p.to_string_lossy().into_owned()),
286
+ );
244
287
  let _ = hash.aset(
245
288
  "created_at_ms",
246
289
  handle.created_at().and_utc().timestamp_millis(),
@@ -0,0 +1,44 @@
1
+ //! Storage diagnosis and recovery (runtime v0.7): `Microsandbox::Native::Storage`.
2
+ //!
3
+ //! Runtime v0.7 moves a sandbox's disks into a protected storage layout. On
4
+ //! Linux an older sandbox migrates on its next start; on macOS (and for
5
+ //! ambiguous or damaged legacy metadata) it needs an explicit recovery while
6
+ //! the sandbox is stopped. Both entry points are JSON bridges over the core's
7
+ //! own wire types, like the official SDKs' (`sdk/ruby/ext/.../storage.rs`):
8
+ //! the Ruby layer builds the request and shapes the report.
9
+
10
+ use magnus::{function, prelude::*, Error, RModule, Ruby};
11
+ use microsandbox::sandbox::StorageRecoveryOptions;
12
+
13
+ use crate::error;
14
+ use crate::runtime::block_on;
15
+
16
+ /// Inspect storage without starting, stopping, repairing or migrating
17
+ /// anything. `config_json` is `{"home": …}` (optional); `scope_json` is
18
+ /// `"all"` or `{"named": [names]}`. Returns the diagnosis as JSON.
19
+ fn diagnose_json(config_json: String, scope_json: String) -> Result<String, Error> {
20
+ block_on(async move {
21
+ microsandbox::setup::binding_diagnose_storage(&config_json, &scope_json).await
22
+ })?
23
+ .map_err(error::to_ruby)
24
+ }
25
+
26
+ /// Import or resume a stopped sandbox's storage without booting it.
27
+ /// `options_json` is `{"selections": [{disk_id, candidate_id}],
28
+ /// "accept_selected_view": bool, "legacy_writers_stopped": bool}`. Returns
29
+ /// `{"name", "ready", "originals_retained"}` as JSON.
30
+ fn recover_json(name: String, options_json: String) -> Result<String, Error> {
31
+ let options: StorageRecoveryOptions = serde_json::from_str(&options_json)
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)?;
35
+ serde_json::to_string(&recovery)
36
+ .map_err(|e| error::base_error(format!("cannot encode the storage recovery result: {e}")))
37
+ }
38
+
39
+ pub fn define(_ruby: &Ruby, native: &RModule) -> Result<(), Error> {
40
+ let module = native.define_module("Storage")?;
41
+ module.define_singleton_method("diagnose_json", function!(diagnose_json, 2))?;
42
+ module.define_singleton_method("recover_json", function!(recover_json, 2))?;
43
+ Ok(())
44
+ }
@@ -30,6 +30,15 @@ module Microsandbox
30
30
  # Configuration / validation errors --------------------------------------
31
31
  define_error(:InvalidConfigError, "invalid-config")
32
32
 
33
+ # Host runtime resolution (runtime v0.7) -----------------------------------
34
+ # No `msb` + `libkrunfw` pair could be found anywhere. Mirrors the Python
35
+ # SDK's RuntimeNotInstalledError.
36
+ define_error(:RuntimeNotInstalledError, "runtime-not-installed")
37
+ # The selected runtime pair is partial, or an explicit `MSB_PATH` /
38
+ # `runtime_path` names an executable with no matching `libkrunfw`. Mirrors
39
+ # the Python SDK's RuntimeIncompleteError.
40
+ define_error(:RuntimeIncompleteError, "runtime-incomplete")
41
+
33
42
  # Lifecycle errors --------------------------------------------------------
34
43
  define_error(:SandboxNotFoundError, "sandbox-not-found")
35
44
  define_error(:SandboxNotRunningError, "sandbox-not-running")
@@ -42,6 +51,13 @@ module Microsandbox
42
51
  # letting them act on the replacement. Mirrors the Python SDK's
43
52
  # SandboxReplacedError.
44
53
  define_error(:SandboxReplacedError, "sandbox-replaced")
54
+ # v0.7: a graceful stop did not establish completion within its budget; the
55
+ # shutdown request may still complete, and no kill was requested. Mirrors
56
+ # the Python SDK's StopTimeoutError (kept flat here: no TimeoutError mixin).
57
+ define_error(:StopTimeoutError, "stop-timeout")
58
+ # Reserved for parity (Python SandboxStopTimedOutError): the core variant has
59
+ # no raise site at the pinned runtime.
60
+ define_error(:SandboxStopTimedOutError, "sandbox-stop-timed-out")
45
61
 
46
62
  # Execution errors --------------------------------------------------------
47
63
  define_error(:ExecTimeoutError, "exec-timeout")
@@ -77,6 +93,11 @@ module Microsandbox
77
93
  # backend connect / artifact open) was blocked and needs repair. Mirrors the
78
94
  # Python SDK's SnapshotMigrationError (code "snapshot-migration").
79
95
  define_error(:SnapshotMigrationError, "snapshot-migration")
96
+ # v0.7: a full checkpoint was captured, but the source sandbox failed to
97
+ # recover afterwards and needs recovery before further use. Carries the
98
+ # recovery locator as attributes (see the class body below). Mirrors the
99
+ # Python SDK's SnapshotSourceRecoveryError.
100
+ define_error(:SnapshotSourceRecoveryError, "snapshot-source-recovery")
80
101
 
81
102
  # Networking / secrets errors ---------------------------------------------
82
103
  # NetworkPolicyError now also carries the core's `NetworkBuilder` build/parse
@@ -101,6 +122,11 @@ module Microsandbox
101
122
  # cloud backend) is distinct from `UnsupportedOperationError` above.
102
123
  define_error(:CloudHttpError, "cloud-http")
103
124
  define_error(:UnsupportedError, "unsupported")
125
+ # v0.7 (cloud only): a change did not complete as asked — it may be saved
126
+ # without being in effect on the running sandbox, or its outcome is unknown.
127
+ # The message says which and whether resending retries it; it never holds a
128
+ # secret value. Mirrors the Python SDK's ModificationNotConfirmedError.
129
+ define_error(:ModificationNotConfirmedError, "modification-not-confirmed")
104
130
 
105
131
  # Process model ------------------------------------------------------------
106
132
  # A handle (a Sandbox, a SandboxHandle, an ExecHandle, a stream, an SSH or
@@ -121,4 +147,41 @@ module Microsandbox
121
147
  # @return [String, nil] why it was rejected / what to use instead
122
148
  attr_reader :hint
123
149
  end
150
+
151
+ # Capture completed, but the source requires recovery before further use.
152
+ # {#artifact} is set only when the requested snapshot was published;
153
+ # otherwise {#checkpoint_path} locates the retained runtime-local checkpoint
154
+ # (removing the source may remove it). The error does not imply that an
155
+ # ordinary resume is safe.
156
+ class SnapshotSourceRecoveryError
157
+ # @return [String, nil] sandbox whose post-capture recovery failed
158
+ attr_reader :source_sandbox
159
+ # @return [String, nil] verified runtime checkpoint id
160
+ attr_reader :checkpoint_id
161
+ # @return [String, nil] content-addressed root of that checkpoint
162
+ attr_reader :checkpoint_root
163
+ # @return [String, nil] runtime-local checkpoint path
164
+ attr_reader :checkpoint_path
165
+ # @return [Hash, nil] the published artifact, when publication completed:
166
+ # `{"kind" => "installed" | "archive", "path" =>, "snapshot_id" =>, "digest" =>}`
167
+ attr_reader :artifact
168
+ # @return [String, nil] the runtime's recovery diagnostic
169
+ attr_reader :detail
170
+ # @return [String, nil] a further failure while publishing the artifact
171
+ attr_reader :publication_error
172
+
173
+ private
174
+
175
+ # Called by the native layer with the core's serialized recovery record.
176
+ def __apply_recovery(details)
177
+ @source_sandbox = details["source_sandbox"]
178
+ @checkpoint_id = details["checkpoint_id"]
179
+ @checkpoint_root = details["checkpoint_root"]
180
+ @checkpoint_path = details["checkpoint_path"]
181
+ @artifact = details["artifact"]
182
+ @detail = details["detail"]
183
+ @publication_error = details["publication_error"]
184
+ self
185
+ end
186
+ end
124
187
  end
@@ -62,7 +62,8 @@ module Microsandbox
62
62
  @native = native
63
63
  end
64
64
 
65
- # Write data to the process stdin.
65
+ # Write data to the process stdin. An empty String is a no-op (since
66
+ # 0.18.0 / runtime v0.7; it used to send EOF) — call {#close} for EOF.
66
67
  # @param data [String] raw bytes to write (binary-safe)
67
68
  # @raise [TypeError] if +data+ is not a String
68
69
  # @return [self]
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Microsandbox
4
+ # The host runtime pair (`msb` + `libkrunfw`) local sandboxes would launch
5
+ # with, from {Microsandbox.runtime_info}. Resolution reads files and the
6
+ # environment only: nothing is downloaded, created or executed.
7
+ class RuntimeInfo
8
+ # @return [String] the `msb` executable
9
+ attr_reader :msb_path
10
+ # @return [String] the matching `libkrunfw` shared library
11
+ attr_reader :libkrunfw_path
12
+
13
+ # @api private
14
+ def initialize(data)
15
+ @msb_path = data.fetch("msb_path")
16
+ @libkrunfw_path = data.fetch("libkrunfw_path")
17
+ @origin = data.fetch("origin")
18
+ @version_read = false
19
+ end
20
+
21
+ # Where the pair came from:
22
+ #
23
+ # - `:environment` — `MSB_PATH` (with `MSB_LIBKRUNFW_PATH` or the library
24
+ # next to it);
25
+ # - `:sdk_package` — the companion `microsandbox-rb-binaries` gem;
26
+ # - `:configuration` — `runtime_path=` / `libkrunfw_path=`, or the paths in
27
+ # the config file;
28
+ # - `:home` — the runtime home (`MSB_HOME`, default `~/.microsandbox`);
29
+ # - `:installed` — an explicit installer source.
30
+ #
31
+ # Gem-classified: runtime v0.7.14 layers `MSB_PATH` and the SDK path slots
32
+ # into the configuration before it resolves, so it reports both as
33
+ # `:configuration`; the SDK tells `:environment` and `:sdk_package` apart
34
+ # by the resolved path (see docs/runtime.md).
35
+ # @return [Symbol]
36
+ def origin
37
+ @origin.to_sym
38
+ end
39
+
40
+ # The runtime version embedded in the `msb` executable, read on first use
41
+ # (the file is inspected, never run). nil for a pre-0.7 `msb` or a wrapper
42
+ # script, neither of which carries one.
43
+ # @return [String, nil] e.g. "0.7.14"
44
+ def version
45
+ unless @version_read
46
+ @version = Native.msb_version(@msb_path)
47
+ @version_read = true
48
+ end
49
+ @version
50
+ end
51
+
52
+ # Whether the `msb` carries no embedded version (a pre-0.7 runtime or a
53
+ # wrapper script). Such a runtime is refused at every local sandbox start.
54
+ def legacy? = version.nil?
55
+
56
+ # Whether the `msb` is exactly the runtime this SDK was built for — the only
57
+ # version the launch contract accepts.
58
+ def matches_sdk? = version == RUNTIME_VERSION.delete_prefix("v")
59
+
60
+ def inspect
61
+ "#<Microsandbox::RuntimeInfo origin=#{@origin} msb_path=#{@msb_path.inspect} " \
62
+ "libkrunfw_path=#{@libkrunfw_path.inspect}>"
63
+ end
64
+ end
65
+ end