Skip to main content

solari/
lib.rs

1//! # solari-sdk
2//!
3//! Rust binding for the Solari sandbox SDK (core surface). Talks the same wire
4//! protocol as the reference `@solarisdk/core` TypeScript package:
5//!
6//! - **REST** to the gateway for session lifecycle (create/connect/get/kill) and
7//!   the one-shot `/exec` fast path.
8//! - **Control WebSocket** (newline-delimited JSON-RPC) for everything a live
9//!   session does: `commands`, `files`, `code.run`, and the client-side `git`
10//!   namespace.
11//!
12//! ```no_run
13//! use solari::{Client, ClientOptions, CreateOptions, RunOptions};
14//!
15//! # async fn ex() -> Result<(), solari::SolariError> {
16//! let client = Client::new(ClientOptions::new("slr_live_…", "https://gw.example.com"))?;
17//! let sbx = client.create(CreateOptions { template: Some("base".into()), ..Default::default() }).await?;
18//! let out = sbx.commands().run("echo", RunOptions::new().args(["hello"])).await?;
19//! println!("exit={} stdout={}", out.exit_code, out.stdout);
20//! let status = sbx.git().status(Some("/repo")).await?;
21//! println!("branch={} clean={}", status.branch, status.clean);
22//! # Ok(()) }
23//! ```
24
25mod channel;
26mod client;
27mod code;
28mod commands;
29mod error;
30mod files;
31mod git;
32mod http;
33mod types;
34
35pub use channel::{AsyncFrame, ControlChannel};
36pub use client::{Client, ClientOptions, CreateOptions, Sandbox};
37pub use code::{Code, RunCodeOptions};
38pub use commands::{CommandHandle, Commands, OutputCallback, RunOptions};
39pub use error::SolariError;
40pub use files::Files;
41pub use git::{
42    Git, GitCloneOptions, GitCommitOptions, GitLogOptions, GitRemoteOptions, GitRunner,
43};
44pub use http::{new_idempotency_key, HttpOptions, HttpTransport};
45pub use types::{
46    Chart, ChartAxis, ChartType, CodeResultItem, CommandResult, CreateSandboxRequest,
47    CreateSandboxResponse, FsEntry, FsStat, GatewayErrorBody, GitBranch, GitCommit, GitStatus,
48    Lifecycle, ResumeResponse, RunCodeResult, SandboxView, StartResponse, VolumeAttachment,
49};
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54    use base64::Engine;
55    use futures_util::{SinkExt, StreamExt};
56    use std::sync::{Arc, Mutex};
57    use tokio::io::{AsyncReadExt, AsyncWriteExt};
58    use tokio::net::TcpListener;
59
60    /// commands().run happy path over an in-process mock control-WS that scripts
61    /// start-reply → cmd.data → cmd.exit.
62    #[tokio::test]
63    async fn commands_run_over_mock_ws() {
64        // Mock control-WS server.
65        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
66        let ws_port = listener.local_addr().unwrap().port();
67        tokio::spawn(async move {
68            let (stream, _) = listener.accept().await.unwrap();
69            let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
70            // Read the cmd.start request frame.
71            let msg = ws.next().await.unwrap().unwrap();
72            let text = msg.into_text().unwrap();
73            let req: serde_json::Value = serde_json::from_str(text.as_str()).unwrap();
74            assert_eq!(req.get("method").unwrap(), "cmd.start");
75            let id = req.get("id").unwrap().as_str().unwrap().to_string();
76            let hello = base64::engine::general_purpose::STANDARD.encode("hello\n");
77            let world = base64::engine::general_purpose::STANDARD.encode("oops");
78            // start reply, then data (stdout+stderr), then exit.
79            let frames = vec![
80                format!("{{\"id\":\"{id}\",\"ok\":true,\"result\":{{\"cmdId\":\"c1\"}}}}"),
81                format!("{{\"type\":\"cmd.data\",\"cmdId\":\"c1\",\"stream\":\"stdout\",\"base64\":\"{hello}\"}}"),
82                format!("{{\"type\":\"cmd.data\",\"cmdId\":\"c1\",\"stream\":\"stderr\",\"base64\":\"{world}\"}}"),
83                "{\"type\":\"cmd.exit\",\"cmdId\":\"c1\",\"exitCode\":3}".to_string(),
84            ];
85            for f in frames {
86                ws.send(tokio_tungstenite::tungstenite::Message::Text(
87                    format!("{f}\n").into(),
88                ))
89                .await
90                .unwrap();
91            }
92            // keep the socket open briefly so frames flush.
93            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
94        });
95
96        // Build a sandbox pointed at the mock WS. base_url is unused because we
97        // pre-connect the channel (fast path is skipped when connected).
98        let resp = CreateSandboxResponse {
99            sandbox_id: "sb".into(),
100            kind: "sandbox".into(),
101            control_url: format!("ws://127.0.0.1:{ws_port}/control/sb"),
102            expires_at: "".into(),
103            stream_url: None,
104        };
105        let sbx = Sandbox::from_response(
106            Arc::new(HttpTransport::new(HttpOptions::new("k", "http://127.0.0.1:1")).unwrap()),
107            resp,
108            Some(5000),
109        )
110        .unwrap();
111        sbx.connect().await.unwrap();
112
113        let out = sbx.commands().run("echo", RunOptions::new().args(["hello"])).await.unwrap();
114        assert_eq!(out.exit_code, 3);
115        assert_eq!(out.stdout, "hello\n");
116        assert_eq!(out.stderr, "oops");
117    }
118
119    /// `timeout_ms` is a command deadline on the WebSocket path: the command is killed (SIGKILL) and
120    /// the result is exit -1 with the output so far.
121    #[tokio::test]
122    async fn commands_run_timeout_kills_the_command() {
123        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
124        let ws_port = listener.local_addr().unwrap().port();
125        let killed = Arc::new(Mutex::new(None::<serde_json::Value>));
126        let killed_srv = killed.clone();
127        tokio::spawn(async move {
128            let (stream, _) = listener.accept().await.unwrap();
129            let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
130            let msg = ws.next().await.unwrap().unwrap();
131            let req: serde_json::Value = serde_json::from_str(msg.into_text().unwrap().as_str()).unwrap();
132            let id = req.get("id").unwrap().as_str().unwrap().to_string();
133            let out = base64::engine::general_purpose::STANDARD.encode("partial\n");
134            for f in [
135                format!("{{\"id\":\"{id}\",\"ok\":true,\"result\":{{\"cmdId\":\"c1\"}}}}"),
136                format!("{{\"type\":\"cmd.data\",\"cmdId\":\"c1\",\"stream\":\"stdout\",\"base64\":\"{out}\"}}"),
137            ] {
138                ws.send(tokio_tungstenite::tungstenite::Message::Text(format!("{f}\n").into())).await.unwrap();
139            }
140            // The command never exits; the next frame must be cmd.kill.
141            if let Some(Ok(msg)) = ws.next().await {
142                let req: serde_json::Value = serde_json::from_str(msg.into_text().unwrap().as_str()).unwrap();
143                let id = req.get("id").unwrap().as_str().unwrap().to_string();
144                *killed_srv.lock().unwrap() = Some(req);
145                let _ = ws
146                    .send(tokio_tungstenite::tungstenite::Message::Text(
147                        format!("{{\"id\":\"{id}\",\"ok\":true,\"result\":{{\"ok\":true}}}}\n").into(),
148                    ))
149                    .await;
150            }
151            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
152        });
153
154        let resp = CreateSandboxResponse {
155            sandbox_id: "sb".into(),
156            kind: "sandbox".into(),
157            control_url: format!("ws://127.0.0.1:{ws_port}/control/sb"),
158            expires_at: "".into(),
159            stream_url: None,
160        };
161        let sbx = Sandbox::from_response(
162            Arc::new(HttpTransport::new(HttpOptions::new("k", "http://127.0.0.1:1")).unwrap()),
163            resp,
164            Some(5000),
165        )
166        .unwrap();
167        sbx.connect().await.unwrap();
168
169        let started = std::time::Instant::now();
170        let mut opts = RunOptions::new().args(["3600"]);
171        opts.timeout_ms = Some(80);
172        let out = sbx.commands().run("sleep", opts).await.unwrap();
173        assert!(started.elapsed() < std::time::Duration::from_secs(3), "run did not honour timeout_ms");
174        assert_eq!(out.exit_code, -1);
175        assert_eq!(out.stdout, "partial\n");
176        let kill = killed.lock().unwrap().clone().expect("cmd.kill was sent");
177        assert_eq!(kill["method"], "cmd.kill");
178        assert_eq!(kill["params"]["signal"], 9);
179        assert_eq!(kill["params"]["cmdId"], "c1");
180    }
181
182    /// files().list / files().stat must parse the guest wire shape exactly:
183    /// the directory flag is "dir" (not "isDir") and the stat timestamp is
184    /// "modTimeMs". Regression guard for the wire-field bug.
185    #[tokio::test]
186    async fn files_list_and_stat_parse_wire_shape() {
187        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
188        let ws_port = listener.local_addr().unwrap().port();
189        tokio::spawn(async move {
190            let (stream, _) = listener.accept().await.unwrap();
191            let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
192            // Answer each RPC by echoing its id and switching on its method.
193            for _ in 0..2 {
194                let msg = ws.next().await.unwrap().unwrap();
195                let text = msg.into_text().unwrap();
196                let req: serde_json::Value = serde_json::from_str(text.as_str()).unwrap();
197                let id = req.get("id").unwrap().as_str().unwrap().to_string();
198                let method = req.get("method").unwrap().as_str().unwrap();
199                let result = match method {
200                    "fs.list" => "{\"entries\":[{\"name\":\"a.txt\",\"dir\":false,\"size\":12},{\"name\":\"sub\",\"dir\":true,\"size\":4096}]}".to_string(),
201                    "fs.stat" => "{\"name\":\"a.txt\",\"dir\":false,\"size\":12,\"mode\":420,\"modTimeMs\":1720000000000}".to_string(),
202                    _ => "{}".to_string(),
203                };
204                ws.send(tokio_tungstenite::tungstenite::Message::Text(
205                    format!("{{\"id\":\"{id}\",\"ok\":true,\"result\":{result}}}\n").into(),
206                ))
207                .await
208                .unwrap();
209            }
210            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
211        });
212
213        let resp = CreateSandboxResponse {
214            sandbox_id: "sb".into(),
215            kind: "sandbox".into(),
216            control_url: format!("ws://127.0.0.1:{ws_port}/control/sb"),
217            expires_at: "".into(),
218            stream_url: None,
219        };
220        let sbx = Sandbox::from_response(
221            Arc::new(HttpTransport::new(HttpOptions::new("k", "http://127.0.0.1:1")).unwrap()),
222            resp,
223            Some(5000),
224        )
225        .unwrap();
226        sbx.connect().await.unwrap();
227
228        let entries = sbx.files().list("/work").await.unwrap();
229        assert_eq!(entries.len(), 2);
230        assert_eq!(entries[0].name, "a.txt");
231        assert!(!entries[0].dir);
232        assert_eq!(entries[0].size, 12);
233        assert_eq!(entries[1].name, "sub");
234        assert!(entries[1].dir);
235        assert_eq!(entries[1].size, 4096);
236
237        let st = sbx.files().stat("/work/a.txt").await.unwrap();
238        assert_eq!(st.name, "a.txt");
239        assert!(!st.dir);
240        assert_eq!(st.size, 12);
241        assert_eq!(st.mode, 420);
242        assert_eq!(st.mod_time_ms, 1720000000000);
243    }
244
245    /// REST create request shape: method/path, headers (Authorization,
246    /// Idempotency-Key, Accept, Content-Type), and body (template + kind).
247    #[tokio::test]
248    async fn create_rest_request_shape() {
249        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
250        let port = listener.local_addr().unwrap().port();
251        let captured: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
252        let cap = captured.clone();
253        tokio::spawn(async move {
254            let (mut sock, _) = listener.accept().await.unwrap();
255            // Read until end of headers, then read the Content-Length body.
256            let mut buf = Vec::new();
257            let mut tmp = [0u8; 1024];
258            loop {
259                let n = sock.read(&mut tmp).await.unwrap();
260                if n == 0 {
261                    break;
262                }
263                buf.extend_from_slice(&tmp[..n]);
264                if let Some(pos) = find_subslice(&buf, b"\r\n\r\n") {
265                    let head = String::from_utf8_lossy(&buf[..pos]).to_string();
266                    let clen = content_length(&head).unwrap_or(0);
267                    let body_start = pos + 4;
268                    while buf.len() < body_start + clen {
269                        let n = sock.read(&mut tmp).await.unwrap();
270                        if n == 0 {
271                            break;
272                        }
273                        buf.extend_from_slice(&tmp[..n]);
274                    }
275                    *cap.lock().unwrap() = Some(String::from_utf8_lossy(&buf).to_string());
276                    break;
277                }
278            }
279            let body = r#"{"sandboxId":"sbx_1","kind":"sandbox","controlUrl":"ws://x/control/sbx_1","expiresAt":"2026-01-01T00:00:00Z"}"#;
280            let resp = format!(
281                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
282                body.len(),
283                body
284            );
285            sock.write_all(resp.as_bytes()).await.unwrap();
286            sock.flush().await.unwrap();
287        });
288
289        let client =
290            Client::new(ClientOptions::new("secret-key", format!("http://127.0.0.1:{port}"))).unwrap();
291        let sbx = client
292            .create(CreateOptions {
293                template: Some("base".into()),
294                ..Default::default()
295            })
296            .await
297            .unwrap();
298        assert_eq!(sbx.id(), "sbx_1");
299        assert_eq!(sbx.control_url(), "ws://x/control/sbx_1");
300
301        let raw = captured.lock().unwrap().clone().unwrap();
302        let (head, body) = raw.split_once("\r\n\r\n").unwrap();
303        // Request line + headers.
304        assert!(head.starts_with("POST /sandboxes "), "head: {head}");
305        let lower = head.to_lowercase();
306        assert!(lower.contains("authorization: bearer secret-key"), "head: {head}");
307        assert!(lower.contains("accept: application/json"));
308        assert!(lower.contains("content-type: application/json"));
309        assert!(lower.contains("idempotency-key: "), "missing idempotency key: {head}");
310        // Body.
311        let json: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
312        assert_eq!(json.get("template").unwrap(), "base");
313        assert_eq!(json.get("kind").unwrap(), "sandbox");
314        // Unset fields are omitted.
315        assert!(json.get("cpu").is_none());
316        assert!(json.get("fromSnapshot").is_none());
317        // A headless sandbox has no display: the gateway sends no streamUrl.
318        assert_eq!(sbx.kind(), "sandbox");
319        assert_eq!(sbx.stream_url(), None);
320    }
321
322    /// `create_desktop` sends `kind:"desktop"` and surfaces the returned
323    /// streamUrl on the handle.
324    #[tokio::test]
325    async fn create_desktop_sends_kind_and_surfaces_stream_url() {
326        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
327        let port = listener.local_addr().unwrap().port();
328        let captured: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
329        let cap = captured.clone();
330        tokio::spawn(async move {
331            let (mut sock, _) = listener.accept().await.unwrap();
332            let mut buf = Vec::new();
333            let mut tmp = [0u8; 1024];
334            loop {
335                let n = sock.read(&mut tmp).await.unwrap();
336                if n == 0 {
337                    break;
338                }
339                buf.extend_from_slice(&tmp[..n]);
340                if let Some(pos) = find_subslice(&buf, b"\r\n\r\n") {
341                    let head = String::from_utf8_lossy(&buf[..pos]).to_string();
342                    let clen = content_length(&head).unwrap_or(0);
343                    let body_start = pos + 4;
344                    while buf.len() < body_start + clen {
345                        let n = sock.read(&mut tmp).await.unwrap();
346                        if n == 0 {
347                            break;
348                        }
349                        buf.extend_from_slice(&tmp[..n]);
350                    }
351                    *cap.lock().unwrap() = Some(String::from_utf8_lossy(&buf).to_string());
352                    break;
353                }
354            }
355            // Mirrors the gateway: streamUrl is present for kind:"desktop".
356            let body = r#"{"sandboxId":"sbx_d","kind":"desktop","controlUrl":"ws://x/control/sbx_d","expiresAt":"2026-01-01T00:00:00Z","streamUrl":"ws://x/stream/sbx_d"}"#;
357            let resp = format!(
358                "HTTP/1.1 201 Created\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
359                body.len(),
360                body
361            );
362            sock.write_all(resp.as_bytes()).await.unwrap();
363            sock.flush().await.unwrap();
364        });
365
366        let client =
367            Client::new(ClientOptions::new("secret-key", format!("http://127.0.0.1:{port}"))).unwrap();
368        let sbx = client
369            .create_desktop(CreateOptions {
370                template: Some("default".into()),
371                cpu: Some(2),
372                ..Default::default()
373            })
374            .await
375            .unwrap();
376
377        assert_eq!(sbx.id(), "sbx_d");
378        assert_eq!(sbx.kind(), "desktop");
379        assert_eq!(sbx.stream_url(), Some("ws://x/stream/sbx_d"));
380        assert_eq!(sbx.control_url(), "ws://x/control/sbx_d");
381
382        let raw = captured.lock().unwrap().clone().unwrap();
383        let (head, body) = raw.split_once("\r\n\r\n").unwrap();
384        assert!(head.starts_with("POST /sandboxes "), "head: {head}");
385        let json: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
386        // The whole point: the gateway keys desktop-ness off this field.
387        assert_eq!(json.get("kind").unwrap(), "desktop");
388        assert_eq!(json.get("template").unwrap(), "default");
389        assert_eq!(json.get("cpu").unwrap(), 2);
390    }
391
392    fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
393        haystack.windows(needle.len()).position(|w| w == needle)
394    }
395
396    fn content_length(head: &str) -> Option<usize> {
397        for line in head.lines() {
398            if let Some(v) = line.to_lowercase().strip_prefix("content-length:") {
399                return v.trim().parse().ok();
400            }
401        }
402        None
403    }
404
405    // A blank id builds a nearly-right "/sandboxes//exec" (double slash), so it
406    // is rejected where it enters: Other for a blank id in a response (our
407    // side), Validation for a blank id the caller passed to connect().
408    #[tokio::test]
409    async fn blank_id_guard() {
410        let resp = CreateSandboxResponse {
411            sandbox_id: "".into(),
412            kind: "sandbox".into(),
413            control_url: "ws://127.0.0.1:1/control/".into(),
414            expires_at: "".into(),
415            stream_url: None,
416        };
417        let http = Arc::new(HttpTransport::new(HttpOptions::new("k", "http://127.0.0.1:1")).unwrap());
418        match Sandbox::from_response(http, resp, Some(5000)) {
419            Err(SolariError::Other(_)) => {}
420            Err(e) => panic!("from_response(blank) = Err({e:?}), want Err(Other)"),
421            Ok(_) => panic!("from_response(blank) = Ok, want Err(Other)"),
422        }
423
424        let client = Client::new(ClientOptions::new("k", "http://127.0.0.1:1")).unwrap();
425        for id in ["", "   ", "\t"] {
426            match client.connect(id).await {
427                Err(SolariError::Validation { .. }) => {}
428                Err(e) => panic!("connect({id:?}) = Err({e:?}), want Validation"),
429                Ok(_) => panic!("connect({id:?}) = Ok, want Validation"),
430            }
431        }
432    }
433}