Skip to main content

rexec/
client.rs

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