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.
@@ -4,11 +4,13 @@ module Microsandbox
4
4
  # Metadata for a snapshot artifact, returned by {Snapshot.create}/{Snapshot.open}/
5
5
  # {Snapshot.get}/{Snapshot.list}/{Snapshot.list_dir}/{Snapshot.load}.
6
6
  #
7
- # `digest` and `path` are always present. The artifact-opening paths
8
- # (`create`/`open`/`list_dir`, and {SandboxHandle#snapshot}) carry the full
9
- # descriptor — `size_bytes`, `image_ref`, `image_manifest_digest`, `format`,
10
- # `fstype`, `parent_digest`, `created_at`, `source_sandbox`, and `labels`. The
11
- # index paths (`get`/`list`/`load`) populate `name`, `parent_digest`,
7
+ # `digest` is always present, and `path` for every local artifact (nil for a
8
+ # cloud one). The artifact-opening paths (`create`/`open`/`list_dir`, and
9
+ # {SandboxHandle#snapshot}) carry the full descriptor — `parent_id`,
10
+ # `size_bytes`, `image_ref`, `image_manifest_digest`, `format`, `fstype`,
11
+ # `created_at`, `source_sandbox`, and `labels` (`parent_digest` is nil there:
12
+ # runtime v0.7 descriptors link their parent by id). The index paths
13
+ # (`get`/`list`/`load`) populate `name`, `parent_digest`,
12
14
  # `image_ref`, `format`, `size_bytes`, `created_at`, and the index-only
13
15
  # `locality`/`availability`/`migration_state` columns (descriptor-only fields
14
16
  # such as `source_sandbox`/`labels` are nil/empty there).
@@ -18,14 +20,34 @@ module Microsandbox
18
20
  # `"checkpoint"` — a manifest-backed state, where those are nil and the
19
21
  # `checkpoint_*` fields are set instead.
20
22
  class SnapshotInfo
21
- # @return [String] descriptor digest ("sha256:…") — the canonical identity
23
+ # @return [String] descriptor digest ("sha256:…")
22
24
  attr_reader :digest
23
- # @return [String] artifact directory path
25
+ # @return [String, nil] stable snapshot id (`snap_…`), independent of the
26
+ # descriptor digest. Set on every local path; it is a selector on its own
27
+ # for {Snapshot.open}/{Snapshot.get}/{Snapshot.verify}/{Snapshot.save}/
28
+ # {Snapshot.remove}, unlike {#name}.
29
+ attr_reader :id
30
+ # @return [String, nil] the backend-neutral reference to pass back to
31
+ # {Sandbox.restore} (runtime v0.7): for a local artifact, its absolute
32
+ # path. {Sandbox.restore} given this {SnapshotInfo} uses it with its kind
33
+ # (see {#reference_kind}).
34
+ attr_reader :reference
35
+ # @return [String, nil] how the backend reads {#reference}: "path", "id"
36
+ # or "auto"
37
+ attr_reader :reference_kind
38
+ # @return [String, nil] artifact directory path (nil for a cloud artifact).
39
+ # Since runtime v0.7 the core chooses this directory; it is no longer
40
+ # `dest_dir/<name>`.
24
41
  attr_reader :path
25
- # @return [String, nil] name alias (nil for digest-only entries)
42
+ # @return [String, nil] the member name alias inside its snapshot group
43
+ # (index paths only; nil for digest-only entries). Since runtime v0.7 a
44
+ # bare name selects a group head, not a member — address a member as
45
+ # `"<group>:<name>"` or by {#id}/{#path}/{#digest}.
26
46
  attr_reader :name
27
- # @return [String, nil] parent snapshot digest
47
+ # @return [String, nil] parent snapshot digest (index paths only)
28
48
  attr_reader :parent_digest
49
+ # @return [String, nil] parent snapshot id (descriptor paths)
50
+ attr_reader :parent_id
29
51
  # @return [String, nil] source OCI image reference
