solari-sandbox 0.2.0

Rust binding for the Solari sandbox SDK (core surface: commands, files, code.run, git).
Documentation
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
//! `Client` (REST create/connect/get/kill) and the `Sandbox` handle exposing
//! `.commands()`, `.files()`, `.code()`, and `.git()`. Mirrors
//! `sandbox-client.ts` (REST shapes) + `SessionHandle` (namespaces).

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use crate::channel::ControlChannel;
use crate::code::Code;
use crate::commands::{run_command, Commands, RunOptions};
use crate::error::SolariError;
use crate::files::Files;
use crate::git::{Git, GitRunner};
use crate::http::{encode_uri_component, new_idempotency_key, HttpOptions, HttpTransport};
use crate::types::{
    CommandResult, CreateSandboxRequest, CreateSandboxResponse, Lifecycle, ResumeResponse, StartResponse,
    SandboxView, VolumeAttachment,
};

/// Options for constructing a [`Client`].
#[derive(Debug, Clone)]
pub struct ClientOptions {
    pub api_key: String,
    pub base_url: String,
    /// Per-call control-WS RPC timeout override (ms). Defaults to 300000.
    pub call_timeout_ms: Option<u64>,
}

impl ClientOptions {
    pub fn new(api_key: impl Into<String>, base_url: impl Into<String>) -> Self {
        ClientOptions {
            api_key: api_key.into(),
            base_url: base_url.into(),
            call_timeout_ms: None,
        }
    }
}

/// Options accepted by `POST /sandboxes` (headless sandbox flavour).
#[derive(Default, Clone)]
pub struct CreateOptions {
    pub template: Option<String>,
    pub cpu: Option<u32>,
    pub mem_mb: Option<u32>,
    pub disk_gb: Option<u32>,
    pub envs: Option<HashMap<String, String>>,
    pub metadata: Option<HashMap<String, String>>,
    pub timeout_ms: Option<u64>,
    /// Legacy, gateway-side FALLBACK idle window in seconds, only used when
    /// `timeout_ms` is unset — prefer `timeout_ms`.
    pub ttl_seconds: Option<u64>,
    pub from_snapshot: Option<String>,
    /// VM isolation tier: `"shared"` (sandbox-only), `"dedicated"` (default)
    /// or `"hardened"` (own VM, no outbound network). See `types::CreateSandboxRequest::isolation`.
    pub isolation: Option<String>,
    pub lifecycle: Option<Lifecycle>,
    /// Initial display resolution, e.g. `"1280x720"`. Desktops only — a headless
    /// sandbox has no display.
    pub resolution: Option<String>,
    /// Record the session server-side; the create response carries a presigned
    /// playback URL. Desktops only.
    pub record: Option<bool>,
    /// Persistent volumes to mount before the session starts.
    pub volumes: Option<Vec<VolumeAttachment>>,
}

impl CreateOptions {
    /// Build the `POST /sandboxes` body for a given VM flavour.
    ///
    /// THE SINGLE PLACE an option becomes a wire field, and therefore the place
    /// the cross-language wire contract is pinned (see `tests/contract_wire.rs`).
    /// A field added above but not mapped here is silently invisible on the wire.
    pub(crate) fn into_request(self, kind: &str) -> CreateSandboxRequest {
        CreateSandboxRequest {
            template: self.template,
            kind: Some(kind.to_string()),
            cpu: self.cpu,
            mem_mb: self.mem_mb,
            disk_gb: self.disk_gb,
            envs: self.envs,
            metadata: self.metadata,
            timeout_ms: self.timeout_ms,
            ttl_seconds: self.ttl_seconds,
            from_snapshot: self.from_snapshot,
            isolation: self.isolation,
            lifecycle: self.lifecycle,
            resolution: self.resolution,
            record: self.record,
            volumes: self.volumes,
        }
    }
}

impl From<CreateOptions> for CreateSandboxRequest {
    fn from(o: CreateOptions) -> Self {
        o.into_request("sandbox")
    }
}

/// Talks the SDK ⇆ Gateway `/sandboxes` REST API and hands back [`Sandbox`]es.
pub struct Client {
    http: Arc<HttpTransport>,
    call_timeout_ms: Option<u64>,
}

impl Client {
    pub fn new(opts: ClientOptions) -> Result<Self, SolariError> {
        let http = HttpTransport::new(HttpOptions::new(opts.api_key, opts.base_url))?;
        Ok(Client {
            http: Arc::new(http),
            call_timeout_ms: opts.call_timeout_ms,
        })
    }

