use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use url::Url;
use super::env::EnvReader;
use super::error::{Error, Result};
use super::hooks::Hooks;
use super::redact::{redact_headers, redact_url};
use super::retry::RetryPolicy;
pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
pub const DEFAULT_TOTAL_TIMEOUT: Duration = Duration::from_secs(120);
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TlsConfig {
pub ca_cert_path: Option<PathBuf>,
pub ca_cert_pem: Option<String>,
pub client_cert_path: Option<PathBuf>,
pub client_key_path: Option<PathBuf>,
pub insecure_skip_verify: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct VendorEnv<'a> {
pub url: &'a [&'a str],
pub ca_cert: &'a [&'a str],
pub client_cert: &'a [&'a str],
pub client_key: &'a [&'a str],
pub insecure_skip_verify: &'a [&'a str],
pub proxy: &'a [&'a str],
}
impl VendorEnv<'static> {
pub const NONE: VendorEnv<'static> = VendorEnv {
url: &[],
ca_cert: &[],
client_cert: &[],
client_key: &[],
insecure_skip_verify: &[],
proxy: &[],
};
}
impl<'a> VendorEnv<'a> {
pub const fn url_only(url: &'a [&'a str]) -> Self {
VendorEnv {
url,
ca_cert: &[],
client_cert: &[],
client_key: &[],
insecure_skip_verify: &[],
proxy: &[],
}
}
}
#[derive(Clone)]
pub struct CommonConfig {
url: Url,
connect_timeout: Duration,
request_timeout: Duration,
total_timeout: Duration,
retry: RetryPolicy,
tls: TlsConfig,
proxy: Option<String>,
headers: Vec<(String, String)>,
user_agent_suffix: Option<String>,
hooks: Option<Arc<dyn Hooks>>,
}
impl CommonConfig {
pub fn builder() -> CommonConfigBuilder {
CommonConfigBuilder::default()
}
pub fn url(&self) -> &Url {
&self.url
}
pub fn connect_timeout(&self) -> Duration {
self.connect_timeout
}
pub fn request_timeout(&self) -> Duration {
self.request_timeout
}
pub fn total_timeout(&self) -> Duration {
self.total_timeout
}
pub fn retry(&self) -> &RetryPolicy {
&self.retry
}
pub fn tls(&self) -> &TlsConfig {
&self.tls
}
pub fn proxy(&self) -> Option<&str> {
self.proxy.as_deref()
}
pub fn headers(&self) -> &[(String, String)] {
&self.headers
}
pub fn user_agent_suffix(&self) -> Option<&str> {
self.user_agent_suffix.as_deref()
}
pub fn hooks(&self) -> Option<&Arc<dyn Hooks>> {
self.hooks.as_ref()
}
pub fn to_builder(&self) -> CommonConfigBuilder {
CommonConfigBuilder {
url: Some(self.url.as_str().to_owned()),
connect_timeout: Some(self.connect_timeout),
request_timeout: Some(self.request_timeout),
total_timeout: Some(self.total_timeout),
retry: Some(self.retry.clone()),
max_retries: None,
tls: self.tls.clone(),
insecure_skip_verify: Some(self.tls.insecure_skip_verify),
proxy: self.proxy.clone(),
headers: self.headers.clone(),
user_agent_suffix: self.user_agent_suffix.clone(),
hooks: self.hooks.clone(),
}
}
}
impl fmt::Debug for CommonConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CommonConfig")
.field("url", &redact_url(self.url.as_str()))
.field("connect_timeout", &self.connect_timeout)
.field("request_timeout", &self.request_timeout)
.field("total_timeout", &self.total_timeout)
.field("retry", &self.retry)
.field("tls", &self.tls)
.field("proxy", &self.proxy.as_deref().map(redact_url))
.field(
"headers",
&redact_headers(self.headers.iter().map(|(k, v)| (k, v))),
)
.field("user_agent_suffix", &self.user_agent_suffix)
.field("hooks", &self.hooks.as_ref().map(|_| "Hooks"))
.finish()
}
}
#[derive(Clone, Default)]
pub struct CommonConfigBuilder {
url: Option<String>,
connect_timeout: Option<Duration>,
request_timeout: Option<Duration>,
total_timeout: Option<Duration>,
retry: Option<RetryPolicy>,
max_retries: Option<u32>,
tls: TlsConfig,
insecure_skip_verify: Option<bool>,
proxy: Option<String>,
headers: Vec<(String, String)>,
user_agent_suffix: Option<String>,
hooks: Option<Arc<dyn Hooks>>,
}
impl fmt::Debug for CommonConfigBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CommonConfigBuilder")
.field("url", &self.url.as_deref().map(redact_url))
.finish_non_exhaustive()
}
}
impl CommonConfigBuilder {
pub fn url(mut self, url: impl Into<String>) -> Self {
self.url = Some(url.into());
self
}
pub fn connect_timeout(mut self, timeout: Duration) -> Self {
self.connect_timeout = Some(timeout);
self
}
pub fn request_timeout(mut self, timeout: Duration) -> Self {
self.request_timeout = Some(timeout);
self
}
pub fn total_timeout(mut self, timeout: Duration) -> Self {
self.total_timeout = Some(timeout);
self
}
pub fn retry(mut self, retry: RetryPolicy) -> Self {
self.retry = Some(retry);
self
}
pub fn max_retries(mut self, max_retries: u32) -> Self {
self.max_retries = Some(max_retries);
self
}
pub fn tls(mut self, tls: TlsConfig) -> Self {
if tls.insecure_skip_verify {
self.insecure_skip_verify = Some(true);
}
self.tls = tls;
self
}
pub fn ca_cert_path(mut self, path: impl Into<PathBuf>) -> Self {
self.tls.ca_cert_path = Some(path.into());
self
}
pub fn ca_cert_pem(mut self, pem: impl Into<String>) -> Self {
self.tls.ca_cert_pem = Some(pem.into());
self
}
pub fn client_cert(mut self, cert: impl Into<PathBuf>, key: impl Into<PathBuf>) -> Self {
self.tls.client_cert_path = Some(cert.into());
self.tls.client_key_path = Some(key.into());
self
}
pub fn insecure_skip_verify(mut self, skip: bool) -> Self {
self.insecure_skip_verify = Some(skip);
self
}
pub fn proxy(mut self, proxy: impl Into<String>) -> Self {
self.proxy = Some(proxy.into());
self
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
pub fn user_agent_suffix(mut self, suffix: impl Into<String>) -> Self {
self.user_agent_suffix = Some(suffix.into());
self
}
pub fn hooks(mut self, hooks: Arc<dyn Hooks>) -> Self {
self.hooks = Some(hooks);
self
}
pub fn apply_env(self, env: &EnvReader, vendor_url_vars: &[&str]) -> Result<Self> {
self.apply_env_with(env, &VendorEnv::url_only(vendor_url_vars))
}
pub fn apply_env_with(mut self, env: &EnvReader, vendor: &VendorEnv<'_>) -> Result<Self> {
if self.url.is_none() {
self.url = env.string("URL", vendor.url);
}
if self.connect_timeout.is_none() {
self.connect_timeout = env.duration("CONNECT_TIMEOUT", &[])?;
}
if self.request_timeout.is_none() {
self.request_timeout = env.duration("REQUEST_TIMEOUT", &[])?;
}
if self.total_timeout.is_none() {
self.total_timeout = env.duration("TOTAL_TIMEOUT", &[])?;
}
if self.max_retries.is_none() && self.retry.is_none() {
if let Some(n) = env.int("MAX_RETRIES", &[])? {
let n = u32::try_from(n).map_err(|_| {
Error::config(format!(
"environment variable {}MAX_RETRIES must be >= 0",
env.prefix()
))
})?;
self.max_retries = Some(n);
}
}
if self.tls.ca_cert_path.is_none() {
self.tls.ca_cert_path = env.string("CA_CERT", vendor.ca_cert).map(PathBuf::from);
}
if self.tls.client_cert_path.is_none() {
self.tls.client_cert_path = env
.string("CLIENT_CERT", vendor.client_cert)
.map(PathBuf::from);
}
if self.tls.client_key_path.is_none() {
self.tls.client_key_path = env
.string("CLIENT_KEY", vendor.client_key)
.map(PathBuf::from);
}
if self.insecure_skip_verify.is_none() {
self.insecure_skip_verify =
env.bool("INSECURE_SKIP_VERIFY", vendor.insecure_skip_verify)?;
}
if self.proxy.is_none() {
self.proxy = env.string("PROXY", vendor.proxy);
}
Ok(self)
}
pub fn build(self, default_url: &str) -> Result<CommonConfig> {
let raw_url = self.url.as_deref().unwrap_or(default_url);
let url =
Url::parse(raw_url).map_err(|_| Error::config("url is not a valid absolute URL"))?;
if !matches!(url.scheme(), "http" | "https") {
return Err(Error::config("url scheme must be http or https"));
}
let mut retry = self.retry.unwrap_or_default();
if let Some(n) = self.max_retries {
retry.max_retries = n;
}
retry.validate()?;
let mut tls = self.tls;
tls.insecure_skip_verify = self.insecure_skip_verify.unwrap_or(false);
if tls.client_cert_path.is_some() != tls.client_key_path.is_some() {
return Err(Error::config(
"client certificate and client key must be given together",
));
}
if let Some(proxy) = &self.proxy {
let parsed =
Url::parse(proxy).map_err(|_| Error::config("proxy is not a valid URL"))?;
if !matches!(parsed.scheme(), "http" | "https" | "socks5" | "socks5h") {
return Err(Error::config("proxy scheme must be http or https"));
}
}
let config = CommonConfig {
url,
connect_timeout: self.connect_timeout.unwrap_or(DEFAULT_CONNECT_TIMEOUT),
request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQUEST_TIMEOUT),
total_timeout: self.total_timeout.unwrap_or(DEFAULT_TOTAL_TIMEOUT),
retry,
tls,
proxy: self.proxy,
headers: self.headers,
user_agent_suffix: self.user_agent_suffix,
hooks: self.hooks,
};
for (name, value) in [
("connect_timeout", config.connect_timeout),
("request_timeout", config.request_timeout),
("total_timeout", config.total_timeout),
] {
if value.is_zero() {
return Err(Error::config(format!("{name} must be positive")));
}
}
Ok(config)
}
}