microsandbox-rb 0.17.5 → 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.
@@ -20,6 +20,7 @@ mod runtime;
20
20
  mod sandbox;
21
21
  mod snapshot;
22
22
  mod ssh;
23
+ mod storage;
23
24
  mod stream;
24
25
  mod volume;
25
26
 
@@ -45,54 +46,258 @@ fn all_sandbox_metrics() -> Result<RHash, Error> {
45
46
  Ok(hash)
46
47
  }
47
48
 
48
- /// Download and install the `msb` runtime + `libkrunfw` into `~/.microsandbox`.
49
- /// Never touches the backend, so a forked child does not take the inherited
50
- /// one over here (see `runtime::block_on_runtime_install`).
51
- fn install() -> Result<(), Error> {
52
- runtime::block_on_runtime_install(microsandbox::setup::install())?.map_err(error::to_ruby)
49
+ /// The effective local runtime configuration: the persisted config file, then
50
+ /// `MSB_HOME`/`MSB_PATH`/`MSB_LIBKRUNFW_PATH`, the SDK path slots and managed
51
+ /// policy, layered exactly as the local backend layers them (`overrides_json`
52
+ /// adds `home`/`msb_path`/`libkrunfw_path` on top). Reads files and the
53
+ /// environment only — no backend is built.
54
+ fn effective_runtime_config(
55
+ overrides_json: &str,
56
+ ) -> microsandbox::MicrosandboxResult<microsandbox::config::GlobalConfig> {
57
+ microsandbox::setup::binding_runtime_config(overrides_json)
53
58
  }
54
59
 
55
- /// Customizable install via the core `Setup` builder. `opts`: base_dir (install
56
- /// root), version (pin the runtime version), force (re-download even if present
57
- /// — repairs a corrupt install), skip_verify. Mirrors the Node `Setup` builder.
60
+ /// Whether the runtime HOME of `config` already holds a complete `msb` +
61
+ /// `libkrunfw` pair — exactly the pair an install would write. Explicit paths
62
+ /// (`MSB_PATH`, the SDK slots, `config.paths`) are cleared first so they can
63
+ /// neither satisfy nor mask the check: `setup` targets the home. Presence
64
+ /// only, like upstream's `is_runtime_installed` (the version-aware decision is
65
+ /// `Microsandbox.install`'s, in Ruby).
66
+ fn home_runtime_complete(config: &microsandbox::config::GlobalConfig) -> bool {
67
+ let mut home_only = config.clone();
68
+ home_only.paths.msb = None;
69
+ home_only.paths.libkrunfw = None;
70
+ matches!(
71
+ microsandbox::setup::resolve_runtime(&home_only),
72
+ Ok(runtime) if runtime.origin == microsandbox::setup::RuntimeOrigin::Home
73
+ )
74
+ }
75
+
76
+ /// A resolved runtime pair as the Ruby Hash `runtime_info` returns:
77
+ /// `{"msb_path", "libkrunfw_path", "origin"}`, origin in upstream's snake_case
78
+ /// `RuntimeOrigin` spelling (`environment`, `sdk_package`, `configuration`,
79
+ /// `home`, `installed`).
80
+ fn resolved_runtime_to_hash(
81
+ runtime: &microsandbox::setup::ResolvedRuntime,
82
+ ) -> Result<RHash, Error> {
83
+ let origin = serde_json::to_value(runtime.origin)
84
+ .ok()
85
+ .and_then(|value| value.as_str().map(str::to_string))
86
+ .unwrap_or_else(|| format!("{:?}", runtime.origin).to_lowercase());
87
+ let hash = runtime::ruby().hash_new();
88
+ hash.aset("msb_path", runtime.msb_path.to_string_lossy().into_owned())?;
89
+ hash.aset(
90
+ "libkrunfw_path",
91
+ runtime.libkrunfw_path.to_string_lossy().into_owned(),
92
+ )?;
93
+ hash.aset("origin", origin)?;
94
+ Ok(hash)
95
+ }
96
+
97
+ /// The `msb` + `libkrunfw` pair the local backend would launch, resolved from
98
+ /// the effective runtime configuration (environment, SDK slots, config file,
99
+ /// home, packaged slot — `effective_runtime_config`) without touching the
100
+ /// network or the filesystem. Raises `RuntimeNotInstalledError` when nothing
101
+ /// resolves and `RuntimeIncompleteError` for a partial or unpaired source.
102
+ /// Independent of the selected backend (cloud included): it describes the host.
103
+ fn runtime_info() -> Result<RHash, Error> {
104
+ let config = effective_runtime_config("{}").map_err(error::to_ruby)?;
105
+ let runtime = microsandbox::setup::resolve_runtime(&config).map_err(error::to_ruby)?;
106
+ resolved_runtime_to_hash(&runtime)
107
+ }
108
+
109
+ /// The runtime version embedded in the `msb` at `path` (its `.msbver`
110
+ /// section), or nil when it has none: a pre-0.7 `msb`, or a wrapper script
111
+ /// (`#!`), which the launch contract also treats as unversioned. Reads the
112
+ /// file only; never executes it.
113
+ fn msb_version(path: String) -> Result<Option<String>, Error> {
114
+ use std::io::Read as _;
115
+ let mut head = [0u8; 2];
116
+ let is_script = std::fs::File::open(&path)
117
+ .and_then(|mut file| file.read_exact(&mut head))
118
+ .map(|()| &head == b"#!")
119
+ .unwrap_or(false);
120
+ if is_script {
121
+ return Ok(None);
122
+ }
123
+ microsandbox::setup::resolve_runtime_version(&path)
124
+ .map(|version| version.map(|v| v.to_string()))
125
+ .map_err(error::to_ruby)
126
+ }
127
+
128
+ /// The exact pair an install writes into the runtime home:
129
+ /// `[<home>/bin/<msb>, <home>/lib/<libkrunfw>]`, with the OS-specific file
130
+ /// names upstream's resolver expects (`runtime_in_home`). The home comes from
131
+ /// the effective configuration (`MSB_HOME`, the config file, default
132
+ /// `~/.microsandbox`).
133
+ fn runtime_home_pair() -> Result<(String, String), Error> {
134
+ let config = effective_runtime_config("{}").map_err(error::to_ruby)?;
135
+ Ok(home_pair_of(&config))
136
+ }
137
+
138
+ /// `[<home>/bin/<msb>, <home>/lib/<libkrunfw>]` of `config`'s runtime home.
139
+ fn home_pair_of(config: &microsandbox::config::GlobalConfig) -> (String, String) {
140
+ let home = config.home();
141
+ let os = std::env::consts::OS;
142
+ let msb = home
143
+ .join(microsandbox_utils::BIN_SUBDIR)
144
+ .join(microsandbox_utils::msb_binary_filename(os));
145
+ let lib = home
146
+ .join(microsandbox_utils::LIB_SUBDIR)
147
+ .join(microsandbox_utils::libkrunfw_filename(os));
148
+ (
149
+ msb.to_string_lossy().into_owned(),
150
+ lib.to_string_lossy().into_owned(),
151
+ )
152
+ }
153
+
154
+ /// Install the runtime pair into the runtime home through upstream's
155
+ /// installer. `opts` (all optional): source (`release_download` (default),
156
+ /// `archive`, `directory`, `embedded_archive`), source_path, version, force,
157
+ /// verify, expected_archive_sha256 — upstream's binding wire
158
+ /// (`binding_install_options`). Returns the installed pair in `runtime_info`'s
159
+ /// shape. Unconditional: the "is there anything to do" decision is
160
+ /// `Microsandbox.install`'s. Never touches the backend, so a forked child does
161
+ /// not take the inherited one over here (see `runtime::block_on_runtime_install`).
162
+ fn install_runtime(opts: RHash) -> Result<RHash, Error> {
163
+ let options = install_options(opts)?;
164
+ let config = effective_runtime_config("{}").map_err(error::to_ruby)?;
165
+ let runtime = runtime::block_on_runtime_install(async move {
166
+ microsandbox::setup::install_runtime(&config, options).await
167
+ })?
168
+ .map_err(error::to_ruby)?;
169
+ resolved_runtime_to_hash(&runtime)
170
+ }
171
+
172
+ /// `install_runtime`'s option Hash decoded through upstream's binding wire.
173
+ fn install_options(opts: RHash) -> Result<microsandbox::setup::InstallOptions, Error> {
174
+ let mut install_opts = serde_json::Map::new();
175
+ for key in [
176
+ "source",
177
+ "source_path",
178
+ "version",
179
+ "expected_archive_sha256",
180
+ ] {
181
+ if let Some(value) = conv::opt_string(opts, key)? {
182
+ install_opts.insert(key.into(), value.into());
183
+ }
184
+ }
185
+ if conv::opt_bool(opts, "force")? {
186
+ install_opts.insert("force".into(), true.into());
187
+ }
188
+ if let Some(verify) = conv::opt::<bool>(opts, "verify")? {
189
+ install_opts.insert("verify".into(), verify.into());
190
+ }
191
+ microsandbox::setup::binding_install_options(
192
+ &serde_json::Value::Object(install_opts).to_string(),
193
+ )
194
+ .map_err(error::to_ruby)
195
+ }
196
+
197
+ /// The runtime configuration the active local backend captured when it was
198
+ /// built (building the default backend now if nothing has yet). `None` for a
199
+ /// non-local backend. Immutable for that backend's lifetime: unlike
200
+ /// `effective_runtime_config`, later changes to the environment or the config
201
+ /// file do not reach it.
202
+ fn captured_local_config() -> Result<Option<microsandbox::config::GlobalConfig>, Error> {
203
+ backend::ensure_this_process_backend()?;
204
+ let backend = microsandbox::default_backend();
205
+ Ok(backend.as_local().map(|local| local.config().clone()))
206
+ }
207
+
208
+ fn require_captured_local_config() -> Result<microsandbox::config::GlobalConfig, Error> {
209
+ captured_local_config()?.ok_or_else(|| error::local_only("ensure_runtime!"))
210
+ }
211
+
212
+ /// `runtime_info` resolved from the local backend's captured configuration:
213
+ /// the pair `create` will launch. Same Hash and errors as `runtime_info`.
214
+ fn backend_runtime_info() -> Result<RHash, Error> {
215
+ let config = require_captured_local_config()?;
216
+ let runtime = microsandbox::setup::resolve_runtime(&config).map_err(error::to_ruby)?;
217
+ resolved_runtime_to_hash(&runtime)
218
+ }
219
+
220
+ /// `runtime_home_pair` of the local backend's captured configuration: the
221
+ /// pair a bootstrap install writes.
222
+ fn backend_runtime_home_pair() -> Result<(String, String), Error> {
223
+ Ok(home_pair_of(&require_captured_local_config()?))
224
+ }
225
+
226
+ /// The first-use bootstrap's install (`Microsandbox.ensure_runtime!`): into
227
+ /// the home of the configuration the local backend captured, never into one
228
+ /// read afresh, so a change to `MSB_HOME`/`MSB_PATH` after the decision cannot
229
+ /// redirect the write. `expected_msb` is the home `msb` path the decision was
230
+ /// made for (`backend_runtime_home_pair`); a backend rebuilt in between with
231
+ /// another home is refused. `opts` as `install_runtime`. The explicit
232
+ /// `Microsandbox.install` keeps using `install_runtime` (ambient, backend-free).
233
+ fn install_backend_runtime(expected_msb: String, opts: RHash) -> Result<RHash, Error> {
234
+ let options = install_options(opts)?;
235
+ let config = require_captured_local_config()?;
236
+ let (msb, _) = home_pair_of(&config);
237
+ if msb != expected_msb {
238
+ return Err(error::to_ruby(
239
+ microsandbox::MicrosandboxError::InvalidConfig(format!(
240
+ "the local backend changed during the runtime bootstrap: it now installs to \
241
+ {msb}, not the {expected_msb} the bootstrap checked; retry"
242
+ )),
243
+ ));
244
+ }
245
+ let runtime = runtime::block_on_runtime_install(async move {
246
+ microsandbox::setup::install_runtime(&config, options).await
247
+ })?
248
+ .map_err(error::to_ruby)?;
249
+ resolved_runtime_to_hash(&runtime)
250
+ }
251
+
252
+ /// Customizable install. `opts`: base_dir (the runtime home to install into),
253
+ /// version (the release to download), force (replace a complete installation —
254
+ /// repairs a corrupt one; without it a complete pair in the home is kept, as
255
+ /// with `install`), skip_verify. Built on upstream's language-SDK
256
+ /// bindings (`binding_runtime_config` / `binding_install_options`), the same
257
+ /// wire the official SDKs use.
58
258
  fn setup(opts: RHash) -> Result<(), Error> {
59
- use microsandbox::setup::Setup;
60
- let base_dir = conv::opt_string(opts, "base_dir")?;
61
- let version = conv::opt_string(opts, "version")?;
62
- let skip_verify = conv::opt_bool(opts, "skip_verify")?;
63
- let force = conv::opt_bool(opts, "force")?;
64
- // `Setup` uses a typed-builder whose `strip_option` setters change the type
65
- // on each call, so optional fields can't be set conditionally on one binding
66
- // — branch on presence instead (matching the Node binding).
67
- let setup = match (base_dir, version) {
68
- (Some(d), Some(v)) => Setup::builder()
69
- .base_dir(d)
70
- .version(v)
71
- .skip_verify(skip_verify)
72
- .force(force)
73
- .build(),
74
- (Some(d), None) => Setup::builder()
75
- .base_dir(d)
76
- .skip_verify(skip_verify)
77
- .force(force)
78
- .build(),
79
- (None, Some(v)) => Setup::builder()
80
- .version(v)
81
- .skip_verify(skip_verify)
82
- .force(force)
83
- .build(),
84
- (None, None) => Setup::builder()
85
- .skip_verify(skip_verify)
86
- .force(force)
87
- .build(),
88
- };
259
+ let mut runtime_cfg = serde_json::Map::new();
260
+ if let Some(dir) = conv::opt_string(opts, "base_dir")? {
261
+ runtime_cfg.insert("home".into(), dir.into());
262
+ }
263
+ let mut install_opts = serde_json::Map::new();
264
+ if let Some(version) = conv::opt_string(opts, "version")? {
265
+ install_opts.insert("version".into(), version.into());
266
+ }
267
+ if conv::opt_bool(opts, "force")? {
268
+ install_opts.insert("force".into(), true.into());
269
+ }
270
+ if conv::opt_bool(opts, "skip_verify")? {
271
+ install_opts.insert("verify".into(), false.into());
272
+ }
273
+ let force = install_opts.contains_key("force");
274
+ let config = effective_runtime_config(&serde_json::Value::Object(runtime_cfg).to_string())
275
+ .map_err(error::to_ruby)?;
276
+ // As `install`: a complete pair in the target home is kept unless forced.
277
+ if !force && home_runtime_complete(&config) {
278
+ return Ok(());
279
+ }
280
+ let options = microsandbox::setup::binding_install_options(
281
+ &serde_json::Value::Object(install_opts).to_string(),
282
+ )
283
+ .map_err(error::to_ruby)?;
89
284
  // Backend-free, like `install`.
90
- runtime::block_on_runtime_install(setup.install())?.map_err(error::to_ruby)
285
+ runtime::block_on_runtime_install(async move {
286
+ microsandbox::setup::install_runtime(&config, options)
287
+ .await
288
+ .map(|_| ())
289
+ })?
290
+ .map_err(error::to_ruby)
91
291
  }
92
292
 
93
- /// Whether the `msb` runtime + `libkrunfw` are installed and resolvable.
293
+ /// Whether a complete `msb` + `libkrunfw` pair resolves from any source the
294
+ /// local backend would use (environment, SDK slots, config, home, packaged).
295
+ /// Presence only: it says nothing about the version (see `Microsandbox.ensure_runtime!`).
296
+ /// A configuration that cannot be loaded counts as "not installed".
94
297
  fn is_installed() -> bool {
95
- microsandbox::setup::is_installed()
298
+ effective_runtime_config("{}")
299
+ .map(|config| microsandbox::setup::is_runtime_installed(&config))
300
+ .unwrap_or(false)
96
301
  }
97
302
 
98
303
  /// Override the resolved `msb` runtime path (SDK tier of the resolver).
@@ -122,6 +327,56 @@ fn resolved_msb_path() -> Result<String, Error> {
122
327
  Ok(path.to_string_lossy().into_owned())
123
328
  }
124
329
 
330
+ /// One side of `verify_backend_runtime_config`'s comparison: a configuration's
331
+ /// runtime home and the pair it resolves (or the resolver's error, rendered).
332
+ fn runtime_selection(config: &microsandbox::config::GlobalConfig) -> (std::path::PathBuf, String) {
333
+ let pair = match microsandbox::setup::resolve_runtime(config) {
334
+ Ok(runtime) => format!(
335
+ "msb {} with libkrunfw {}",
336
+ runtime.msb_path.display(),
337
+ runtime.libkrunfw_path.display()
338
+ ),
339
+ Err(error) => format!("no runtime ({error})"),
340
+ };
341
+ (config.home(), pair)
342
+ }
343
+
344
+ /// Refuse to bootstrap a runtime the active local backend would not launch.
345
+ /// The backend captures its configuration (runtime home, `MSB_PATH`,
346
+ /// `MSB_LIBKRUNFW_PATH`, the SDK slots, the config file) once, when it is
347
+ /// first built — this call builds it if nothing has yet — while `runtime_info`,
348
+ /// `runtime_home_pair` and `install_runtime` read the configuration afresh.
349
+ /// When the two disagree on the home or the resolved pair, the readiness
350
+ /// check and any install would target a runtime `create` does not use, so
351
+ /// this raises `InvalidConfigError` instead; when they agree, every later
352
+ /// bootstrap decision is the backend's. A non-local backend has nothing to
353
+ /// compare.
354
+ fn verify_backend_runtime_config() -> Result<(), Error> {
355
+ backend::ensure_this_process_backend()?;
356
+ let backend = microsandbox::default_backend();
357
+ let Some(local) = backend.as_local() else {
358
+ return Ok(());
359
+ };
360
+ let current = effective_runtime_config("{}").map_err(error::to_ruby)?;
361
+ let (captured_home, captured_pair) = runtime_selection(local.config());
362
+ let (current_home, current_pair) = runtime_selection(&current);
363
+ if captured_home == current_home && captured_pair == current_pair {
364
+ return Ok(());
365
+ }
366
+ Err(error::to_ruby(
367
+ microsandbox::MicrosandboxError::InvalidConfig(format!(
368
+ "the runtime configuration changed after this process's local backend was created: \
369
+ the backend uses runtime home {} and {captured_pair}, but the current configuration \
370
+ selects runtime home {} and {current_pair}. The backend reads MSB_HOME, MSB_PATH, \
371
+ MSB_LIBKRUNFW_PATH and the config file once, when it is first used; restore the \
372
+ earlier setting, or call Microsandbox.set_default_backend(:local) to rebuild it \
373
+ from the current configuration",
374
+ captured_home.display(),
375
+ current_home.display()
376
+ )),
377
+ ))
378
+ }
379
+
125
380
  /// This process's fork generation (see `runtime::ProcessIdentity`): how many
126
381
  /// `fork`s led from the process that loaded the extension to this one. A
127
382
  /// diagnostic for the fork specs, not part of the Ruby API (nothing in
@@ -172,7 +427,10 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
172
427
  let native = module.define_module("Native")?;
173
428
 
174
429
  native.define_singleton_method("version", function!(version, 0))?;
175
- native.define_singleton_method("install", function!(install, 0))?;
430
+ native.define_singleton_method("runtime_info", function!(runtime_info, 0))?;
431
+ native.define_singleton_method("msb_version", function!(msb_version, 1))?;
432
+ native.define_singleton_method("runtime_home_pair", function!(runtime_home_pair, 0))?;
433
+ native.define_singleton_method("install_runtime", function!(install_runtime, 1))?;
176
434
  native.define_singleton_method("setup", function!(setup, 1))?;
177
435
  native.define_singleton_method("installed?", function!(is_installed, 0))?;
178
436
  native.define_singleton_method("set_runtime_msb_path", function!(set_runtime_msb_path, 1))?;
@@ -181,6 +439,19 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
181
439
  function!(set_runtime_libkrunfw_path, 1),
182
440
  )?;