30
52
  attr_reader :image_ref
31
53
  # @return [String, nil] OCI manifest digest of the pinned image (descriptor paths)
@@ -55,9 +77,13 @@ module Microsandbox
55
77
 
56
78
  def initialize(data)
57
79
  @digest = data["digest"]
80
+ @id = data["id"]
81
+ @reference = data["reference"]
82
+ @reference_kind = data["reference_kind"]
58
83
  @path = data["path"]
59
84
  @name = data["name"]
60
85
  @parent_digest = data["parent_digest"]
86
+ @parent_id = data["parent_id"]
61
87
  @image_ref = data["image_ref"]
62
88
  @image_manifest_digest = data["image_manifest_digest"]
63
89
  @fstype = data["fstype"]
@@ -81,8 +107,9 @@ module Microsandbox
81
107
  @format&.to_sym
82
108
  end
83
109
 
84
- # @return [Symbol, nil] payload scope — :disk today, :resumable once VM
85
- # pause/resume lands upstream
110
+ # @return [Symbol, nil] payload scope — :disk (file-backed disk state) or
111
+ # :full (a composite checkpoint, see {Snapshot.create}'s `full:`).
112
+ # Runtime v0.7 renamed `:resumable` to `:full`.
86
113
  def scope
87
114
  @scope&.to_sym
88
115
  end
@@ -146,42 +173,76 @@ module Microsandbox
146
173
 
147
174
  # Creation and management of sandbox snapshots. A snapshot captures a stopped
148
175
  # sandbox's disk state into a portable artifact; boot from it with
149
- # `Sandbox.create(from_snapshot: "name-or-digest")`.
176
+ # {Sandbox.restore}.
177
+ #
178
+ # Runtime v0.7 descriptor contract: an artifact carries its own stable
179
+ # {SnapshotInfo#id}, and the core chooses its directory (read it from
180
+ # {SnapshotInfo#path}; it is no longer `dest_dir/<name>`). Artifacts written
181
+ # by older gems are migrated automatically by the runtime on first use —
182
+ # after which older gem versions can no longer read them.
183
+ #
184
+ # Snapshot groups (runtime v0.7): {create} publishes the artifact into a
185
+ # group named after the source sandbox, as a member aliased `name`, and makes
186
+ # it the group's head. Selectors passed to {open}/{get}/{verify}/{save}/
187
+ # {remove} resolve as follows:
188
+ #
189
+ # - `"<group>"` (a bare name) — the group's current head;
190
+ # - `"<group>:<member>"` — that member, e.g. `"#{from_sandbox}:#{name}"`;
191
+ # - a snapshot id (`snap_…`) or descriptor digest (`sha256:…`);
192
+ # - a path (anything containing `/` or starting with `.`).
150
193
  #
151
- # v0.6.7 descriptor contract: artifacts are identified by their own name and
152
- # live at `dest_dir/<name>`; the descriptor file is `snapshot.json`. Artifacts
153
- # written by ≤0.10.x gems (`manifest.json`) are migrated automatically by the
154
- # runtime on first use — after which older gem versions can no longer read
155
- # them (downgrade requires the `msb self downgrade` tooling).
194
+ # So the `name` given to {create} is NOT a selector on its own. Keep the
195
+ # returned {SnapshotInfo#id} (or {SnapshotInfo#path}) instead. A {load}ed
196
+ # archive lands in a fresh generated group with no head selected, so address
197
+ # it by its {SnapshotInfo#id} or {SnapshotInfo#path}. Binding the group
198
+ # surface itself (`group:`, head selection) is planned for a later release.
156
199
  class Snapshot
157
200
  class << self
158
201
  # Create a snapshot named `name` from a stopped sandbox.
159
202
  #