    /// Create a new headless sandbox (`POST /sandboxes`).
    pub async fn create(&self, opts: CreateOptions) -> Result<Sandbox, SolariError> {
        self.create_with_kind(opts, "sandbox").await
    }

    /// Create a GUI desktop VM (`POST /sandboxes` with `kind:"desktop"`).
    ///
    /// Mirrors TS `createDesktop()` / Python `create_desktop()`. The returned
    /// handle carries [`Sandbox::stream_url`] for the live view, and exposes the
    /// same core namespaces as a sandbox (`commands`/`files`/`code`/`git`).
    /// Driving the GUI (mouse/keyboard/screenshot) is not part of this surface.
    ///
    /// Requires the `desktop` entitlement on the org's plan; the gateway
    /// answers 402 `FeatureRequiresPlan` otherwise.
    pub async fn create_desktop(&self, opts: CreateOptions) -> Result<Sandbox, SolariError> {
        self.create_with_kind(opts, "desktop").await
    }

    async fn create_with_kind(
        &self,
        opts: CreateOptions,
        kind: &str,
    ) -> Result<Sandbox, SolariError> {
        let req = opts.into_request(kind);
        let body = serde_json::to_value(&req).unwrap();
        let resp: CreateSandboxResponse = self
            .http
            .request("POST", "/sandboxes", Some(body), Some(new_idempotency_key()))
            .await?;
        Sandbox::from_response(self.http.clone(), resp, self.call_timeout_ms)
    }

    /// Re-attach to a running sandbox by id (`GET /sandboxes/:id`).
    pub async fn connect(&self, sandbox_id: &str) -> Result<Sandbox, SolariError> {
        // Guard B: the caller supplied this id, so a blank one is their input to
        // fix -> Validation (distinct from the response-side Other above).
        if sandbox_id.trim().is_empty() {
            return Err(SolariError::Validation {
                message: "Solari: connect() requires a non-blank sandbox id.".to_string(),
            });
        }
        let view = self.get(sandbox_id).await?;
        let control_url = view.control_url.clone().unwrap_or_else(|| {
            format!(
                "{}/control/{}",
                self.http.ws_origin(),
                encode_uri_component(sandbox_id)
            )
        });
        // `GET /sandboxes/:id` carries no streamUrl (the gateway's view
        // serializer omits it), so derive it exactly as control_url is derived
        // above — both are built from the same origin. Desktops only: a
        // headless sandbox has no display to stream.
        let stream_url = if view.kind == "desktop" {
            Some(format!(
                "{}/stream/{}",
                self.http.ws_origin(),
                encode_uri_component(sandbox_id)
            ))
        } else {
            None
        };
        let resp = CreateSandboxResponse {
            sandbox_id: view.sandbox_id,
            kind: view.kind,
            control_url,
            expires_at: view.expires_at,
            stream_url,
        };
        Sandbox::from_response(self.http.clone(), resp, self.call_timeout_ms)
    }

    /// Fetch a sandbox's current view (`GET /sandboxes/:id`).
    pub async fn get(&self, sandbox_id: &str) -> Result<SandboxView, SolariError> {
        self.http
            .request(
                "GET",
                &format!("/sandboxes/{}", encode_uri_component(sandbox_id)),
                None,
                None,
            )
            .await
    }

    /// Destroy a sandbox (`DELETE /sandboxes/:id`). Idempotent.
    pub async fn kill(&self, sandbox_id: &str) -> Result<(), SolariError> {
        let _: serde_json::Value = self
            .http
            .request(
                "DELETE",
                &format!("/sandboxes/{}", encode_uri_component(sandbox_id)),
                None,
                None,
            )
            .await?;
        Ok(())
    }

    /// Pause a session (`POST /sandboxes/:id/pause`): snapshot its RAM+disk and
    /// free its host slot. The session keeps its id; bring it back with
    /// [`Client::resume`].
    pub async fn pause(&self, sandbox_id: &str) -> Result<(), SolariError> {
        let _: serde_json::Value = self
            .http
            .request(
                "POST",
                &format!("/sandboxes/{}/pause", encode_uri_component(sandbox_id)),
                None,
                None,
            )
            .await?;
        Ok(())
    }