183
441
  native.define_singleton_method("resolved_msb_path", function!(resolved_msb_path, 0))?;
442
+ native.define_singleton_method(
443
+ "verify_backend_runtime_config",
444
+ function!(verify_backend_runtime_config, 0),
445
+ )?;
446
+ native.define_singleton_method("backend_runtime_info", function!(backend_runtime_info, 0))?;
447
+ native.define_singleton_method(
448
+ "backend_runtime_home_pair",
449
+ function!(backend_runtime_home_pair, 0),
450
+ )?;
451
+ native.define_singleton_method(
452
+ "install_backend_runtime",
453
+ function!(install_backend_runtime, 2),
454
+ )?;
184
455
  native.define_singleton_method("all_sandbox_metrics", function!(all_sandbox_metrics, 0))?;
185
456
  native.define_singleton_method("fork_generation", function!(fork_generation, 0))?;
186
457
  native.define_singleton_method("fork_identity_equal", function!(fork_identity_equal, 4))?;
@@ -196,6 +467,7 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
196
467
  volume::define(ruby, &native)?;
197
468
  agent::define(ruby, &native)?;
198
469
  ssh::define(ruby, &native)?;
470
+ storage::define(ruby, &native)?;
199
471
 
200
472
  Ok(())
201
473
  }
