microsandbox 0.7.0

`microsandbox` is the core library for the microsandbox project.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//! Sandbox lifecycle backend trait.
//!
//! Per the SDK local-cloud parity plan (D6.4): `Sandbox` and `SandboxHandle`
//! stay single types with no variants. They hold `Arc<dyn Backend>` plus a
//! backend-private `*Inner` enum that the outer types never expose directly.
//! The trait returns the outer types — the local/cloud `Inner` variants are
//! constructed inside each backend's trait impl and wrapped with the
//! `Arc<dyn Backend>` the caller passes in.

use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use bytes::Bytes;
use chrono::{DateTime, Utc};
use futures::Stream;
use futures::future::BoxFuture;

use super::Backend;
use crate::MicrosandboxResult;
use crate::agent::AgentClient;
use crate::logs::{BootError, LogEntry, LogOptions, LogStreamOptions};
#[cfg(feature = "local")]
use crate::runtime::ProcessHandle;
use crate::sandbox::exec::{ExecHandle, ExecOptions, ExecOutput};
use crate::sandbox::fs::{FsEntry, FsMetadata, FsReadStream, FsWriteSink};
use crate::sandbox::metrics::SandboxMetrics;
use crate::sandbox::{
    DEFAULT_STOP_TIMEOUT, Sandbox, SandboxConfig, SandboxHandle, SandboxListBuilder, SandboxPage,
    SandboxStatus,
};

// Keep the pre-split path `crate::backend::sandbox::cloud_status_to_sandbox_status`
// working for callers like `sandbox/handle.rs`.
#[cfg(feature = "cloud")]
pub(crate) use super::cloud::sandbox::{
    cloud_status_to_sandbox_status, sandbox_config_from_cloud_spec,
};

//--------------------------------------------------------------------------------------------------
// Type Aliases
//--------------------------------------------------------------------------------------------------

/// Boxed stream of metrics samples returned by [`SandboxBackend::metrics_stream`].
pub type MetricsStream =
    Pin<Box<dyn Stream<Item = MicrosandboxResult<SandboxMetrics>> + Send + 'static>>;

/// Boxed stream of log entries returned by [`SandboxBackend::log_stream`].
pub type LogStream = Pin<Box<dyn Stream<Item = MicrosandboxResult<LogEntry>> + Send + 'static>>;

//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------

/// Backend-private state behind [`Sandbox`].
///
/// Users never see this enum directly — they get the outer `Sandbox` and reach
/// variant-specific data through the [`Sandbox::local`](crate::sandbox::Sandbox::local)
/// / [`Sandbox::cloud`](crate::sandbox::Sandbox::cloud) accessors.
pub enum SandboxInner {
    /// Local libkrun-backed sandbox state.
    Local(SandboxLocalState),
    /// Cloud msb-cloud-backed sandbox state.
    Cloud(SandboxCloudState),
}

/// Local libkrun-backed sandbox state held inside [`SandboxInner::Local`].
pub struct SandboxLocalState {
    /// SQLite row id for this sandbox.
    pub db_id: i32,
    /// Owned libkrun process handle, when this `Sandbox` owns the lifecycle.
    #[cfg(feature = "local")]
    pub handle: Option<Arc<tokio::sync::Mutex<ProcessHandle>>>,
    /// UDS connection to the in-VM agentd relay.
    pub client: Arc<AgentClient>,
}

/// Cloud msb-cloud-backed sandbox state held inside [`SandboxInner::Cloud`].
pub struct SandboxCloudState {
    /// Server-side UUID (kept as a string to match the cloud wire format).
    pub id: String,
    /// Owning org's UUID.
    pub org_id: String,
    /// Creation timestamp returned by msb-cloud.
    pub created_at: DateTime<Utc>,
}

/// Backend-private state behind [`SandboxHandle`] — the lightweight DB-row view.
pub enum SandboxHandleInner {
    /// Local persisted sandbox handle.
    Local(SandboxHandleLocalState),
    /// Cloud msb-cloud sandbox handle.
    Cloud(SandboxHandleCloudState),
}

/// Backend-private selector used to protect receiver-based lifecycle calls
/// from acting on a different sandbox that reused the same name.
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SandboxIdentity {
    /// Local SQLite sandbox row id.
    Local(i32),
    /// Cloud control-plane sandbox UUID.
    Cloud(String),
}

