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<T> = std::result::Result<T, SpawnboxError>;
#[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<str>, api_key: impl Into<String>) -> Result<Self> {
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<Bytes>,
content_type: Option<&str>,
auth_override: Option<&str>,
) -> Result<Option<Response>> {
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<Option<Value>> {
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<Option<Value>> {
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<Option<Value>> {
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<Option<Value>> {
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<Option<Value>> {
self.send_json(Method::PATCH, path, body, auth_override)
.await
}
pub async fn delete(&self, path: &str, auth_override: Option<&str>) -> Result<bool> {
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<Value>) -> 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<String> {
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<Value> {
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<Option<Value>> {
let path = format!("/sandboxes/{}", encode_path_segment(sandbox_id));
self.get_json(&path, None).await
}
pub async fn list_sandboxes(&self) -> Result<Vec<Value>> {
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<bool> {
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<Value> {
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<String>,
}
impl ForwardClient {
pub fn new(forward_url: impl AsRef<str>, forward_api_key: Option<String>) -> Result<Self> {
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-target", format!("{sandbox_id}:{port}"));
if let Some(key) = self.forward_api_key.as_deref()
&& !key.is_empty()
{
builder = builder.header("x-spawnbox-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<reqwest::Client> {
let _ = rustls::crypto::ring::default_provider().install_default();
Ok(reqwest::Client::builder()
.user_agent(concat!("spawnbox/", env!("CARGO_PKG_VERSION")))
.build()?)
}
fn normalize_http_url(raw: &str) -> Result<String> {
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::<u64>().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::<u64>() % 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<Value> = 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<Value> {
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<String, String>,
body: String,
}
struct MockResponse {
status: u16,
headers: Vec<(String, String)>,
body: Vec<u8>,
}
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<F>(handler: F) -> (String, Arc<Mutex<Vec<RecordedRequest>>>)
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::<usize>().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::<Value>(&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-target").map(String::as_str),
Some("sbx_abc:3000")
);
assert_eq!(
reqs[0].headers.get("x-spawnbox-key").map(String::as_str),
Some("fwd_secret")
);
}
}