From 172e50ab6b6c632988eb3adb9e2cb38540559c01 Mon Sep 17 00:00:00 2001 From: Dhruv Jain Date: Mon, 30 Nov 2026 20:53:56 +0530 Subject: [PATCH 1/5] feat: add official spawnbox-client Rust SDK crate --- Cargo.lock | 16 + Cargo.toml | 2 +- crates/spawnbox-client/Cargo.toml | 26 + crates/spawnbox-client/README.md | 47 ++ crates/spawnbox-client/src/lib.rs | 883 ++++++++++++++++++++++++++++++ 5 files changed, 973 insertions(+), 1 deletion(-) create mode 100644 crates/spawnbox-client/Cargo.toml create mode 100644 crates/spawnbox-client/README.md create mode 100644 crates/spawnbox-client/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index eaa5999..8bb5e24 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2930,6 +2930,22 @@ dependencies = [ "url", ] +[[package]] +name = "spawnbox-client" +version = "0.1.0" +dependencies = [ + "bytes", + "futures-util", + "rand 0.10.3", + "reqwest", + "rustls", + "serde", + "serde_json", + "thiserror", + "tokio", + "url", +] + [[package]] name = "spin" version = "0.10.1" diff --git a/Cargo.toml b/Cargo.toml index ae7b735..1c726a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/spawn-api","crates/spawn-bench","crates/spawn-egress","crates/spawn-guest","crates/spawn-node","crates/spawn-proto","crates/spawnbox-cli"] +members = ["crates/spawn-api","crates/spawn-bench","crates/spawn-egress","crates/spawn-guest","crates/spawn-node","crates/spawn-proto","crates/spawnbox-cli","crates/spawnbox-client"] resolver = "3" [workspace.package] diff --git a/crates/spawnbox-client/Cargo.toml b/crates/spawnbox-client/Cargo.toml new file mode 100644 index 0000000..de235d7 --- /dev/null +++ b/crates/spawnbox-client/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "spawnbox-client" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +description = "Async Rust HTTP client SDK for the self-hosted Spawnbox sandbox runtime" + +[lints] +workspace = true + +[dependencies] +bytes = "1" +rand = "0.10.3" +reqwest = { version = "0.13.5", default-features = false, features = ["rustls-no-provider", "json", "stream", "http2"] } +rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12"] } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +thiserror = "2.0.21" +tokio = { version = "1.54.1", features = ["time"] } +url = "2.5.8" + +[dev-dependencies] +futures-util = "0.3.34" +tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net", "io-util", "time"] } diff --git a/crates/spawnbox-client/README.md b/crates/spawnbox-client/README.md new file mode 100644 index 0000000..4e315f4 --- /dev/null +++ b/crates/spawnbox-client/README.md @@ -0,0 +1,47 @@ +# spawnbox-client + +Async Rust HTTP client SDK for the self-hosted Spawnbox sandbox runtime. + +## Quickstart + +```rust,no_run +use std::time::Duration; +use serde_json::json; +use spawnbox_client::{ForwardClient, Method, SpawnboxClient}; + +#[tokio::main] +async fn main() -> spawnbox_client::Result<()> { + let client = SpawnboxClient::new("http://127.0.0.1:8080", "sbx_api_key")?; + + client.ensure_tenant("default", None).await?; + client + .ensure_template( + "python-dev", + &json!({ "name": "python-dev", "base": "base" }), + Duration::from_secs(2), + 60, + ) + .await?; + + let sandbox = client + .create_sandbox(&json!({ "template": "python-dev" })) + .await?; + let sandbox_id = sandbox["id"].as_str().unwrap(); + + let exec_result = client + .exec(sandbox_id, &json!({ "cmd": ["python3", "--version"] })) + .await?; + println!("{exec_result}"); + + let forward = ForwardClient::new("http://127.0.0.1:8082", Some("fwd_key".into()))?; + let resp = forward + .request(Method::GET, sandbox_id, 8000, "/events") + .header("Accept", "text/event-stream") + .send() + .await?; + println!("forward status: {}", resp.status()); + + client.delete_sandbox(sandbox_id).await?; + Ok(()) +} +``` diff --git a/crates/spawnbox-client/src/lib.rs b/crates/spawnbox-client/src/lib.rs new file mode 100644 index 0000000..99beb9b --- /dev/null +++ b/crates/spawnbox-client/src/lib.rs @@ -0,0 +1,883 @@ +use std::fmt::Write as _; +use std::time::Duration; + +use bytes::Bytes; +pub use reqwest::{Method, RequestBuilder, Response}; +use serde::Serialize; +use serde_json::{Value, json}; +use url::Url; + +const DEFAULT_MAX_RETRIES: usize = 8; +const BASE_BACKOFF_MS: u64 = 100; +const MAX_BACKOFF_MS: u64 = 10_000; +const JITTER_MAX_MS: u64 = 50; + +pub type Result = std::result::Result; + +#[derive(Debug, thiserror::Error)] +pub enum SpawnboxError { + #[error("invalid URL: {0}")] + InvalidUrl(String), + #[error("HTTP error: {0}")] + Http(#[from] reqwest::Error), + #[error("JSON error: {0}")] + Json(#[from] serde_json::Error), + #[error("Spawnbox API error ({status} {code}): {message}")] + Api { + status: u16, + code: String, + message: String, + }, + #[error("template {template:?} build failed with state {state:?}")] + TemplateBuildFailed { template: String, state: String }, + #[error("timeout: {0}")] + Timeout(String), +} + +#[derive(Clone, Debug)] +pub struct SpawnboxClient { + http: reqwest::Client, + base_url: String, + api_key: String, + max_retries: usize, +} + +impl SpawnboxClient { + pub fn new(base_url: impl AsRef, api_key: impl Into) -> Result { + let normalized = normalize_http_url(base_url.as_ref())?; + let base_url = if normalized.ends_with("/v1") { + normalized + } else { + format!("{normalized}/v1") + }; + + Ok(Self { + http: build_http_client()?, + base_url, + api_key: api_key.into(), + max_retries: DEFAULT_MAX_RETRIES, + }) + } + + pub fn with_max_retries(mut self, max_retries: usize) -> Self { + self.max_retries = max_retries; + self + } + + pub fn base_url(&self) -> &str { + &self.base_url + } + + pub async fn call( + &self, + method: Method, + path: &str, + body: Option, + content_type: Option<&str>, + auth_override: Option<&str>, + ) -> Result> { + let url = join_url(&self.base_url, path); + let token = auth_override.unwrap_or(&self.api_key); + + let mut attempt = 0usize; + loop { + let mut req = self.http.request(method.clone(), &url); + if !token.is_empty() { + req = req.bearer_auth(token); + } + if let Some(ct) = content_type { + req = req.header(reqwest::header::CONTENT_TYPE, ct); + } + if let Some(bytes) = &body { + req = req.body(bytes.clone()); + } + + let response = req.send().await?; + let status = response.status(); + + if status == reqwest::StatusCode::NOT_FOUND { + return Ok(None); + } + if status.is_success() { + return Ok(Some(response)); + } + + if is_retryable_status(status) && attempt < self.max_retries { + let delay = retry_delay(response.headers(), attempt); + attempt += 1; + tokio::time::sleep(delay).await; + continue; + } + + let raw = response.bytes().await.unwrap_or_default(); + return Err(parse_api_error(status, &raw)); + } + } + + pub async fn get_json(&self, path: &str, auth_override: Option<&str>) -> Result> { + let Some(response) = self + .call(Method::GET, path, None, None, auth_override) + .await? + else { + return Ok(None); + }; + read_json(response).await.map(Some) + } + + pub async fn send_json( + &self, + method: Method, + path: &str, + body: &impl Serialize, + auth_override: Option<&str>, + ) -> Result> { + let payload = Bytes::from(serde_json::to_vec(body)?); + let Some(response) = self + .call( + method, + path, + Some(payload), + Some("application/json"), + auth_override, + ) + .await? + else { + return Ok(None); + }; + read_json(response).await.map(Some) + } + + pub async fn post_json( + &self, + path: &str, + body: &impl Serialize, + auth_override: Option<&str>, + ) -> Result> { + self.send_json(Method::POST, path, body, auth_override) + .await + } + + pub async fn put_json( + &self, + path: &str, + body: &impl Serialize, + auth_override: Option<&str>, + ) -> Result> { + self.send_json(Method::PUT, path, body, auth_override).await + } + + pub async fn patch_json( + &self, + path: &str, + body: &impl Serialize, + auth_override: Option<&str>, + ) -> Result> { + self.send_json(Method::PATCH, path, body, auth_override) + .await + } + + pub async fn delete(&self, path: &str, auth_override: Option<&str>) -> Result { + let response = self + .call(Method::DELETE, path, None, None, auth_override) + .await?; + Ok(response.is_some()) + } + + pub async fn ensure_tenant(&self, tenant: &str, quotas: Option) -> Result<()> { + let path = format!("/tenants/{}", encode_path_segment(tenant)); + if self.get_json(&path, None).await?.is_some() { + return Ok(()); + } + + let mut payload = json!({ "id": tenant }); + if let Some(quotas) = quotas + && let Some(obj) = payload.as_object_mut() + { + obj.insert("quotas".to_owned(), quotas); + } + + match self.post_json("/tenants", &payload, None).await { + Ok(_) => Ok(()), + Err(SpawnboxError::Api { status: 409, .. }) => Ok(()), + Err(err) => Err(err), + } + } + + pub async fn upsert_secret( + &self, + name: &str, + spec: &Value, + auth_override: Option<&str>, + ) -> Result<()> { + match self.post_json("/secrets", spec, auth_override).await { + Ok(_) => Ok(()), + Err(SpawnboxError::Api { status: 409, .. }) => { + let path = format!("/secrets/{}", encode_path_segment(name)); + self.patch_json(&path, spec, auth_override).await?; + Ok(()) + } + Err(err) => Err(err), + } + } + + pub async fn ensure_template( + &self, + name: &str, + spec: &Value, + poll_interval: Duration, + max_polls: usize, + ) -> Result { + let encoded_name = encode_path_segment(name); + let template_path = format!("/templates/{encoded_name}"); + + let mut build_id = None; + + if let Some(existing) = self.get_json(&template_path, None).await? { + if let Some(current) = non_empty_str(existing.get("current_build")) { + return Ok(current.to_owned()); + } + + if let Some(latest) = existing.get("latest_build") { + let state = latest.get("state").and_then(Value::as_str).unwrap_or(""); + if matches!(state, "queued" | "building") + && let Some(id) = non_empty_str(latest.get("id")) + { + build_id = Some(id.to_owned()); + } + } + } + + let build_id = match build_id { + Some(id) => id, + None => { + let created = self + .post_json("/templates", spec, None) + .await? + .unwrap_or(Value::Null); + let build = created.get("build"); + if let Some(id) = build + .and_then(|b| { + let ready = b.get("state").and_then(Value::as_str) == Some("ready"); + ready.then(|| non_empty_str(b.get("id"))).flatten() + }) + .or_else(|| { + non_empty_str(created.get("template").and_then(|t| t.get("current_build"))) + }) + { + return Ok(id.to_owned()); + } + + build + .and_then(|b| non_empty_str(b.get("id"))) + .or_else(|| { + created + .get("latest_build") + .and_then(|b| non_empty_str(b.get("id"))) + }) + .or_else(|| non_empty_str(created.get("current_build"))) + .or_else(|| non_empty_str(created.get("id"))) + .map(str::to_owned) + .ok_or_else(|| SpawnboxError::Api { + status: 500, + code: "missing_build_id".to_owned(), + message: format!( + "template {name:?} creation response did not contain a build id" + ), + })? + } + }; + + let build_path = format!( + "/templates/{encoded_name}/builds/{}", + encode_path_segment(&build_id) + ); + + for poll in 0..max_polls { + if poll > 0 { + tokio::time::sleep(poll_interval).await; + } + + let Some(build) = self.get_json(&build_path, None).await? else { + continue; + }; + + let state = build + .get("state") + .and_then(Value::as_str) + .unwrap_or("unknown"); + + match state { + "ready" => return Ok(build_id), + "queued" | "building" => {} + other => { + return Err(SpawnboxError::TemplateBuildFailed { + template: name.to_owned(), + state: other.to_owned(), + }); + } + } + } + + Err(SpawnboxError::Timeout(format!( + "template {name:?} build {build_id:?} did not become ready within {max_polls} polls" + ))) + } + + pub async fn create_sandbox(&self, spec: &Value) -> Result { + self.post_json("/sandboxes", spec, None) + .await? + .ok_or_else(|| SpawnboxError::Api { + status: 404, + code: "not_found".to_owned(), + message: "sandboxes endpoint returned 404".to_owned(), + }) + } + + pub async fn get_sandbox(&self, sandbox_id: &str) -> Result> { + let path = format!("/sandboxes/{}", encode_path_segment(sandbox_id)); + self.get_json(&path, None).await + } + + pub async fn list_sandboxes(&self) -> Result> { + let Some(value) = self.get_json("/sandboxes", None).await? else { + return Ok(Vec::new()); + }; + if let Some(items) = value.get("sandboxes").and_then(Value::as_array) { + return Ok(items.clone()); + } + if let Some(items) = value.as_array() { + return Ok(items.clone()); + } + Ok(Vec::new()) + } + + pub async fn delete_sandbox(&self, sandbox_id: &str) -> Result { + let path = format!("/sandboxes/{}", encode_path_segment(sandbox_id)); + self.delete(&path, None).await + } + + pub async fn exec(&self, sandbox_id: &str, spec: &Value) -> Result { + let path = format!("/sandboxes/{}/exec", encode_path_segment(sandbox_id)); + self.post_json(&path, spec, None) + .await? + .ok_or_else(|| SpawnboxError::Api { + status: 404, + code: "not_found".to_owned(), + message: format!("sandbox {sandbox_id:?} not found"), + }) + } +} + +#[derive(Clone, Debug)] +pub struct ForwardClient { + http: reqwest::Client, + forward_url: String, + forward_api_key: Option, +} + +impl ForwardClient { + pub fn new(forward_url: impl AsRef, forward_api_key: Option) -> Result { + let forward_url = normalize_http_url(forward_url.as_ref())?; + Ok(Self { + http: build_http_client()?, + forward_url, + forward_api_key, + }) + } + + pub fn forward_url(&self) -> &str { + &self.forward_url + } + + pub fn request( + &self, + method: Method, + sandbox_id: &str, + port: u16, + path: &str, + ) -> RequestBuilder { + let url = join_url(&self.forward_url, path); + let mut builder = self + .http + .request(method, url) + .header("X-Spawnbox-Sandbox", sandbox_id) + .header("X-Spawnbox-Port", port.to_string()); + if let Some(key) = self.forward_api_key.as_deref() + && !key.is_empty() + { + builder = builder.header("X-Spawnbox-Forward-Key", key); + } + builder + } +} + +pub fn encode_path_segment(segment: &str) -> String { + let mut out = String::with_capacity(segment.len()); + for byte in segment.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + out.push(char::from(byte)); + } else { + let _ = write!(out, "%{byte:02X}"); + } + } + out +} + +fn build_http_client() -> Result { + let _ = rustls::crypto::ring::default_provider().install_default(); + Ok(reqwest::Client::builder() + .user_agent(concat!("spawnbox-client/", env!("CARGO_PKG_VERSION"))) + .build()?) +} + +fn normalize_http_url(raw: &str) -> Result { + let trimmed = raw.trim().trim_end_matches('/'); + let parsed = + Url::parse(trimmed).map_err(|err| SpawnboxError::InvalidUrl(format!("{raw:?}: {err}")))?; + if !matches!(parsed.scheme(), "http" | "https") { + return Err(SpawnboxError::InvalidUrl(format!( + "{raw:?}: scheme must be http or https" + ))); + } + if parsed.host_str().is_none() { + return Err(SpawnboxError::InvalidUrl(format!("{raw:?}: missing host"))); + } + Ok(trimmed.to_owned()) +} + +fn join_url(base: &str, path: &str) -> String { + if path.is_empty() { + base.to_owned() + } else if path.starts_with('/') { + format!("{base}{path}") + } else { + format!("{base}/{path}") + } +} + +fn is_retryable_status(status: reqwest::StatusCode) -> bool { + matches!(status.as_u16(), 429 | 502 | 503 | 504) +} + +fn retry_delay(headers: &reqwest::header::HeaderMap, attempt: usize) -> Duration { + if let Some(secs) = headers + .get(reqwest::header::RETRY_AFTER) + .and_then(|v| v.to_str().ok()) + .and_then(|s| s.trim().parse::().ok()) + { + return Duration::from_secs(secs); + } + + let shift = u32::try_from(attempt).unwrap_or(u32::MAX).min(16); + let exp_ms = BASE_BACKOFF_MS + .saturating_mul(1u64 << shift) + .min(MAX_BACKOFF_MS); + let jitter_ms = rand::random::() % JITTER_MAX_MS; + Duration::from_millis(exp_ms.saturating_add(jitter_ms)) +} + +fn parse_api_error(status: reqwest::StatusCode, body: &[u8]) -> SpawnboxError { + let parsed: Option = serde_json::from_slice(body).ok(); + let error_obj = parsed.as_ref().and_then(|v| v.get("error")); + let field = |key: &str| { + error_obj + .and_then(|e| e.get(key)) + .and_then(Value::as_str) + .map(str::to_owned) + }; + + let code = field("code").unwrap_or_else(|| format!("http_{}", status.as_u16())); + let message = field("message").unwrap_or_else(|| { + let text = String::from_utf8_lossy(body).trim().to_owned(); + if text.is_empty() { + status.canonical_reason().unwrap_or("error").to_owned() + } else { + text + } + }); + + SpawnboxError::Api { + status: status.as_u16(), + code, + message, + } +} + +async fn read_json(response: Response) -> Result { + let body = response.bytes().await?; + if body.is_empty() { + return Ok(Value::Null); + } + Ok(serde_json::from_slice(&body)?) +} + +fn non_empty_str(value: Option<&Value>) -> Option<&str> { + value.and_then(Value::as_str).filter(|s| !s.is_empty()) +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + + use futures_util::StreamExt; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::TcpListener; + + use super::*; + + #[derive(Debug, Clone)] + struct RecordedRequest { + method: String, + path: String, + headers: HashMap, + body: String, + } + + struct MockResponse { + status: u16, + headers: Vec<(String, String)>, + body: Vec, + } + + impl MockResponse { + fn json(status: u16, value: Value) -> Self { + Self { + status, + headers: vec![("Content-Type".to_owned(), "application/json".to_owned())], + body: serde_json::to_vec(&value).unwrap(), + } + } + + fn with_header(mut self, name: &str, value: &str) -> Self { + self.headers.push((name.to_owned(), value.to_owned())); + self + } + } + + async fn spawn_mock_server(handler: F) -> (String, Arc>>) + where + F: Fn(&RecordedRequest, usize) -> MockResponse + Send + Sync + 'static, + { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let recorded = Arc::new(Mutex::new(Vec::new())); + let recorded_clone = Arc::clone(&recorded); + let handler = Arc::new(handler); + + tokio::spawn(async move { + let mut count = 0usize; + while let Ok((mut socket, _)) = listener.accept().await { + let req_index = count; + count += 1; + let recorded = Arc::clone(&recorded_clone); + let handler = Arc::clone(&handler); + tokio::spawn(async move { + let req = read_http_request(&mut socket).await; + recorded.lock().unwrap().push(req.clone()); + let resp = handler(&req, req_index); + write_http_response(&mut socket, resp).await; + }); + } + }); + + (format!("http://{addr}"), recorded) + } + + async fn read_http_request(socket: &mut tokio::net::TcpStream) -> RecordedRequest { + let mut buf = Vec::new(); + let mut tmp = [0u8; 4096]; + let header_end = loop { + let n = socket.read(&mut tmp).await.unwrap(); + assert!(n > 0, "unexpected EOF before headers"); + buf.extend_from_slice(&tmp[..n]); + if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + break pos + 4; + } + }; + + let header_text = String::from_utf8_lossy(&buf[..header_end]).into_owned(); + let mut lines = header_text.split("\r\n"); + let request_line = lines.next().unwrap(); + let mut parts = request_line.split_whitespace(); + let method = parts.next().unwrap().to_owned(); + let path = parts.next().unwrap().to_owned(); + + let mut headers = HashMap::new(); + for line in lines { + if let Some((k, v)) = line.split_once(':') { + headers.insert(k.trim().to_ascii_lowercase(), v.trim().to_owned()); + } + } + + let content_len = headers + .get("content-length") + .and_then(|v| v.parse::().ok()) + .unwrap_or(0); + + let mut body_bytes = buf[header_end..].to_vec(); + while body_bytes.len() < content_len { + let n = socket.read(&mut tmp).await.unwrap(); + if n == 0 { + break; + } + body_bytes.extend_from_slice(&tmp[..n]); + } + body_bytes.truncate(content_len); + + RecordedRequest { + method, + path, + headers, + body: String::from_utf8_lossy(&body_bytes).into_owned(), + } + } + + async fn write_http_response(socket: &mut tokio::net::TcpStream, resp: MockResponse) { + let reason = reqwest::StatusCode::from_u16(resp.status) + .ok() + .and_then(|s| s.canonical_reason()) + .unwrap_or("OK"); + let mut head = format!( + "HTTP/1.1 {} {}\r\nContent-Length: {}\r\nConnection: close\r\n", + resp.status, + reason, + resp.body.len() + ); + for (k, v) in resp.headers { + let _ = write!(head, "{k}: {v}\r\n"); + } + head.push_str("\r\n"); + socket.write_all(head.as_bytes()).await.unwrap(); + socket.write_all(&resp.body).await.unwrap(); + let _ = socket.shutdown().await; + } + + #[test] + fn url_validation_and_normalization() { + let client = SpawnboxClient::new("https://spawn.example.com///", "sk_test").unwrap(); + assert_eq!(client.base_url(), "https://spawn.example.com/v1"); + + let client_v1 = SpawnboxClient::new("http://127.0.0.1:8080/v1/", "sk_test").unwrap(); + assert_eq!(client_v1.base_url(), "http://127.0.0.1:8080/v1"); + + assert!(matches!( + SpawnboxClient::new("ftp://spawn.example.com", "sk_test"), + Err(SpawnboxError::InvalidUrl(_)) + )); + assert!(matches!( + SpawnboxClient::new("not a url", "sk_test"), + Err(SpawnboxError::InvalidUrl(_)) + )); + + let fwd = ForwardClient::new("http://127.0.0.1:8082/", None).unwrap(); + assert_eq!(fwd.forward_url(), "http://127.0.0.1:8082"); + + assert_eq!( + encode_path_segment("team/my secret+1"), + "team%2Fmy%20secret%2B1" + ); + } + + #[tokio::test] + async fn handles_404_as_none_and_retries_429_with_retry_after() { + let (url, recorded) = + spawn_mock_server( + |req, idx| match (req.method.as_str(), req.path.as_str(), idx) { + ("GET", "/v1/sandboxes/missing", _) => MockResponse::json( + 404, + json!({"error": {"code": "not_found", "message": "gone"}}), + ), + ("GET", "/v1/sandboxes/sbx_1", 1) => MockResponse::json( + 429, + json!({"error": {"code": "rate_limited", "message": "slow down"}}), + ) + .with_header("Retry-After", "0"), + ("GET", "/v1/sandboxes/sbx_1", _) => { + MockResponse::json(200, json!({"id": "sbx_1", "state": "running"})) + } + _ => MockResponse::json( + 500, + json!({"error": {"code": "unexpected", "message": "bad"}}), + ), + }, + ) + .await; + + let client = SpawnboxClient::new(url, "sk_live").unwrap(); + assert_eq!(client.get_sandbox("missing").await.unwrap(), None); + + let sandbox = client.get_sandbox("sbx_1").await.unwrap().unwrap(); + assert_eq!(sandbox["id"], "sbx_1"); + + let reqs = recorded.lock().unwrap(); + assert_eq!(reqs.len(), 3); + assert_eq!( + reqs[0].headers.get("authorization").map(String::as_str), + Some("Bearer sk_live") + ); + } + + #[tokio::test] + async fn upsert_secret_creates_and_falls_back_to_patch_on_409() { + let (url, recorded) = + spawn_mock_server( + |req, idx| match (req.method.as_str(), req.path.as_str(), idx) { + ("POST", "/v1/secrets", 0) => { + MockResponse::json(201, json!({"name": "api-key"})) + } + ("POST", "/v1/secrets", 1) => MockResponse::json( + 409, + json!({"error": {"code": "conflict", "message": "already exists"}}), + ), + ("PATCH", "/v1/secrets/api%2Fkey", 2) => { + MockResponse::json(200, json!({"name": "api/key"})) + } + _ => MockResponse::json( + 500, + json!({"error": {"code": "unexpected", "message": "bad"}}), + ), + }, + ) + .await; + + let client = SpawnboxClient::new(url, "sk_live").unwrap(); + client + .upsert_secret("api-key", &json!({"name": "api-key", "value": "v1"}), None) + .await + .unwrap(); + client + .upsert_secret( + "api/key", + &json!({"name": "api/key", "value": "v2"}), + Some("sk_override"), + ) + .await + .unwrap(); + + let reqs = recorded.lock().unwrap(); + assert_eq!(reqs.len(), 3); + assert_eq!(reqs[2].method, "PATCH"); + assert_eq!(reqs[2].path, "/v1/secrets/api%2Fkey"); + assert_eq!( + serde_json::from_str::(&reqs[2].body).unwrap(), + json!({"name": "api/key", "value": "v2"}) + ); + assert_eq!( + reqs[2].headers.get("authorization").map(String::as_str), + Some("Bearer sk_override") + ); + } + + #[tokio::test] + async fn ensure_template_returns_ready_or_creates_and_polls() { + let (url, recorded) = + spawn_mock_server( + |req, idx| match (req.method.as_str(), req.path.as_str(), idx) { + ("GET", "/v1/templates/ready-tpl", _) => MockResponse::json( + 200, + json!({"name": "ready-tpl", "current_build": "bld_existing"}), + ), + ("GET", "/v1/templates/new-tpl", _) => MockResponse::json( + 404, + json!({"error": {"code": "not_found", "message": "missing"}}), + ), + ("POST", "/v1/templates", _) => MockResponse::json( + 202, + json!({ + "template": {"name": "new-tpl", "current_build": null}, + "build": {"id": "bld_42", "state": "queued"} + }), + ), + ("GET", "/v1/templates/new-tpl/builds/bld_42", 3) => { + MockResponse::json(200, json!({"id": "bld_42", "state": "building"})) + } + ("GET", "/v1/templates/new-tpl/builds/bld_42", _) => { + MockResponse::json(200, json!({"id": "bld_42", "state": "ready"})) + } + _ => MockResponse::json( + 500, + json!({"error": {"code": "unexpected", "message": "bad"}}), + ), + }, + ) + .await; + + let client = SpawnboxClient::new(url, "sk_live").unwrap(); + + let existing = client + .ensure_template( + "ready-tpl", + &json!({"name": "ready-tpl"}), + Duration::from_millis(1), + 3, + ) + .await + .unwrap(); + assert_eq!(existing, "bld_existing"); + + let built = client + .ensure_template( + "new-tpl", + &json!({"name": "new-tpl"}), + Duration::from_millis(1), + 5, + ) + .await + .unwrap(); + assert_eq!(built, "bld_42"); + + let reqs = recorded.lock().unwrap(); + assert_eq!(reqs.len(), 5); + assert_eq!(reqs[2].method, "POST"); + assert_eq!(reqs[2].path, "/v1/templates"); + } + + #[tokio::test] + async fn forward_client_sets_headers_and_streams_response() { + let (url, recorded) = spawn_mock_server(|_req, _idx| MockResponse { + status: 200, + headers: vec![("Content-Type".to_owned(), "text/event-stream".to_owned())], + body: b"data: hello\n\ndata: world\n\n".to_vec(), + }) + .await; + + let forward = ForwardClient::new(url, Some("fwd_secret".to_owned())).unwrap(); + let response = forward + .request(Method::GET, "sbx_abc", 3000, "/events") + .header("Accept", "text/event-stream") + .send() + .await + .unwrap(); + + assert_eq!(response.status(), reqwest::StatusCode::OK); + let mut collected = Vec::new(); + let mut stream = response.bytes_stream(); + while let Some(chunk) = stream.next().await { + collected.extend_from_slice(&chunk.unwrap()); + } + assert_eq!(collected, b"data: hello\n\ndata: world\n\n"); + + let reqs = recorded.lock().unwrap(); + assert_eq!(reqs.len(), 1); + assert_eq!(reqs[0].path, "/events"); + assert_eq!( + reqs[0] + .headers + .get("x-spawnbox-sandbox") + .map(String::as_str), + Some("sbx_abc") + ); + assert_eq!( + reqs[0].headers.get("x-spawnbox-port").map(String::as_str), + Some("3000") + ); + assert_eq!( + reqs[0] + .headers + .get("x-spawnbox-forward-key") + .map(String::as_str), + Some("fwd_secret") + ); + } +} From 36c5d7d6b81005cb5d65efdc8868ea8a7eb13b4c Mon Sep 17 00:00:00 2001 From: Dhruv Jain Date: Mon, 30 Nov 2026 21:09:17 +0530 Subject: [PATCH 2/5] chore: add spawnbox-client release workflow, changelog, and crates.io metadata --- .github/workflows/release-client.yml | 76 ++++++++++++++++++++++++++++ crates/spawnbox-client/CHANGELOG.md | 14 +++++ crates/spawnbox-client/Cargo.toml | 7 ++- 3 files changed, 96 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/release-client.yml create mode 100644 crates/spawnbox-client/CHANGELOG.md diff --git a/.github/workflows/release-client.yml b/.github/workflows/release-client.yml new file mode 100644 index 0000000..8553b11 --- /dev/null +++ b/.github/workflows/release-client.yml @@ -0,0 +1,76 @@ +name: Release spawnbox-client + +# Tagging `spawnbox-client-vX.Y.Z` verifies the crate, publishes it to crates.io, +# and creates a GitHub Release with notes from `crates/spawnbox-client/CHANGELOG.md`. +# Running manually via workflow_dispatch performs a dry-run verification without publishing. +on: + push: + tags: ["spawnbox-client-v*"] + workflow_dispatch: + +permissions: + contents: read + +jobs: + release: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v7.0.1 + + - name: Install Rust toolchain + run: rustup toolchain install + + - name: Verify crate version matches tag + if: startsWith(github.ref, 'refs/tags/spawnbox-client-v') + run: | + tag_version="${GITHUB_REF_NAME#spawnbox-client-v}" + crate_version="$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "spawnbox-client") | .version')" + echo "tag=${tag_version} crate=${crate_version}" + test "$tag_version" = "$crate_version" + + - name: Check formatting, lints, and tests + run: | + cargo fmt --all -- --check + cargo clippy -p spawnbox-client --all-targets --locked -- -D warnings + cargo test -p spawnbox-client --locked + + - name: Dry-run package verification + run: cargo publish --dry-run -p spawnbox-client --locked + + - name: Publish to crates.io + if: startsWith(github.ref, 'refs/tags/spawnbox-client-v') + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + run: | + if [ -z "$CARGO_REGISTRY_TOKEN" ]; then + echo "CARGO_REGISTRY_TOKEN secret is not configured" >&2 + exit 1 + fi + cargo publish -p spawnbox-client --locked + + - name: Extract changelog notes + if: startsWith(github.ref, 'refs/tags/spawnbox-client-v') + run: | + version="${GITHUB_REF_NAME#spawnbox-client-v}" + awk -v ver="$version" ' + $0 ~ "^## \\[" ver "\\]" { in_section = 1; next } + in_section && /^## \[/ { exit } + in_section { print } + ' crates/spawnbox-client/CHANGELOG.md > release-notes.md + + - name: Create GitHub Release + if: startsWith(github.ref, 'refs/tags/spawnbox-client-v') + env: + GH_TOKEN: ${{ github.token }} + run: | + if [ -s release-notes.md ]; then + gh release create "$GITHUB_REF_NAME" \ + --title "spawnbox-client v${GITHUB_REF_NAME#spawnbox-client-v}" \ + --notes-file release-notes.md + else + gh release create "$GITHUB_REF_NAME" \ + --title "spawnbox-client v${GITHUB_REF_NAME#spawnbox-client-v}" \ + --generate-notes + fi diff --git a/crates/spawnbox-client/CHANGELOG.md b/crates/spawnbox-client/CHANGELOG.md new file mode 100644 index 0000000..efce67a --- /dev/null +++ b/crates/spawnbox-client/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +All notable changes to `spawnbox-client` are documented in this file. + +The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this crate adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.1.0] - 2026-11-30 + +### Added +- `SpawnboxClient` async HTTP client for the Spawnbox control plane (`/v1`) with validated base URLs, bearer token authentication, typed `SpawnboxError`, automatic retries on `429`/`502`/`503`/`504` (`Retry-After` and jittered exponential backoff), and `404` -> `Ok(None)` lookups. +- High-level helpers for tenants (`ensure_tenant`), secrets (`upsert_secret`), templates (`ensure_template`), sandboxes (`create_sandbox`, `get_sandbox`, `list_sandboxes`, `delete_sandbox`), and command execution (`exec`). +- `ForwardClient` for streaming HTTP/SSE proxying through Spawnbox's app-forward listener with `x-spawnbox-target` and optional shared-secret headers. +- `encode_path_segment` helper for safe URL path construction. diff --git a/crates/spawnbox-client/Cargo.toml b/crates/spawnbox-client/Cargo.toml index de235d7..7a7fa62 100644 --- a/crates/spawnbox-client/Cargo.toml +++ b/crates/spawnbox-client/Cargo.toml @@ -1,11 +1,16 @@ [package] name = "spawnbox-client" -version.workspace = true +version = "0.1.0" edition.workspace = true rust-version.workspace = true license.workspace = true repository.workspace = true +homepage = "https://github.com/TulipFarm/spawnbox" +documentation = "https://docs.rs/spawnbox-client" +readme = "README.md" description = "Async Rust HTTP client SDK for the self-hosted Spawnbox sandbox runtime" +keywords = ["spawnbox", "sandbox", "microvm", "firecracker", "sdk"] +categories = ["api-bindings", "asynchronous"] [lints] workspace = true From 72fa4901d57ffc378f9887bf4cfca60f81cd5175 Mon Sep 17 00:00:00 2001 From: Dhruv Jain Date: Mon, 30 Nov 2026 21:09:39 +0530 Subject: [PATCH 3/5] chore: remove redundant package.homepage from spawnbox-client --- crates/spawnbox-client/Cargo.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/spawnbox-client/Cargo.toml b/crates/spawnbox-client/Cargo.toml index 7a7fa62..d0e4bd2 100644 --- a/crates/spawnbox-client/Cargo.toml +++ b/crates/spawnbox-client/Cargo.toml @@ -5,7 +5,6 @@ edition.workspace = true rust-version.workspace = true license.workspace = true repository.workspace = true -homepage = "https://github.com/TulipFarm/spawnbox" documentation = "https://docs.rs/spawnbox-client" readme = "README.md" description = "Async Rust HTTP client SDK for the self-hosted Spawnbox sandbox runtime" From e97e7c01e320c8c20b590a064d515110a87e951a Mon Sep 17 00:00:00 2001 From: Dhruv Jain Date: Mon, 30 Nov 2026 21:12:22 +0530 Subject: [PATCH 4/5] chore: make release-client workflow manual dry-run for local publishing --- .github/workflows/release-client.yml | 56 ++-------------------------- 1 file changed, 3 insertions(+), 53 deletions(-) diff --git a/.github/workflows/release-client.yml b/.github/workflows/release-client.yml index 8553b11..a68b669 100644 --- a/.github/workflows/release-client.yml +++ b/.github/workflows/release-client.yml @@ -1,35 +1,21 @@ -name: Release spawnbox-client +name: Verify spawnbox-client release -# Tagging `spawnbox-client-vX.Y.Z` verifies the crate, publishes it to crates.io, -# and creates a GitHub Release with notes from `crates/spawnbox-client/CHANGELOG.md`. -# Running manually via workflow_dispatch performs a dry-run verification without publishing. +# Dry-run verification of the `spawnbox-client` crate before a local `cargo publish`. on: - push: - tags: ["spawnbox-client-v*"] workflow_dispatch: permissions: contents: read jobs: - release: + verify: runs-on: ubuntu-latest - permissions: - contents: write steps: - uses: actions/checkout@v7.0.1 - name: Install Rust toolchain run: rustup toolchain install - - name: Verify crate version matches tag - if: startsWith(github.ref, 'refs/tags/spawnbox-client-v') - run: | - tag_version="${GITHUB_REF_NAME#spawnbox-client-v}" - crate_version="$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "spawnbox-client") | .version')" - echo "tag=${tag_version} crate=${crate_version}" - test "$tag_version" = "$crate_version" - - name: Check formatting, lints, and tests run: | cargo fmt --all -- --check @@ -38,39 +24,3 @@ jobs: - name: Dry-run package verification run: cargo publish --dry-run -p spawnbox-client --locked - - - name: Publish to crates.io - if: startsWith(github.ref, 'refs/tags/spawnbox-client-v') - env: - CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} - run: | - if [ -z "$CARGO_REGISTRY_TOKEN" ]; then - echo "CARGO_REGISTRY_TOKEN secret is not configured" >&2 - exit 1 - fi - cargo publish -p spawnbox-client --locked - - - name: Extract changelog notes - if: startsWith(github.ref, 'refs/tags/spawnbox-client-v') - run: | - version="${GITHUB_REF_NAME#spawnbox-client-v}" - awk -v ver="$version" ' - $0 ~ "^## \\[" ver "\\]" { in_section = 1; next } - in_section && /^## \[/ { exit } - in_section { print } - ' crates/spawnbox-client/CHANGELOG.md > release-notes.md - - - name: Create GitHub Release - if: startsWith(github.ref, 'refs/tags/spawnbox-client-v') - env: - GH_TOKEN: ${{ github.token }} - run: | - if [ -s release-notes.md ]; then - gh release create "$GITHUB_REF_NAME" \ - --title "spawnbox-client v${GITHUB_REF_NAME#spawnbox-client-v}" \ - --notes-file release-notes.md - else - gh release create "$GITHUB_REF_NAME" \ - --title "spawnbox-client v${GITHUB_REF_NAME#spawnbox-client-v}" \ - --generate-notes - fi From d93ff85923148a5a0056f2a31ffa21b3803f522a Mon Sep 17 00:00:00 2001 From: Dhruv Jain Date: Mon, 30 Nov 2026 21:16:43 +0530 Subject: [PATCH 5/5] chore: rename SDK crate to spawnbox --- .github/workflows/release-client.yml | 10 ++++---- Cargo.lock | 24 +++++++++---------- Cargo.toml | 2 +- .../CHANGELOG.md | 2 +- .../{spawnbox-client => spawnbox}/Cargo.toml | 4 ++-- .../{spawnbox-client => spawnbox}/README.md | 6 ++--- .../{spawnbox-client => spawnbox}/src/lib.rs | 2 +- 7 files changed, 25 insertions(+), 25 deletions(-) rename crates/{spawnbox-client => spawnbox}/CHANGELOG.md (93%) rename crates/{spawnbox-client => spawnbox}/Cargo.toml (92%) rename crates/{spawnbox-client => spawnbox}/README.md (90%) rename crates/{spawnbox-client => spawnbox}/src/lib.rs (99%) diff --git a/.github/workflows/release-client.yml b/.github/workflows/release-client.yml index a68b669..a96ee35 100644 --- a/.github/workflows/release-client.yml +++ b/.github/workflows/release-client.yml @@ -1,6 +1,6 @@ -name: Verify spawnbox-client release +name: Verify spawnbox crate release -# Dry-run verification of the `spawnbox-client` crate before a local `cargo publish`. +# Dry-run verification of the `spawnbox` crate before a local `cargo publish`. on: workflow_dispatch: @@ -19,8 +19,8 @@ jobs: - name: Check formatting, lints, and tests run: | cargo fmt --all -- --check - cargo clippy -p spawnbox-client --all-targets --locked -- -D warnings - cargo test -p spawnbox-client --locked + cargo clippy -p spawnbox --all-targets --locked -- -D warnings + cargo test -p spawnbox --locked - name: Dry-run package verification - run: cargo publish --dry-run -p spawnbox-client --locked + run: cargo publish --dry-run -p spawnbox --locked diff --git a/Cargo.lock b/Cargo.lock index 8bb5e24..d9ad12d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2911,38 +2911,38 @@ dependencies = [ ] [[package]] -name = "spawnbox-cli" +name = "spawnbox" version = "0.1.0" dependencies = [ - "anyhow", - "clap", - "crossterm", + "bytes", "futures-util", - "libc", + "rand 0.10.3", "reqwest", - "rpassword", "rustls", - "rustls-platform-verifier", "serde", "serde_json", + "thiserror", "tokio", - "tokio-tungstenite 0.30.0", "url", ] [[package]] -name = "spawnbox-client" +name = "spawnbox-cli" version = "0.1.0" dependencies = [ - "bytes", + "anyhow", + "clap", + "crossterm", "futures-util", - "rand 0.10.3", + "libc", "reqwest", + "rpassword", "rustls", + "rustls-platform-verifier", "serde", "serde_json", - "thiserror", "tokio", + "tokio-tungstenite 0.30.0", "url", ] diff --git a/Cargo.toml b/Cargo.toml index 1c726a3..be4ad1b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/spawn-api","crates/spawn-bench","crates/spawn-egress","crates/spawn-guest","crates/spawn-node","crates/spawn-proto","crates/spawnbox-cli","crates/spawnbox-client"] +members = ["crates/spawn-api","crates/spawn-bench","crates/spawn-egress","crates/spawn-guest","crates/spawn-node","crates/spawn-proto","crates/spawnbox","crates/spawnbox-cli"] resolver = "3" [workspace.package] diff --git a/crates/spawnbox-client/CHANGELOG.md b/crates/spawnbox/CHANGELOG.md similarity index 93% rename from crates/spawnbox-client/CHANGELOG.md rename to crates/spawnbox/CHANGELOG.md index efce67a..c7527ac 100644 --- a/crates/spawnbox-client/CHANGELOG.md +++ b/crates/spawnbox/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -All notable changes to `spawnbox-client` are documented in this file. +All notable changes to `spawnbox` are documented in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this crate adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). diff --git a/crates/spawnbox-client/Cargo.toml b/crates/spawnbox/Cargo.toml similarity index 92% rename from crates/spawnbox-client/Cargo.toml rename to crates/spawnbox/Cargo.toml index d0e4bd2..e9d8802 100644 --- a/crates/spawnbox-client/Cargo.toml +++ b/crates/spawnbox/Cargo.toml @@ -1,11 +1,11 @@ [package] -name = "spawnbox-client" +name = "spawnbox" version = "0.1.0" edition.workspace = true rust-version.workspace = true license.workspace = true repository.workspace = true -documentation = "https://docs.rs/spawnbox-client" +documentation = "https://docs.rs/spawnbox" readme = "README.md" description = "Async Rust HTTP client SDK for the self-hosted Spawnbox sandbox runtime" keywords = ["spawnbox", "sandbox", "microvm", "firecracker", "sdk"] diff --git a/crates/spawnbox-client/README.md b/crates/spawnbox/README.md similarity index 90% rename from crates/spawnbox-client/README.md rename to crates/spawnbox/README.md index 4e315f4..5dd3940 100644 --- a/crates/spawnbox-client/README.md +++ b/crates/spawnbox/README.md @@ -1,4 +1,4 @@ -# spawnbox-client +# spawnbox Async Rust HTTP client SDK for the self-hosted Spawnbox sandbox runtime. @@ -7,10 +7,10 @@ Async Rust HTTP client SDK for the self-hosted Spawnbox sandbox runtime. ```rust,no_run use std::time::Duration; use serde_json::json; -use spawnbox_client::{ForwardClient, Method, SpawnboxClient}; +use spawnbox::{ForwardClient, Method, SpawnboxClient}; #[tokio::main] -async fn main() -> spawnbox_client::Result<()> { +async fn main() -> spawnbox::Result<()> { let client = SpawnboxClient::new("http://127.0.0.1:8080", "sbx_api_key")?; client.ensure_tenant("default", None).await?; diff --git a/crates/spawnbox-client/src/lib.rs b/crates/spawnbox/src/lib.rs similarity index 99% rename from crates/spawnbox-client/src/lib.rs rename to crates/spawnbox/src/lib.rs index 99beb9b..1c5daf5 100644 --- a/crates/spawnbox-client/src/lib.rs +++ b/crates/spawnbox/src/lib.rs @@ -426,7 +426,7 @@ pub fn encode_path_segment(segment: &str) -> String { fn build_http_client() -> Result { let _ = rustls::crypto::ring::default_provider().install_default(); Ok(reqwest::Client::builder() - .user_agent(concat!("spawnbox-client/", env!("CARGO_PKG_VERSION"))) + .user_agent(concat!("spawnbox/", env!("CARGO_PKG_VERSION"))) .build()?) }