product-os-request 0.0.55

Product OS : Request provides a fully featured HTTP request library combining elements of reqwest and hyper for async requests with a series of helper methods to allow for easier usage depending upon your needs for one-time or repeat usage.
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
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! Hyper-based HTTP client implementation
//!
//! This module provides the `ProductOSHyperClient` which implements
//! `ProductOSClient` using the hyper library directly for lower-level control.

use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use core::str::FromStr;
use core::time::Duration;
use std::sync::Arc;

use bytes::Bytes;

use crate::client::ProductOSClient;
use crate::error::ProductOSRequestError;
use crate::method::Method;
use crate::policy::RedirectPolicy;
use crate::request::ProductOSRequest;
use crate::requester::ProductOSRequester;
use crate::response::ProductOSResponse;

use product_os_http::Request;
use product_os_http_body::{BodyBytes, BodyDataStream, BodyExt};

use hyper::body::Incoming;
use hyper_rustls::{HttpsConnector, HttpsConnectorBuilder};
use hyper_util::client::legacy::{connect::HttpConnector, Client};
use hyper_util::rt::TokioExecutor;

/// Configuration for the Hyper client
#[derive(Clone)]
#[allow(dead_code)]
struct ClientConfig {
    /// Default headers to include in all requests
    default_headers: product_os_http::HeaderMap,
    /// Whether to only allow HTTPS connections
    https_only: bool,
    /// Request timeout duration
    timeout: Option<Duration>,
    /// Connection timeout duration
    connect_timeout: Option<Duration>,
    /// Whether to trust all certificates (dangerous!)
    trust_all_certificates: bool,
    /// Redirect policy
    redirect_policy: RedirectPolicy,
    /// Maximum number of idle connections per host
    max_idle_per_host: usize,
    /// Cookie jar for managing cookies
    #[cfg(feature = "hyper_cookies")]
    cookie_jar: Option<Arc<std::sync::Mutex<cookie_store::CookieStore>>>,
}

impl Default for ClientConfig {
    fn default() -> Self {
        Self {
            default_headers: product_os_http::HeaderMap::new(),
            https_only: false,
            timeout: None,
            connect_timeout: None,
            trust_all_certificates: false,
            redirect_policy: RedirectPolicy::Default,
            max_idle_per_host: 32,
            #[cfg(feature = "hyper_cookies")]
            cookie_jar: Some(Arc::new(std::sync::Mutex::new(
                cookie_store::CookieStore::default(),
            ))),
        }
    }
}

/// Hyper-based HTTP client
///
/// Implements the `ProductOSClient` trait using the hyper library for making HTTP requests.
#[derive(Clone)]
pub struct ProductOSHyperClient {
    client: Client<HttpsConnector<HttpConnector>, BodyBytes>,
    config: Arc<ClientConfig>,
}

impl ProductOSHyperClient {
    /// Create a new client with default configuration
    pub fn new() -> Self {
        Self::default()
    }

    /// Convert Method enum to http::Method
    fn method_to_http(method: &Method) -> product_os_http::Method {
        match method {
            Method::GET => product_os_http::Method::GET,
            Method::POST => product_os_http::Method::POST,
            Method::PATCH => product_os_http::Method::PATCH,
            Method::PUT => product_os_http::Method::PUT,
            Method::DELETE => product_os_http::Method::DELETE,
            Method::TRACE => product_os_http::Method::TRACE,
            Method::HEAD => product_os_http::Method::HEAD,
            Method::OPTIONS => product_os_http::Method::OPTIONS,
            Method::CONNECT => product_os_http::Method::CONNECT,
            Method::ANY => product_os_http::Method::GET,
        }
    }

    /// Build a hyper request from ProductOSRequest
    fn build_request_with_body(
        &self,
        request: ProductOSRequest<BodyBytes>,
    ) -> Result<Request<BodyBytes>, ProductOSRequestError> {
        let method = Self::method_to_http(&request.method);
        let mut builder = Request::builder();

        let mut query_string = String::new();
        for (i, (key, value)) in request.query.iter().enumerate() {
            if i > 0 {
                query_string.push('&');
            }
            query_string.push_str(&crate::encode::percent_encode(key));
            query_string.push('=');
            query_string.push_str(&crate::encode::percent_encode(value));
        }

        // Append query string to URL
        let url = if !query_string.is_empty() {
            if request.url.to_string().contains('?') {
                format!("{}&{}", request.url, query_string)
            } else {
                format!("{}?{}", request.url, query_string)
            }
        } else {
            request.url.to_string()
        };

        let uri = match product_os_http::Uri::from_str(&url) {
            Ok(u) => u,
            Err(e) => {
                tracing::error!("Invalid URI: {:?}", e);
                return Err(ProductOSRequestError::Error(format!("Invalid URI: {}", e)));
            }
        };

        builder = builder.uri(uri);
        builder = builder.method(method);

        // Add default headers from config
        for (name, value) in self.config.default_headers.iter() {
            builder = builder.header(name, value);
        }

        // Add request-specific headers
        for (key, value) in &request.headers {
            if let Ok(name) = product_os_http::HeaderName::from_str(key.as_str()) {
                builder = builder.header(name, value.clone());
            }
        }

        // Add bearer auth if present
        if let Some(auth) = &request.bearer_auth {
            let auth_value = format!("Bearer {}", auth);
            if let Ok(val) = product_os_http::HeaderValue::from_str(&auth_value) {
                builder = builder.header(product_os_http::header::AUTHORIZATION, val);
            }
        }

        #[cfg(feature = "hyper_compression")]
        {
            // Add Accept-Encoding header for compression support
            if !request.headers.contains_key("accept-encoding") {
                if let Ok(val) = product_os_http::HeaderValue::from_str("gzip, br, deflate") {
                    builder = builder.header(product_os_http::header::ACCEPT_ENCODING, val);
                }
            }
        }

        #[cfg(feature = "hyper_cookies")]
        {
            // Add cookies from jar if available
            if let Some(ref cookie_jar) = self.config.cookie_jar {
                if let Ok(jar) = cookie_jar.lock() {
                    if let Ok(url_parsed) = url::Url::parse(&url) {
                        let matching_cookies = jar.matches(&url_parsed);
                        let cookie_strings: Vec<String> = matching_cookies
                            .iter()
                            .map(|c| format!("{}={}", c.name(), c.value()))
                            .collect();

                        if !cookie_strings.is_empty() {
                            let cookie_header = cookie_strings.join("; ");
                            if let Ok(val) = product_os_http::HeaderValue::from_str(&cookie_header)
                            {
                                builder = builder.header(product_os_http::header::COOKIE, val);
                            }
                        }
                    }
                }
            }
        }

        // Build with body
        let body = request.body.unwrap_or_else(|| BodyBytes::new(Bytes::new()));

        match builder.body(body) {
            Ok(req) => Ok(req),
            Err(e) => {
                tracing::error!("Failed to build request: {:?}", e);
                Err(ProductOSRequestError::Error(e.to_string()))
            }
        }
    }

    /// Execute a request with redirect handling
    async fn execute_with_redirects(
        &self,
        request: Request<BodyBytes>,
    ) -> Result<hyper::Response<Incoming>, ProductOSRequestError> {
        self.execute_with_redirects_and_timeout(request).await
    }

    /// Execute a request with redirect handling and optional timeout
    async fn execute_with_redirects_and_timeout(
        &self,
        request: Request<BodyBytes>,
    ) -> Result<hyper::Response<Incoming>, ProductOSRequestError> {
        #[cfg(feature = "hyper_timeout")]
        {
            if let Some(timeout_duration) = self.config.timeout {
                return self.execute_with_timeout(request, timeout_duration).await;
            }
        }

        // No timeout configured or feature not enabled
        self.execute_redirects_internal(request).await
    }

    #[cfg(feature = "hyper_timeout")]
    async fn execute_with_timeout(
        &self,
        request: Request<BodyBytes>,
        timeout_duration: Duration,
    ) -> Result<hyper::Response<Incoming>, ProductOSRequestError> {
        match tokio::time::timeout(timeout_duration, self.execute_redirects_internal(request)).await
        {
            Ok(result) => result,
            Err(_) => Err(ProductOSRequestError::Error(format!(
                "Request timed out after {:?}",
                timeout_duration
            ))),
        }
    }