160
- # @param name [String] the snapshot's own name (its identity)
203
+ # @param name [String] the member name alias inside the snapshot group
204
+ # (the group is named after `from_sandbox`; see the class notes on
205
+ # selectors — select it later as `"#{from_sandbox}:#{name}"` or by the
206
+ # returned {SnapshotInfo#id})
161
207
  # @param from_sandbox [String] name of the (stopped) source sandbox
162
- # @param dest_dir [String, nil] parent directory override — the artifact
163
- # is written at `dest_dir/<name>` (default: the snapshots dir)
208
+ # @param dest_dir [String, nil] parent directory override (default: the
209
+ # snapshots dir); the core picks the artifact directory beneath it
164
210
  # @param labels [Hash, nil] user labels
165
- # @param force [Boolean] overwrite an existing artifact at the destination
211
+ # @param force [Boolean] runtime v0.7 rejects it: grouped snapshots are
212
+ # immutable, so `force: true` raises {InvalidConfigError} — choose
213
+ # another name or {remove} the existing member first
166
214
  # @param record_integrity [Boolean] record persistent payload integrity
167
215
  # (a Merkle content digest) in the artifact — opt-in since runtime
168
216
  # v0.6.9 because hashing large allocated uppers is expensive; without
169
217
  # it {Snapshot.verify} reports `:not_recorded`
170
- # @param resumable [Boolean] request a resumable (memory+device) snapshot;
171
- # raises {UnsupportedError} until VM pause/resume lands upstream
218
+ # @param full [Boolean] capture a full (memory + device) checkpoint
219
+ # instead of disk state only (runtime v0.7; the backend rejects it with
220
+ # {UnsupportedError} where full checkpoints are not available)
221
+ # @param guest_flush [Symbol, String, nil] optional guest filesystem
222
+ # writeback before capture (runtime v0.7): `:auto` (the default:
223
+ # required for a live disk-only capture), `:required`, or `:skip`.
224
+ # Mandatory storage barriers apply either way; it does not flush
225
+ # application buffers. A stopped source cannot satisfy `:required`.
226
+ # @param resumable [nil] removed in 0.18.0 — renamed to `full:` upstream;
227
+ # passing it raises ArgumentError
172
228
  # @return [SnapshotInfo]
173
229
  def create(name, from_sandbox:, dest_dir: nil, labels: nil, force: false,
174
- record_integrity: false, resumable: false)
230
+ record_integrity: false, full: false, guest_flush: nil, resumable: nil)
231
+ unless resumable.nil?
232
+ raise ArgumentError, "Snapshot.create(resumable:) was renamed to full: in 0.18.0 (runtime v0.7)"
233
+ end
234
+ flush = normalize_guest_flush(guest_flush)
175
235
  opts = {"from_sandbox" => from_sandbox.to_s}
176
236
  opts["dest_dir"] = dest_dir.to_s if dest_dir
177
237
  opts["labels"] = stringify(labels) if labels
178
238
  opts["force"] = true if force
179
239
  opts["record_integrity"] = true if record_integrity
180
- opts["resumable"] = true if resumable
240
+ opts["full"] = true if full
241
+ opts["guest_flush"] = flush if flush
181
242
  SnapshotInfo.new(Native::Snapshot.create(name.to_s, opts))
182
243
  end
183
244
 
184
- # Open a snapshot artifact by bare name or path (cheap metadata
245
+ # Open a snapshot artifact by selector or path (cheap metadata
185
246
  # validation; does not read the payload). Unlike {get}, this also
186
247
  # works for artifacts addressed by path that were never indexed, and it
187
248
  # returns the full descriptor.
@@ -190,7 +251,8 @@ module Microsandbox
190
251
  SnapshotInfo.new(Native::Snapshot.open(name_or_path.to_s))
191
252
  end
192
253
 
193
- # Metadata for a snapshot by name or digest.
254
+ # Index metadata for a snapshot by selector (see the class notes), id or
255
+ # digest.
194
256
  # @return [SnapshotInfo]
