frakt 0.1.0

Ergonomic platform HTTP client bindings for Rust
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
//! Client implementation using backend abstraction

pub mod background;
pub mod download;
pub mod upload;

use crate::backend::Backend;
use http::{HeaderMap, HeaderName, HeaderValue};

pub use background::BackgroundDownloadBuilder;
pub use download::{DownloadBuilder, DownloadResponse};
pub use upload::UploadBuilder;
use url::Url;

/// Proxy configuration for requests
#[derive(Clone, Debug)]
pub struct ProxyConfig {
    /// Proxy host
    pub host: String,
    /// Proxy port
    pub port: u16,
    /// Optional username for authentication
    pub username: Option<String>,
    /// Optional password for authentication
    pub password: Option<String>,
}

/// HTTP client for making requests
///
/// The client provides a high-level interface for making HTTP requests,
/// downloading files, uploading data, and establishing WebSocket connections.
/// It uses pluggable backends (Foundation on Apple platforms, reqwest on others)
/// to provide optimal performance and native integration.
pub struct Client {
    backend: Backend,
}

impl Client {
    /// Create a new HTTP client with default configuration.
    ///
    /// The client will automatically select the best backend for the current platform:
    /// - Apple platforms: Uses NSURLSession for native integration
    /// - Other platforms: Uses reqwest for cross-platform compatibility
    ///
    /// # Returns
    ///
    /// Returns a new `Client` instance ready to make HTTP requests.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying HTTP backend cannot be initialized.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use frakt::Client;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let response = client.get("https://httpbin.org/get")?.send().await?;
    /// println!("Status: {}", response.status());
    /// # Ok(())
    /// # }
    /// ```
    pub fn new() -> crate::Result<Self> {
        Ok(Self {
            backend: Backend::default_for_platform()?,
        })
    }