    /// Internal redirect handling without timeout wrapper
    async fn execute_redirects_internal(
        &self,
        request: Request<BodyBytes>,
    ) -> Result<hyper::Response<Incoming>, ProductOSRequestError> {
        let max_redirects = match &self.config.redirect_policy {
            RedirectPolicy::None => 0,
            RedirectPolicy::Limit(n) => *n,
            RedirectPolicy::Default => 10,
        };

        let mut current_request = request;
        let mut redirect_count = 0;

        // Store original request headers for use in redirects
        let original_headers = current_request.headers().clone();

        loop {
            // Clone the request parts for potential retries
            let (parts, body) = current_request.into_parts();
            let uri = parts.uri.clone();
            current_request = Request::from_parts(parts, body);

            // Execute the request
            let response = match self.client.request(current_request).await {
                Ok(resp) => resp,
                Err(e) => {
                    tracing::error!("Request failed: {:?}", e);
                    return Err(ProductOSRequestError::Error(e.to_string()));
                }
            };

            // Check if this is a redirect
            let status = response.status();
            if status.is_redirection() && redirect_count < max_redirects {
                // Get the Location header
                if let Some(location) = response.headers().get(product_os_http::header::LOCATION) {
                    if let Ok(location_str) = location.to_str() {
                        redirect_count += 1;
                        tracing::debug!(
                            "Following redirect {} to: {}",
                            redirect_count,
                            location_str
                        );

                        // Parse the new URI (could be relative or absolute)
                        let new_uri = if location_str.starts_with("http://")
                            || location_str.starts_with("https://")
                        {
                            // Absolute URL
                            match product_os_http::Uri::from_str(location_str) {
                                Ok(u) => u,
                                Err(e) => {
                                    tracing::error!("Invalid redirect URI: {:?}", e);
                                    return Err(ProductOSRequestError::Error(format!(
                                        "Invalid redirect URI: {}",
                                        e
                                    )));
                                }
                            }
                        } else {
                            // Relative URL - build from current URI
                            let scheme = uri.scheme_str().unwrap_or("https");
                            let authority = uri.authority().map(|a| a.as_str()).unwrap_or("");
                            let new_url = if location_str.starts_with('/') {
                                format!("{}://{}{}", scheme, authority, location_str)
                            } else {
                                let path = uri.path();
                                let base_path = if let Some(pos) = path.rfind('/') {
                                    &path[..=pos]
                                } else {
                                    "/"
                                };
                                format!("{}://{}{}{}", scheme, authority, base_path, location_str)
                            };
                            match product_os_http::Uri::from_str(&new_url) {
                                Ok(u) => u,
                                Err(e) => {
                                    tracing::error!("Invalid redirect URI: {:?}", e);
                                    return Err(ProductOSRequestError::Error(format!(
                                        "Invalid redirect URI: {}",
                                        e
                                    )));
                                }
                            }
                        };

                        // Build new request with the redirect URI
                        let mut new_req = Request::builder()
                            .uri(new_uri)
                            .method(product_os_http::Method::GET)
                            .body(BodyBytes::new(Bytes::new()))
                            .map_err(|e| ProductOSRequestError::Error(e.to_string()))?;

                        // Copy original request headers (except Host) to the redirect request
                        for (name, value) in original_headers.iter() {
                            if name != product_os_http::header::HOST {
                                new_req.headers_mut().insert(name.clone(), value.clone());
                            }
                        }

                        current_request = new_req;
                        continue;
                    }
                }
            }

            // Not a redirect or max redirects reached
            return Ok(response);
        }
    }

