1use 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#[derive(Debug, Clone)]
14pub struct ClientConfig {
15 pub base_url: String,
17 pub token: String,
19 pub timeout: u64,
21}
22
23impl ClientConfig {
24 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 pub fn timeout(mut self, seconds: u64) -> Self {
35 self.timeout = seconds;
36 self
37 }
38}
39
40pub(crate) struct ClientInner {
42 pub(crate) http: Client,
43 pub(crate) base_url: String,
44 pub(crate) token: String,
45}
46
47impl ClientInner {
48 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 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 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 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 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 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 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#[derive(Clone)]
164pub struct RexecClient {
165 inner: Arc<ClientInner>,
166}
167
168impl RexecClient {
169 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 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 pub fn containers(&self) -> ContainerService {
197 ContainerService::new(self.inner.clone())
198 }
199
200 pub fn files(&self) -> FileService {
202 FileService::new(self.inner.clone())
203 }
204
205 pub fn terminal(&self) -> TerminalService {
207 TerminalService::new(self.inner.clone())
208 }
209}