1use 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#[derive(Debug, Clone)]
15pub struct ClientConfig {
16 pub base_url: String,
18 pub token: String,
20 pub timeout: u64,
22}
23
24impl ClientConfig {
25 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 pub fn timeout(mut self, seconds: u64) -> Self {
36 self.timeout = seconds;
37 self
38 }
39}
40
41pub(crate) struct ClientInner {
43 pub(crate) http: Client,
44 pub(crate) base_url: String,
45 pub(crate) token: String,
46}
47
48impl ClientInner {
49 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 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 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 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 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 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 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#[derive(Clone)]
165pub struct RexecClient {
166 inner: Arc<ClientInner>,
167}
168
169impl RexecClient {
170 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 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 pub fn sandboxes(&self) -> SandboxService {
198 SandboxService::new(self.inner.clone())
199 }
200
201 #[deprecated(since = "1.1.0", note = "use sandboxes()")]
205 #[allow(deprecated)]
206 pub fn containers(&self) -> ContainerService {
207 self.sandboxes()
208 }
209
210 pub fn files(&self) -> FileService {
212 FileService::new(self.inner.clone())
213 }
214
215 pub fn terminal(&self) -> TerminalService {
217 TerminalService::new(self.inner.clone())
218 }
219}