195
257
  def get(name_or_digest)
196
258
  SnapshotInfo.new(Native::Snapshot.get(name_or_digest.to_s))
@@ -219,7 +281,8 @@ module Microsandbox
219
281
  Native::Snapshot.reindex(dir&.to_s)
220
282
  end
221
283
 
222
- # Remove a snapshot artifact by name or path.
284
+ # Remove a snapshot artifact by selector or path (see the class notes).
285
+ # Removing a group's head leaves the group with no head selected.
223
286
  # @param force [Boolean] remove even if referenced
224
287
  # @return [nil]
225
288
  def remove(name_or_path, force: false)
@@ -261,6 +324,16 @@ module Microsandbox
261
324
  def stringify(hash)
262
325
  hash.each_with_object({}) { |(k, v), acc| acc[k.to_s] = v.to_s }
263
326
  end
327
+
328
+ GUEST_FLUSH = %w[auto required skip].freeze
329
+ private_constant :GUEST_FLUSH
330
+
331
+ def normalize_guest_flush(value)
332
+ return nil if value.nil?
333
+ flush = (value.is_a?(Symbol) || value.is_a?(String)) ? value.to_s : nil
334
+ return flush if GUEST_FLUSH.include?(flush)
335
+ raise ArgumentError, "guest_flush: must be :auto, :required or :skip, got #{value.inspect}"
336
+ end
264
337
  end
265
338
  end
266
339
  end
@@ -0,0 +1,205 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Microsandbox
6
+ # One complete disk view a storage inspection found, for an explicit
7
+ # {Sandbox.recover_storage} selection. The id is opaque and is revalidated
8
+ # under locks when used.
9
+ class StorageCandidate
10
+ # @return [String] the candidate id to pass in `selections:`
11
+ attr_reader :id
12
+ # @return [String] `"root"` or the owned-volume mount id
13
+ attr_reader :disk_id
14
+ # @return [Integer] number of authorized layers
15
+ attr_reader :layers
16
+ # @return [Integer] guest-visible capacity in bytes
17
+ attr_reader :virtual_size
18
+ # @return [Integer] conservative bytes a recovery would stage
19
+ attr_reader :estimated_bytes
20
+
21
+ # @api private
22
+ def initialize(data)
23
+ @id = data["id"]
24
+ @disk_id = data["disk_id"]
25
+ @layers = data["layers"]
26
+ @virtual_size = data["virtual_size"]
27
+ @estimated_bytes = data["estimated_bytes"]
28
+ end
29
+
30
+ def inspect
31
+ "#<Microsandbox::StorageCandidate id=#{@id.inspect} disk_id=#{@disk_id.inspect}>"
32
+ end
33
+ end
34
+
35
+ # The storage engine's (provisional) inspection of one sandbox.
36
+ class StorageInspection
37
+ # @return [Symbol, nil] the engine's migration classification
38
+ attr_reader :status
39
+ # @return [Array<String>] actionable reasons
40
+ attr_reader :reasons
41
+ # @return [Array<StorageCandidate>]
42
+ attr_reader :candidates
43
+ # @return [Integer, nil] conservative bytes a recovery would stage
44
+ attr_reader :estimated_bytes
45
+
46
+ # @api private
47
+ def initialize(data)
48
+ @status = data["status"]&.to_sym
49
+ @reasons = Array(data["reasons"])
50
+ @candidates = Array(data["candidates"]).map { |c| StorageCandidate.new(c) }
51
+ @estimated_bytes = data["estimated_bytes"]
52
+ @preview_available = data["preview_available"] == true
53
+ end
54
+
55
+ # Whether a recovery preview is available.
56
+ def preview_available? = @preview_available
57
+
58
+ def inspect
59
+ "#<Microsandbox::StorageInspection status=#{@status.inspect} candidates=#{@candidates.size}>"
60
+ end
61
+ end
62
+
63
+ # One requested sandbox's storage diagnosis.
64
+ class StorageSandboxDiagnosis
65
+ # @return [String]
66
+ attr_reader :name
67
+ # @return [Symbol] `:ready`, `:eligible`, `:maintenance_required`,
68
+ # `:recovery_required`, `:in_progress` or `:unavailable`
69
+ attr_reader :status
70
+ # @return [Symbol, nil] why the check could not finish: `:not_found`,
71
+ # `:invalid_configuration`, `:incomplete_creation` or
72
+ # `:storage_unavailable`
73
+ attr_reader :reason
74
+ # @return [StorageInspection, nil]
75
+ attr_reader :inspection
76
+ # @return [Hash{String=>String}] guest mount path per disk id
77
+ attr_reader :guest_mounts
78
+
79
+ # @api private
80
+ def initialize(data)
81
+ @name = data["name"]
82
+ @status = data["status"]&.to_sym
83
+ @running = data["running"] == true
84
+ @protection_registered = data["protection_registered"] == true
85
+ @reason = data["reason"]&.to_sym
86
+ @inspection = data["inspection"] && StorageInspection.new(data["inspection"])
87
+ @guest_mounts = data["guest_mounts"] || {}
88
+ end
89
+
90
+ # Whether the catalog records a running VM (the report is then provisional).
91
+ def running? = @running
92
+
93
+ # Whether the sandbox's storage is registered for protection.
94
+ def protection_registered? = @protection_registered
95
+
96
+ def inspect
97
+ "#<Microsandbox::StorageSandboxDiagnosis name=#{@name.inspect} status=#{@status.inspect}" \
98
+ "#{" reason=#{@reason.inspect}" if @reason}>"
99
+ end
100
+ end
101
+
102
+ # The result of {Microsandbox.diagnose_storage}.
103
+ class StorageDiagnosis
104
+ # @return [String] the runtime home that was inspected
105
+ attr_reader :home
106
+ # @return [Array<StorageSandboxDiagnosis>]
107
+ attr_reader :sandboxes
108
+ # @return [String] the runtime capability a protected start requires
109
+ attr_reader :required_runtime_capability
110
+
111
+ # @api private
112
+ def initialize(data)
113
+ @home = data["home"]
114
+ @sandboxes = Array(data["sandboxes"]).map { |item| StorageSandboxDiagnosis.new(item) }
115
+ @required_runtime_capability = data["required_runtime_capability"]
116
+ end
117
+
118
+ def inspect
119
+ "#<Microsandbox::StorageDiagnosis home=#{@home.inspect} sandboxes=#{@sandboxes.map(&:name).inspect}>"
120
+ end
121
+ end
122
+
123
+ # The result of {Sandbox.recover_storage}.
124
+ class StorageRecovery
125
+ # @return [String]
126
+ attr_reader :name
127
+
128
+ # @api private
129
+ def initialize(data)
130
+ @name = data["name"]
131
+ @ready = data["ready"] == true
132
+ @originals_retained = data["originals_retained"] == true
133
+ end
134
+
135
+ # Whether the sandbox's storage is now in the protected layout.
136
+ def ready? = @ready
137
+
138
+ # Whether the original legacy disks were kept (the runtime always keeps them).
139
+ def originals_retained? = @originals_retained
140
+
141
+ def inspect
142
+ "#<Microsandbox::StorageRecovery name=#{@name.inspect} ready=#{@ready}>"
143
+ end
144
+ end
145
+
146
+ class << self
147
+ # Inspect the runtime-`v0.7` storage state of sandboxes in the local
148
+ # runtime home. Never starts, stops, repairs or migrates anything; the
149
+ # report is provisional (a recovery revalidates under locks). Pick exactly
150
+ # one scope.
151
+ #
152
+ # @param names [Array<String>, nil] sandboxes to inspect
153
+ # @param all_sandboxes [Boolean] inspect every sandbox in the catalog
154
+ # @param home [String, nil] runtime home to inspect (default: the
155
+ # configured one)
156
+ # @return [StorageDiagnosis]
157
+ def diagnose_storage(names: nil, all_sandboxes: false, home: nil)
158
+ unless (all_sandboxes == true) ^ !names.nil?
159
+ raise ArgumentError, "diagnose_storage: pass names: or all_sandboxes: true (exactly one)"
160
+ end
161
+ unless all_sandboxes
162
+ names = Array(names).map(&:to_s)
163
+ raise ArgumentError, "diagnose_storage: names: must not be empty" if names.empty?
164
+ end
165
+ scope = all_sandboxes ? "all" : {"named" => names}
166
+ config = home.nil? ? {} : {"home" => home.to_s}
167
+ StorageDiagnosis.new(JSON.parse(Native::Storage.diagnose_json(JSON.generate(config), JSON.generate(scope))))
168
+ end
169
+ end
170
+
171
+ class Sandbox
172
+ class << self
173
+ # Import or resume a **stopped** sandbox's storage into the runtime
174
+ # `v0.7` protected layout without booting it (runtime `v0.7`). On Linux
175
+ # an older sandbox migrates on its next start; on macOS, or when
176
+ # {Microsandbox.diagnose_storage} reports `:recovery_required`, run this
177
+ # first. The original legacy disks are kept.
178
+ #
179
+ # @param name [String] the stopped sandbox
180
+ # @param selections [Hash{String=>String}] for ambiguous or damaged
181
+ # legacy metadata: disk id (`"root"` or an owned-volume mount id) =>
182
+ # candidate id from {Microsandbox.diagnose_storage}
183
+ # @param accept_selected_view [Boolean] required with `selections:`:
184
+ # acknowledge that the selected view may omit later writes
185
+ # @param legacy_writers_stopped [Boolean] macOS: confirm that every
186
+ # pre-0.18 VM in every runtime home has stopped and that no older tool
187
+ # will touch this storage until recovery finishes. Never inferred.
188
+ # @return [StorageRecovery]
189
+ def recover_storage(name, selections: {}, accept_selected_view: false, legacy_writers_stopped: false)
190
+ unless selections.is_a?(Hash)
191
+ raise ArgumentError, "recover_storage: selections: must be a Hash of disk id => candidate id"
192
+ end
193
+ options = {
194
+ "selections" => selections.map { |disk, candidate| {"disk_id" => disk.to_s, "candidate_id" => candidate.to_s} },
195
+ "accept_selected_view" => accept_selected_view == true,
196
+ "legacy_writers_stopped" => legacy_writers_stopped == true
197
+ }
198
+ sandbox_name = name.to_s
199
+ # The recovery checks the runtime's launch contract, like a start.
200
+ Microsandbox.ensure_runtime!
201
+ StorageRecovery.new(JSON.parse(Native::Storage.recover_json(sandbox_name, JSON.generate(options))))
202
+ end
203
+ end
204
+ end
205
+ end
@@ -8,12 +8,13 @@ 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.17.4"
11
+ VERSION = "0.18.0"
12
12
 
13
13
  # The upstream microsandbox runtime release this gem build embeds — the `tag`
14
- # pinned on the `microsandbox`/`microsandbox-network` git deps in
15
- # ext/microsandbox/Cargo.toml. Exposed at runtime as
14
+ # pinned on every upstream git dep in ext/microsandbox/Cargo.toml. The `msb`
15
+ # runtime binary must be exactly this release: the core refuses to launch a
16
+ # sandbox on any other `msb` version. Exposed at runtime as
16
17
  # {Microsandbox.runtime_version}. spec/unit/version_spec.rb asserts it stays in
17
18
  # sync with the Cargo tag so it can't silently drift out of date.
18
- RUNTIME_VERSION = "v0.6.18"
19
+ RUNTIME_VERSION = "v0.7.14"
19
20
  end