    /// Resume a paused session (`POST /sandboxes/:id/resume`) and return the
    /// control URL to re-attach to.
    ///
    /// The session comes back on a FRESH slot, so its pre-pause control URL is
    /// stale. The gateway normally returns the new one; when it does not, derive
    /// it from the gateway origin exactly as [`Client::connect`] does.
    pub async fn resume(&self, sandbox_id: &str) -> Result<String, SolariError> {
        let r: ResumeResponse = self
            .http
            .request(
                "POST",
                &format!("/sandboxes/{}/resume", encode_uri_component(sandbox_id)),
                None,
                None,
            )
            .await?;
        Ok(r.control_url.unwrap_or_else(|| {
            format!(
                "{}/control/{}",
                self.http.ws_origin(),
                encode_uri_component(sandbox_id)
            )
        }))
    }

    /// Cold-boot a STOPPED sandbox (`POST /sandboxes/:id/start`) from the disk the
    /// host kept, and return the fresh control URL to re-attach to.
    ///
    /// A sandbox is stopped when its guest powered itself off. This is a cold
    /// boot, not a resume: running processes and memory are gone, files on disk
    /// are kept. It takes a concurrency slot (429 at the cap) and opens a new
    /// billing segment. Idempotent: an already-running sandbox answers 200 and its
    /// current control URL.
    ///
    /// Any other state is refused with `SolariError::Gateway { status: 409, code }`
    /// where `code` is `NotStopped` (use [`Client::resume`] for a paused one) or
    /// `StartInProgress`. A stopped disk that cannot be started answers 409 with
    /// its code (`StoppedDiskMissing`, `StoppedDiskUnsafe`, `GoldenMismatch`,
    /// `DiskPlatformMismatch`, `DiskShaMismatch`, `DiskExceedsSpec`,
    /// `DiskOwnerMismatch`). 409 `HostCapabilityMissing` means the host pool is not
    /// armed for start (not retryable). 503 `NoCapacity` / `StartTimeout` is
    /// `SolariError::NoCapacity` and 502 `StartHostError` is a gateway error, both
    /// retryable; 500 `StartFailed` is not, and leaves the sandbox stopped with its
    /// disk, so a later start is safe.
    pub async fn start(&self, sandbox_id: &str) -> Result<String, SolariError> {
        let r: StartResponse = self
            .http
            .request(
                "POST",
                &format!("/sandboxes/{}/start", encode_uri_component(sandbox_id)),
                None,
                None,
            )
            .await?;
        Ok(r.control_url.unwrap_or_else(|| {
            format!(
                "{}/control/{}",
                self.http.ws_origin(),
                encode_uri_component(sandbox_id)
            )
        }))
    }
}

/// A live sandbox handle. Exposes the core namespaces.
pub struct Sandbox {
    id: String,
    kind: String,
    control_url: String,
    stream_url: Option<String>,
    expires_at: String,
    http: Arc<HttpTransport>,
    channel: Arc<ControlChannel>,
}

impl Sandbox {
    pub(crate) fn from_response(
        http: Arc<HttpTransport>,
        resp: CreateSandboxResponse,
        call_timeout_ms: Option<u64>,
    ) -> Result<Self, SolariError> {
        // A blank id in the response builds a nearly-right "/sandboxes//exec"
        // (double slash), not an obviously wrong path, so it slips through while
        // every call the handle makes is malformed. A blank id in a RESPONSE is
        // a bad reply from our side, not caller input -> Other. (Test blank.)
        if resp.sandbox_id.trim().is_empty() {
            return Err(SolariError::Other(
                "Solari: the session response carried a blank id - a blank id builds a malformed /sandboxes// request"
                    .to_string(),
            ));
        }
        let channel = ControlChannel::new(
            resp.control_url.clone(),
            http.auth_headers(),
            call_timeout_ms,
        );
        Ok(Sandbox {
            id: resp.sandbox_id,
            kind: resp.kind,
            control_url: resp.control_url,
            stream_url: resp.stream_url,
            expires_at: resp.expires_at,
            http,
            channel: Arc::new(channel),
        })
    }

    /// The session id.
    pub fn id(&self) -> &str {
        &self.id
    }
    /// The VM flavour — `"sandbox"` or `"desktop"`.
    pub fn kind(&self) -> &str {
        &self.kind
    }
    /// The control-WS URL.
    pub fn control_url(&self) -> &str {
        &self.control_url
    }
    /// The live-view stream URL. `Some` for desktops only — a headless sandbox
    /// has no display, so the gateway omits it.
    pub fn stream_url(&self) -> Option<&str> {
        self.stream_url.as_deref()
    }
    /// ISO-8601 expiry timestamp.
    pub fn expires_at(&self) -> &str {
        &self.expires_at
    }
    /// Whether the control channel is open.
    pub fn connected(&self) -> bool {
        self.channel.connected()
    }

