Skip to main content

openai_tools/common/
client.rs

1//! HTTP client utilities for OpenAI API requests.
2//!
3//! This module provides helper functions for creating HTTP clients with
4//! configurable timeout settings.
5
6use crate::common::errors::{OpenAIToolError, Result};
7use std::time::Duration;
8
9/// Creates an HTTP client with optional timeout configuration.
10///
11/// This function creates a `reqwest::Client` instance with an optional request
12/// timeout. If no timeout is specified, the client will have no timeout limit
13/// (the default reqwest behavior).
14///
15/// # Arguments
16///
17/// * `timeout` - Optional request timeout duration. If `None`, no timeout is set.
18///
19/// # Returns
20///
21/// * `Ok(request::Client)` - A configured HTTP client
22/// * `Err(OpenAIToolError)` - If client creation fails
23///
24/// # Example
25///
26/// ```rust
27/// use std::time::Duration;
28/// use openai_tools::common::client::create_http_client;
29///
30/// // With timeout (30 seconds)
31/// let client = create_http_client(Some(Duration::from_secs(30))).unwrap();
32///
33/// // Without timeout (default behavior)
34/// let client = create_http_client(None).unwrap();
35/// ```
36pub fn create_http_client(timeout: Option<Duration>) -> Result<request::Client> {
37    let mut builder = request::Client::builder();
38
39    if let Some(duration) = timeout {
40        builder = builder.timeout(duration);
41    }
42
43    builder.build().map_err(|e| OpenAIToolError::Error(format!("Failed to create HTTP client: {}", e)))
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn test_create_http_client_without_timeout() {
52        let result = create_http_client(None);
53        assert!(result.is_ok());
54    }
55
56    #[test]
57    fn test_create_http_client_with_timeout() {
58        let result = create_http_client(Some(Duration::from_secs(30)));
59        assert!(result.is_ok());
60    }
61
62    #[test]
63    fn test_create_http_client_with_millisecond_timeout() {
64        let result = create_http_client(Some(Duration::from_millis(500)));
65        assert!(result.is_ok());
66    }
67}