lc/
http_client.rs

1use anyhow::Result;
2use reqwest::Client;
3use std::time::Duration;
4
5/// Create an optimized HTTP client with connection pooling, keep-alive settings,
6/// and appropriate timeouts for better performance and connection reuse.
7#[allow(dead_code)]
8pub fn create_optimized_client() -> Result<Client> {
9    use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
10
11    // Create default headers including the required tracking headers
12    let mut headers = HeaderMap::new();
13    headers.insert(
14        HeaderName::from_static("http-referer"),
15        HeaderValue::from_static("https://lc.viwq.dev/"),
16    );
17    headers.insert(
18        HeaderName::from_static("x-title"),
19        HeaderValue::from_static("lc"),
20    );
21
22    Ok(Client::builder()
23        // Connection pooling and keep-alive settings
24        .pool_max_idle_per_host(10) // Keep up to 10 idle connections per host
25        .pool_idle_timeout(Duration::from_secs(90)) // Keep connections alive for 90 seconds
26        .tcp_keepalive(Duration::from_secs(60)) // TCP keep-alive every 60 seconds
27        // Timeout configurations
28        .timeout(Duration::from_secs(60)) // Total request timeout
29        .connect_timeout(Duration::from_secs(10)) // Connection establishment timeout
30        // User agent for identification
31        .user_agent(concat!(
32            env!("CARGO_PKG_NAME"),
33            "/",
34            env!("CARGO_PKG_VERSION")
35        ))
36        // Add default headers including tracking headers
37        .default_headers(headers)
38        .build()?)
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn test_optimized_client_creation() {
47        let result = create_optimized_client();
48        assert!(result.is_ok());
49
50        // Verify the client has the expected configuration
51        let client = result.unwrap();
52        // We can't directly test the internal configuration, but we can verify it was created successfully
53        assert!(format!("{:?}", client).contains("Client"));
54    }
55
56    #[test]
57    fn test_multiple_optimized_clients() {
58        let client1 = create_optimized_client();
59        let client2 = create_optimized_client();
60
61        assert!(client1.is_ok());
62        assert!(client2.is_ok());
63    }
64}