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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +16 -1
- data/Cargo.lock +1565 -1168
- data/README.md +3 -2
- data/docs/runtime.md +10 -11
- data/docs/surface.md +3 -1
- data/ext/microsandbox/Cargo.toml +4 -4
- data/ext/microsandbox/src/backend.rs +59 -75
- data/ext/microsandbox/src/exec.rs +79 -17
- data/ext/microsandbox/src/host_path.rs +2 -3
- data/ext/microsandbox/src/lib.rs +3 -6
- data/ext/microsandbox/src/sandbox.rs +86 -55
- data/ext/microsandbox/src/snapshot.rs +45 -43
- data/ext/microsandbox/src/storage.rs +2 -2
- data/ext/microsandbox/src/volume.rs +25 -22
- data/lib/microsandbox/sandbox.rb +4 -0
- data/lib/microsandbox/version.rb +2 -2
- data/lib/microsandbox.rb +7 -8
- data/sig/microsandbox.rbs +1 -0
- metadata +1 -1
data/README.md
CHANGED
|
@@ -214,8 +214,8 @@ share the upstream tag, but the numbers have diverged since and the gem version
|
|
|
214
214
|
is **not** an indicator of the embedded runtime. Ask the build instead:
|
|
215
215
|
|
|
216
216
|
```ruby
|
|
217
|
-
Microsandbox::VERSION # => "0.
|
|
218
|
-
Microsandbox.runtime_version # => "v0.
|
|
217
|
+
Microsandbox::VERSION # => "0.19.0" (the gem's own version)
|
|
218
|
+
Microsandbox.runtime_version # => "v0.8.4" (the embedded upstream runtime tag)
|
|
219
219
|
```
|
|
220
220
|
|
|
221
221
|
While the gem is `0.x`, a breaking API change bumps the minor and a fix bumps
|
|
@@ -256,6 +256,7 @@ constants against this gem's. Every release records its runtime in
|
|
|
256
256
|
| `0.17.4` | `v0.6.18` | gem-only fix release: fork safety identifies a process by pid and fork generation (survives pid reuse), `install`/`setup` leave the backend alone in a forked child, a `Sandbox` subclass's `initialize` runs outside the interrupt mask, and the macOS limit that a forked child must not build network clients is documented; rustls 0.23.46 fixes four TLS advisories (RUSTSEC-2026-0346 to -0349) |
|
|
257
257
|
| `0.17.5` | `v0.6.18` | gem-only security release: dependency updates clear RUSTSEC-2026-0381 to -0410, including the zstd used for image-layer decompression (three zstd advisories remain only on an external-kernel path the runtime never takes, see `CHANGELOG.md`); `SECURITY.md` maps more upstream advisories to gem versions |
|
|
258
258
|
| `0.18.0` | `v0.7.14` | adopts upstream `v0.7.14` (**breaking**): the `msb` runtime must be exactly the SDK's version (a stale home runtime is replaced automatically, other sources are refused); secrets vocabulary (`allow:`/`allow_placeholder_for:`/`substitution:`/`violation_action:`), `secret_violation_action:`; `Sandbox.restore` replaces `create(from_snapshot:)`, `full:` replaces `resumable:`; HTTP denials default to a JSON 403 (`http:` option); one-way catalog migrations and macOS storage recovery for existing sandboxes; Ruby >= 3.3 |
|
|
259
|
+
| `0.19.0` | `v0.8.4` | adopts upstream contexts and checkpoint APIs while preserving Ruby lifecycle handles, status values, and paginated results |
|
|
259
260
|
|
|
260
261
|
## Development
|
|
261
262
|
|
data/docs/runtime.md
CHANGED
|
@@ -51,19 +51,18 @@ skips the installer entirely and nothing is written to `~/.microsandbox`.
|
|
|
51
51
|
|
|
52
52
|
### One runtime version
|
|
53
53
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
sandbox start `Microsandbox.ensure_runtime!` checks the selected runtime:
|
|
54
|
+
The companion gem bundles the exact runtime named by
|
|
55
|
+
`Microsandbox::RUNTIME_VERSION`. Upstream v0.8 checks launch capabilities for
|
|
56
|
+
an explicitly selected executable. Keep its version and firmware paired
|
|
57
|
+
with the SDK for predictable operation. Before the first local sandbox
|
|
58
|
+
start, `Microsandbox.ensure_runtime!` checks the selected runtime:
|
|
60
59
|
|
|
61
60
|
| Selected runtime | What the SDK does |
|
|
62
61
|
|---|---|
|
|
63
62
|
| this version | nothing |
|
|
64
63
|
| none at all | warns, then `install`s into the runtime home |
|
|
65
64
|
| the runtime home's, another version | warns, then `install(force: true)` replaces the pair in the home |
|
|
66
|
-
| `MSB_PATH`, `runtime_path=`, a configured path — another version | never touched: warns that
|
|
65
|
+
| `MSB_PATH`, `runtime_path=`, a configured path — another version | never touched: warns that launch compatibility is not guaranteed |
|
|
67
66
|
| a partial pair | raises `RuntimeIncompleteError`, naming the files to delete or the variable to set |
|
|
68
67
|
|
|
69
68
|
With `MICROSANDBOX_NO_AUTO_INSTALL` set nothing is installed or replaced in any
|
|
@@ -115,7 +114,7 @@ info = Microsandbox.runtime_info # => #<Microsandbox::RuntimeInfo origin=home
|
|
|
115
114
|
info.origin # => :home (:environment, :sdk_package, :configuration, :installed)
|
|
116
115
|
info.msb_path # => "/Users/you/.microsandbox/bin/msb"
|
|
117
116
|
info.libkrunfw_path # => "/Users/you/.microsandbox/lib/libkrunfw.5.dylib"
|
|
118
|
-
info.version # => "0.
|
|
117
|
+
info.version # => "0.8.4" (nil for an unversioned executable)
|
|
119
118
|
info.matches_sdk? # => true
|
|
120
119
|
|
|
121
120
|
Microsandbox.installed? # => true/false (any complete pair, any version)
|
|
@@ -303,9 +302,9 @@ The runtime home (`MSB_HOME`, default `~/.microsandbox`) belongs to one
|
|
|
303
302
|
runtime line at a time. This gem embeds the runtime named by
|
|
304
303
|
`Microsandbox::RUNTIME_VERSION` and, on first use, installs that version of `msb` into the home — replacing a different version
|
|
305
304
|
that is already there, including a newer `msb` installed by the official CLI.
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
305
|
+
Opening the home with a newer runtime may upgrade the catalog schema. Keep
|
|
306
|
+
a tested backup of the catalog and matching state. An older runtime may
|
|
307
|
+
refuse the migrated copy.
|
|
309
308
|
|
|
310
309
|
If the official CLI (or another SDK) on a different runtime line shares the
|
|
311
310
|
machine, give this gem its own home:
|
data/docs/surface.md
CHANGED
|
@@ -15,7 +15,9 @@ counterpart, and [DESIGN.md](../DESIGN.md) explains how the layers fit.
|
|
|
15
15
|
`snapshot`), the cursor-paginated `list`/`list_with` with label filters, and
|
|
16
16
|
the convergent lifecycle (`connect_or_create`, `#id`, `wait_for_status`,
|
|
17
17
|
`restart`, `destroy`, `SandboxHandle#connect_or_start`,
|
|
18
|
-
`SandboxReplacedError`).
|
|
18
|
+
`SandboxReplacedError`). `Sandbox#local_runtime_version` reads the
|
|
19
|
+
executable embedded version from the retained local context. It returns nil
|
|
20
|
+
for remote contexts or an unversioned executable.
|
|
19
21
|
- **Backend routing** — `set_default_backend`/`with_backend`/
|
|
20
22
|
`default_backend_kind`/`default_backend_info`.
|
|
21
23
|
- **Execution** — `exec`/`shell` (collected and streaming), the default
|
data/ext/microsandbox/Cargo.toml
CHANGED
|
@@ -8,7 +8,7 @@ description = "Ruby SDK native extension for microsandbox — secure, fast micro
|
|
|
8
8
|
# returns this via env!("CARGO_PKG_VERSION") and version_spec.rb asserts equality.
|
|
9
9
|
# The core-crate dependencies below stay on their own tag, which is
|
|
10
10
|
# Microsandbox::RUNTIME_VERSION and moves independently of this version.
|
|
11
|
-
version = "0.
|
|
11
|
+
version = "0.19.0"
|
|
12
12
|
authors = ["Super Rad Company <development@superrad.company>"]
|
|
13
13
|
repository = "https://github.com/superradcompany/microsandbox"
|
|
14
14
|
license = "Apache-2.0"
|
|
@@ -59,13 +59,13 @@ libc = "0.2"
|
|
|
59
59
|
# `microsandbox-network` is a direct dependency only for its builder/config
|
|
60
60
|
# types; `default-features = false` keeps its packet-processing engine out of
|
|
61
61
|
# this extension (the SDK depends on it the same way).
|
|
62
|
-
microsandbox = { git = "https://github.com/superradcompany/microsandbox", tag = "v0.
|
|
63
|
-
microsandbox-network = { git = "https://github.com/superradcompany/microsandbox", tag = "v0.
|
|
62
|
+
microsandbox = { git = "https://github.com/superradcompany/microsandbox", tag = "v0.8.4", default-features = false, features = ["cloud", "keyring", "local", "net", "ssh"] }
|
|
63
|
+
microsandbox-network = { git = "https://github.com/superradcompany/microsandbox", tag = "v0.8.4", default-features = false }
|
|
64
64
|
# `microsandbox-utils` is a direct dependency only for `msb_binary_filename` /
|
|
65
65
|
# `libkrunfw_filename`, which the SDK does not re-export: the runtime-home
|
|
66
66
|
# self-check (`Native.runtime_home_pair`) must name exactly the files the
|
|
67
67
|
# resolver's `runtime_in_home` expects. Already in the dependency graph.
|
|
68
|
-
microsandbox-utils = { git = "https://github.com/superradcompany/microsandbox", tag = "v0.
|
|
68
|
+
microsandbox-utils = { git = "https://github.com/superradcompany/microsandbox", tag = "v0.8.4" }
|
|
69
69
|
|
|
70
70
|
# Async core bridged to Ruby's synchronous API via a blocking tokio runtime.
|
|
71
71
|
tokio = { version = "1", features = ["rt-multi-thread", "sync", "time"] }
|
|
@@ -1,70 +1,33 @@
|
|
|
1
1
|
//! Backend routing: the ambient process-wide backend and its selection surface.
|
|
2
2
|
//!
|
|
3
|
-
//!
|
|
4
|
-
//!
|
|
5
|
-
//!
|
|
6
|
-
//! ambient default is a lazily-initialised [`microsandbox::LocalBackend`], and
|
|
7
|
-
//! callers may install a different default process-wide or for a scoped block.
|
|
8
|
-
//!
|
|
9
|
-
//! Local-only operations (image cache, aggregate metrics, `msb` path) need a
|
|
10
|
-
//! concrete `&LocalBackend`; [`local_backend`] resolves the ambient default and
|
|
11
|
-
//! downcasts it, surfacing a clean [`MicrosandboxError::Unsupported`] under a
|
|
12
|
-
//! cloud backend (exactly as the pyo3 `resolve_local` helper does). The backend
|
|
13
|
-
//! selection setters (`set_default_backend` / `with_backend` push-pop /
|
|
14
|
-
//! `default_backend_kind`) deliberately expose only a `kind`/`url`/`api_key`/
|
|
15
|
-
//! `profile` facade — the raw `LocalBackend`/`CloudBackend` builders stay hidden,
|
|
16
|
-
//! matching Python and Node.
|
|
3
|
+
//! The Ruby API retains a process-wide selection. Upstream provides explicit
|
|
4
|
+
//! contexts; each operation binds to the selected context before releasing the
|
|
5
|
+
//! GVL, and each returned handle retains its original context.
|
|
17
6
|
|
|
18
7
|
use std::collections::HashMap;
|
|
19
8
|
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
|
|
20
9
|
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
|
|
21
10
|
|
|
22
11
|
use magnus::{function, prelude::*, Error, RModule, Ruby};
|
|
23
|
-
use microsandbox::{
|
|
12
|
+
use microsandbox::{Context, MicrosandboxError, Operation};
|
|
24
13
|
|
|
25
14
|
use crate::error;
|
|
26
15
|
use crate::runtime::{block_on, ProcessIdentity};
|
|
27
16
|
|
|
28
|
-
///
|
|
29
|
-
///
|
|
30
|
-
/// Returns the `Arc<dyn Backend>` so the caller can keep it alive while
|
|
31
|
-
/// borrowing `&LocalBackend` from it (`as_local()` borrows the `Arc`). Pure
|
|
32
|
-
/// Rust — safe to call inside `block_on` (no Ruby C API), and it returns a raw
|
|
33
|
-
/// `MicrosandboxError` so the Ruby-exception mapping happens *after* `block_on`
|
|
34
|
-
/// re-acquires the GVL. It does not run [`ensure_this_process_backend`] (that
|
|
35
|
-
/// needs the GVL): the `block_on` it executes under already did. Cloud backends yield `Unsupported` for the given
|
|
36
|
-
/// operation (v0.6.8 `Operation`-keyed shape), mirroring pyo3's `resolve_local`.
|
|
37
|
-
pub fn local_backend(op: Operation) -> Result<Arc<dyn Backend>, MicrosandboxError> {
|
|
38
|
-
let backend = microsandbox::default_backend();
|
|
39
|
-
if backend.as_local().is_some() {
|
|
40
|
-
Ok(backend)
|
|
41
|
-
} else {
|
|
42
|
-
Err(MicrosandboxError::local_only(op))
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/// Resolve the ambient backend (requiring it to be local), then run `op` with a
|
|
47
|
-
/// borrowed `&LocalBackend` inside the blocking runtime, mapping any core error
|
|
48
|
-
/// to a Ruby exception. Local-only operations (image cache, aggregate metrics)
|
|
49
|
-
/// share this instead of repeating the resolve/downcast dance; the single
|
|
50
|
-
/// `as_local()` unwrap is provably infallible — [`local_backend`] just checked
|
|
51
|
-
/// it and returns the same `Arc` kept alive for the borrow — so it lives here
|
|
52
|
-
/// once rather than at every call site.
|
|
17
|
+
/// Run an operation on the current local context. Capture it while holding the
|
|
18
|
+
/// GVL so fork cannot inherit its selection mutex locked by a Rust worker.
|
|
53
19
|
pub fn with_local_backend<T>(
|
|
54
20
|
operation: Operation,
|
|
55
|
-
op: impl AsyncFnOnce(µsandbox::
|
|
21
|
+
op: impl AsyncFnOnce(µsandbox::LocalContext) -> Result<T, MicrosandboxError>,
|
|
56
22
|
) -> Result<T, Error> {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
op(local).await
|
|
63
|
-
})?
|
|
64
|
-
.map_err(error::to_ruby)
|
|
23
|
+
let context = active_context()?;
|
|
24
|
+
let local = context
|
|
25
|
+
.as_local()
|
|
26
|
+
.ok_or_else(|| error::to_ruby(MicrosandboxError::local_only(operation)))?;
|
|
27
|
+
block_on(op(local))?.map_err(error::to_ruby)
|
|
65
28
|
}
|
|
66
29
|
|
|
67
|
-
/// Build an `Arc<dyn
|
|
30
|
+
/// Build an `Arc<dyn Context>` from the SDK facade. Ported from pyo3
|
|
68
31
|
/// `build_backend` (`sdk/python/src/lib.rs`) / node `build_backend`. Synchronous
|
|
69
32
|
/// (no network I/O): cloud construction only builds the HTTP client. Pure Rust
|
|
70
33
|
/// — it is also called with one of the mutexes below held, where calling into
|
|
@@ -75,14 +38,17 @@ fn build_backend(
|
|
|
75
38
|
url: Option<String>,
|
|
76
39
|
api_key: Option<String>,
|
|
77
40
|
profile: Option<String>,
|
|
78
|
-
) -> Result<Arc<dyn
|
|
41
|
+
) -> Result<Arc<dyn Context>, MicrosandboxError> {
|
|
79
42
|
match kind.trim().to_ascii_lowercase().as_str() {
|
|
80
|
-
"local" => Ok(Arc::new(microsandbox::
|
|
43
|
+
"local" => Ok(Arc::new(microsandbox::LocalContext::lazy()?)),
|
|
81
44
|
"cloud" => {
|
|
82
45
|
let cloud = match profile {
|
|
83
|
-
Some(profile) => microsandbox::
|
|
46
|
+
Some(profile) => microsandbox::RemoteContext::from_profile(&profile),
|
|
84
47
|
None => match (url, api_key) {
|
|
85
|
-
(Some(url), Some(api_key)) => microsandbox::
|
|
48
|
+
(Some(url), Some(api_key)) => microsandbox::RemoteContext::builder()
|
|
49
|
+
.url(url)
|
|
50
|
+
.api_key(api_key)
|
|
51
|
+
.build(),
|
|
86
52
|
_ => {
|
|
87
53
|
return Err(MicrosandboxError::InvalidConfig(
|
|
88
54
|
"cloud backend requires url + api_key or profile".into(),
|
|
@@ -103,9 +69,9 @@ fn build_backend(
|
|
|
103
69
|
//--------------------------------------------------------------------------------------------------
|
|
104
70
|
//
|
|
105
71
|
// `fork(2)` copies only the calling thread. A child of a process that used the
|
|
106
|
-
// SDK inherits the
|
|
72
|
+
// SDK inherits the extension's process-wide context — a `LocalContext`
|
|
107
73
|
// whose SQLite connections are each served by a worker thread that does not
|
|
108
|
-
// exist in the child, or a `
|
|
74
|
+
// exist in the child, or a `RemoteContext` whose pooled connections belong to
|
|
109
75
|
// the parent's dead tokio runtime. Using it hangs (Linux: the pool's 30 s
|
|
110
76
|
// acquire timeout) or kills the process (macOS: waking the missing worker
|
|
111
77
|
// thread traps in libdispatch), and so does DROPPING it, because the
|
|
@@ -116,7 +82,7 @@ fn build_backend(
|
|
|
116
82
|
// swaps it in, and every inherited `Arc` is `mem::forget`-ed — leaked once per
|
|
117
83
|
// forked process — instead of dropped.
|
|
118
84
|
//
|
|
119
|
-
// Locking. The
|
|
85
|
+
// Locking. The selection mutexes below are only ever taken on a Ruby thread that
|
|
120
86
|
// holds the GVL, and nothing that runs while one is held calls into Ruby or
|
|
121
87
|
// releases the GVL (which is why the code under them is pure Rust and Ruby
|
|
122
88
|
// exceptions are built after they are released). Ruby-level `fork` needs the
|
|
@@ -143,7 +109,7 @@ enum Selection {
|
|
|
143
109
|
|
|
144
110
|
impl Selection {
|
|
145
111
|
/// A fresh backend for this selection, owned by the calling process.
|
|
146
|
-
fn build(&self) -> Result<Arc<dyn
|
|
112
|
+
fn build(&self) -> Result<Arc<dyn Context>, MicrosandboxError> {
|
|
147
113
|
match self {
|
|
148
114
|
Selection::Ladder => microsandbox::resolve_default_backend(),
|
|
149
115
|
Selection::Explicit {
|
|
@@ -157,8 +123,25 @@ impl Selection {
|
|
|
157
123
|
}
|
|
158
124
|
|
|
159
125
|
static SELECTION: Mutex<Selection> = Mutex::new(Selection::Ladder);
|
|
126
|
+
static CONTEXT: Mutex<Option<Arc<dyn Context>>> = Mutex::new(None);
|
|
160
127
|
|
|
161
|
-
///
|
|
128
|
+
/// Capture the active context on the Ruby thread, with the GVL held.
|
|
129
|
+
pub fn active_context() -> Result<Arc<dyn Context>, Error> {
|
|
130
|
+
ensure_this_process_backend()?;
|
|
131
|
+
Ok(lock(&CONTEXT)
|
|
132
|
+
.get_or_insert_with(microsandbox::configured_context)
|
|
133
|
+
.clone())
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
fn swap_context(context: Arc<dyn Context>) -> Option<Arc<dyn Context>> {
|
|
137
|
+
lock(&CONTEXT).replace(context)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
fn set_context(context: Arc<dyn Context>) {
|
|
141
|
+
drop(swap_context(context));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/// The identity of the process whose default backend the extension currently holds
|
|
162
145
|
/// ([`ProcessIdentity::to_bits`]: pid and fork generation in one word, so it
|
|
163
146
|
/// is read and written whole). 0 = no native operation has touched the
|
|
164
147
|
/// backend in this process lineage.
|
|
@@ -173,7 +156,7 @@ fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
|
|
|
173
156
|
mutex.lock().unwrap_or_else(PoisonError::into_inner)
|
|
174
157
|
}
|
|
175
158
|
|
|
176
|
-
/// Make sure the
|
|
159
|
+
/// Make sure the selected context belongs to THIS process, rebuilding it
|
|
177
160
|
/// after a fork. Every Ruby-facing entry that can reach the default backend
|
|
178
161
|
/// runs this first: [`crate::runtime::block_on`] for the async operations, and
|
|
179
162
|
/// each synchronous entry that reads the backend itself. (The three that are
|
|
@@ -221,7 +204,7 @@ fn adopt_backend(
|
|
|
221
204
|
return Ok(None);
|
|
222
205
|
}
|
|
223
206
|
if seen == 0 {
|
|
224
|
-
// Nothing was inherited; the
|
|
207
|
+
// Nothing was inherited; the extension resolves its default lazily, in this
|
|
225
208
|
// process, on first use.
|
|
226
209
|
BACKEND_OWNER.store(cur_bits, Ordering::Release);
|
|
227
210
|
return Ok(None);
|
|
@@ -234,7 +217,7 @@ fn adopt_backend(
|
|
|
234
217
|
None => lock(&SELECTION).build()?,
|
|
235
218
|
};
|
|
236
219
|
// The inherited default must never be dropped (see above).
|
|
237
|
-
std::mem::forget(
|
|
220
|
+
std::mem::forget(swap_context(fresh));
|
|
238
221
|
// Neither may the backends that open `with_backend` scopes saved for their
|
|
239
222
|
// restore. The entries themselves stay — owner and selection — so a scope
|
|
240
223
|
// the parent opened can still be closed here (see `pop_default_backend`).
|
|
@@ -270,7 +253,7 @@ fn set_default_backend(
|
|
|
270
253
|
{
|
|
271
254
|
return Ok(());
|
|
272
255
|
}
|
|
273
|
-
|
|
256
|
+
set_context(selection.build().map_err(error::to_ruby)?);
|
|
274
257
|
*lock(&SELECTION) = selection;
|
|
275
258
|
Ok(())
|
|
276
259
|
}
|
|
@@ -292,7 +275,7 @@ struct Scope {
|
|
|
292
275
|
/// this process's own: a forked child took it out to leak it, or the push
|
|
293
276
|
/// was the child's first use of the backend and replaced an inherited
|
|
294
277
|
/// default ([`adopt_backend`]). The pop then rebuilds from `selection`.
|
|
295
|
-
previous: Option<Arc<dyn
|
|
278
|
+
previous: Option<Arc<dyn Context>>,
|
|
296
279
|
/// How that previous backend had been chosen: what a rebuild starts from,
|
|
297
280
|
/// and what `SELECTION` goes back to when the scope closes.
|
|
298
281
|
selection: Selection,
|
|
@@ -325,10 +308,12 @@ fn push_default_backend(
|
|
|
325
308
|
// default had been chosen.
|
|
326
309
|
Some(inherited) => (None, inherited),
|
|
327
310
|
None => {
|
|
328
|
-
|
|
329
|
-
|
|
311
|
+
// Freeze the previous ambient choice even when this is the first
|
|
312
|
+
// scoped call. Restoring the scope must not re-read changed config.
|
|
313
|
+
active_context()?;
|
|
314
|
+
let previous = swap_context(selection.build().map_err(error::to_ruby)?);
|
|
330
315
|
let before = std::mem::replace(&mut *lock(&SELECTION), selection);
|
|
331
|
-
(
|
|
316
|
+
(previous, before)
|
|
332
317
|
}
|
|
333
318
|
};
|
|
334
319
|
let token = NEXT_BACKEND_SCOPE.fetch_add(1, Ordering::Relaxed);
|
|
@@ -387,7 +372,7 @@ fn pop_default_backend(token: u32) -> Result<(), Error> {
|
|
|
387
372
|
|
|
388
373
|
match scope.previous {
|
|
389
374
|
// Opened and closed in the same process: put the saved backend back.
|
|
390
|
-
Some(previous) if scope.owner == cur =>
|
|
375
|
+
Some(previous) if scope.owner == cur => set_context(previous),
|
|
391
376
|
// No backend of this process's own was saved (see `Scope::previous`):
|
|
392
377
|
// restore one built here from how the saved one had been chosen. On
|
|
393
378
|
// failure the temporary backend stays installed (see above). The
|
|
@@ -401,7 +386,7 @@ fn pop_default_backend(token: u32) -> Result<(), Error> {
|
|
|
401
386
|
// An inherited `Arc` would be leaked either way.
|
|
402
387
|
std::mem::forget(previous);
|
|
403
388
|
let fresh = scope.selection.build().map_err(error::to_ruby)?;
|
|
404
|
-
std::mem::forget(
|
|
389
|
+
std::mem::forget(swap_context(fresh));
|
|
405
390
|
}
|
|
406
391
|
}
|
|
407
392
|
*lock(&SELECTION) = scope.selection;
|
|
@@ -413,15 +398,14 @@ fn pop_default_backend(token: u32) -> Result<(), Error> {
|
|
|
413
398
|
/// failed to resolve reports `BackendKind::Cloud` from `kind()` (upstream's
|
|
414
399
|
/// "safe intent marker"), so `kind()` alone would misreport a configuration
|
|
415
400
|
/// error as a cloud backend; `info()` returns the error instead.
|
|
416
|
-
fn active_backend_info() -> Result<microsandbox::
|
|
417
|
-
|
|
418
|
-
microsandbox::default_backend_info().map_err(error::to_ruby)
|
|
401
|
+
fn active_backend_info() -> Result<microsandbox::ContextInfo, Error> {
|
|
402
|
+
active_context()?.info().map_err(error::to_ruby)
|
|
419
403
|
}
|
|
420
404
|
|
|
421
|
-
fn kind_str(kind: microsandbox::
|
|
405
|
+
fn kind_str(kind: microsandbox::ContextKind) -> &'static str {
|
|
422
406
|
match kind {
|
|
423
|
-
microsandbox::
|
|
424
|
-
microsandbox::
|
|
407
|
+
microsandbox::ContextKind::Local => "local",
|
|
408
|
+
microsandbox::ContextKind::Remote => "cloud",
|
|
425
409
|
}
|
|
426
410
|
}
|
|
427
411
|
|
|
@@ -6,7 +6,9 @@
|
|
|
6
6
|
//! Signal/kill go through a cloned `ExecControl` so they never contend with an
|
|
7
7
|
//! in-flight `recv`. Stdin (when piped) is exposed as a separate `ExecSink`.
|
|
8
8
|
|
|
9
|
+
use std::sync::atomic::{AtomicBool, Ordering};
|
|
9
10
|
use std::sync::Arc;
|
|
11
|
+
use std::time::Duration;
|
|
10
12
|
|
|
11
13
|
use magnus::{method, prelude::*, Error, RHash, RModule, RString, Ruby};
|
|
12
14
|
use tokio::sync::Mutex;
|
|
@@ -24,10 +26,39 @@ pub struct ExecHandle {
|
|
|
24
26
|
/// Everything of an exec session that is bound to the creating process.
|
|
25
27
|
struct ExecParts {
|
|
26
28
|
handle: Arc<Mutex<microsandbox::ExecHandle>>,
|
|
27
|
-
|
|
29
|
+
lifetime: Arc<ExecLifetime>,
|
|
28
30
|
stdin: std::sync::Mutex<Option<Arc<microsandbox::sandbox::exec::ExecSink>>>,
|
|
29
31
|
}
|
|
30
32
|
|
|
33
|
+
struct ExecLifetime {
|
|
34
|
+
control: microsandbox::ExecControl,
|
|
35
|
+
terminal: AtomicBool,
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
impl ExecLifetime {
|
|
39
|
+
fn record_completion<T>(&self, result: &Result<T, microsandbox::MicrosandboxError>) {
|
|
40
|
+
use microsandbox::MicrosandboxError::{ExecFailed, ExecTimeout};
|
|
41
|
+
if matches!(result, Ok(_) | Err(ExecFailed(_) | ExecTimeout(_))) {
|
|
42
|
+
self.terminal.store(true, Ordering::Relaxed);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
impl Drop for ExecLifetime {
|
|
48
|
+
fn drop(&mut self) {
|
|
49
|
+
if self.terminal.load(Ordering::Relaxed) {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
// In v0.8 the VM retains the connection independently of this
|
|
53
|
+
// session. Terminate only when both the reader and any extracted
|
|
54
|
+
// stdin sink are gone. Both owners carry a ForkGuarded value.
|
|
55
|
+
let control = self.control.clone();
|
|
56
|
+
crate::runtime::runtime().spawn(async move {
|
|
57
|
+
let _ = tokio::time::timeout(Duration::from_secs(5), control.kill()).await;
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
31
62
|
impl ExecHandle {
|
|
32
63
|
/// Wrap a freshly-opened core handle, lifting out its id and stdin sink.
|
|
33
64
|
pub fn from_core(mut handle: microsandbox::ExecHandle) -> Self {
|
|
@@ -39,7 +70,10 @@ impl ExecHandle {
|
|
|
39
70
|
"Microsandbox::ExecHandle",
|
|
40
71
|
ExecParts {
|
|
41
72
|
handle: Arc::new(Mutex::new(handle)),
|
|
42
|
-
|
|
73
|
+
lifetime: Arc::new(ExecLifetime {
|
|
74
|
+
control,
|
|
75
|
+
terminal: AtomicBool::new(false),
|
|
76
|
+
}),
|
|
43
77
|
stdin: std::sync::Mutex::new(stdin),
|
|
44
78
|
},
|
|
45
79
|
),
|
|
@@ -53,16 +87,29 @@ impl ExecHandle {
|
|
|
53
87
|
|
|
54
88
|
/// Next event as a Hash, or nil when the stream ends.
|
|
55
89
|
fn recv(&self) -> Result<Option<RHash>, Error> {
|
|
56
|
-
let
|
|
57
|
-
let event = block_on(async
|
|
90
|
+
let parts = self.inner.get()?;
|
|
91
|
+
let event = block_on(async {
|
|
92
|
+
let event = parts.handle.lock().await.recv().await;
|
|
93
|
+
if matches!(
|
|
94
|
+
event,
|
|
95
|
+
Some(microsandbox::ExecEvent::Exited { .. } | microsandbox::ExecEvent::Failed(_))
|
|
96
|
+
) {
|
|
97
|
+
parts.lifetime.terminal.store(true, Ordering::Relaxed);
|
|
98
|
+
}
|
|
99
|
+
event
|
|
100
|
+
})?;
|
|
58
101
|
Ok(event.map(exec_event_to_hash))
|
|
59
102
|
}
|
|
60
103
|
|
|
61
104
|
/// Block until exit; returns {exit_code, success}.
|
|
62
105
|
fn wait(&self) -> Result<RHash, Error> {
|
|
63
|
-
let
|
|
64
|
-
let status =
|
|
65
|
-
|
|
106
|
+
let parts = self.inner.get()?;
|
|
107
|
+
let status = block_on(async {
|
|
108
|
+
let result = parts.handle.lock().await.wait().await;
|
|
109
|
+
parts.lifetime.record_completion(&result);
|
|
110
|
+
result
|
|
111
|
+
})?
|
|
112
|
+
.map_err(error::to_ruby)?;
|
|
66
113
|
let hash = ruby().hash_new();
|
|
67
114
|
hash.aset("exit_code", status.code)?;
|
|
68
115
|
hash.aset("success", status.success)?;
|
|
@@ -71,22 +118,26 @@ impl ExecHandle {
|
|
|
71
118
|
|
|
72
119
|
/// Drain the stream and return a collected exec-output Hash.
|
|
73
120
|
fn collect(&self) -> Result<RHash, Error> {
|
|
74
|
-
let
|
|
75
|
-
let output =
|
|
76
|
-
|
|
121
|
+
let parts = self.inner.get()?;
|
|
122
|
+
let output = block_on(async {
|
|
123
|
+
let result = parts.handle.lock().await.collect().await;
|
|
124
|
+
parts.lifetime.record_completion(&result);
|
|
125
|
+
result
|
|
126
|
+
})?
|
|
127
|
+
.map_err(error::to_ruby)?;
|
|
77
128
|
crate::sandbox::exec_output_to_hash(output)
|
|
78
129
|
}
|
|
79
130
|
|
|
80
131
|
fn signal(&self, sig: i32) -> Result<(), Error> {
|
|
81
|
-
block_on(self.inner.get()?.control.signal(sig))?.map_err(error::to_ruby)
|
|
132
|
+
block_on(self.inner.get()?.lifetime.control.signal(sig))?.map_err(error::to_ruby)
|
|
82
133
|
}
|
|
83
134
|
|
|
84
135
|
fn kill(&self) -> Result<(), Error> {
|
|
85
|
-
block_on(self.inner.get()?.control.kill())?.map_err(error::to_ruby)
|
|
136
|
+
block_on(self.inner.get()?.lifetime.control.kill())?.map_err(error::to_ruby)
|
|
86
137
|
}
|
|
87
138
|
|
|
88
139
|
fn resize(&self, rows: u16, cols: u16) -> Result<(), Error> {
|
|
89
|
-
block_on(self.inner.get()?.control.resize(rows, cols))?.map_err(error::to_ruby)
|
|
140
|
+
block_on(self.inner.get()?.lifetime.control.resize(rows, cols))?.map_err(error::to_ruby)
|
|
90
141
|
}
|
|
91
142
|
|
|
92
143
|
/// The stdin sink (only the first call returns it; nil afterwards or if
|
|
@@ -95,25 +146,36 @@ impl ExecHandle {
|
|
|
95
146
|
let parts = self.inner.get()?;
|
|
96
147
|
let mut guard = parts.stdin.lock().expect("exec stdin mutex poisoned");
|
|
97
148
|
Ok(guard.take().map(|sink| ExecSink {
|
|
98
|
-
inner: ForkGuarded::new(
|
|
149
|
+
inner: ForkGuarded::new(
|
|
150
|
+
"Microsandbox::ExecStdin",
|
|
151
|
+
ExecSinkParts {
|
|
152
|
+
sink,
|
|
153
|
+
_lifetime: Arc::clone(&parts.lifetime),
|
|
154
|
+
},
|
|
155
|
+
),
|
|
99
156
|
}))
|
|
100
157
|
}
|
|
101
158
|
}
|
|
102
159
|
|
|
103
160
|
#[magnus::wrap(class = "Microsandbox::Native::ExecSink", free_immediately, size)]
|
|
104
161
|
pub struct ExecSink {
|
|
105
|
-
inner: ForkGuarded<
|
|
162
|
+
inner: ForkGuarded<ExecSinkParts>,
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
struct ExecSinkParts {
|
|
166
|
+
sink: Arc<microsandbox::sandbox::exec::ExecSink>,
|
|
167
|
+
_lifetime: Arc<ExecLifetime>,
|
|
106
168
|
}
|
|
107
169
|
|
|
108
170
|
impl ExecSink {
|
|
109
171
|
fn write(&self, data: RString) -> Result<(), Error> {
|
|
110
172
|
// Copy out while holding the GVL (see sandbox::fs_write for the rationale).
|
|
111
173
|
let bytes = unsafe { data.as_slice() }.to_vec();
|
|
112
|
-
block_on(self.inner.get()?.write(&bytes))?.map_err(error::to_ruby)
|
|
174
|
+
block_on(self.inner.get()?.sink.write(&bytes))?.map_err(error::to_ruby)
|
|
113
175
|
}
|
|
114
176
|
|
|
115
177
|
fn close(&self) -> Result<(), Error> {
|
|
116
|
-
block_on(self.inner.get()?.close())?.map_err(error::to_ruby)
|
|
178
|
+
block_on(self.inner.get()?.sink.close())?.map_err(error::to_ruby)
|
|
117
179
|
}
|
|
118
180
|
}
|
|
119
181
|
|
|
@@ -31,7 +31,7 @@ use std::path::PathBuf;
|
|
|
31
31
|
|
|
32
32
|
use magnus::Error;
|
|
33
33
|
use microsandbox::sandbox::{IntoImage, RootfsSource};
|
|
34
|
-
use microsandbox::{
|
|
34
|
+
use microsandbox::{ContextKind, MicrosandboxError};
|
|
35
35
|
|
|
36
36
|
use crate::error;
|
|
37
37
|
|
|
@@ -56,9 +56,8 @@ impl HostPaths {
|
|
|
56
56
|
/// so paths pass through untouched — and the create itself then fails with
|
|
57
57
|
/// that configuration error before anything is persisted.
|
|
58
58
|
pub fn for_default_backend() -> Result<Self, Error> {
|
|
59
|
-
crate::backend::ensure_this_process_backend()?;
|
|
60
59
|
Ok(Self {
|
|
61
|
-
local: matches!(
|
|
60
|
+
local: matches!(crate::backend::active_context()?.kind(), ContextKind::Local),
|
|
62
61
|
})
|
|
63
62
|
}
|
|
64
63
|
|
data/ext/microsandbox/src/lib.rs
CHANGED
|
@@ -200,8 +200,7 @@ fn install_options(opts: RHash) -> Result<microsandbox::setup::InstallOptions, E
|
|
|
200
200
|
/// `effective_runtime_config`, later changes to the environment or the config
|
|
201
201
|
/// file do not reach it.
|
|
202
202
|
fn captured_local_config() -> Result<Option<microsandbox::config::GlobalConfig>, Error> {
|
|
203
|
-
backend::
|
|
204
|
-
let backend = microsandbox::default_backend();
|
|
203
|
+
let backend = backend::active_context()?;
|
|
205
204
|
Ok(backend.as_local().map(|local| local.config().clone()))
|
|
206
205
|
}
|
|
207
206
|
|
|
@@ -316,8 +315,7 @@ fn set_runtime_libkrunfw_path(path: String) {
|
|
|
316
315
|
/// no async) — runs on the Ruby thread; resolves the path from the local
|
|
317
316
|
/// backend's config.
|
|
318
317
|
fn resolved_msb_path() -> Result<String, Error> {
|
|
319
|
-
backend::
|
|
320
|
-
let backend = microsandbox::default_backend();
|
|
318
|
+
let backend = backend::active_context()?;
|
|
321
319
|
// Shim-only entry point with no SDK `Operation` — report the Ruby-facing
|
|
322
320
|
// name (`Microsandbox.runtime_path`), like Python's name-based local_only.
|
|
323
321
|
let local = backend
|
|
@@ -352,8 +350,7 @@ fn runtime_selection(config: µsandbox::config::GlobalConfig) -> (std::path:
|
|
|
352
350
|
/// bootstrap decision is the backend's. A non-local backend has nothing to
|
|
353
351
|
/// compare.
|
|
354
352
|
fn verify_backend_runtime_config() -> Result<(), Error> {
|
|
355
|
-
backend::
|
|
356
|
-
let backend = microsandbox::default_backend();
|
|
353
|
+
let backend = backend::active_context()?;
|
|
357
354
|
let Some(local) = backend.as_local() else {
|
|
358
355
|
return Ok(());
|
|
359
356
|
};
|