@@ -523,15 +523,15 @@ where
523
523
  }
524
524
 
525
525
  /// [`block_on`] without its backend check, for the runtime installer ONLY:
526
- /// `Native.install` and `Native.setup` (`microsandbox::setup`).
526
+ /// `Native.install_runtime` and `Native.setup` (`microsandbox::setup`).
527
527
  ///
528
528
  /// The check at the top of [`block_on`] is deliberate and stays there: it is
529
529
  /// what makes every other native call safe after a fork. This entry is not a
530
530
  /// cheaper alternative to it. It exists because the installer never touches
531
- /// the default backend or the catalog — `Setup::install` creates the
532
- /// `bin`/`lib` directories, runs the installed `msb --version`, copies a CI
533
- /// build or downloads and unpacks the release bundle, and checks that the two
534
- /// files exist, all under the base directory it resolves from `MSB_HOME` —
531
+ /// the default backend or the catalog — `setup::install_runtime` downloads
532
+ /// (or reads) the release bundle, unpacks it into a staging directory,
533
+ /// publishes the `msb` + `libkrunfw` pair under `.runtime-install.lock` and
534
+ /// verifies it, all under the runtime home it resolves from `MSB_HOME` —
535
535
  /// so in a forked child the check would only rebuild (and leak) a backend
536
536
  /// nothing uses, or fail the install when the inherited backend selection no
537
537
  /// longer resolves there. Skipping it leaves the backend record as it was: