soar-dl 0.12.1

Downloader for soar package manager
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
445
446
447
448
449
450
451
452
453
454
use std::{
    sync::{Arc, LazyLock, RwLock},
    time::Duration,
};

use ureq::{
    config::IpFamily,
    http::{self, HeaderMap, Uri},
    typestate::{WithBody, WithoutBody},
    Agent, Proxy, RequestBuilder,
};

/// Bounds TCP connect and TLS handshake, so an unroutable address fails over to the next one
/// instead of stalling forever.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(30);

#[derive(Clone, Debug)]
pub struct ClientConfig {
    pub user_agent: Option<String>,
    pub headers: Option<HeaderMap>,
    pub proxy: Option<Proxy>,
    pub timeout: Option<Duration>,
    pub ip_family: IpFamily,
}

impl Default for ClientConfig {
    /// Creates a default ClientConfig populated with sensible defaults for HTTP requests.
    ///
    /// The default sets a user agent of "pkgforge/soar", allows both IPv4 and IPv6, and leaves
    /// proxy, headers, and timeout unset.
    ///
    /// # Examples
    ///
    /// ```
    /// use soar_dl::http_client::ClientConfig;
    /// use ureq::config::IpFamily;
    ///
    /// let cfg = ClientConfig::default();
    /// assert_eq!(cfg.user_agent.as_deref(), Some("pkgforge/soar"));
    /// assert!(cfg.proxy.is_none());
    /// assert!(cfg.headers.is_none());
    /// assert!(cfg.timeout.is_none());
    /// assert_eq!(cfg.ip_family, IpFamily::Any);
    /// ```
    fn default() -> Self {
        Self {
            user_agent: Some("pkgforge/soar".into()),
            proxy: None,
            headers: None,
            timeout: None,
            ip_family: IpFamily::Any,
        }
    }
}

impl ClientConfig {
    /// Builds an HTTP `Agent` configured from this `ClientConfig`.
    ///
    /// The returned `Agent` will incorporate the configured proxy, global timeout,
    /// IP family, and user agent header (if present).
    ///
    /// When no proxy is set, the `ALL_PROXY`, `HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY`
    /// environment variables are honored.
    ///
    /// # Examples
    ///
    /// ```
    /// use soar_dl::http_client::ClientConfig;
    ///
    /// let config = ClientConfig::default();
    /// let agent = config.build();
    /// // create a request builder using the configured agent
    /// let _req = agent.get("http://example.com");
    /// ```
    pub fn build(&self) -> Agent {
        let mut config = ureq::Agent::config_builder()
            .timeout_global(self.timeout)
            .timeout_connect(Some(CONNECT_TIMEOUT))
            .ip_family(self.ip_family);

        if self.proxy.is_some() {
            config = config.proxy(self.proxy.clone());
        }

        if let Some(user_agent) = &self.user_agent {
            config = config.user_agent(user_agent);
        }

        config.build().into()
    }
}

struct SharedClient {
    agent: Agent,
    config: ClientConfig,
}

static SHARED_CLIENT_STATE: LazyLock<Arc<RwLock<SharedClient>>> = LazyLock::new(|| {
    let config = ClientConfig::default();
    let agent = config.build();

    Arc::new(RwLock::new(SharedClient {
        agent,
        config,
    }))
});

#[derive(Clone, Default)]
pub struct SharedAgent;

impl SharedAgent {
    /// Create a new `SharedAgent` instance.
    ///
    /// # Examples
    ///
    /// ```
    /// use soar_dl::http_client::SharedAgent;
    ///
    /// let _agent = SharedAgent::new();
    /// ```
    pub fn new() -> Self {
        Self
    }

    pub fn head<T>(&self, uri: T) -> RequestBuilder<WithoutBody>
    where
        Uri: TryFrom<T>,
        <Uri as TryFrom<T>>::Error: Into<http::Error>,
    {
        let state = SHARED_CLIENT_STATE.read().unwrap();
        let req = state.agent.head(uri);
        apply_headers(req, &state.config.headers)
    }

    /// Create a GET request builder for the given URI using the shared agent.
    ///
    /// The returned `RequestBuilder` does not contain a body; any global headers
    /// configured in the shared client are applied to the request.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use soar_dl::http_client::SHARED_AGENT;
    ///
    /// // Create and send a GET request to the specified URI.
    /// let response = SHARED_AGENT.get("https://example.com").call();
    /// ```
    pub fn get<T>(&self, uri: T) -> RequestBuilder<WithoutBody>
    where
        Uri: TryFrom<T>,
        <Uri as TryFrom<T>>::Error: Into<http::Error>,
    {
        let state = SHARED_CLIENT_STATE.read().unwrap();
        let req = state.agent.get(uri);
        apply_headers(req, &state.config.headers)
    }

    /// Starts a POST request to the given URI using the shared agent and applies any globally configured headers.
    ///
    /// The returned `RequestBuilder<WithBody>` is ready to accept a request body and further per-request modifications.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use soar_dl::http_client::SHARED_AGENT;
    ///
    /// let req = SHARED_AGENT.post("https://example.com/");
    /// ```
    pub fn post<T>(&self, uri: T) -> RequestBuilder<WithBody>
    where
        Uri: TryFrom<T>,
        <Uri as TryFrom<T>>::Error: Into<http::Error>,
    {
        let state = SHARED_CLIENT_STATE.read().unwrap();
        let req = state.agent.post(uri);
        apply_headers(req, &state.config.headers)
    }

    /// Creates a PUT request builder for the specified URI using the shared agent and applies any configured global headers.
    ///
    /// # Examples
    ///
    /// ```
    /// use soar_dl::http_client::SHARED_AGENT;
    ///
    /// let req = SHARED_AGENT.put("https://example.com/resource");
    /// ```
    pub fn put<T>(&self, uri: T) -> RequestBuilder<WithBody>
    where
        Uri: TryFrom<T>,
        <Uri as TryFrom<T>>::Error: Into<http::Error>,
    {
        let state = SHARED_CLIENT_STATE.read().unwrap();
        let req = state.agent.put(uri);
        apply_headers(req, &state.config.headers)
    }

    /// Creates a DELETE request for the given URI using the shared agent and applies configured global headers.
    ///
    /// # Returns
    ///
    /// A `RequestBuilder<WithoutBody>` for the DELETE request with any configured global headers applied.
    ///
    /// # Examples
    ///
    /// ```
    /// use soar_dl::http_client::SharedAgent;
    ///
    /// let agent = SharedAgent::new();
    /// let _req = agent.delete("https://example.com/resource");
    /// ```
    pub fn delete<T>(&self, uri: T) -> RequestBuilder<WithoutBody>
    where
        Uri: TryFrom<T>,
        <Uri as TryFrom<T>>::Error: Into<http::Error>,
    {
        let state = SHARED_CLIENT_STATE.read().unwrap();
        let req = state.agent.delete(uri);
        apply_headers(req, &state.config.headers)
    }
}

/// Apply headers from an optional `HeaderMap` to a `RequestBuilder`.
///
/// If `headers` is `Some`, each header key/value pair is added to the provided request
/// and the modified `RequestBuilder` is returned. If `headers` is `None`, the original
/// request is returned unchanged.
fn apply_headers<B>(mut req: RequestBuilder<B>, headers: &Option<HeaderMap>) -> RequestBuilder<B> {
    if let Some(headers) = headers {
        for (key, value) in headers.iter() {
            req = req.header(key, value);
        }
    }
    req
}

pub static SHARED_AGENT: LazyLock<SharedAgent> = LazyLock::new(SharedAgent::new);

/// Updates the global shared HTTP client configuration by applying the provided updater and rebuilding the shared Agent.
///
/// The `updater` closure receives a mutable reference to a `ClientConfig` that will replace the current shared configuration.
/// After the updater runs, a new `Agent` is built from the updated config and atomically replaces the shared agent and config.
///
/// # Examples
///
/// ```
/// use soar_dl::http_client::configure_http_client;
///
/// // Change the global user agent string used by the shared HTTP client.
/// configure_http_client(|cfg| {
///     cfg.user_agent = Some("my-app/1.0".to_string());
/// });
/// ```
pub fn configure_http_client<F>(updater: F)
where
    F: FnOnce(&mut ClientConfig),
{
    let mut state = SHARED_CLIENT_STATE.write().unwrap();
    let mut new_config = state.config.clone();
    updater(&mut new_config);
    let new_agent = new_config.build();
    state.agent = new_agent;
    state.config = new_config;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_client_config_default() {
        let config = ClientConfig::default();
        assert_eq!(config.user_agent, Some("pkgforge/soar".to_string()));
        assert!(config.proxy.is_none());
        assert!(config.headers.is_none());
        assert!(config.timeout.is_none());
        assert_eq!(config.ip_family, IpFamily::Any);
    }

    #[test]
    fn test_client_config_build() {
        let config = ClientConfig::default();
        let agent = config.build();
        // Just verify it builds without panicking
        let _ = agent;
    }

    #[test]
    fn test_client_config_with_timeout() {
        let config = ClientConfig {
            user_agent: Some("test-agent".to_string()),
            proxy: None,
            headers: None,
            timeout: Some(Duration::from_secs(30)),
            ip_family: IpFamily::Any,
        };
        let agent = config.build();
        let _ = agent;
    }

    #[test]
    fn test_client_config_sets_connect_timeout() {
        let agent = ClientConfig::default().build();
        assert_eq!(agent.config().timeouts().connect, Some(CONNECT_TIMEOUT));
    }

    #[test]
    fn test_client_config_without_proxy_falls_back_to_env() {
        let agent = ClientConfig::default().build();
        assert_eq!(
            agent.config().proxy().is_some(),
            Proxy::try_from_env().is_some()
        );
    }

    #[test]
    fn test_client_config_explicit_proxy_overrides_env() {
        let config = ClientConfig {
            proxy: Some(Proxy::new("http://127.0.0.1:8080").unwrap()),
            ..Default::default()
        };
        let agent = config.build();
        assert_eq!(agent.config().proxy().unwrap().port(), 8080);
    }

    #[test]
    fn test_client_config_ip_family() {
        for family in [IpFamily::Any, IpFamily::Ipv4Only, IpFamily::Ipv6Only] {
            let config = ClientConfig {
                ip_family: family,
                ..Default::default()
            };
            let agent = config.build();
            assert_eq!(agent.config().ip_family(), family);
        }
    }

    #[test]
    fn test_shared_agent_new() {
        let agent = SharedAgent::new();
        let _ = agent;
    }

    #[test]
    fn test_shared_agent_get() {
        let agent = SharedAgent::new();
        let req = agent.get("https://example.com");
        // Verify the request builder was created
        let _ = req;
    }

    #[test]
    fn test_shared_agent_post() {
        let agent = SharedAgent::new();
        let req = agent.post("https://example.com");
        let _ = req;
    }

    #[test]
    fn test_shared_agent_put() {
        let agent = SharedAgent::new();
        let req = agent.put("https://example.com");
        let _ = req;
    }

    #[test]
    fn test_shared_agent_delete() {
        let agent = SharedAgent::new();
        let req = agent.delete("https://example.com");
        let _ = req;
    }

    #[test]
    fn test_shared_agent_head() {
        let agent = SharedAgent::new();
        let req = agent.head("https://example.com");
        let _ = req;
    }

    #[test]
    fn test_configure_http_client() {
        configure_http_client(|cfg| {
            cfg.user_agent = Some("custom-agent/1.0".to_string());
        });

        // Verify configuration was applied by checking we can still create requests
        let agent = SharedAgent::new();
        let _ = agent.get("https://example.com");
    }

    #[test]
    fn test_configure_http_client_timeout() {
        configure_http_client(|cfg| {
            cfg.timeout = Some(Duration::from_secs(10));
        });

        let agent = SharedAgent::new();
        let _ = agent.get("https://example.com");
    }

    #[test]
    fn test_shared_agent_clone() {
        let agent1 = SharedAgent::new();
        let agent2 = agent1.clone();

        // Both should work
        let _ = agent1.get("https://example.com");
        let _ = agent2.get("https://example.com");
    }

    #[test]
    fn test_shared_agent_default() {
        let agent = SharedAgent;
        let _ = agent.get("https://example.com");
    }

    #[test]
    fn test_apply_headers_none() {
        let agent: ureq::Agent = ureq::Agent::config_builder().build().into();
        let req = agent.get("https://example.com");
        let req = apply_headers(req, &None);
        let _ = req;
    }

    #[test]
    fn test_apply_headers_some() {
        let agent: ureq::Agent = ureq::Agent::config_builder().build().into();
        let req = agent.get("https://example.com");

        let mut headers = ureq::http::HeaderMap::new();
        headers.insert(
            ureq::http::header::USER_AGENT,
            ureq::http::HeaderValue::from_static("test-agent"),
        );

        let req = apply_headers(req, &Some(headers));
        let _ = req;
    }

    #[test]
    fn test_client_config_clone() {
        let config1 = ClientConfig::default();
        let config2 = config1.clone();

        assert_eq!(config1.user_agent, config2.user_agent);
    }

    #[test]
    fn test_client_config_debug() {
        let config = ClientConfig::default();
        let debug = format!("{:?}", config);
        assert!(debug.contains("ClientConfig"));
    }
}