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, 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        sbx.connect().await.unwrap();
111
112        let out = sbx.commands().run("echo", RunOptions::new().args(["hello"])).await.unwrap();
113        assert_eq!(out.exit_code, 3);
114        assert_eq!(out.stdout, "hello\n");
115        assert_eq!(out.stderr, "oops");
116    }
117
118    /// files().list / files().stat must parse the guest wire shape exactly:
119    /// the directory flag is "dir" (not "isDir") and the stat timestamp is
120    /// "modTimeMs". Regression guard for the wire-field bug.
121    #[tokio::test]
122    async fn files_list_and_stat_parse_wire_shape() {
123        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
124        let ws_port = listener.local_addr().unwrap().port();
125        tokio::spawn(async move {
126            let (stream, _) = listener.accept().await.unwrap();
127            let mut ws = tokio_tungstenite::accept_async(stream).await.unwrap();
128            // Answer each RPC by echoing its id and switching on its method.
129            for _ in 0..2 {
130                let msg = ws.next().await.unwrap().unwrap();
131                let text = msg.into_text().unwrap();
132                let req: serde_json::Value = serde_json::from_str(text.as_str()).unwrap();
133                let id = req.get("id").unwrap().as_str().unwrap().to_string();
134                let method = req.get("method").unwrap().as_str().unwrap();
135                let result = match method {
136                    "fs.list" => "{\"entries\":[{\"name\":\"a.txt\",\"dir\":false,\"size\":12},{\"name\":\"sub\",\"dir\":true,\"size\":4096}]}".to_string(),
137                    "fs.stat" => "{\"name\":\"a.txt\",\"dir\":false,\"size\":12,\"mode\":420,\"modTimeMs\":1720000000000}".to_string(),
138                    _ => "{}".to_string(),
139                };
140                ws.send(tokio_tungstenite::tungstenite::Message::Text(
141                    format!("{{\"id\":\"{id}\",\"ok\":true,\"result\":{result}}}\n").into(),
142                ))
143                .await
144                .unwrap();
145            }
146            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
147        });
148
149        let resp = CreateSandboxResponse {
150            sandbox_id: "sb".into(),
151            kind: "sandbox".into(),
152            control_url: format!("ws://127.0.0.1:{ws_port}/control/sb"),
153            expires_at: "".into(),
154            stream_url: None,
155        };
156        let sbx = Sandbox::from_response(
157            Arc::new(HttpTransport::new(HttpOptions::new("k", "http://127.0.0.1:1")).unwrap()),
158            resp,
159            Some(5000),
160        );
161        sbx.connect().await.unwrap();
162
163        let entries = sbx.files().list("/work").await.unwrap();
164        assert_eq!(entries.len(), 2);
165        assert_eq!(entries[0].name, "a.txt");
166        assert!(!entries[0].dir);
167        assert_eq!(entries[0].size, 12);
168        assert_eq!(entries[1].name, "sub");
169        assert!(entries[1].dir);
170        assert_eq!(entries[1].size, 4096);
171
172        let st = sbx.files().stat("/work/a.txt").await.unwrap();
173        assert_eq!(st.name, "a.txt");
174        assert!(!st.dir);
175        assert_eq!(st.size, 12);
176        assert_eq!(st.mode, 420);
177        assert_eq!(st.mod_time_ms, 1720000000000);
178    }
179
180    /// REST create request shape: method/path, headers (Authorization,
181    /// Idempotency-Key, Accept, Content-Type), and body (template + kind).
182    #[tokio::test]
183    async fn create_rest_request_shape() {
184        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
185        let port = listener.local_addr().unwrap().port();
186        let captured: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
187        let cap = captured.clone();
188        tokio::spawn(async move {
189            let (mut sock, _) = listener.accept().await.unwrap();
190            // Read until end of headers, then read the Content-Length body.
191            let mut buf = Vec::new();
192            let mut tmp = [0u8; 1024];
193            loop {
194                let n = sock.read(&mut tmp).await.unwrap();
195                if n == 0 {
196                    break;
197                }
198                buf.extend_from_slice(&tmp[..n]);
199                if let Some(pos) = find_subslice(&buf, b"\r\n\r\n") {
200                    let head = String::from_utf8_lossy(&buf[..pos]).to_string();
201                    let clen = content_length(&head).unwrap_or(0);
202                    let body_start = pos + 4;
203                    while buf.len() < body_start + clen {
204                        let n = sock.read(&mut tmp).await.unwrap();
205                        if n == 0 {
206                            break;
207                        }
208                        buf.extend_from_slice(&tmp[..n]);
209                    }
210                    *cap.lock().unwrap() = Some(String::from_utf8_lossy(&buf).to_string());
211                    break;
212                }
213            }
214            let body = r#"{"sandboxId":"sbx_1","kind":"sandbox","controlUrl":"ws://x/control/sbx_1","expiresAt":"2026-01-01T00:00:00Z"}"#;
215            let resp = format!(
216                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
217                body.len(),
218                body
219            );
220            sock.write_all(resp.as_bytes()).await.unwrap();
221            sock.flush().await.unwrap();
222        });
223
224        let client =
225            Client::new(ClientOptions::new("secret-key", format!("http://127.0.0.1:{port}"))).unwrap();
226        let sbx = client
227            .create(CreateOptions {
228                template: Some("base".into()),
229                ..Default::default()
230            })
231            .await
232            .unwrap();
233        assert_eq!(sbx.id(), "sbx_1");
234        assert_eq!(sbx.control_url(), "ws://x/control/sbx_1");
235
236        let raw = captured.lock().unwrap().clone().unwrap();
237        let (head, body) = raw.split_once("\r\n\r\n").unwrap();
238        // Request line + headers.
239        assert!(head.starts_with("POST /sandboxes "), "head: {head}");
240        let lower = head.to_lowercase();
241        assert!(lower.contains("authorization: bearer secret-key"), "head: {head}");
242        assert!(lower.contains("accept: application/json"));
243        assert!(lower.contains("content-type: application/json"));
244        assert!(lower.contains("idempotency-key: "), "missing idempotency key: {head}");
245        // Body.
246        let json: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
247        assert_eq!(json.get("template").unwrap(), "base");
248        assert_eq!(json.get("kind").unwrap(), "sandbox");
249        // Unset fields are omitted.
250        assert!(json.get("cpu").is_none());
251        assert!(json.get("fromSnapshot").is_none());
252        // A headless sandbox has no display: the gateway sends no streamUrl.
253        assert_eq!(sbx.kind(), "sandbox");
254        assert_eq!(sbx.stream_url(), None);
255    }
256
257    /// `create_desktop` sends `kind:"desktop"` and surfaces the returned
258    /// streamUrl on the handle.
259    #[tokio::test]
260    async fn create_desktop_sends_kind_and_surfaces_stream_url() {
261        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
262        let port = listener.local_addr().unwrap().port();
263        let captured: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
264        let cap = captured.clone();
265        tokio::spawn(async move {
266            let (mut sock, _) = listener.accept().await.unwrap();
267            let mut buf = Vec::new();
268            let mut tmp = [0u8; 1024];
269            loop {
270                let n = sock.read(&mut tmp).await.unwrap();
271                if n == 0 {
272                    break;
273                }
274                buf.extend_from_slice(&tmp[..n]);
275                if let Some(pos) = find_subslice(&buf, b"\r\n\r\n") {
276                    let head = String::from_utf8_lossy(&buf[..pos]).to_string();
277                    let clen = content_length(&head).unwrap_or(0);
278                    let body_start = pos + 4;
279                    while buf.len() < body_start + clen {
280                        let n = sock.read(&mut tmp).await.unwrap();
281                        if n == 0 {
282                            break;
283                        }
284                        buf.extend_from_slice(&tmp[..n]);
285                    }
286                    *cap.lock().unwrap() = Some(String::from_utf8_lossy(&buf).to_string());
287                    break;
288                }
289            }
290            // Mirrors the gateway: streamUrl is present for kind:"desktop".
291            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"}"#;
292            let resp = format!(
293                "HTTP/1.1 201 Created\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
294                body.len(),
295                body
296            );
297            sock.write_all(resp.as_bytes()).await.unwrap();
298            sock.flush().await.unwrap();
299        });
300
301        let client =
302            Client::new(ClientOptions::new("secret-key", format!("http://127.0.0.1:{port}"))).unwrap();
303        let sbx = client
304            .create_desktop(CreateOptions {
305                template: Some("default".into()),
306                cpu: Some(2),
307                ..Default::default()
308            })
309            .await
310            .unwrap();
311
312        assert_eq!(sbx.id(), "sbx_d");
313        assert_eq!(sbx.kind(), "desktop");
314        assert_eq!(sbx.stream_url(), Some("ws://x/stream/sbx_d"));
315        assert_eq!(sbx.control_url(), "ws://x/control/sbx_d");
316
317        let raw = captured.lock().unwrap().clone().unwrap();
318        let (head, body) = raw.split_once("\r\n\r\n").unwrap();
319        assert!(head.starts_with("POST /sandboxes "), "head: {head}");
320        let json: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
321        // The whole point: the gateway keys desktop-ness off this field.
322        assert_eq!(json.get("kind").unwrap(), "desktop");
323        assert_eq!(json.get("template").unwrap(), "default");
324        assert_eq!(json.get("cpu").unwrap(), 2);
325    }
326
327    fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
328        haystack.windows(needle.len()).position(|w| w == needle)
329    }
330
331    fn content_length(head: &str) -> Option<usize> {
332        for line in head.lines() {
333            if let Some(v) = line.to_lowercase().strip_prefix("content-length:") {
334                return v.trim().parse().ok();
335            }
336        }
337        None
338    }
339}