Skip to main content

vtcode_commons/
http.rs

1//! HTTP client utilities
2
3use reqwest::{Client, ClientBuilder};
4use std::time::Duration;
5
6pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
7pub const SHORT_TIMEOUT: Duration = Duration::from_secs(5);
8pub const LONG_TIMEOUT: Duration = Duration::from_secs(300);
9
10/// Create a default HTTP client with standard timeouts
11pub fn create_default_client() -> Client {
12    create_client_with_timeout(DEFAULT_TIMEOUT)
13}
14
15/// Create an HTTP client with a custom timeout
16pub fn create_client_with_timeout(timeout: Duration) -> Client {
17    ClientBuilder::new()
18        .timeout(timeout)
19        .connect_timeout(SHORT_TIMEOUT)
20        .build()
21        .unwrap_or_else(|_| Client::new())
22}
23
24/// Create an HTTP client with custom connect and request timeouts
25pub fn create_client_with_timeouts(connect_timeout: Duration, request_timeout: Duration) -> Client {
26    ClientBuilder::new()
27        .timeout(request_timeout)
28        .connect_timeout(connect_timeout)
29        .build()
30        .unwrap_or_else(|_| Client::new())
31}
32
33/// Create an HTTP client with a specific user agent
34pub fn create_client_with_user_agent(user_agent: &str) -> Client {
35    ClientBuilder::new()
36        .user_agent(user_agent)
37        .timeout(DEFAULT_TIMEOUT)
38        .build()
39        .unwrap_or_else(|_| Client::new())
40}
41
42/// Create an HTTP client optimized for streaming
43pub fn create_streaming_client() -> Client {
44    ClientBuilder::new()
45        .connect_timeout(SHORT_TIMEOUT)
46        .tcp_keepalive(Some(Duration::from_secs(60)))
47        .build()
48        .unwrap_or_else(|_| Client::new())
49}
50
51/// Get a default client or create one
52pub fn get_or_create_default_client(existing: Option<Client>) -> Client {
53    existing.unwrap_or_else(create_default_client)
54}