    /// Convert hyper Response to ProductOSResponse
    async fn convert_response(
        &self,
        response: hyper::Response<Incoming>,
        final_url: String,
    ) -> Result<ProductOSResponse<BodyBytes>, ProductOSRequestError> {
        #[cfg(feature = "hyper_cookies")]
        {
            // Store cookies from Set-Cookie headers
            if let Some(ref cookie_jar) = self.config.cookie_jar {
                if let Ok(url) = url::Url::parse(&final_url) {
                    if let Ok(mut jar) = cookie_jar.lock() {
                        for cookie_val in response
                            .headers()
                            .get_all(product_os_http::header::SET_COOKIE)
                        {
                            if let Ok(cookie_str) = cookie_val.to_str() {
                                if let Ok(cookie) =
                                    cookie_store::Cookie::parse(cookie_str.to_string(), &url)
                                {
                                    let _ = jar.insert(cookie, &url);
                                }
                            }
                        }
                    }
                }
            }
        }

        #[cfg(feature = "hyper_compression")]
        {
            // Check if response has content-encoding
            if let Some(encoding) = response
                .headers()
                .get(product_os_http::header::CONTENT_ENCODING)
            {
                if let Ok(encoding_str) = encoding.to_str() {
                    tracing::debug!("Response has content-encoding: {}", encoding_str);
                }
            }
        }

        // Preserve status and headers before consuming the body
        let (parts, incoming_body) = response.into_parts();

        // Collect the body using http_body_util
        let body_bytes = match http_body_util::BodyExt::collect(incoming_body).await {
            Ok(collected) => collected.to_bytes(),
            Err(e) => {
                tracing::error!("Failed to read response body: {:?}", e);
                return Err(ProductOSRequestError::Error(e.to_string()));
            }
        };

        let body = BodyBytes::new(body_bytes);

        // Rebuild the response with the original status and headers but our body type
        let mut builder = product_os_http::Response::builder().status(parts.status);

        for (name, value) in parts.headers.iter() {
            builder = builder.header(name, value);
        }

        match builder.body(body) {
            Ok(http_response) => Ok(ProductOSResponse::from_response(http_response, final_url)),
            Err(e) => Err(ProductOSRequestError::Error(e.to_string())),
        }
    }
}

