use once_cell::sync::Lazy;
use reqwest::Client;
use std::time::Duration;
pub const DEFAULT_POOL_SIZE: usize = 200;
pub const DEFAULT_CONNECT_TIMEOUT_SECS: u64 = 30;
pub const DEFAULT_TIMEOUT_SECS: u64 = 300;
pub static SHARED_CLIENT: Lazy<Client> = Lazy::new(|| build_pooled_client(None));
pub fn build_pooled_client(timeout_secs: Option<u64>) -> Client {
let timeout = Duration::from_secs(timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS));
Client::builder()
.pool_max_idle_per_host(DEFAULT_POOL_SIZE)
.pool_idle_timeout(Duration::from_secs(90))
.connect_timeout(Duration::from_secs(DEFAULT_CONNECT_TIMEOUT_SECS))
.timeout(timeout)
.tcp_keepalive(Duration::from_secs(60))
.tcp_nodelay(true)
.build()
.unwrap_or_else(|_| Client::new())
}
pub fn build_pooled_client_with_size(pool_size: usize, timeout_secs: Option<u64>) -> Client {
let timeout = Duration::from_secs(timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS));
Client::builder()
.pool_max_idle_per_host(pool_size)
.pool_idle_timeout(Duration::from_secs(90))
.connect_timeout(Duration::from_secs(DEFAULT_CONNECT_TIMEOUT_SECS))
.timeout(timeout)
.tcp_keepalive(Duration::from_secs(60))
.tcp_nodelay(true)
.build()
.unwrap_or_else(|_| Client::new())
}
pub fn build_pooled_client_with_headers(
headers: reqwest::header::HeaderMap,
timeout_secs: Option<u64>,
) -> Result<Client, reqwest::Error> {
let timeout = Duration::from_secs(timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS));
Client::builder()
.pool_max_idle_per_host(DEFAULT_POOL_SIZE)
.pool_idle_timeout(Duration::from_secs(90))
.connect_timeout(Duration::from_secs(DEFAULT_CONNECT_TIMEOUT_SECS))
.timeout(timeout)
.tcp_keepalive(Duration::from_secs(60))
.tcp_nodelay(true)
.default_headers(headers)
.build()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_shared_client_exists() {
let _ = &*SHARED_CLIENT;
}
#[test]
fn test_build_pooled_client_default() {
let client = build_pooled_client(None);
drop(client);
}
#[test]
fn test_build_pooled_client_custom_timeout() {
let client = build_pooled_client(Some(60));
drop(client);
}
#[test]
fn test_build_pooled_client_with_size() {
let client = build_pooled_client_with_size(50, Some(120));
drop(client);
}
}