capp-config 0.7.2

Common things i use to build Rust CLI tools for web crawlers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! HTTP client module for making web requests with configurable proxy support.
//!
//! This module provides functionality for building and configuring HTTP clients with
//! features such as:
//! - Configurable proxy support with port range expansion
//! - Timeout settings
//! - User agent customization
//! - Retry mechanisms with exponential backoff
//!
//! # Example
//! ```no_run
//! use capp_config::http::{HttpClientParams, build_http_client};
//! use toml::Value;
//!
//! let config: Value = toml::from_str(r#"
//! [http]
//! timeout = 30
//! connect_timeout = 10
//! [http.proxy]
//! use = true
//! uri = "http://proxy.example.com:{8080-8082}"
//! "#).unwrap();
//!
//! let params = HttpClientParams::from_config(&config["http"], "my-crawler/1.0");
//! let client = build_http_client(params).unwrap();
//! ```
use crate::proxy::{ProxyProvider, RandomProxyProvider};
use backoff::ExponentialBackoffBuilder;

/// Parameters for configuring an HTTP client.
///
/// This struct holds all configuration needed to build a customized HTTP client,
/// including timeout settings, proxy configuration, and user agent string.
#[derive(Debug)]
pub struct HttpClientParams<'a> {
    pub timeout: u64,
    pub connect_timeout: u64,
    pub proxy_provider: Option<Box<dyn ProxyProvider + Send + Sync>>,
    pub user_agent: &'a str,
}

impl<'a> HttpClientParams<'a> {
    /// Creates an HttpClientParams instance from a TOML configuration.
    ///
    /// The configuration should follow this structure:
    /// ```toml
    /// [http]
    /// timeout = 30
    /// connect_timeout = 10
    ///
    /// [http.proxy]
    /// use = true
    /// uri = "http://user:pass@proxy.example.com:8080"
    /// ```
    ///
    /// The proxy URI can include a port range using the format:
    /// `http://proxy.example.com:{8080-8090}`
    ///
    /// # Arguments
    /// * `http_config` - TOML configuration containing HTTP settings
    /// * `user_agent` - User agent string to be used in requests
    ///
    /// # Panics
    /// Panics if required configuration fields are missing (timeout, connect_timeout)
    pub fn from_config(http_config: &toml::Value, user_agent: &'a str) -> Self {
        let timeout = http_config
            .get("timeout")
            .and_then(|v| v.as_integer())
            .and_then(|v| u64::try_from(v).ok())
            .expect("No timeout field in config");
        let connect_timeout = http_config
            .get("connect_timeout")
            .and_then(|v| v.as_integer())
            .and_then(|v| u64::try_from(v).ok())
            .expect("No connect_timeout field in config");

        let proxy_provider = http_config.get("proxy").and_then(|proxy_cfg| {
            if proxy_cfg
                .get("use")
                .and_then(|v| v.as_bool())
                .unwrap_or(false)
            {
                RandomProxyProvider::from_config(proxy_cfg).map(|provider| {
                    Box::new(provider) as Box<dyn ProxyProvider + Send + Sync>
                })
            } else {
                None
            }
        });

        Self {
            timeout,
            connect_timeout,
            proxy_provider,
            user_agent,
        }
    }
}

/// Builds an HTTP client with the specified parameters.
///
/// Creates a reqwest::Client configured with:
/// - TLS settings
/// - Timeout configurations
/// - User agent
/// - Optional proxy support
///
/// # Arguments
/// * `params` - Configuration parameters for the client
///
/// # Returns
/// A Result containing either the configured client or an error
pub fn build_http_client(
    params: HttpClientParams,
) -> Result<reqwest::Client, reqwest::Error> {
    let mut client_builder = reqwest::ClientBuilder::new()
        .use_rustls_tls()
        .danger_accept_invalid_certs(true)
        .timeout(std::time::Duration::from_secs(params.timeout))
        .connect_timeout(std::time::Duration::from_secs(params.connect_timeout))
        .user_agent(params.user_agent);

    if let Some(proxy_provider) = params.proxy_provider {
        if let Some(proxy_uri) = proxy_provider.get_proxy() {
            client_builder = client_builder.proxy(
                reqwest::Proxy::all(&proxy_uri).expect("Failed to create proxy"),
            );
        }
    }

    client_builder.build()
}

