use reqwest::{Client, ClientBuilder};
use std::time::Duration;
#[derive(Debug, Clone)]
pub struct OptimizedHttpConfig {
pub pool_max_idle_per_host: usize,
pub pool_idle_timeout: Duration,
pub connect_timeout: Duration,
pub request_timeout: Duration,
pub gzip: bool,
pub brotli: bool,
pub user_agent: String,
}
impl Default for OptimizedHttpConfig {
fn default() -> Self {
Self {
pool_max_idle_per_host: 90,
pool_idle_timeout: Duration::from_secs(90),
connect_timeout: Duration::from_secs(10),
request_timeout: Duration::from_secs(30),
gzip: true,
brotli: true,
user_agent: format!("open-lark/{}", env!("CARGO_PKG_VERSION")),
}
}
}
impl OptimizedHttpConfig {
pub fn production() -> Self {
Self {
pool_max_idle_per_host: 100,
pool_idle_timeout: Duration::from_secs(120),
connect_timeout: Duration::from_secs(5),
request_timeout: Duration::from_secs(30),
gzip: true,
brotli: true,
user_agent: format!("open-lark/{}", env!("CARGO_PKG_VERSION")),
}
}
pub fn high_throughput() -> Self {
Self {
pool_max_idle_per_host: 200,
pool_idle_timeout: Duration::from_secs(180),
connect_timeout: Duration::from_secs(3),
request_timeout: Duration::from_secs(15),
gzip: true,
brotli: true,
user_agent: format!("open-lark/{}", env!("CARGO_PKG_VERSION")),
}
}
pub fn low_latency() -> Self {
Self {
pool_max_idle_per_host: 50,
pool_idle_timeout: Duration::from_secs(60),
connect_timeout: Duration::from_secs(2),
request_timeout: Duration::from_secs(10),
gzip: false, brotli: false,
user_agent: format!("open-lark/{}", env!("CARGO_PKG_VERSION")),
}
}
pub fn build_client(&self) -> Result<Client, reqwest::Error> {
let mut builder = ClientBuilder::new()
.pool_max_idle_per_host(self.pool_max_idle_per_host)
.pool_idle_timeout(self.pool_idle_timeout)
.connect_timeout(self.connect_timeout)
.timeout(self.request_timeout)
.user_agent(&self.user_agent);
if !self.gzip {
builder = builder.no_gzip();
}
if !self.brotli {
builder = builder.no_brotli();
}
builder.build()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_config_variants_build_client() {
let configs = [
OptimizedHttpConfig::default(),
OptimizedHttpConfig::production(),
OptimizedHttpConfig::high_throughput(),
OptimizedHttpConfig::low_latency(),
];
for cfg in configs {
let client = cfg.build_client();
assert!(client.is_ok());
}
}
}