use std::time::Duration;
use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderValue};
use crate::error::TesseraError;
pub const DEFAULT_BASE_URL: &str = "https://tesseralytics.dev";
pub const API_KEY_ENV_VAR: &str = "TESSERA_API_KEY";
pub const USER_AGENT: &str = concat!("tessera-rust/", env!("CARGO_PKG_VERSION"));
pub(crate) const RETRYABLE: &[u16] = &[429, 500, 502, 503, 504];
pub fn resolve_api_key(api_key: Option<&str>) -> Result<String, TesseraError> {
api_key
.map(str::to_string)
.or_else(|| std::env::var(API_KEY_ENV_VAR).ok())
.filter(|key| !key.is_empty())
.ok_or_else(|| {
TesseraError::Configuration(
"No API key provided. Pass api_key=... or set the TESSERA_API_KEY environment variable. Get a free key at https://tesseralytics.dev.".to_string(),
)
})
}
#[must_use]
pub fn backoff_delay(attempt: u32, retry_after: Option<f64>) -> Duration {
if let Some(seconds) = retry_after.filter(|s| *s >= 0.0) {
return Duration::from_secs_f64(seconds);
}
let base = 0.5 * 2f64.powi(i32::try_from(attempt).unwrap_or(63));
Duration::from_secs_f64(fastrand::f64() * base)
}
#[derive(Debug, Clone)]
pub struct ClientConfig {
pub api_key: String,
pub base_url: String,
pub timeout: Duration,
pub max_retries: u32,
pub user_agent: String,
}
impl ClientConfig {
pub fn new(api_key: Option<&str>) -> Result<Self, TesseraError> {
Ok(Self {
api_key: resolve_api_key(api_key)?,
base_url: DEFAULT_BASE_URL.to_string(),
timeout: Duration::from_secs(30),
max_retries: 3,
user_agent: USER_AGENT.to_string(),
})
}
#[must_use]
pub fn auth_headers(&self) -> HeaderMap {
let mut headers = HeaderMap::new();
if let Ok(value) = HeaderValue::from_str(&format!("Bearer {}", self.api_key)) {
headers.insert(AUTHORIZATION, value);
}
if let Ok(value) = HeaderValue::from_str(&self.user_agent) {
headers.insert(reqwest::header::USER_AGENT, value);
}
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
headers
}
}