use reqwest::{Client, Response};
use std::sync::Arc;
use url::Url;
#[allow(deprecated)]
use crate::containers::{ContainerService, SandboxService};
use crate::error::{Error, Result};
use crate::files::FileService;
use crate::terminal::TerminalService;
#[derive(Debug, Clone)]
pub struct ClientConfig {
pub base_url: String,
pub token: String,
pub timeout: u64,
}
impl ClientConfig {
pub fn new(base_url: impl Into<String>, token: impl Into<String>) -> Self {
Self {
base_url: base_url.into(),
token: token.into(),
timeout: 30,
}
}
pub fn timeout(mut self, seconds: u64) -> Self {
self.timeout = seconds;
self
}
}
pub(crate) struct ClientInner {
pub(crate) http: Client,
pub(crate) base_url: String,
pub(crate) token: String,
}
impl ClientInner {
pub(crate) async fn request<T: serde::de::DeserializeOwned>(
&self,
method: reqwest::Method,
path: &str,
) -> Result<T> {
let response = self.raw_request::<()>(method, path, None).await?;
self.handle_response(response).await
}
pub(crate) async fn request_with_body<T, B>(
&self,
method: reqwest::Method,
path: &str,
body: &B,
) -> Result<T>
where
T: serde::de::DeserializeOwned,
B: serde::Serialize,
{
let response = self.raw_request(method, path, Some(body)).await?;
self.handle_response(response).await
}
pub(crate) async fn request_empty(
&self,
method: reqwest::Method,
path: &str,
) -> Result<()> {
let response = self.raw_request::<()>(method, path, None).await?;
if response.status().is_success() {
Ok(())
} else {
self.handle_error(response).await
}
}
pub(crate) async fn raw_request<B: serde::Serialize>(
&self,
method: reqwest::Method,
path: &str,
body: Option<&B>,
) -> Result<Response> {
let url = format!("{}{}", self.base_url, path);
let mut builder = self
.http
.request(method, &url)
.header("Authorization", format!("Bearer {}", self.token))
.header("Accept", "application/json");
if let Some(b) = body {
builder = builder.json(b);
}
Ok(builder.send().await?)
}
async fn handle_response<T: serde::de::DeserializeOwned>(
&self,
response: Response,
) -> Result<T> {
if response.status().is_success() {
Ok(response.json().await?)
} else {
self.handle_error(response).await
}
}
async fn handle_error<T>(&self, response: Response) -> Result<T> {
let status = response.status().as_u16();
let message = response
.json::<serde_json::Value>()
.await
.ok()
.and_then(|v| v.get("error").and_then(|e| e.as_str()).map(String::from))
.unwrap_or_else(|| "Unknown error".into());
Err(Error::api(status, message))
}
pub(crate) fn ws_url(&self, path: &str) -> Result<String> {
let url = Url::parse(&self.base_url)?;
let ws_scheme = if url.scheme() == "https" { "wss" } else { "ws" };
let host = url.host_str().ok_or_else(|| Error::connection("Invalid host"))?;
let port = url.port().map(|p| format!(":{}", p)).unwrap_or_default();
Ok(format!("{}://{}{}{}", ws_scheme, host, port, path))
}
}
#[derive(Clone)]
pub struct RexecClient {
inner: Arc<ClientInner>,
}
impl RexecClient {
pub fn new(base_url: impl Into<String>, token: impl Into<String>) -> Self {
Self::with_config(ClientConfig::new(base_url, token))
}
pub fn with_config(config: ClientConfig) -> Self {
let http = Client::builder()
.timeout(std::time::Duration::from_secs(config.timeout))
.build()
.expect("Failed to create HTTP client");
let inner = Arc::new(ClientInner {
http,
base_url: config.base_url.trim_end_matches('/').to_string(),
token: config.token,
});
Self { inner }
}
pub fn sandboxes(&self) -> SandboxService {
SandboxService::new(self.inner.clone())
}
#[deprecated(since = "1.1.0", note = "use sandboxes()")]
#[allow(deprecated)]
pub fn containers(&self) -> ContainerService {
self.sandboxes()
}
pub fn files(&self) -> FileService {
FileService::new(self.inner.clone())
}
pub fn terminal(&self) -> TerminalService {
TerminalService::new(self.inner.clone())
}
}