/// Local handle state. Snapshot of the database row + active PID, if any.
pub struct SandboxHandleLocalState {
    /// SQLite row id for this sandbox.
    pub db_id: i32,
    /// Sandbox lifecycle status at handle-creation time.
    pub status: SandboxStatus,
    /// Serialized `SandboxConfig` as stored in the database.
    pub config_json: String,
    /// Serialized `SandboxConfig` used by the active VM, when known.
    pub active_config_json: Option<String>,
    /// When this sandbox was first created, if recorded.
    pub created_at: Option<DateTime<Utc>>,
    /// When this sandbox's database record was last modified.
    pub updated_at: Option<DateTime<Utc>>,
    /// Active sandbox process PID, if any.
    pub pid: Option<i32>,
}

/// Cloud handle state. Captures the snapshot msb-cloud returned at fetch time.
pub struct SandboxHandleCloudState {
    /// Server-side UUID.
    pub id: String,
    /// Owning org's UUID.
    pub org_id: String,
    /// Lifecycle status mapped from msb-cloud's
    /// [`CloudSandboxStatus`](crate::CloudSandboxStatus).
    pub status: SandboxStatus,
    /// Serialized [`CloudCreateSandboxRequest`](crate::CloudCreateSandboxRequest)
    /// returned by msb-cloud.
    pub config_json: String,
    /// Creation timestamp returned by msb-cloud.
    pub created_at: Option<DateTime<Utc>>,
    /// Last start timestamp, when known.
    pub started_at: Option<DateTime<Utc>>,
    /// Last stop timestamp, when known.
    pub stopped_at: Option<DateTime<Utc>>,
    /// Human-readable message for the most recent failure, when any.
    pub last_failure_message: Option<String>,
}

/// Resource-specific backend for sandbox lifecycle operations.
///
/// Trait methods take the [`Arc<dyn Backend>`] that they should wrap any
/// returned [`Sandbox`] / [`SandboxHandle`] with. Callers (e.g.
/// `Sandbox::create`) resolve the backend via
/// [`default_backend`](super::default_backend) and forward it through.
pub trait SandboxBackend: Send + Sync {
    /// Suggested budget for callers choosing a bounded graceful-stop observation.
    ///
    /// Backends whose stop path includes durable persistence work may suggest a longer budget.
    /// `SandboxHandle::stop` waits without a deadline; `stop_with_timeout` uses the caller's
    /// explicit budget. Neither operation applies this hint implicitly.
    fn default_stop_timeout(&self) -> Duration {
        DEFAULT_STOP_TIMEOUT
    }

    /// Backend preference for callers implementing an explicit timeout-escalation policy.
    ///
    /// The SDK's graceful-stop methods never escalate implicitly. Callers must explicitly
    /// choose `kill` for force termination; a backend whose accepted stop continues
    /// asynchronously can return `false` to advise against that policy.
    #[doc(hidden)]
    fn should_force_kill_after_stop_timeout(&self) -> bool {
        true
    }