    /// Open the control WebSocket. Idempotent.
    pub async fn connect(&self) -> Result<(), SolariError> {
        self.channel.connect().await
    }

    /// Close the control channel locally (does NOT release the remote session).
    pub fn close(&self) {
        self.channel.close();
    }

    /// Pause this session: snapshot its RAM+disk, free its host slot, and close
    /// the control channel. The session keeps its id; bring it back with
    /// [`Sandbox::resume`].
    ///
    /// Mirrors TS `handle.pause()` / Python `handle.pause()`: remote call first,
    /// then the local channel close.
    pub async fn pause(&self) -> Result<(), SolariError> {
        let _: serde_json::Value = self
            .http
            .request(
                "POST",
                &format!("/sandboxes/{}/pause", encode_uri_component(&self.id)),
                None,
                None,
            )
            .await?;
        self.close();
        Ok(())
    }

    /// Resume this paused session and re-point the control channel at the fresh
    /// slot it came back on.
    ///
    /// Mirrors TS `handle.resume()` / Python `handle.resume()`: resume, adopt the
    /// new control URL, reconnect.
    ///
    /// Takes `&mut self` where the rest of the handle takes `&self`: resuming
    /// genuinely replaces this handle's `control_url`, and [`Sandbox::control_url`]
    /// hands out a borrow of it. Interior mutability would let that borrow go
    /// stale behind the caller's back — the compiler should be the one saying
    /// this call mutates the handle.
    pub async fn resume(&mut self) -> Result<(), SolariError> {
        let r: ResumeResponse = self
            .http
            .request(
                "POST",
                &format!("/sandboxes/{}/resume", encode_uri_component(&self.id)),
                None,
                None,
            )
            .await?;
        let control_url = r.control_url.unwrap_or_else(|| {
            format!(
                "{}/control/{}",
                self.http.ws_origin(),
                encode_uri_component(&self.id)
            )
        });
        self.control_url = control_url.clone();
        self.channel.set_control_url(control_url);
        self.channel.reconnect().await
    }

    /// Cold-boot this STOPPED session from its kept disk and re-point the control
    /// channel at the fresh control URL. Processes and memory are gone, files on
    /// disk are kept. See [`Client::start`] for the refusal codes.
    ///
    /// Takes `&mut self` for the same reason as [`Sandbox::resume`]: it replaces
    /// this handle's `control_url`.
    pub async fn start(&mut self) -> Result<(), SolariError> {
        let r: StartResponse = self
            .http
            .request(
                "POST",
                &format!("/sandboxes/{}/start", encode_uri_component(&self.id)),
                None,
                None,
            )
            .await?;
        let control_url = r.control_url.unwrap_or_else(|| {
            format!(
                "{}/control/{}",
                self.http.ws_origin(),
                encode_uri_component(&self.id)
            )
        });
        self.control_url = control_url.clone();
        self.channel.set_control_url(control_url);
        self.channel.reconnect().await
    }

    /// Destroy the remote session and close the channel. Idempotent.
    pub async fn kill(&self) -> Result<(), SolariError> {
        let _: serde_json::Value = self
            .http
            .request(
                "DELETE",
                &format!("/sandboxes/{}", encode_uri_component(&self.id)),
                None,
                None,
            )
            .await?;
        self.close();
        Ok(())
    }

    // --- namespaces ----------------------------------------------------------

    pub fn commands(&self) -> Commands<'_> {
        Commands { sb: self }
    }
    pub fn files(&self) -> Files<'_> {
        Files { sb: self }
    }
    pub fn code(&self) -> Code<'_> {
        Code { sb: self }
    }
    pub fn git(&self) -> Git<'_> {
        Git::new(self)
    }

    // --- internal accessors (used by the namespace modules) ------------------

    pub(crate) fn channel(&self) -> &ControlChannel {
        &self.channel
    }
    pub(crate) fn channel_arc(&self) -> Arc<ControlChannel> {
        self.channel.clone()
    }
    pub(crate) fn http(&self) -> &HttpTransport {
        &self.http
    }
}

/// `Sandbox` runs `git` through `commands.run("git", …)` (no shell).
impl GitRunner for Sandbox {
    fn run_git<'a>(
        &'a self,
        args: Vec<String>,
        cwd: Option<String>,
    ) -> Pin<Box<dyn Future<Output = Result<CommandResult, SolariError>> + Send + 'a>> {
        Box::pin(async move {
            let opts = RunOptions {
                args: Some(args),
                cwd,
                ..Default::default()
            };
            run_command(self, "git", &opts).await
        })
    }
}