use crate::auth;
use crate::http::HttpClient;
use crate::urls::backend_url_base;
use crate::CoreError;
use super::eval::EvalClient;
use super::graph_evolve::GraphEvolveClient;
use super::graphs::GraphsClient;
use super::inference::InferenceClient;
use super::jobs::JobsClient;
use super::container::ContainerDeployClient;
pub const DEFAULT_BACKEND_URL: &str = crate::urls::DEFAULT_BACKEND_URL;
pub const DEFAULT_TIMEOUT_SECS: u64 = 120;
pub struct SynthClient {
pub(crate) http: HttpClient,
pub(crate) base_url: String,
}
impl SynthClient {
pub fn new(api_key: &str, base_url: Option<&str>) -> Result<Self, CoreError> {
let base_url = base_url
.map(|url| url.to_string())
.unwrap_or_else(backend_url_base);
let http = HttpClient::new(&base_url, api_key, DEFAULT_TIMEOUT_SECS)
.map_err(|e| CoreError::Internal(format!("failed to create HTTP client: {}", e)))?;
Ok(Self { http, base_url })
}
pub fn with_timeout(
api_key: &str,
base_url: Option<&str>,
timeout_secs: u64,
) -> Result<Self, CoreError> {
let base_url = base_url
.map(|url| url.to_string())
.unwrap_or_else(backend_url_base);
let http = HttpClient::new(&base_url, api_key, timeout_secs)
.map_err(|e| CoreError::Internal(format!("failed to create HTTP client: {}", e)))?;
Ok(Self { http, base_url })
}
pub fn from_env() -> Result<Self, CoreError> {
let api_key = auth::get_api_key(None).ok_or_else(|| {
CoreError::Authentication("SYNTH_API_KEY environment variable not set".to_string())
})?;
let base_url = std::env::var("SYNTH_BACKEND_URL").ok();
Self::new(&api_key, base_url.as_deref())
}
pub async fn from_env_or_mint(
allow_mint: bool,
base_url: Option<&str>,
) -> Result<Self, CoreError> {
let api_key = auth::get_or_mint_api_key(base_url, allow_mint).await?;
Self::new(&api_key, base_url)
}
pub fn base_url(&self) -> &str {
&self.base_url
}
pub fn http(&self) -> &HttpClient {
&self.http
}
pub fn jobs(&self) -> JobsClient<'_> {
JobsClient::new(self)
}
pub fn eval(&self) -> EvalClient<'_> {
EvalClient::new(self)
}
pub fn graphs(&self) -> GraphsClient<'_> {
GraphsClient::new(self)
}
pub fn graph_evolve(&self) -> GraphEvolveClient<'_> {
GraphEvolveClient::new(self)
}
pub fn inference(&self) -> InferenceClient<'_> {
InferenceClient::new(&self.http)
}
pub fn container(&self) -> ContainerDeployClient<'_> {
ContainerDeployClient::new(self)
}
}
impl std::fmt::Debug for SynthClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SynthClient")
.field("base_url", &self.base_url)
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_backend_url() {
assert_eq!(DEFAULT_BACKEND_URL, crate::urls::DEFAULT_BACKEND_URL);
}
}