impl ProductOSClient<product_os_http_body::BodyBytes, product_os_http_body::BodyBytes>
    for ProductOSHyperClient
{
    fn build(&mut self, requester: &ProductOSRequester) {
        // Install default crypto provider if not already set
        let _ = rustls::crypto::ring::default_provider().install_default();

        // Build the HTTPS connector with rustls
        let mut roots = rustls::RootCertStore::empty();

        // Add system certificates
        let native_cert_result = rustls_native_certs::load_native_certs();
        for err in &native_cert_result.errors {
            tracing::warn!("Error loading native certificate: {:?}", err);
        }
        for cert in native_cert_result.certs {
            if let Err(e) = roots.add(cert) {
                tracing::warn!("Failed to add certificate: {:?}", e);
            }
        }

        // Add custom certificates
        for cert_der in &requester.certificates {
            let cert = rustls::pki_types::CertificateDer::from(cert_der.clone());
            if let Err(e) = roots.add(cert) {
                tracing::error!("Failed to add custom certificate: {:?}", e);
            }
        }

        let mut tls_config = rustls::ClientConfig::builder()
            .with_root_certificates(roots)
            .with_no_client_auth();

        // Handle trust all certificates (dangerous!)
        if requester.trust_all_certificates {
            tls_config
                .dangerous()
                .set_certificate_verifier(Arc::new(NoVerifier));
        }

        let https_connector = HttpsConnectorBuilder::new()
            .with_tls_config(tls_config)
            .https_or_http()
            .enable_http1()
            .enable_http2()
            .build();

        // Build the hyper client
        let client = Client::builder(TokioExecutor::new())
            .pool_idle_timeout(Duration::from_secs(90))
            .pool_max_idle_per_host(32)
            .build(https_connector);

        // Build configuration
        let config = ClientConfig {
            https_only: requester.secure,
            timeout: Some(requester.timeout),
            connect_timeout: Some(requester.connect_timeout),
            trust_all_certificates: requester.trust_all_certificates,
            redirect_policy: requester.redirect_policy.clone(),
            ..Default::default()
        };

        // Copy default headers
        let mut config = config;
        config.default_headers = requester.headers.clone();

        self.client = client;
        self.config = Arc::new(config);

        tracing::trace!("Updated hyper client with configuration");
    }

    fn new_request(
        &self,
        method: Method,
        url: &str,
    ) -> ProductOSRequest<product_os_http_body::BodyBytes> {
        ProductOSRequest::new(method, url)
    }

    async fn request(
        &self,
        r: ProductOSRequest<product_os_http_body::BodyBytes>,
    ) -> Result<ProductOSResponse<product_os_http_body::BodyBytes>, ProductOSRequestError> {
        let url = r.url.to_string();
        let request = self.build_request_with_body(r)?;
        let response = self.execute_with_redirects(request).await?;
        self.convert_response(response, url).await
    }

    #[cfg(feature = "stream_hyper")]
    async fn request_stream(
        &self,
        r: ProductOSRequest<product_os_http_body::BodyBytes>,
    ) -> Result<ProductOSResponse<product_os_http_body::BodyBytes>, ProductOSRequestError> {
        let url = r.url.to_string();
        let request = self.build_request_with_body(r)?;
        let response = self.execute_with_redirects(request).await?;

        // For streaming, we don't collect the body
        // TODO: Implement proper streaming support
        self.convert_response(response, url).await
    }

    async fn request_simple(
        &self,
        method: Method,
        url: &str,
    ) -> Result<ProductOSResponse<product_os_http_body::BodyBytes>, ProductOSRequestError> {
        let r = ProductOSRequest::<product_os_http_body::BodyBytes>::new(method, url);
        self.request(r).await
    }

    async fn request_raw(
        &self,
        r: Request<product_os_http_body::BodyBytes>,
    ) -> Result<ProductOSResponse<product_os_http_body::BodyBytes>, ProductOSRequestError> {
        let req = ProductOSRequest::from_request(r);
        self.request(req).await
    }

    #[cfg(feature = "stream_hyper")]
    async fn request_stream_raw(
        &self,
        r: Request<product_os_http_body::BodyBytes>,
    ) -> Result<ProductOSResponse<product_os_http_body::BodyBytes>, ProductOSRequestError> {
        let req = ProductOSRequest::from_request(r);
        self.request_stream(req).await
    }

    #[cfg(feature = "json")]
    async fn set_body_json(
        &self,
        r: &mut ProductOSRequest<product_os_http_body::BodyBytes>,
        json: serde_json::Value,
    ) {
        let json_string = json.to_string();
        let body = product_os_http_body::BodyBytes::new(bytes::Bytes::from(json_string));
        r.body = Some(body);
        r.add_header("content-type", "application/json", false);
    }

    #[cfg(feature = "form")]
    async fn set_body_form(
        &self,
        r: &mut ProductOSRequest<product_os_http_body::BodyBytes>,
        form: &str,
    ) {
        match serde_urlencoded::to_string(form) {
            Ok(form_string) => {
                let body = product_os_http_body::BodyBytes::new(bytes::Bytes::from(form_string));
                r.body = Some(body);
                r.add_header("content-type", "application/x-www-form-urlencoded", false);
            }
            Err(e) => {
                tracing::error!("Failed to serialize form: {:?}", e);
            }
        }
    }

    async fn text(
        &self,
        r: ProductOSResponse<product_os_http_body::BodyBytes>,
    ) -> Result<String, ProductOSRequestError> {
        match r.response_async {
            Some(res) => {
                match <product_os_http_body::BodyBytes as Clone>::clone(res.body())
                    .collect()
                    .await
                {
                    Ok(body) => match String::from_utf8(body.to_bytes().as_ref().to_vec()) {
                        Ok(res) => Ok(res),
                        Err(e) => Err(ProductOSRequestError::Error(e.to_string())),
                    },
                    Err(e) => Err(ProductOSRequestError::Error(e.to_string())),
                }
            }
            None => Err(ProductOSRequestError::Error(String::from(
                "No response found",
            ))),
        }
    }

    #[cfg(feature = "json")]
    async fn json(
        &self,
        r: ProductOSResponse<product_os_http_body::BodyBytes>,
    ) -> Result<serde_json::Value, ProductOSRequestError> {
        match r.response_async {
            Some(res) => {
                match <product_os_http_body::BodyBytes as Clone>::clone(res.body())
                    .collect()
                    .await
                {
                    Ok(body) => match String::from_utf8(body.to_bytes().as_ref().to_vec()) {
                        Ok(res) => match serde_json::from_str(&res) {
                            Ok(res) => Ok(res),
                            Err(e) => Err(ProductOSRequestError::Error(e.to_string())),
                        },
                        Err(e) => Err(ProductOSRequestError::Error(e.to_string())),
                    },
                    Err(e) => Err(ProductOSRequestError::Error(e.to_string())),
                }
            }
            None => Err(ProductOSRequestError::Error(String::from(
                "No response found",
            ))),
        }
    }

    async fn bytes(
        &self,
        r: ProductOSResponse<product_os_http_body::BodyBytes>,
    ) -> Result<bytes::Bytes, ProductOSRequestError> {
        match r.response_async {
            Some(res) => {
                match <product_os_http_body::BodyBytes as Clone>::clone(res.body())
                    .collect()
                    .await
                {
                    Ok(body) => Ok(body.to_bytes()),
                    Err(e) => Err(ProductOSRequestError::Error(e.to_string())),
                }
            }
            None => Err(ProductOSRequestError::Error(String::from(
                "No response found",
            ))),
        }
    }

    async fn next_bytes(
        &self,
        r: &mut ProductOSResponse<product_os_http_body::BodyBytes>,
    ) -> Result<Option<bytes::Bytes>, ProductOSRequestError> {
        match r.response_async {
            Some(ref mut res) => {
                // loop to ignore unrecognized frames
                loop {
                    if let Some(res) = res.body_mut().frame().await {
                        let frame = match res {
                            Ok(frame) => frame,
                            Err(e) => return Err(ProductOSRequestError::Error(e.to_string())),
                        };
                        if let Ok(buf) = frame.into_data() {
                            return Ok(Some(buf));
                        }
                        // else continue
                    } else {
                        return Ok(None);
                    }
                }
            }
            None => Err(ProductOSRequestError::Error(String::from(
                "No response found",
            ))),
        }
    }

    fn to_stream(
        &self,
        r: ProductOSResponse<product_os_http_body::BodyBytes>,
    ) -> Result<BodyDataStream<BodyBytes>, ProductOSRequestError> {
        match r.response_async {
            Some(res) => Ok(BodyDataStream::new(res.into_body())),
            None => Err(ProductOSRequestError::Error(String::from(
                "No response found",
            ))),
        }
    }
}