    /// Create a client builder for advanced configuration.
    ///
    /// The builder provides a fluent interface for configuring client settings
    /// such as timeouts, headers, authentication, proxy settings, and backend selection.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use frakt::Client;
    /// # use std::time::Duration;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::builder()
    ///     .user_agent("MyApp/1.0")
    ///     .timeout(Duration::from_secs(30))
    ///     .header("X-API-Key", "secret")?
    ///     .use_cookies(true)
    ///     .build()?;
    ///
    /// let response = client.get("https://api.example.com/data")?.send().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn builder() -> ClientBuilder {
        ClientBuilder::new()
    }

    /// Create a GET request to the specified URL.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL to send the GET request to
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use frakt::Client;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let response = client
    ///     .get("https://httpbin.org/get")?
    ///     .header("Accept", "application/json")?
    ///     .send()
    ///     .await?;
    ///
    /// println!("Response: {}", response.text().await?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get(&self, url: impl TryInto<Url>) -> crate::Result<crate::RequestBuilder> {
        let url = url.try_into().map_err(|_| crate::Error::InvalidUrl)?;
        Ok(crate::RequestBuilder::new(
            http::Method::GET,
            url,
            self.backend.clone(),
        ))
    }

    /// Create a POST request to the specified URL.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL to send the POST request to
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use frakt::Client;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let json_data = r#"{"name": "John", "age": 30}"#;
    /// let response = client
    ///     .post("https://httpbin.org/post")?
    ///     .header("Content-Type", "application/json")?
    ///     .body(json_data)
    ///     .send()
    ///     .await?;
    ///
    /// println!("Status: {}", response.status());
    /// # Ok(())
    /// # }
    /// ```
    pub fn post(&self, url: impl TryInto<Url>) -> crate::Result<crate::RequestBuilder> {
        let url = url.try_into().map_err(|_| crate::Error::InvalidUrl)?;
        Ok(crate::RequestBuilder::new(
            http::Method::POST,
            url,
            self.backend.clone(),
        ))
    }

    /// Create a PUT request to the specified URL.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL to send the PUT request to
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use frakt::Client;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let json_data = r#"{"name": "Jane", "age": 25}"#;
    /// let response = client
    ///     .put("https://httpbin.org/put")?
    ///     .header("Content-Type", "application/json")?
    ///     .body(json_data)
    ///     .send()
    ///     .await?;
    ///
    /// println!("Status: {}", response.status());
    /// # Ok(())
    /// # }
    /// ```
    pub fn put(&self, url: impl TryInto<Url>) -> crate::Result<crate::RequestBuilder> {
        let url = url.try_into().map_err(|_| crate::Error::InvalidUrl)?;
        Ok(crate::RequestBuilder::new(
            http::Method::PUT,
            url,
            self.backend.clone(),
        ))
    }

    /// Create a DELETE request to the specified URL.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL to send the DELETE request to
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use frakt::Client;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let response = client
    ///     .delete("https://httpbin.org/delete")?
    ///     .header("Authorization", "Bearer token123")?
    ///     .send()
    ///     .await?;
    ///
    /// println!("Deleted successfully: {}", response.status().is_success());
    /// # Ok(())
    /// # }
    /// ```
    pub fn delete(&self, url: impl TryInto<Url>) -> crate::Result<crate::RequestBuilder> {
        let url = url.try_into().map_err(|_| crate::Error::InvalidUrl)?;
        Ok(crate::RequestBuilder::new(
            http::Method::DELETE,
            url,
            self.backend.clone(),
        ))
    }

    /// Create a HEAD request to the specified URL.
    ///
    /// HEAD requests are like GET requests but only return headers without the response body.
    /// They are useful for checking if a resource exists or getting metadata.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL to send the HEAD request to
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use frakt::Client;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let response = client
    ///     .head("https://httpbin.org/get")?
    ///     .send()
    ///     .await?;
    ///
    /// // Check if resource exists and get content length
    /// if response.status().is_success() {
    ///     if let Some(content_length) = response.headers().get("content-length") {
    ///         println!("Content length: {:?}", content_length);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn head(&self, url: impl TryInto<Url>) -> crate::Result<crate::RequestBuilder> {
        let url = url.try_into().map_err(|_| crate::Error::InvalidUrl)?;
        Ok(crate::RequestBuilder::new(
            http::Method::HEAD,
            url,
            self.backend.clone(),
        ))
    }

    /// Create a PATCH request to the specified URL.
    ///
    /// PATCH requests are used to make partial updates to a resource.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL to send the PATCH request to
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use frakt::Client;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let patch_data = r#"{"age": 31}"#;
    /// let response = client
    ///     .patch("https://httpbin.org/patch")?
    ///     .header("Content-Type", "application/json")?
    ///     .body(patch_data)
    ///     .send()
    ///     .await?;
    ///
    /// println!("Patch successful: {}", response.status().is_success());
    /// # Ok(())
    /// # }
    /// ```
    pub fn patch(&self, url: impl TryInto<Url>) -> crate::Result<crate::RequestBuilder> {
        let url = url.try_into().map_err(|_| crate::Error::InvalidUrl)?;
        Ok(crate::RequestBuilder::new(
            http::Method::PATCH,
            url,
            self.backend.clone(),
        ))
    }

    /// Create a download builder for streaming downloads to disk.
    ///
    /// The download builder provides a fluent interface for configuring file downloads,
    /// including the destination path and progress monitoring. Downloads are streamed
    /// directly to disk to handle large files efficiently.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL to download from
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use frakt::Client;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let response = client
    ///     .download("https://httpbin.org/bytes/1048576")? // 1MB file
    ///     .to_file("large_file.bin")
    ///     .progress(|downloaded, total| {
    ///         if let Some(total) = total {
    ///             println!("Progress: {}%", (downloaded * 100) / total);
    ///         }
    ///     })
    ///     .send()
    ///     .await?;
    ///
    /// println!("Downloaded to: {:?}", response.file_path);
    /// # Ok(())
    /// # }
    /// ```
    pub fn download(&self, url: impl TryInto<Url>) -> crate::Result<DownloadBuilder> {
        Ok(DownloadBuilder::new(
            self.backend.clone(),
            url.try_into().map_err(|_| crate::Error::InvalidUrl)?,
        ))
    }

    /// Create a background download builder for downloads that survive app termination.
    ///
    /// Background downloads continue even when the application is closed or the system
    /// is restarted. The behavior varies by platform:
    /// - **Apple platforms**: Uses NSURLSession background downloads
    /// - **Unix platforms**: Uses daemon processes
    /// - **Other platforms**: Uses resumable downloads with retry logic
    ///
    /// # Arguments
    ///
    /// * `url` - The URL to download from
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use frakt::Client;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let response = client
    ///     .download_background("https://httpbin.org/bytes/1073741824") // 1GB file
    ///     .session_identifier("app-update-v2.0")
    ///     .to_file("updates/app-v2.0.dmg")
    ///     .progress(|downloaded, total| {
    ///         if let Some(total) = total {
    ///             println!("Background download: {}%", (downloaded * 100) / total);
    ///         }
    ///     })
    ///     .send()
    ///     .await?;
    ///
    /// println!("Background download started for: {:?}", response.file_path);
    /// // App can now terminate - download continues in background
    /// # Ok(())
    /// # }
    /// ```
    pub fn download_background(&self, url: impl TryInto<Url>) -> BackgroundDownloadBuilder {
        BackgroundDownloadBuilder::new(
            self.backend.clone(),
            url.try_into()
                .map_err(|_| crate::Error::InvalidUrl)
                .unwrap(),
        )
    }

    /// Create an upload builder for uploading files or data.
    ///
    /// The upload builder provides a fluent interface for configuring uploads,
    /// including file uploads, raw data uploads, and progress monitoring.
    ///
    /// # Arguments
    ///
    /// * `url` - The URL to upload to
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use frakt::Client;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let response = client
    ///     .upload("https://httpbin.org/post")?
    ///     .from_file("document.pdf")
    ///     .progress(|uploaded, total| {
    ///         if let Some(total) = total {
    ///             println!("Upload progress: {}%", (uploaded * 100) / total);
    ///         }
    ///     })
    ///     .send()
    ///     .await?;
    ///
    /// println!("Upload completed: {}", response.status());
    /// # Ok(())
    /// # }
    /// ```
    pub fn upload(&self, url: impl TryInto<Url>) -> crate::Result<UploadBuilder> {
        Ok(UploadBuilder::new(
            self.backend.clone(),
            url.try_into().map_err(|_| crate::Error::InvalidUrl)?,
        ))
    }

    /// Create a WebSocket connection builder.
    ///
    /// WebSockets provide full-duplex communication over a single TCP connection.
    /// The implementation varies by platform:
    /// - **Apple platforms**: Uses NSURLSession WebSocket support
    /// - **Other platforms**: Uses tokio-tungstenite for WebSocket connections
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use frakt::{Client, Message};
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let mut websocket = client
    ///     .websocket()
    ///     .connect("wss://echo.websocket.org")
    ///     .await?;
    ///
    /// // Send a message
    /// websocket.send(Message::text("Hello WebSocket!")).await?;
    ///
    /// // Receive a message
    /// let message = websocket.receive().await?;
    /// match message {
    ///     Message::Text(text) => println!("Received: {}", text),
    ///     Message::Binary(data) => println!("Received {} bytes", data.len()),
    /// }
    ///
    /// websocket.close(frakt::CloseCode::Normal, None).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn websocket(&self) -> crate::websocket::WebSocketBuilder {
        match &self.backend {
            #[cfg(target_vendor = "apple")]
            Backend::Foundation(foundation_backend) => {
                // Use Foundation backend for WebSocket
                crate::websocket::WebSocketBuilder::Foundation(
                    crate::backend::foundation::FoundationWebSocketBuilder::new(
                        foundation_backend.session().clone(),
                    ),
                )
            }
            #[cfg(windows)]
            Backend::Windows(_) => crate::websocket::WebSocketBuilder::Windows(
                crate::backend::windows::WindowsWebSocketBuilder::new(),
            ),
            Backend::Reqwest(_) => {
                // Use Reqwest backend for WebSocket with tokio-tungstenite
                crate::websocket::WebSocketBuilder::Reqwest(
                    crate::backend::reqwest::ReqwestWebSocketBuilder::new(),
                )
            }
        }
    }

    /// Get the cookie jar (if available).
    ///
    /// Returns a reference to the client's cookie jar if cookie handling is enabled
    /// and the backend supports exposing the cookie jar. Currently returns `None`
    /// as cookie jars are handled internally by the backends.
    ///
    /// # Returns
    ///
    /// Returns `Some(&CookieJar)` if a cookie jar is available for inspection,
    /// or `None` if cookies are disabled or handled internally by the backend.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use frakt::Client;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::builder()
    ///     .use_cookies(true)
    ///     .build()?;
    ///
    /// // Make a request that might set cookies
    /// let _response = client
    ///     .get("https://httpbin.org/cookies/set/session/abc123")?
    ///     .send()
    ///     .await?;
    ///
    /// // Check if cookie jar is available (currently returns None)
    /// if let Some(jar) = client.cookie_jar() {
    ///     println!("Cookie jar contains cookies");
    /// } else {
    ///     println!("Cookie jar not available for inspection");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn cookie_jar(&self) -> Option<&crate::CookieJar> {
        // For now, return None since cookie jars are handled internally by backends
        // This could be extended in the future to expose the backend's cookie jar
        None
    }
}