    /// Create a sandbox. The returned outer [`Sandbox`] carries the supplied
    /// `backend` Arc and the variant-specific state inside `SandboxInner`.
    ///
    /// `start` controls whether the sandbox is booted as part of create.
    /// **Cloud honours `start`** (forwards it as `?start=true|false` on the
    /// create request). **Local always boots immediately** — the local impl
    /// ignores the flag, because libkrun has no equivalent "create-without-
    /// start" state. This asymmetry is intentional per the SDK parity plan
    /// (D6.4); callers that need a stopped local sandbox should create then
    /// `stop()` it explicitly.
    fn create<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        config: SandboxConfig,
        start: bool,
    ) -> BoxFuture<'a, MicrosandboxResult<Sandbox>>;

    /// Create a sandbox that must survive after the creating process exits.
    fn create_detached<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        config: SandboxConfig,
    ) -> BoxFuture<'a, MicrosandboxResult<Sandbox>>;

    /// Start a stopped sandbox by name.
    fn start<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<Sandbox>>;

    /// Start a stopped sandbox by name in detached mode.
    fn start_detached<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<Sandbox>>;

    /// Start the exact persisted sandbox identified by `identity`.
    ///
    /// Custom backends should override this method with an atomic or
    /// ID-addressed implementation. The default delegates by name only to
    /// preserve source compatibility for existing backend implementations.
    fn start_identified<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        _identity: SandboxIdentity,
    ) -> BoxFuture<'a, MicrosandboxResult<Sandbox>> {
        self.start(backend, name)
    }

    /// Start the exact persisted sandbox in detached mode.
    ///
    /// Custom backends should override this method for identity safety.
    fn start_detached_identified<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        _identity: SandboxIdentity,
    ) -> BoxFuture<'a, MicrosandboxResult<Sandbox>> {
        self.start_detached(backend, name)
    }

    /// Get a sandbox handle by name.
    fn get<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<SandboxHandle>>;

    /// List a filtered page of sandboxes.
    fn list<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        query: SandboxListBuilder,
    ) -> BoxFuture<'a, MicrosandboxResult<SandboxPage>>;

    /// Remove/destroy a sandbox by name.
    fn remove<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<()>>;

    /// Remove the exact persisted sandbox identified by `identity`.
    ///
    /// Custom backends should override this method for identity safety.
    fn remove_identified<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        _identity: SandboxIdentity,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        self.remove(backend, name)
    }

    /// Stop a running sandbox by name (graceful).
    fn stop<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<()>>;

    /// Stop the exact persisted sandbox identified by `identity`.
    ///
    /// Custom backends should override this method for identity safety.
    fn stop_identified<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        _identity: SandboxIdentity,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        self.stop(backend, name)
    }

    /// Kill a running sandbox by name (SIGKILL).
    fn kill<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<()>>;

    /// Kill the exact persisted sandbox identified by `identity`.
    ///
    /// Custom backends should override this method for identity safety.
    fn kill_identified<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        _identity: SandboxIdentity,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        self.kill(backend, name)
    }

    /// Trigger a graceful drain on a sandbox by name.
    fn drain<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<()>>;

    /// Drain the exact persisted sandbox identified by `identity`.
    ///
    /// Custom backends should override this method for identity safety.
    fn drain_identified<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        _identity: SandboxIdentity,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        self.drain(backend, name)
    }

    // ============================================================
    // Exec
    // ============================================================

    /// Execute a command inside the named sandbox and wait for it to complete.
    fn exec<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        config: &'a SandboxConfig,
        cmd: String,
        opts: ExecOptions,
    ) -> BoxFuture<'a, MicrosandboxResult<ExecOutput>> {
        Box::pin(async move {
            crate::sandbox::exec::agent::exec(backend.as_ref(), name, config, cmd, opts).await
        })
    }

    /// Execute a command and return a streaming [`ExecHandle`].
    fn exec_stream<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        config: &'a SandboxConfig,
        cmd: String,
        opts: ExecOptions,
    ) -> BoxFuture<'a, MicrosandboxResult<ExecHandle>> {
        Box::pin(async move {
            crate::sandbox::exec::agent::exec_stream(backend.as_ref(), name, config, cmd, opts)
                .await
        })
    }

    /// Attach the host terminal to a PTY session in the named sandbox.
    ///
    /// Returns the exit code. Local routes through libkrun + agentd; cloud
    /// routes the same session over the sandbox's agent WebSocket route.
    fn attach<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        config: &'a SandboxConfig,
        cmd: String,
        opts: crate::sandbox::AttachOptionsBuilder,
    ) -> BoxFuture<'a, MicrosandboxResult<i32>> {
        Box::pin(async move {
            crate::sandbox::attach::agent::attach(backend.as_ref(), name, config, cmd, opts).await
        })
    }

    // ============================================================
    // Logs / metrics
    // ============================================================

    /// Return the most recent startup diagnostic for the named sandbox, when
    /// the selected backend provides one.
    fn boot_error<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<Option<BootError>>>;

    /// Read captured output for the named sandbox.
    fn logs<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        opts: &'a LogOptions,
    ) -> BoxFuture<'a, MicrosandboxResult<Vec<LogEntry>>>;

    /// Stream captured output for the named sandbox.
    fn log_stream<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        opts: &'a LogStreamOptions,
    ) -> BoxFuture<'a, MicrosandboxResult<LogStream>>;

    /// Replay a filtered snapshot, then follow new log entries.
    ///
    /// The backend owns the snapshot-to-stream handoff so callers do not need
    /// backend-specific cursor or transport logic.
    fn follow_logs<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        opts: &'a LogOptions,
    ) -> BoxFuture<'a, MicrosandboxResult<LogStream>>;

    /// Latest metrics sample for the named sandbox.
    fn metrics<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        config: &'a SandboxConfig,
    ) -> BoxFuture<'a, MicrosandboxResult<SandboxMetrics>>;

    /// Streaming metrics samples at `interval`. Local opens a DB poll loop;
    /// cloud returns a stream that yields a single
    /// [`MicrosandboxError::Unsupported`](crate::MicrosandboxError::Unsupported).
    fn metrics_stream(
        &self,
        backend: Arc<dyn Backend>,
        name: String,
        config: SandboxConfig,
        interval: Duration,
    ) -> MetricsStream;

    // ============================================================
    // Guest FS (sandbox.fs() surface)
    // ============================================================

    /// Read an entire guest file into memory.
    fn fs_read<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        path: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<Bytes>> {
        Box::pin(async move { crate::sandbox::fs::agent::read(backend.as_ref(), name, path).await })
    }

    /// Stream a guest file. Returns a [`FsReadStream`] yielding chunks.
    fn fs_read_stream<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        path: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<FsReadStream>> {
        Box::pin(async move {
            crate::sandbox::fs::agent::read_stream(backend.as_ref(), name, path).await
        })
    }

    /// Write `data` to a guest file (overwriting if it exists).
    fn fs_write<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        path: &'a str,
        data: Vec<u8>,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        Box::pin(async move {
            crate::sandbox::fs::agent::write(backend.as_ref(), name, path, data).await
        })
    }

    /// Open a streaming writer for a guest file.
    fn fs_write_stream<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        path: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<FsWriteSink>> {
        Box::pin(async move {
            crate::sandbox::fs::agent::write_stream(backend.as_ref(), name, path).await
        })
    }

    /// List immediate children of a guest directory.
    fn fs_list<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        path: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<Vec<FsEntry>>> {
        Box::pin(async move { crate::sandbox::fs::agent::list(backend.as_ref(), name, path).await })
    }

    /// Get file/directory metadata.
    fn fs_stat<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        path: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<FsMetadata>> {
        Box::pin(async move { crate::sandbox::fs::agent::stat(backend.as_ref(), name, path).await })
    }

    /// Create a directory (and parents).
    fn fs_mkdir<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        path: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        Box::pin(
            async move { crate::sandbox::fs::agent::mkdir(backend.as_ref(), name, path).await },
        )
    }

    /// Remove a file or (when `recursive`) directory.
    fn fs_remove<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        path: &'a str,
        recursive: bool,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        Box::pin(async move {
            crate::sandbox::fs::agent::remove(backend.as_ref(), name, path, recursive).await
        })
    }

    /// Copy a guest file from `from` to `to`.
    fn fs_copy<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        from: &'a str,
        to: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        Box::pin(
            async move { crate::sandbox::fs::agent::copy(backend.as_ref(), name, from, to).await },
        )
    }

    /// Rename/move a guest file or directory.
    fn fs_rename<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        from: &'a str,
        to: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        Box::pin(async move {
            crate::sandbox::fs::agent::rename(backend.as_ref(), name, from, to).await
        })
    }

    /// Check whether a guest path exists.
    fn fs_exists<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        path: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<bool>> {
        Box::pin(
            async move { crate::sandbox::fs::agent::exists(backend.as_ref(), name, path).await },
        )
    }

    /// Copy a host file into the guest sandbox.
    fn fs_copy_from_host<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        host: &'a Path,
        guest: &'a str,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        Box::pin(async move {
            crate::sandbox::fs::agent::copy_from_host(backend.as_ref(), name, host, guest).await
        })
    }

    /// Copy a guest file out to the host with buffered atomic publication.
    fn fs_copy_to_host<'a>(
        &'a self,
        backend: Arc<dyn Backend>,
        name: &'a str,
        guest: &'a str,
        host: &'a Path,
    ) -> BoxFuture<'a, MicrosandboxResult<()>> {
        Box::pin(async move {
            crate::sandbox::fs::agent::copy_to_host(backend.as_ref(), name, guest, host).await
        })
    }
}