use reqwest::Client;
use std::time::Duration;
use vtcode_config::TimeoutsConfig;
pub struct HttpClientFactory;
impl HttpClientFactory {
pub fn for_llm(config: &TimeoutsConfig) -> Client {
vtcode_commons::http::create_client_with_timeouts(Self::connect_timeout(config), Self::llm_timeout(config))
}
pub(crate) fn for_llm_without_redirects(config: &TimeoutsConfig) -> Result<Client, reqwest::Error> {
vtcode_commons::http::create_client_without_redirects(Self::connect_timeout(config), Self::llm_timeout(config))
}
fn llm_timeout(config: &TimeoutsConfig) -> Duration {
let timeout_secs = if config.default_ceiling_seconds > 0 {
config.default_ceiling_seconds
} else {
180 };
Duration::from_secs(timeout_secs)
}
fn connect_timeout(config: &TimeoutsConfig) -> Duration {
match config.ceiling_duration(config.http_connect_seconds) {
Some(connect) => connect,
None => Duration::from_secs(30),
}
}
pub fn for_streaming(config: &TimeoutsConfig) -> Client {
let timeout_secs = if config.streaming_ceiling_seconds > 0 {
config.streaming_ceiling_seconds
} else {
600 };
Client::builder()
.timeout(Duration::from_secs(timeout_secs))
.connect_timeout(Self::connect_timeout(config))
.pool_idle_timeout(Some(Duration::from_secs(90)))
.pool_max_idle_per_host(1)
.build()
.unwrap_or_else(|_| Client::new())
}
pub(crate) fn with_timeouts(request_timeout: Duration, connect_timeout: Duration) -> Client {
vtcode_commons::http::create_client_with_timeouts(connect_timeout, request_timeout)
}
pub fn default_client() -> Client {
vtcode_commons::http::create_client_with_timeouts(Duration::from_secs(30), Duration::from_secs(180))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_client_is_created() {
let client = HttpClientFactory::default_client();
drop(client);
}
#[test]
fn for_llm_uses_config_timeout() {
let config = TimeoutsConfig::default();
let client = HttpClientFactory::for_llm(&config);
drop(client);
}
#[test]
fn for_streaming_uses_longer_timeout() {
let config = TimeoutsConfig::default();
let client = HttpClientFactory::for_streaming(&config);
drop(client);
}
#[test]
fn connect_timeout_follows_the_configured_http_key() {
let config = TimeoutsConfig { http_connect_seconds: 45, ..Default::default() };
assert_eq!(HttpClientFactory::connect_timeout(&config), Duration::from_secs(45));
}
#[test]
fn connect_timeout_falls_back_when_disabled() {
let config = TimeoutsConfig { http_connect_seconds: 0, ..Default::default() };
assert_eq!(HttpClientFactory::connect_timeout(&config), Duration::from_secs(30));
}
}