/// Fetches a URL with automatic retries.
///
/// Makes a GET request to the specified URL, automatically retrying on failure
/// using exponential backoff. This method only retrieves headers and status,
/// not the response body.
///
/// # Arguments
/// * `client` - The HTTP client to use for the request
/// * `url` - The URL to fetch
///
/// # Returns
/// A Result containing either the response or an error
pub async fn fetch_url(
    client: reqwest::Client,
    url: &str,
) -> Result<reqwest::Response, reqwest::Error> {
    let backoff = ExponentialBackoffBuilder::new()
        .with_max_interval(std::time::Duration::from_secs(10))
        .build();
    backoff::future::retry(backoff, || async { Ok(client.get(url).send().await?) })
        .await
}

/// Fetches content from a URL with automatic retries.
///
/// Makes a GET request to the specified URL and retrieves the full response body,
/// automatically retrying on failure using exponential backoff.
///
/// # Arguments
/// * `client` - The HTTP client to use for the request
/// * `url` - The URL to fetch
///
/// # Returns
/// A Result containing either a tuple of (StatusCode, response_body) or an error
pub async fn fetch_url_content(
    client: reqwest::Client,
    url: &str,
) -> Result<(reqwest::StatusCode, String), reqwest::Error> {
    let backoff = ExponentialBackoffBuilder::new()
        .with_max_interval(std::time::Duration::from_secs(10))
        .with_max_elapsed_time(Some(std::time::Duration::from_secs(30)))
        .build();

    let fetch_content = || async {
        let response = client.get(url).send().await?;
        let status = response.status();
        let text = response.text().await?;
        Ok((status, text))
    };

    backoff::future::retry(backoff, fetch_content).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;
    use std::time::Duration;
    use toml::Value;

    const TOML_CONF_SINGLE_PORT: &str = r#"
    [http]
    timeout = 30
    connect_timeout = 10
    [http.proxy]
    use = true
    uri = "http://proxy1.example.com:8080"
    "#;

    const TOML_CONF_PORT_RANGE: &str = r#"
    [http]
    timeout = 30
    connect_timeout = 10
    [http.proxy]
    use = true
    uri = "http://proxy1.example.com:{8080-8082}"
    "#;

    const TOML_CONF_MULTIPLE_PORT_RANGES: &str = r#"
    [http]
    timeout = 30
    connect_timeout = 10
    [http.proxy]
    use = true
    uris = [
        "http://proxy1.example.com:{8080-8082}",
        "http://proxy2.example.com:9090",
        "http://proxy3.example.com:{9000-9001}",
    ]
    "#;

    const TOML_CONF_TEXT: &str = r#"
    [http]
    timeout = 30
    connect_timeout = 10
    [http.proxy]
    use = true
    uri = "http://bro:admin@proxygate1.com:42042"
    "#;

    const WRONG_TOML_CONF_TEXT: &str = r#"
    [http]
    connect_timeout = 10
    [http.proxy]
    use = true
    uri = "http://bro:admin@proxygate1.com:42042"
    "#;

    #[test]
    fn test_build_client() {
        let client = build_http_client(HttpClientParams {
            timeout: 10,
            connect_timeout: 5,
            proxy_provider: None,
            user_agent: "hello",
        });

        assert!(client.is_ok());
    }

    #[test]
    fn test_build_client_from_config() {
        let config: toml::Value = toml::from_str(TOML_CONF_TEXT).unwrap();
        let client = build_http_client(HttpClientParams::from_config(
            config.get("http").unwrap(),
            "hellobot",
        ));
        assert!(client.is_ok());
    }

    #[test]
    #[should_panic(expected = "No timeout field in config")]
    fn test_build_client_bad_config() {
        let config: toml::Value = toml::from_str(WRONG_TOML_CONF_TEXT).unwrap();
        let _ = build_http_client(HttpClientParams::from_config(
            config.get("http").unwrap(),
            "hellobot",
        ));
    }

    #[test]
    fn test_http_client_single_port() {
        let config: Value = toml::from_str(TOML_CONF_SINGLE_PORT).unwrap();
        let client_params =
            HttpClientParams::from_config(&config["http"], "test-agent/1.0");

        assert_eq!(client_params.timeout, 30);
        assert_eq!(client_params.connect_timeout, 10);

        if let Some(provider) = client_params.proxy_provider {
            let proxy = provider.get_proxy().unwrap();
            assert_eq!(proxy, "http://proxy1.example.com:8080");
        } else {
            panic!("Expected proxy provider to be configured");
        }
    }

    #[test]
    fn test_http_client_port_range() {
        let config: Value = toml::from_str(TOML_CONF_PORT_RANGE).unwrap();
        let client_params =
            HttpClientParams::from_config(&config["http"], "test-agent/1.0");

        let mut seen_ports = HashSet::new();
        if let Some(provider) = client_params.proxy_provider {
            // Test multiple calls to verify different ports are used
            for _ in 0..100 {
                let proxy = provider.get_proxy().unwrap();
                let port = extract_port_from_proxy_url(&proxy);
                seen_ports.insert(port);
            }
        }

        // Should see all three ports from range 8080-8082
        assert_eq!(seen_ports.len(), 3);
        assert!(seen_ports.contains(&8080));
        assert!(seen_ports.contains(&8081));
        assert!(seen_ports.contains(&8082));
    }

    #[test]
    fn test_http_client_multiple_port_ranges() {
        let config: Value = toml::from_str(TOML_CONF_MULTIPLE_PORT_RANGES).unwrap();
        let client_params =
            HttpClientParams::from_config(&config["http"], "test-agent/1.0");

        let mut seen_proxies = HashSet::new();
        if let Some(provider) = client_params.proxy_provider {
            // Test multiple calls to verify different proxies are used
            for _ in 0..100 {
                let proxy = provider.get_proxy().unwrap();
                seen_proxies.insert(proxy);
            }
        }

        // Should see:
        // 3 ports from proxy1 (8080-8082)
        // 1 from proxy2 (9090)
        // 2 from proxy3 (9000-9001)
        assert_eq!(seen_proxies.len(), 6);

        // Verify specific proxy patterns
        assert!(
            seen_proxies
                .iter()
                .any(|p| p == "http://proxy1.example.com:8080")
        );
        assert!(
            seen_proxies
                .iter()
                .any(|p| p == "http://proxy1.example.com:8081")
        );
        assert!(
            seen_proxies
                .iter()
                .any(|p| p == "http://proxy1.example.com:8082")
        );
        assert!(
            seen_proxies
                .iter()
                .any(|p| p == "http://proxy2.example.com:9090")
        );
        assert!(
            seen_proxies
                .iter()
                .any(|p| p == "http://proxy3.example.com:9000")
        );
        assert!(
            seen_proxies
                .iter()
                .any(|p| p == "http://proxy3.example.com:9001")
        );
    }

    #[test]
    fn test_http_client_builder_timeouts_are_set() {
        let config: Value = toml::from_str(TOML_CONF_PORT_RANGE).unwrap();
        let client_params =
            HttpClientParams::from_config(&config["http"], "test-agent/1.0");

        assert_eq!(client_params.timeout, Duration::from_secs(30).as_secs());
        assert_eq!(
            client_params.connect_timeout,
            Duration::from_secs(10).as_secs()
        );
    }

    #[test]
    fn test_proxy_disabled() {
        let toml = r#"
        [http]
        timeout = 30
        connect_timeout = 10
        [http.proxy]
        use = false
        uri = "http://proxy1.example.com:8080"
        "#;

        let config: Value = toml::from_str(toml).unwrap();
        let client_params =
            HttpClientParams::from_config(&config["http"], "test-agent/1.0");

        assert!(
            client_params.proxy_provider.is_none(),
            "Proxy provider should be None when disabled"
        );
    }

    #[test]
    #[should_panic(expected = "No timeout field in config")]
    fn test_missing_timeout() {
        let toml = r#"
        [http]
        connect_timeout = 10
        [http.proxy]
        use = true
        uri = "http://proxy1.example.com:8080"
        "#;

        let config: Value = toml::from_str(toml).unwrap();
        let _ = HttpClientParams::from_config(&config["http"], "test-agent/1.0");
    }

    #[test]
    fn test_invalid_port_range() {
        let toml = r#"
        [http]
        timeout = 30
        connect_timeout = 10
        [http.proxy]
        use = true
        uri = "http://proxy1.example.com:{8082-8080}"
        "#;

        let config: Value = toml::from_str(toml).unwrap();
        let client_params =
            HttpClientParams::from_config(&config["http"], "test-agent/1.0");

        if let Some(provider) = client_params.proxy_provider {
            let proxy = provider.get_proxy().unwrap();
            // Should treat invalid range as literal string
            assert_eq!(proxy, "http://proxy1.example.com:{8082-8080}");
        }
    }

    // Helper function to extract port number from proxy URL
    fn extract_port_from_proxy_url(url: &str) -> u16 {
        let parts: Vec<&str> = url.split(':').collect();
        parts.last().unwrap().parse().unwrap()
    }
}