| 1 | //! Alibaba OpenSandbox backend adapter. |
| 2 | //! |
| 3 | //! Sends shell commands to an OpenSandbox-compatible HTTP API for remote |
| 4 | //! execution. The API endpoint is `POST {base_url}/v1/sandbox/run` with |
| 5 | //! JSON body `{"cmd": "...", "env": {...}}` and expects a JSON response |
| 6 | //! `{"stdout": "...", "stderr": "...", "exit_code": 0}`. |
| 7 | |
| 8 | use std::collections::HashMap; |
| 9 | use std::time::Duration; |
| 10 | |
| 11 | use anyhow::{Context, Result}; |
| 12 | use async_trait::async_trait; |
| 13 | use serde::Deserialize; |
| 14 | use serde::Serialize; |
| 15 | |
| 16 | use super::backend::{SandboxBackend, SandboxKind, SandboxOutput}; |
| 17 | |
| 18 | const RESPONSE_MAX_BYTES: usize = 8 * 1024 * 1024; |
| 19 | |
| 20 | /// Request body sent to the OpenSandbox `/v1/sandbox/run` endpoint. |
| 21 | #[derive(Debug, Serialize)] |
| 22 | struct SandboxRunRequest { |
| 23 | /// Full shell command to execute. |
| 24 | cmd: String, |
| 25 | /// Environment variables to set in the sandbox. |
| 26 | env: HashMap<String, String>, |
| 27 | } |
| 28 | |
| 29 | /// Response body from the OpenSandbox `/v1/sandbox/run` endpoint. |
| 30 | #[derive(Debug, Deserialize)] |
| 31 | struct SandboxRunResponse { |
| 32 | /// Standard output from the command. |
| 33 | stdout: String, |
| 34 | /// Standard error from the command. |
| 35 | stderr: String, |
| 36 | /// Exit code (0 for success). |
| 37 | exit_code: i32, |
| 38 | } |
| 39 | |
| 40 | /// An OpenSandbox-compatible remote execution backend. |
| 41 | /// |
| 42 | /// Constructed with a base URL (e.g. `"http://localhost:8080"`), an optional |
| 43 | /// API key sent as a `Bearer` token, and a timeout in seconds. |
| 44 | pub struct OpenSandboxBackend { |
| 45 | base_url: String, |
| 46 | api_key: Option<String>, |
| 47 | client: reqwest::Client, |
| 48 | } |
| 49 | |
| 50 | impl OpenSandboxBackend { |
| 51 | /// Create a new OpenSandbox backend. |
| 52 | /// |
| 53 | /// `base_url` should be the root of the OpenSandbox API (e.g. |
| 54 | /// `"http://localhost:8080"`). `api_key` is optional and sent as |
| 55 | /// `Authorization: Bearer <key>` when set. `timeout_secs` controls the |
| 56 | /// HTTP request timeout. |
| 57 | pub fn new(base_url: String, api_key: Option<String>, timeout_secs: u64) -> Result<Self> { |
| 58 | let client = codewhale_release::tls::reqwest_client_builder() |
| 59 | .timeout(Duration::from_secs(timeout_secs)) |
| 60 | .build() |
| 61 | .context("failed to construct HTTP client for OpenSandbox backend")?; |
| 62 | |
| 63 | Ok(Self { |
| 64 | base_url, |
| 65 | api_key, |
| 66 | client, |
| 67 | }) |
| 68 | } |
| 69 | |
| 70 | /// Build the full URL for the sandbox run endpoint. |
| 71 | fn run_url(&self) -> String { |
| 72 | format!("{}/v1/sandbox/run", self.base_url.trim_end_matches('/')) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | #[async_trait] |
| 77 | impl SandboxBackend for OpenSandboxBackend { |
| 78 | fn kind(&self) -> SandboxKind { |
| 79 | SandboxKind::OpenSandbox |
| 80 | } |
| 81 | |
| 82 | async fn exec(&self, cmd: &str, env: &HashMap<String, String>) -> Result<SandboxOutput> { |
| 83 | let request_body = SandboxRunRequest { |
| 84 | cmd: cmd.to_string(), |
| 85 | env: env.clone(), |
| 86 | }; |
| 87 | |
| 88 | let mut req = self.client.post(self.run_url()).json(&request_body); |
| 89 | |
| 90 | if let Some(ref api_key) = self.api_key { |
| 91 | req = req.bearer_auth(api_key); |
| 92 | } |
| 93 | |
| 94 | let response = req |
| 95 | .send() |
| 96 | .await |
| 97 | .context("Failed to reach OpenSandbox endpoint")?; |
| 98 | |
| 99 | let status = response.status(); |
| 100 | let body = codewhale_release::read_http_response(response, RESPONSE_MAX_BYTES) |
| 101 | .await |
| 102 | .context("Failed to read OpenSandbox response")?; |
| 103 | if !status.is_success() { |
| 104 | anyhow::bail!( |
| 105 | "OpenSandbox returned HTTP {}: {}", |
| 106 | status.as_u16(), |
| 107 | String::from_utf8_lossy(&body) |
| 108 | ); |
| 109 | } |
| 110 | |
| 111 | let parsed: SandboxRunResponse = serde_json::from_slice(&body).map_err(|error| { |
| 112 | anyhow::anyhow!( |
| 113 | "Failed to parse OpenSandbox response at line {}, column {}: {error}", |
| 114 | error.line(), |
| 115 | error.column() |
| 116 | ) |
| 117 | })?; |
| 118 | |
| 119 | Ok(SandboxOutput { |
| 120 | stdout: parsed.stdout, |
| 121 | stderr: parsed.stderr, |
| 122 | exit_code: parsed.exit_code, |
| 123 | }) |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | #[cfg(test)] |
| 128 | mod tests { |
| 129 | use super::*; |
| 130 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 131 | |
| 132 | #[tokio::test] |
| 133 | async fn exec_parse_error_preserves_serde_cause() { |
| 134 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 135 | let addr = listener.local_addr().unwrap(); |
| 136 | let server = tokio::spawn(async move { |
| 137 | let (mut socket, _) = listener.accept().await.unwrap(); |
| 138 | let mut req = Vec::new(); |
| 139 | let mut buf = [0u8; 1024]; |
| 140 | while let Ok(n) = socket.read(&mut buf).await { |
| 141 | if n == 0 { |
| 142 | break; |
| 143 | } |
| 144 | req.extend_from_slice(&buf[..n]); |
| 145 | if req.windows(4).any(|w| w == b"\r\n\r\n") { |
| 146 | break; |
| 147 | } |
| 148 | } |
| 149 | let body = r#"{"stdout":"ok"}"#; |
| 150 | let resp = format!( |
| 151 | "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", |
| 152 | body.len(), |
| 153 | body |
| 154 | ); |
| 155 | let _ = socket.write_all(resp.as_bytes()).await; |
| 156 | }); |
| 157 | |
| 158 | let backend = OpenSandboxBackend::new(format!("http://{addr}"), None, 5).unwrap(); |
| 159 | let err = backend.exec("echo ok", &HashMap::new()).await.unwrap_err(); |
| 160 | let msg = err.to_string(); |
| 161 | assert!( |
| 162 | msg.contains("Failed to parse OpenSandbox response at line"), |
| 163 | "unexpected error: {msg}" |
| 164 | ); |
| 165 | assert!( |
| 166 | msg.contains("missing field") && msg.contains("stderr"), |
| 167 | "expected serde cause in error, got: {msg}" |
| 168 | ); |
| 169 | let _ = server.await; |
| 170 | } |
| 171 | } |
| 172 |