impl Default for ProductOSHyperClient {
    fn default() -> Self {
        // Install default crypto provider if not already set
        let _ = rustls::crypto::ring::default_provider().install_default();

        // Build a default HTTPS connector
        let mut roots = rustls::RootCertStore::empty();

        let native_cert_result = rustls_native_certs::load_native_certs();
        for cert in native_cert_result.certs {
            let _ = roots.add(cert);
        }

        let tls_config = rustls::ClientConfig::builder()
            .with_root_certificates(roots)
            .with_no_client_auth();

        let https_connector = HttpsConnectorBuilder::new()
            .with_tls_config(tls_config)
            .https_or_http()
            .enable_http1()
            .enable_http2()
            .build();

        let client = Client::builder(TokioExecutor::new()).build(https_connector);

        Self {
            client,
            config: Arc::new(ClientConfig::default()),
        }
    }
}

/// Certificate verifier that accepts all certificates (DANGEROUS!)
#[derive(Debug)]
struct NoVerifier;

impl rustls::client::danger::ServerCertVerifier for NoVerifier {
    fn verify_server_cert(
        &self,
        _end_entity: &rustls::pki_types::CertificateDer<'_>,
        _intermediates: &[rustls::pki_types::CertificateDer<'_>],
        _server_name: &rustls::pki_types::ServerName<'_>,
        _ocsp_response: &[u8],
        _now: rustls::pki_types::UnixTime,
    ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
        Ok(rustls::client::danger::ServerCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        _message: &[u8],
        _cert: &rustls::pki_types::CertificateDer<'_>,
        _dss: &rustls::DigitallySignedStruct,
    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
    }

    fn verify_tls13_signature(
        &self,
        _message: &[u8],
        _cert: &rustls::pki_types::CertificateDer<'_>,
        _dss: &rustls::DigitallySignedStruct,
    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
    }

    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
        vec![
            rustls::SignatureScheme::RSA_PKCS1_SHA256,
            rustls::SignatureScheme::RSA_PKCS1_SHA384,
            rustls::SignatureScheme::RSA_PKCS1_SHA512,
            rustls::SignatureScheme::ECDSA_NISTP256_SHA256,
            rustls::SignatureScheme::ECDSA_NISTP384_SHA384,
            rustls::SignatureScheme::RSA_PSS_SHA256,
            rustls::SignatureScheme::RSA_PSS_SHA384,
            rustls::SignatureScheme::RSA_PSS_SHA512,
            rustls::SignatureScheme::ED25519,
        ]
    }
}