Skip to main content

rexec/
client.rs

1//! Main Rexec client.
2
3use reqwest::{Client, Response};
4use std::sync::Arc;
5use url::Url;
6
7#[allow(deprecated)]
8use crate::containers::{ContainerService, SandboxService};
9use crate::error::{Error, Result};
10use crate::files::FileService;
11use crate::terminal::TerminalService;
12
13/// Configuration for the Rexec client.
14#[derive(Debug, Clone)]
15pub struct ClientConfig {
16    /// Base URL of the Rexec instance.
17    pub base_url: String,
18    /// API token for authentication.
19    pub token: String,
20    /// Request timeout in seconds.
21    pub timeout: u64,
22}
23
24impl ClientConfig {
25    /// Create a new client configuration.
26    pub fn new(base_url: impl Into<String>, token: impl Into<String>) -> Self {
27        Self {
28            base_url: base_url.into(),
29            token: token.into(),
30            timeout: 30,
31        }
32    }
33
34    /// Set the request timeout.
35    pub fn timeout(mut self, seconds: u64) -> Self {
36        self.timeout = seconds;
37        self
38    }
39}
40
41/// Internal client state shared between services.
42pub(crate) struct ClientInner {
43    pub(crate) http: Client,
44    pub(crate) base_url: String,
45    pub(crate) token: String,
46}
47
48impl ClientInner {
49    /// Make an API request and parse JSON response.
50    pub(crate) async fn request<T: serde::de::DeserializeOwned>(
51        &self,
52        method: reqwest::Method,
53        path: &str,
54    ) -> Result<T> {
55        let response = self.raw_request::<()>(method, path, None).await?;
56        self.handle_response(response).await
57    }
58
59    /// Make an API request with JSON body.
60    pub(crate) async fn request_with_body<T, B>(
61        &self,
62        method: reqwest::Method,
63        path: &str,
64        body: &B,
65    ) -> Result<T>
66    where
67        T: serde::de::DeserializeOwned,
68        B: serde::Serialize,
69    {
70        let response = self.raw_request(method, path, Some(body)).await?;
71        self.handle_response(response).await
72    }
73
74    /// Make an API request without expecting a response body.
75    pub(crate) async fn request_empty(
76        &self,
77        method: reqwest::Method,
78        path: &str,
79    ) -> Result<()> {
80        let response = self.raw_request::<()>(method, path, None).await?;
81        if response.status().is_success() {
82            Ok(())
83        } else {
84            self.handle_error(response).await
85        }
86    }
87
88    /// Make a raw API request.
89    pub(crate) async fn raw_request<B: serde::Serialize>(
90        &self,
91        method: reqwest::Method,
92        path: &str,
93        body: Option<&B>,
94    ) -> Result<Response> {
95        let url = format!("{}{}", self.base_url, path);
96
97        let mut builder = self
98            .http
99            .request(method, &url)
100            .header("Authorization", format!("Bearer {}", self.token))
101            .header("Accept", "application/json");
102
103        if let Some(b) = body {
104            builder = builder.json(b);
105        }
106
107        Ok(builder.send().await?)
108    }
109
110    /// Handle a successful response.
111    async fn handle_response<T: serde::de::DeserializeOwned>(
112        &self,
113        response: Response,
114    ) -> Result<T> {
115        if response.status().is_success() {
116            Ok(response.json().await?)
117        } else {
118            self.handle_error(response).await
119        }
120    }
121
122    /// Handle an error response.
123    async fn handle_error<T>(&self, response: Response) -> Result<T> {
124        let status = response.status().as_u16();
125        let message = response
126            .json::<serde_json::Value>()
127            .await
128            .ok()
129            .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(String::from))
130            .unwrap_or_else(|| "Unknown error".into());
131
132        Err(Error::api(status, message))
133    }
134
135    /// Get WebSocket URL for a path.
136    pub(crate) fn ws_url(&self, path: &str) -> Result<String> {
137        let url = Url::parse(&self.base_url)?;
138        let ws_scheme = if url.scheme() == "https" { "wss" } else { "ws" };
139        let host = url.host_str().ok_or_else(|| Error::connection("Invalid host"))?;
140        let port = url.port().map(|p| format!(":{}", p)).unwrap_or_default();
141        Ok(format!("{}://{}{}{}", ws_scheme, host, port, path))
142    }
143}
144
145/// Main client for interacting with Rexec API.
146///
147/// # Example
148///
149/// ```rust,no_run
150/// use rexec::RexecClient;
151///
152/// #[tokio::main]
153/// async fn main() -> Result<(), rexec::Error> {
154///     let client = RexecClient::new("https://your-instance.com", "your-token");
155///     
156///     let sandboxes = client.sandboxes().list().await?;
157///     for c in sandboxes {
158///         println!("{}: {}", c.name, c.status);
159///     }
160///     
161///     Ok(())
162/// }
163/// ```
164#[derive(Clone)]
165pub struct RexecClient {
166    inner: Arc<ClientInner>,
167}
168
169impl RexecClient {
170    /// Create a new Rexec client.
171    ///
172    /// # Arguments
173    ///
174    /// * `base_url` - Base URL of your Rexec instance
175    /// * `token` - API token for authentication
176    pub fn new(base_url: impl Into<String>, token: impl Into<String>) -> Self {
177        Self::with_config(ClientConfig::new(base_url, token))
178    }
179
180    /// Create a new Rexec client with custom configuration.
181    pub fn with_config(config: ClientConfig) -> Self {
182        let http = Client::builder()
183            .timeout(std::time::Duration::from_secs(config.timeout))
184            .build()
185            .expect("Failed to create HTTP client");
186
187        let inner = Arc::new(ClientInner {
188            http,
189            base_url: config.base_url.trim_end_matches('/').to_string(),
190            token: config.token,
191        });
192
193        Self { inner }
194    }
195
196    /// Get the sandbox service (preferred).
197    pub fn sandboxes(&self) -> SandboxService {
198        SandboxService::new(self.inner.clone())
199    }
200
201    /// Get the sandbox service.
202    ///
203    /// Deprecated: use [`sandboxes`](Self::sandboxes).
204    #[deprecated(since = "1.1.0", note = "use sandboxes()")]
205    #[allow(deprecated)]
206    pub fn containers(&self) -> ContainerService {
207        self.sandboxes()
208    }
209
210    /// Get the file service.
211    pub fn files(&self) -> FileService {
212        FileService::new(self.inner.clone())
213    }
214
215    /// Get the terminal service.
216    pub fn terminal(&self) -> TerminalService {
217        TerminalService::new(self.inner.clone())
218    }
219}