/// Builder for configuring HTTP clients
///
/// Provides a fluent interface for configuring client settings like timeouts,
/// headers, authentication, and backend selection.
pub struct ClientBuilder {
    config: crate::backend::BackendConfig,
    backend_type: Option<BackendType>,
}

/// Backend type
///
/// - `Foundation`: Use Foundation backend (Apple platforms only)
/// - `Reqwest`: Use Reqwest backend (all platforms)
#[derive(Clone, Copy, Debug)]
pub enum BackendType {
    /// Foundation backend (Apple only)
    #[cfg(target_vendor = "apple")]
    Foundation,
    /// Reqwest backend (all platforms)
    Reqwest,
    /// Windows backend (Windows only)
    #[cfg(windows)]
    Windows,
}

impl ClientBuilder {
    /// Create a new client builder
    pub fn new() -> Self {
        Self {
            config: crate::backend::BackendConfig::default(),
            backend_type: None,
        }
    }

    /// Set request timeout
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.config.timeout = Some(timeout);
        self
    }

    /// Set user agent string
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.config.user_agent = Some(user_agent.into());
        self
    }

    /// Set whether to ignore certificate errors (for testing only)
    pub fn ignore_certificate_errors(mut self, ignore: bool) -> Self {
        self.config.ignore_certificate_errors = Some(ignore);
        self
    }

    /// Add a default header to all requests
    pub fn header(
        mut self,
        name: impl TryInto<HeaderName>,
        value: impl Into<String>,
    ) -> crate::Result<Self> {
        let header_name = name.try_into().map_err(|_| crate::Error::InvalidHeader)?;
        let header_value =
            HeaderValue::from_str(&value.into()).map_err(|_| crate::Error::InvalidHeader)?;

        if self.config.default_headers.is_none() {
            self.config.default_headers = Some(HeaderMap::new());
        }
        self.config
            .default_headers
            .as_mut()
            .unwrap()
            .insert(header_name, header_value);
        Ok(self)
    }

    /// Enable or disable cookie handling
    pub fn use_cookies(mut self, use_cookies: bool) -> Self {
        self.config.use_cookies = Some(use_cookies);
        self
    }

    /// Set a custom cookie jar
    pub fn cookie_jar(mut self, jar: crate::CookieJar) -> Self {
        self.config.cookie_jar = Some(jar);
        self
    }

    /// Set HTTP proxy
    pub fn http_proxy(mut self, host: impl Into<String>, port: u16) -> Self {
        self.config.http_proxy = Some(ProxyConfig {
            host: host.into(),
            port,
            username: None,
            password: None,
        });
        self
    }

    /// Set proxy authentication for the most recently configured proxy
    pub fn proxy_auth(mut self, username: impl Into<String>, password: impl Into<String>) -> Self {
        let username = Some(username.into());
        let password = Some(password.into());

        // Apply to the most recently set proxy
        if let Some(ref mut proxy) = self.config.socks_proxy {
            proxy.username = username.clone();
            proxy.password = password.clone();
        } else if let Some(ref mut proxy) = self.config.https_proxy {
            proxy.username = username.clone();
            proxy.password = password.clone();
        } else if let Some(ref mut proxy) = self.config.http_proxy {
            proxy.username = username;
            proxy.password = password;
        }
        self
    }

    /// Set HTTPS proxy
    pub fn https_proxy(mut self, host: impl Into<String>, port: u16) -> Self {
        self.config.https_proxy = Some(ProxyConfig {
            host: host.into(),
            port,
            username: None,
            password: None,
        });
        self
    }

    /// Set SOCKS proxy
    pub fn socks_proxy(mut self, host: impl Into<String>, port: u16) -> Self {
        self.config.socks_proxy = Some(ProxyConfig {
            host: host.into(),
            port,
            username: None,
            password: None,
        });
        self
    }

    /// Force use of reqwest backend (available on all platforms)
    pub fn backend(mut self, backend_type: BackendType) -> Self {
        self.backend_type = Some(backend_type);
        self
    }

    /// Build the client with the configured settings
    pub fn build(self) -> crate::Result<Client> {
        let backend = match self.backend_type {
            Some(BackendType::Reqwest) => Backend::reqwest_with_config(self.config)?,
            #[cfg(target_vendor = "apple")]
            Some(BackendType::Foundation) => Backend::foundation_with_config(self.config)?,
            #[cfg(windows)]
            Some(BackendType::Windows) => Backend::windows_with_config(self.config)?,
            None => {
                // Auto-select with config
                #[cfg(target_vendor = "apple")]
                {
                    Backend::foundation_with_config(self.config)?
                }
                #[cfg(not(target_vendor = "apple"))]
                {
                    Backend::reqwest_with_config(self.config)?
                }
            }
        };

        Ok(Client { backend })
    }
}

impl Default for ClientBuilder {
    fn default() -> Self {
        Self::new()
    }
}