wrest 0.5.5

Async HTTP client for Windows backed by WinHTTP, with a reqwest-compatible API
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
//! HTTP client and builder.
//!
//! [`Client`] is the main entry point. Create one via [`Client::builder()`],
//! configure timeouts and options, then call [`.build()`](ClientBuilder::build).
//! `Client` is cheap to clone (`Arc` internally).

use crate::{
    Body, Response, Url,
    error::{ContextError, Error},
    proxy::{self, ProxyConfig},
    redirect,
    request::{self, RequestBuilder},
    retry,
    url::IntoUrl,
    util,
    winhttp::{self, SessionConfig, WinHttpSession},
};
use http::{HeaderMap, HeaderValue};
use std::{sync::Arc, time::Duration};

/// An async HTTP client backed by WinHTTP.
///
/// `Client` is cheap to [`Clone`] -- clones share the underlying WinHTTP
/// session handle and connection pool.
///
/// # Example
///
/// ```rust,ignore
/// let client = Client::builder()
///     .timeout(Duration::from_secs(30))
///     .connect_timeout(Duration::from_secs(10))
///     .connection_verbose(true)
///     .build()?;
///
/// let resp = client.get("https://example.com").send().await?;
/// ```
#[derive(Clone)]
pub struct Client {
    pub(crate) inner: Arc<ClientInner>,
}

impl std::fmt::Debug for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client").finish()
    }
}

/// Shared state behind `Arc` in [`Client`].
pub(crate) struct ClientInner {
    /// The WinHTTP session handle (connection pool, callback, options).
    pub session: WinHttpSession,
    /// Total request timeout (including body streaming).
    pub total_timeout: Option<Duration>,
    /// Cached proxy configuration from environment variables.
    pub proxy_config: ProxyConfig,
    /// Default headers applied to every request.
    pub default_headers: HeaderMap,
    /// Whether to ignore certificate errors.
    pub accept_invalid_certs: bool,
    /// Whether to restrict requests to HTTPS-only.
    pub https_only: bool,
    /// Retry policy for automatically retrying failed requests.
    pub retry_policy: retry::Policy,
}

/// Builder for configuring and constructing a [`Client`].
///
/// Obtain via [`Client::builder()`].
#[derive(Debug)]
pub struct ClientBuilder {
    user_agent: String,
    timeout: Option<Duration>,
    connect_timeout: Option<Duration>,
    send_timeout: Option<Duration>,
    read_timeout: Option<Duration>,
    verbose: bool,
    max_connections_per_host: Option<u32>,
    proxy_config: Option<ProxyConfig>,
    default_headers: HeaderMap,
    redirect_policy: Option<redirect::Policy>,
    tls_danger_accept_invalid_certs: bool,
    https_only: bool,
    http1_only: bool,
    error: Option<Error>,
    retry_policy: Option<retry::Builder>,
}

impl Client {
    /// Create a new `Client` with default settings.
    ///
    /// # Panics
    ///
    /// Panics if the WinHTTP session cannot be opened. This matches
    /// [`reqwest::Client::new()`](https://docs.rs/reqwest/latest/reqwest/struct.Client.html#method.new),
    /// which also panics on TLS backend failure.
    /// Prefer [`Client::builder().build()`](ClientBuilder::build) for
    /// fallible construction.
    #[cfg(feature = "panicking-compat")]
    pub fn new() -> Self {
        Client::builder()
            .build()
            .expect("Client::new() failed to build")
    }

    /// Create a new [`ClientBuilder`].
    pub fn builder() -> ClientBuilder {
        ClientBuilder::new()
    }

    /// Send a GET request to the given URL.
    pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        RequestBuilder::new(self.clone(), "GET", url)
    }

    /// Send a POST request to the given URL.
    pub fn post<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        RequestBuilder::new(self.clone(), "POST", url)
    }

    /// Send a PUT request to the given URL.
    pub fn put<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        RequestBuilder::new(self.clone(), "PUT", url)
    }

    /// Send a PATCH request to the given URL.
    pub fn patch<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        RequestBuilder::new(self.clone(), "PATCH", url)
    }

    /// Send a DELETE request to the given URL.
    pub fn delete<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        RequestBuilder::new(self.clone(), "DELETE", url)
    }

    /// Send a HEAD request to the given URL.
    pub fn head<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        RequestBuilder::new(self.clone(), "HEAD", url)
    }

    /// Start building a request with the given HTTP method and URL.
    pub fn request<U: IntoUrl>(&self, method: http::Method, url: U) -> RequestBuilder {
        RequestBuilder::new(self.clone(), method.as_str(), url)
    }

    /// Execute a pre-built [`Request`](crate::request::Request).
    ///
    /// This is the lower-level counterpart of
    /// [`RequestBuilder::send()`](crate::RequestBuilder::send).
    /// Build a request with [`RequestBuilder::build()`](crate::RequestBuilder::build),
    /// inspect or modify it, then execute it here.
    pub async fn execute(&self, request: request::Request) -> Result<Response, Error> {
        use retry::Action;

        let policy = &self.inner.retry_policy;

        // Ensure we always deposit a token when the execution finishes,
        // regardless of which exit path is taken (success, error, or panic).
        // The budget tracks throughput (requests we chose not to retry).
        struct DepositGuard<'a> {
            policy: &'a retry::Policy,
        }
        impl<'a> Drop for DepositGuard<'a> {
            fn drop(&mut self) {
                self.policy.deposit();
            }
        }
        let _guard = DepositGuard { policy };

        let max = policy.max_retries();

        // Decompose the request so we only clone the body on retries.
        let (method, url, headers_map, mut body, timeout) = request.into_parts();
        let method_str = method.as_str().to_owned();

        // Convert HeaderMap to Vec<(String, String)> for WinHTTP once.
        // HTTP header values are octets (RFC 9110 §5.5). WinHTTP accepts
        // UTF-16 strings, so we widen each byte to its Unicode code point
        // via Latin-1 identity mapping for a lossless round-trip.
        let headers: Vec<(String, String)> = headers_map
            .iter()
            .map(|(name, value)| (name.as_str().to_owned(), util::widen_latin1(value.as_bytes())))
            .collect();

        // Calculate the absolute deadline for the entire request lifecycle (including retries).
        let effective_timeout = timeout.or(self.inner.total_timeout);
        let deadline = effective_timeout.and_then(|d| std::time::Instant::now().checked_add(d));

        // Fast path: if retries are disabled, skip cloning entirely.
        if max == 0 {
            let result = self
                .execute_inner(&url, &method_str, &headers, body, deadline)
                .await;
            return result;
        }

        // We know max >= 1.
        // Total attempts = 1 (initial) + up to `max` retries.
        let mut remaining_retries = max;

        loop {
            // Try to clone the body. If we can't (e.g. streaming body),
            // or if we're out of retries, we consume the original body
            // and this becomes the final attempt.
            // Note: For in-memory bodies, `try_clone()` is very cheap — it's
            // just a reference count bump via the `bytes` crate.
            let (body_to_send, can_retry) = if remaining_retries > 0 {
                match &body {
                    Some(b) => {
                        if let Some(cloned) = b.try_clone() {
                            (Some(cloned), true)
                        } else {
                            (body.take(), false)
                        }
                    }
                    None => (None, true),
                }
            } else {
                (body.take(), false)
            };

            let result = self
                .execute_inner(&url, &method_str, &headers, body_to_send, deadline)
                .await;

            if !can_retry {
                return result;
            }

            let action = policy.classify_result(&url, &method, &result);

            if let Action::Retryable = action
                && policy.can_withdraw()
            {
                remaining_retries -= 1;
                trace!(
                    attempt = max - remaining_retries + 1,
                    url = %url,
                    "retrying request"
                );
                continue;
            }

            // Terminal: return (success, non-retryable, or exhausted budget).
            return result;
        }
    }

    /// Inner execution — a single request attempt (no retry logic).
    async fn execute_inner(
        &self,
        url: &Url,
        method_str: &str,
        headers: &[(String, String)],
        body: Option<Body>,
        deadline: Option<std::time::Instant>,
    ) -> Result<Response, Error> {
        let inner = &self.inner;

        // Reject http:// URLs when https_only is enabled.
        if inner.https_only && !url.is_https {
            return Err(Error::builder("URL scheme is not allowed").with_url(url.clone()));
        }

        // Calculate remaining time for this attempt
        let remaining_timeout =
            deadline.map(|d| d.saturating_duration_since(std::time::Instant::now()));

        // If the deadline has already passed, fail immediately
        if let Some(rem) = remaining_timeout
            && rem.is_zero()
        {
            return Err(Error::timeout("total request timeout elapsed").with_url(url.clone()));
        }

        trace!(
            method = method_str,
            url = %url,
            timeout_ms = remaining_timeout.map(|d| d.as_millis() as u64),
            "Client::execute",
        );

        // Execute request -- body is passed through to the WinHTTP layer
        // which handles in-memory bytes and streaming bodies differently.
        let send_future = async {
            winhttp::execute_request(
                &inner.session,
                url,
                method_str,
                headers,
                body,
                &inner.proxy_config,
                inner.accept_invalid_certs,
            )
            .await
        };

        // Race against total timeout if configured
        let raw = if let Some(timeout) = remaining_timeout {
            let delay = futures_timer::Delay::new(timeout);
            let send_future = std::pin::pin!(send_future);
            let delay = std::pin::pin!(delay);

            match futures_util::future::select(send_future, delay).await {
                futures_util::future::Either::Left((result, _)) => result?,
                futures_util::future::Either::Right(((), _)) => {
                    return Err(
                        Error::timeout("total request timeout elapsed").with_url(url.clone())
                    );
                }
            }
        } else {
            send_future.await?
        };

        Ok(Response::from_raw(raw, deadline, self.clone()))
    }
}

#[cfg(feature = "panicking-compat")]
impl Default for Client {
    /// Creates a `Client` with default settings.
    ///
    /// # Panics
    ///
    /// Panics if the WinHTTP session cannot be opened.
    fn default() -> Self {
        Client::builder()
            .build()
            .expect("Client::default() failed to build")
    }
}

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

impl ClientBuilder {
    /// Create a new `ClientBuilder` with default settings.
    pub fn new() -> Self {
        Self {
            user_agent: String::new(),
            timeout: None,
            connect_timeout: None,
            send_timeout: None,
            read_timeout: None,
            verbose: false,
            max_connections_per_host: None,
            proxy_config: None,
            default_headers: HeaderMap::new(),
            redirect_policy: None,
            tls_danger_accept_invalid_certs: false,
            https_only: false,
            http1_only: false,
            error: None,
            retry_policy: None,
        }
    }

    /// Set the total request timeout.
    ///
    /// This covers the entire request lifecycle -- connection, sending,
    /// and receiving the response (including streaming body reads).
    /// Implemented via `futures_util::future::select` + `futures_timer::Delay`.
    ///
    /// Default: **no timeout** (the request can run indefinitely).
    /// WinHTTP enforces a 60-second connect timeout by default;
    /// see [`connect_timeout()`](Self::connect_timeout).
    /// Send/receive stall timeouts default to infinite (matching
    /// reqwest); see [`send_timeout()`](Self::send_timeout) and
    /// [`read_timeout()`](Self::read_timeout).
    #[must_use]
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Set the connection timeout.
    ///
    /// This limits only the TCP connect phase. Maps to WinHTTP's
    /// `nConnectTimeout` parameter in `WinHttpSetTimeouts`.
    ///
    /// # Deviation from reqwest
    ///
    /// Default: **60 seconds** (WinHTTP's built-in default).  reqwest
    /// defaults to **no connect timeout** (`None`).  For end-to-end
    /// control use [`timeout()`](Self::timeout) instead.
    #[must_use]
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = Some(timeout);
        self
    }

    /// Set the per-operation send (write) stall timeout.
    ///
    /// # wrest extension -- not present in reqwest
    ///
    /// reqwest exposes only [`timeout()`](Self::timeout) (total deadline)
    /// and [`connect_timeout()`](Self::connect_timeout).  This method
    /// controls the WinHTTP-level *idle stall* timeout for send
    /// operations: if zero bytes are transmitted for this duration,
    /// WinHTTP aborts the request immediately rather than waiting for
    /// the full total timeout to expire.  Maps to WinHTTP's
    /// `nSendTimeout` parameter in `WinHttpSetTimeouts`.
    ///
    /// Default: **no timeout** (infinite), matching hyper/tokio behaviour.
    /// For end-to-end control use [`timeout()`](Self::timeout) instead.
    #[must_use]
    pub fn send_timeout(mut self, timeout: Duration) -> Self {
        self.send_timeout = Some(timeout);
        self
    }

    /// Set the per-operation read stall timeout.
    ///
    /// # wrest extension -- not present in reqwest
    ///
    /// reqwest exposes only [`timeout()`](Self::timeout) (total deadline)
    /// and [`connect_timeout()`](Self::connect_timeout).  This method
    /// controls the WinHTTP-level *idle stall* timeout for receive
    /// operations: if zero bytes arrive for this duration, WinHTTP
    /// aborts the request immediately rather than waiting for the full
    /// total timeout to expire.  Maps to WinHTTP's `nReceiveTimeout`
    /// parameter in `WinHttpSetTimeouts`.
    ///
    /// Default: **no timeout** (infinite), matching hyper/tokio behaviour.
    /// For end-to-end control use [`timeout()`](Self::timeout) instead.
    #[must_use]
    pub fn read_timeout(mut self, timeout: Duration) -> Self {
        self.read_timeout = Some(timeout);
        self
    }

    /// Enable verbose connection logging via `tracing`.
    ///
    /// When enabled, WinHTTP callback events (resolving name, connecting,
    /// sending request, redirects, etc.) are logged at `TRACE` level.
    #[must_use]
    pub fn connection_verbose(mut self, verbose: bool) -> Self {
        self.verbose = verbose;
        self
    }

    /// Set the User-Agent header string.
    ///
    /// Accepts any type convertible to an HTTP header value, matching
    /// the `reqwest::ClientBuilder::user_agent` signature.
    ///
    /// By default no User-Agent header is sent (matching reqwest).
    #[must_use]
    pub fn user_agent<V>(mut self, value: V) -> Self
    where
        HeaderValue: TryFrom<V>,
        <HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
    {
        match HeaderValue::try_from(value) {
            Ok(v) => match v.to_str() {
                Ok(s) => self.user_agent = s.to_owned(),
                Err(e) => {
                    self.error =
                        Some(Error::builder(ContextError::new("invalid user-agent value", e)));
                }
            },
            Err(e) => {
                let e: http::Error = e.into();
                self.error = Some(Error::builder(ContextError::new("invalid user-agent", e)));
            }
        }
        self
    }

    /// Set the maximum number of connections per server.
    ///
    /// Maps to `WINHTTP_OPTION_MAX_CONNS_PER_SERVER`. Default is INFINITE
    /// (WinHTTP default). Set to a lower value to limit concurrency to a
    /// specific server.
    #[must_use]
    pub fn max_connections_per_host(mut self, max: u32) -> Self {
        self.max_connections_per_host = Some(max);
        self
    }

    /// Set default headers that will be included in every request.
    ///
    /// Headers set on individual requests will override these defaults
    /// if they share the same header name.
    #[must_use]
    pub fn default_headers(mut self, headers: HeaderMap) -> Self {
        self.default_headers = headers;
        self
    }

    // -----------------------------------------------------------------
    // No-op reqwest compatibility stubs
    //
    // These methods accept and ignore their arguments so that code
    // written against reqwest compiles without changes.  Gated behind
    // the `noop-compat` Cargo feature.
    // -----------------------------------------------------------------

    /// Set a timeout for idle connections in the pool.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages its own connection pool internally and does not
    /// expose idle-timeout configuration.  Requires the `noop-compat`
    /// feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn pool_idle_timeout<T: Into<Option<Duration>>>(self, _val: T) -> Self {
        self
    }

    /// Set the maximum idle connections per host.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages its own connection pool internally.  Requires
    /// the `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn pool_max_idle_per_host(self, _val: usize) -> Self {
        self
    }

    /// Enable `TCP_NODELAY` on the connection.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages TCP socket options internally and does not
    /// expose `TCP_NODELAY`.  Requires the `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn tcp_nodelay(self, _val: bool) -> Self {
        self
    }

    /// Set TCP keepalive.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages TCP socket options internally and does not
    /// expose keepalive settings.  Requires the `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn tcp_keepalive<T: Into<Option<Duration>>>(self, _val: T) -> Self {
        self
    }

    /// Enable gzip content-encoding for responses.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP handles content-encoding decompression automatically
    /// and does not expose per-algorithm toggles.  Requires both the
    /// `gzip` and `noop-compat` features.
    #[cfg(all(feature = "noop-compat", feature = "gzip"))]
    #[must_use]
    pub fn gzip(self, _val: bool) -> Self {
        self
    }

    /// Enable brotli content-encoding for responses.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP only decompresses gzip and deflate responses natively.
    /// Calling `brotli(true)` is accepted for API compatibility but
    /// **will not** cause brotli-encoded responses to be decompressed.
    /// Requires both the `brotli` and `noop-compat` features.
    #[cfg(all(feature = "noop-compat", feature = "brotli"))]
    #[must_use]
    pub fn brotli(self, _val: bool) -> Self {
        self
    }

    /// Enable deflate content-encoding for responses.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP handles content-encoding decompression automatically
    /// and does not expose per-algorithm toggles.  Requires both the
    /// `deflate` and `noop-compat` features.
    #[cfg(all(feature = "noop-compat", feature = "deflate"))]
    #[must_use]
    pub fn deflate(self, _val: bool) -> Self {
        self
    }

    /// Enable zstd content-encoding for responses.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP only decompresses gzip and deflate responses natively.
    /// Calling `zstd(true)` is accepted for API compatibility but
    /// **will not** cause zstd-encoded responses to be decompressed.
    /// Requires both the `zstd` and `noop-compat` features.
    #[cfg(all(feature = "noop-compat", feature = "zstd"))]
    #[must_use]
    pub fn zstd(self, _val: bool) -> Self {
        self
    }

    /// Enable HTTP/2 with prior knowledge.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages protocol negotiation internally via ALPN.
    /// See [`http1_only()`](Self::http1_only) to restrict to HTTP/1.x.
    /// Requires the `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn http2_prior_knowledge(self) -> Self {
        self
    }

    /// Set the TCP keepalive probe interval.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages TCP socket options internally.  Requires the
    /// `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn tcp_keepalive_interval<T: Into<Option<Duration>>>(self, _val: T) -> Self {
        self
    }

    /// Set the TCP keepalive probe retry count.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages TCP socket options internally.  Requires the
    /// `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn tcp_keepalive_retries<T: Into<Option<u32>>>(self, _val: T) -> Self {
        self
    }

    /// Allow HTTP/0.9 responses.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP does not support HTTP/0.9.  Requires the `noop-compat`
    /// feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn http09_responses(self) -> Self {
        self
    }

    /// Send headers as title case instead of lowercase.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages header formatting internally.  Requires the
    /// `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn http1_title_case_headers(self) -> Self {
        self
    }

    /// Accept obsolete multiline headers in HTTP/1 responses.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages header parsing internally.  Requires the
    /// `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn http1_allow_obsolete_multiline_headers_in_responses(self, _val: bool) -> Self {
        self
    }

    /// Ignore invalid header lines in HTTP/1 responses.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages header parsing internally.  Requires the
    /// `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn http1_ignore_invalid_headers_in_responses(self, _val: bool) -> Self {
        self
    }

    /// Allow spaces after header names in HTTP/1 responses.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages header parsing internally.  Requires the
    /// `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn http1_allow_spaces_after_header_name_in_responses(self, _val: bool) -> Self {
        self
    }

    /// Set the HTTP/2 initial stream window size.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages HTTP/2 flow control internally.  Requires the
    /// `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn http2_initial_stream_window_size(self, _sz: impl Into<Option<u32>>) -> Self {
        self
    }

    /// Set the HTTP/2 initial connection window size.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages HTTP/2 flow control internally.  Requires the
    /// `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn http2_initial_connection_window_size(self, _sz: impl Into<Option<u32>>) -> Self {
        self
    }

    /// Enable HTTP/2 adaptive flow control.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages HTTP/2 flow control internally.  Requires the
    /// `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn http2_adaptive_window(self, _enabled: bool) -> Self {
        self
    }

    /// Set the maximum HTTP/2 frame size.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages HTTP/2 framing internally.  Requires the
    /// `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn http2_max_frame_size(self, _sz: impl Into<Option<u32>>) -> Self {
        self
    }

    /// Set the maximum HTTP/2 header list size.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages HTTP/2 headers internally.  Requires the
    /// `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn http2_max_header_list_size(self, _max: u32) -> Self {
        self
    }

    /// Set the HTTP/2 keep-alive ping interval.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages HTTP/2 connection health internally.  Requires
    /// the `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn http2_keep_alive_interval(self, _interval: impl Into<Option<Duration>>) -> Self {
        self
    }

    /// Set the HTTP/2 keep-alive ping timeout.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages HTTP/2 connection health internally.  Requires
    /// the `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn http2_keep_alive_timeout(self, _timeout: Duration) -> Self {
        self
    }

    /// Enable HTTP/2 keep-alive while idle.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP manages HTTP/2 connection health internally.  Requires
    /// the `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn http2_keep_alive_while_idle(self, _enabled: bool) -> Self {
        self
    }

    /// Control TLS Server Name Indication.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// WinHTTP always enables SNI via SChannel; this hint is ignored.
    /// Requires the `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn tls_sni(self, _tls_sni: bool) -> Self {
        self
    }

    /// Force using the native TLS backend.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// wrest always uses the native TLS backend (SChannel via WinHTTP).
    /// Requires the `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn tls_backend_native(self) -> Self {
        self
    }

    /// Deprecated alias for [`tls_backend_native()`](Self::tls_backend_native).
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn use_native_tls(self) -> Self {
        self
    }

    /// Disable the hickory-dns async resolver.
    ///
    /// # No-op -- reqwest compatibility
    ///
    /// wrest does not bundle any DNS resolver; WinHTTP manages DNS
    /// internally.  Requires the `noop-compat` feature.
    #[cfg(feature = "noop-compat")]
    #[must_use]
    pub fn no_hickory_dns(self) -> Self {
        self
    }

    /// Set the redirect policy for the client.
    ///
    /// Controls how many redirects are followed automatically.
    /// Default: follow up to 10 redirects (matching reqwest).
    ///
    /// Use [`redirect::Policy::none()`](crate::redirect::Policy::none) to
    /// disable automatic redirects entirely.
    ///
    /// # Deviation from reqwest
    ///
    /// Only [`Policy::limited()`](crate::redirect::Policy::limited) and
    /// [`Policy::none()`](crate::redirect::Policy::none) are supported.
    /// reqwest's `Policy::custom()` callback is not available because
    /// redirect handling is performed by WinHTTP internally.
    #[must_use]
    pub fn redirect(mut self, policy: redirect::Policy) -> Self {
        self.redirect_policy = Some(policy);
        self
    }

    /// Add a proxy to the client.
    ///
    /// Overrides the corresponding scheme(s) from environment variables.
    /// Can be called multiple times for different schemes.
    ///
    /// # Deviation from reqwest
    ///
    /// SOCKS proxies (`socks4://`, `socks5://`) are rejected because
    /// WinHTTP only supports HTTP CONNECT proxies. reqwest supports
    /// SOCKS via the `socks` feature.
    #[must_use]
    pub fn proxy(mut self, proxy: proxy::Proxy) -> Self {
        let config = self.proxy_config.get_or_insert_with(ProxyConfig::from_env);
        proxy.apply_to(config);
        self
    }

    /// Disable proxy auto-detection.
    ///
    /// Prevents the client from using any automatically detected system
    /// proxies. Proxies explicitly added via [`proxy()`](Self::proxy)
    /// are still used.
    ///
    /// Matches [`reqwest::ClientBuilder::no_proxy()`](https://docs.rs/reqwest/latest/reqwest/struct.ClientBuilder.html#method.no_proxy).
    #[must_use]
    pub fn no_proxy(mut self) -> Self {
        // Initialize a proxy config with NO env-var defaults.
        // Explicit .proxy() calls will still merge into this config.
        self.proxy_config = Some(ProxyConfig::none_from_env());
        self
    }

    /// Accept invalid TLS certificates.
    ///
    /// # Warning
    ///
    /// This is **dangerous** and should only be used for testing or
    /// in controlled environments. It disables all certificate validation.
    #[must_use]
    pub fn tls_danger_accept_invalid_certs(mut self, accept: bool) -> Self {
        self.tls_danger_accept_invalid_certs = accept;
        self
    }

    /// Deprecated alias for [`tls_danger_accept_invalid_certs()`](Self::tls_danger_accept_invalid_certs).
    #[must_use]
    pub fn danger_accept_invalid_certs(self, accept: bool) -> Self {
        self.tls_danger_accept_invalid_certs(accept)
    }

    /// Restrict the client to HTTPS-only requests.
    ///
    /// When enabled, any request to an `http://` URL will return an
    /// error instead of being sent.
    ///
    /// Default: `false` (both HTTP and HTTPS are allowed).
    #[must_use]
    pub fn https_only(mut self, enabled: bool) -> Self {
        self.https_only = enabled;
        self
    }

    /// Restrict the client to HTTP/1.x only.
    ///
    /// When set, the WinHTTP session will not enable HTTP/2 protocol
    /// negotiation.
    #[must_use]
    pub fn http1_only(mut self) -> Self {
        self.http1_only = true;
        self
    }

    /// Set a retry policy for the client.
    ///
    /// By default the client retries connection-reset errors (the
    /// WinHTTP equivalent of HTTP/2 GOAWAY / REFUSED\_STREAM).  Use
    /// [`retry::never()`](crate::retry::never) to disable this.
    #[must_use]
    pub fn retry(mut self, policy: retry::Builder) -> Self {
        self.retry_policy = Some(policy);
        self
    }

    /// Build the [`Client`].
    ///
    /// This opens a WinHTTP session, installs the async callback, and
    /// reads proxy configuration from environment variables.
    pub fn build(self) -> Result<Client, Error> {
        if let Some(err) = self.error {
            return Err(err);
        }

        let proxy_config = self.proxy_config.unwrap_or_else(ProxyConfig::from_env);

        // Determine session-level proxy action.
        // If env vars specify a proxy, use NAMED_PROXY at session level.
        // Otherwise use AUTOMATIC_PROXY. Per-request NO_PROXY overrides happen later.
        let session_proxy =
            if proxy_config.https_proxy_url.is_some() || proxy_config.http_proxy_url.is_some() {
                // Use HTTPS proxy as the session default (most requests are HTTPS).
                // Per-request resolution will pick the right one.
                let url = proxy_config
                    .https_proxy_url
                    .as_ref()
                    .or(proxy_config.http_proxy_url.as_ref())
                    .cloned()
                    .unwrap_or_default();
                proxy::ProxyAction::Named(url, None)
            } else {
                proxy::ProxyAction::Automatic
            };

        // Saturate to i32::MAX rather than silently truncating.
        // WinHttpSetTimeouts takes i32 milliseconds (~24.8 days); any
        // Duration longer than that is effectively infinite.
        let to_ms = |d: std::time::Duration| -> u32 {
            u32::try_from(d.as_millis())
                .unwrap_or(i32::MAX as u32)
                .min(i32::MAX as u32)
        };
        let connect_timeout_ms = self.connect_timeout.map_or(60_000, to_ms); // 60s default

        // send/receive stall timeouts -- default 0 (infinite, no stall
        // detection) to match hyper/tokio behaviour where reqwest has no
        // per-operation idle timeout.  Callers can opt in to stall
        // detection via the send_timeout() / read_timeout() extensions.
        // Total end-to-end timeout is enforced separately via
        // futures_timer::Delay.
        let send_timeout_ms = self.send_timeout.map_or(0, to_ms);
        let read_timeout_ms = self.read_timeout.map_or(0, to_ms);

        let config = SessionConfig {
            user_agent: self.user_agent,
            connect_timeout_ms,
            send_timeout_ms,
            read_timeout_ms,
            verbose: self.verbose,
            max_connections_per_host: self.max_connections_per_host,
            proxy: session_proxy,
            redirect_policy: self.redirect_policy,
            http1_only: self.http1_only,
        };

        let session = WinHttpSession::open(&config)?;

        debug!(
            connect_timeout_ms,
            send_timeout_ms,
            read_timeout_ms,
            total_timeout_ms = self.timeout.map(|d| d.as_millis() as u64),
            proxy = ?config.proxy,
            accept_invalid_certs = self.tls_danger_accept_invalid_certs,
            "client built",
        );

        Ok(Client {
            inner: Arc::new(ClientInner {
                session,
                total_timeout: self.timeout,
                proxy_config,
                default_headers: self.default_headers,
                accept_invalid_certs: self.tls_danger_accept_invalid_certs,
                https_only: self.https_only,
                retry_policy: self
                    .retry_policy
                    .unwrap_or_else(retry::Builder::default)
                    .into_policy(),
            }),
        })
    }
}

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

    #[test]
    fn client_is_clone() {
        fn assert_clone<T: Clone>() {}
        assert_clone::<Client>();
    }

    #[test]
    fn builder_defaults() {
        let builder = ClientBuilder::new();
        assert!(builder.timeout.is_none());
        assert!(builder.connect_timeout.is_none());
        assert!(!builder.verbose);
        assert!(builder.max_connections_per_host.is_none());
        assert!(
            builder.user_agent.is_empty(),
            "default user-agent should be empty (matching reqwest)"
        );
    }

    #[test]
    fn builder_fluent_api() {
        let builder = ClientBuilder::new()
            .timeout(Duration::from_secs(30))
            .connect_timeout(Duration::from_secs(10))
            .connection_verbose(true)
            .user_agent("test-agent/1.0")
            .max_connections_per_host(6);

        assert_eq!(builder.timeout, Some(Duration::from_secs(30)));
        assert_eq!(builder.connect_timeout, Some(Duration::from_secs(10)));
        assert!(builder.verbose);
        assert_eq!(builder.user_agent, "test-agent/1.0");
        assert_eq!(builder.max_connections_per_host, Some(6));
    }

    #[test]
    fn client_build_succeeds() {
        // This actually opens a WinHTTP session
        let client = Client::builder().build();
        assert!(client.is_ok());

        // Durations larger than i32::MAX ms (~24.8 days) saturate
        // rather than wrapping (covers `unwrap_or` in `to_ms`).
        let huge = Duration::from_millis(u64::from(i32::MAX as u32) + 1);
        assert!(Client::builder().connect_timeout(huge).build().is_ok());

        // Redirect policies: exercises the WinHTTP session option arms.
        use crate::redirect::Policy;
        assert!(Client::builder().redirect(Policy::none()).build().is_ok());
        assert!(
            Client::builder()
                .redirect(Policy::limited(5))
                .build()
                .is_ok()
        );
    }

    #[test]
    fn client_clone_shares_session() {
        let client = Client::builder().build().unwrap();
        let clone = client.clone();
        assert!(Arc::ptr_eq(&client.inner, &clone.inner));
    }

    #[test]
    #[cfg(feature = "panicking-compat")]
    fn client_default() {
        let client = Client::default();
        // Verify it produced a working client (session opened)
        assert!(Arc::strong_count(&client.inner) >= 1);

        // Client::new() is the same as Client::default().
        let client2 = Client::new();
        assert!(Arc::strong_count(&client2.inner) >= 1);
    }

    #[test]
    fn client_builder_default() {
        let builder = ClientBuilder::default();
        assert!(
            builder.user_agent.is_empty(),
            "default user-agent should be empty (matching reqwest)"
        );
    }

    #[test]
    fn client_builder_new_is_pub() {
        // Proves ClientBuilder::new() is publicly accessible.
        let builder = ClientBuilder::new();
        assert!(builder.timeout.is_none());
    }

    #[test]
    fn client_http_methods() {
        let client = Client::builder().build().unwrap();
        let methods = [
            ("PUT", client.put("https://example.com")),
            ("PATCH", client.patch("https://example.com")),
            ("DELETE", client.delete("https://example.com")),
            ("HEAD", client.head("https://example.com")),
        ];
        for (expected, rb) in &methods {
            let debug = format!("{rb:?}");
            assert!(debug.contains(expected), "{expected} not found in debug");
        }
    }

    #[test]
    fn client_request_generic() {
        let client = Client::builder().build().unwrap();
        let rb = client.request(http::Method::OPTIONS, "https://example.com");
        let debug = format!("{rb:?}");
        assert!(debug.contains("OPTIONS"));
    }

    #[test]
    fn builder_default_headers() {
        let mut headers = HeaderMap::new();
        headers.insert("x-custom", HeaderValue::from_static("test-value"));
        let builder = ClientBuilder::new().default_headers(headers);
        // Verify stored in builder
        assert_eq!(
            builder
                .default_headers
                .get("x-custom")
                .unwrap()
                .to_str()
                .unwrap(),
            "test-value"
        );
    }

    #[test]
    fn builder_default_headers_propagated() {
        let mut headers = HeaderMap::new();
        headers.insert("x-custom", HeaderValue::from_static("test-value"));
        let client = Client::builder().default_headers(headers).build().unwrap();
        // Verify propagated to ClientInner
        assert_eq!(
            client
                .inner
                .default_headers
                .get("x-custom")
                .unwrap()
                .to_str()
                .unwrap(),
            "test-value"
        );
    }

    /// All noop-compat builder stubs compile, return Self, and don't panic.
    ///
    /// Decompression toggles (`gzip`, `brotli`, `deflate`, `zstd`) are in
    /// [`compression_builder_stubs`] -- they are gated by their own features.
    #[test]
    #[cfg(feature = "noop-compat")]
    fn noop_compat_builder_stubs() {
        // Each stub must accept its argument and return ClientBuilder.
        let builder = ClientBuilder::new()
            // Connection pool
            .pool_idle_timeout(Duration::from_secs(30))
            .pool_idle_timeout(None) // also accepts Option<Duration>
            .pool_max_idle_per_host(10)
            // TCP options
            .tcp_nodelay(true)
            .tcp_keepalive(Duration::from_secs(60))
            .tcp_keepalive(None)
            .tcp_keepalive_interval(Duration::from_secs(15))
            .tcp_keepalive_interval(None)
            .tcp_keepalive_retries(3u32)
            .tcp_keepalive_retries(None)
            // HTTP/1 tuning
            .http09_responses()
            .http1_title_case_headers()
            .http1_allow_obsolete_multiline_headers_in_responses(true)
            .http1_ignore_invalid_headers_in_responses(true)
            .http1_allow_spaces_after_header_name_in_responses(true)
            // HTTP/2 tuning
            .http2_prior_knowledge()
            .http2_initial_stream_window_size(65_535u32)
            .http2_initial_stream_window_size(None)
            .http2_initial_connection_window_size(65_535u32)
            .http2_initial_connection_window_size(None)
            .http2_adaptive_window(true)
            .http2_max_frame_size(16_384u32)
            .http2_max_frame_size(None)
            .http2_max_header_list_size(16_384)
            .http2_keep_alive_interval(Duration::from_secs(30))
            .http2_keep_alive_interval(None)
            .http2_keep_alive_timeout(Duration::from_secs(20))
            .http2_keep_alive_while_idle(true)
            // TLS
            .tls_sni(true)
            .use_native_tls()
            .tls_backend_native()
            // DNS
            .no_hickory_dns();

        // Verify the builder is still usable after all stubs.
        let client = builder.build();
        assert!(client.is_ok(), "builder should still produce a valid client");
    }

    /// Decompression builder stubs compile, return Self, and don't panic.
    ///
    /// Each method is gated by both `noop-compat` and its own cargo
    /// feature (`gzip`, `brotli`, `deflate`, `zstd`).
    #[test]
    #[cfg(all(
        feature = "noop-compat",
        feature = "gzip",
        feature = "brotli",
        feature = "deflate",
        feature = "zstd"
    ))]
    fn compression_builder_stubs() {
        let client = ClientBuilder::new()
            .gzip(true)
            .brotli(true)
            .deflate(true)
            .zstd(true)
            .build();
        assert!(client.is_ok(), "builder should still produce a valid client");
    }

    // -- Builder field storage (data-driven) --

    #[test]
    fn builder_field_storage_table() {
        // (setup, check, label)
        type TestCase<'a> =
            (fn(ClientBuilder) -> ClientBuilder, fn(&ClientBuilder) -> bool, &'a str);
        let cases: &[TestCase] = &[
            (
                |b| b.send_timeout(Duration::from_secs(5)),
                |b| b.send_timeout == Some(Duration::from_secs(5)),
                "send_timeout",
            ),
            (
                |b| b.read_timeout(Duration::from_secs(7)),
                |b| b.read_timeout == Some(Duration::from_secs(7)),
                "read_timeout",
            ),
            (
                |b| b.redirect(redirect::Policy::none()),
                |b| b.redirect_policy.is_some(),
                "redirect_policy",
            ),
            (
                |b| b.tls_danger_accept_invalid_certs(true),
                |b| b.tls_danger_accept_invalid_certs,
                "tls_danger_accept_invalid_certs",
            ),
            (|b| b.http1_only(), |b| b.http1_only, "http1_only"),
            (|b| b.no_proxy(), |b| b.proxy_config.is_some(), "no_proxy"),
            // Duration::MAX should saturate to i32::MAX, not panic
            (
                |b| b.connect_timeout(Duration::MAX),
                |b| b.connect_timeout == Some(Duration::MAX),
                "connect_timeout_max",
            ),
        ];

        for &(setup, check, label) in cases {
            let b = setup(ClientBuilder::new());
            assert!(check(&b), "builder.{label}() was not stored");
        }
    }

    #[test]
    fn builder_user_agent_table() {
        // (value_bytes, expect_ok, label)
        //
        // Three user_agent() code paths:
        //   1. Valid visible-ASCII string → stored in builder
        //   2. Non-ASCII bytes (0x01) → HeaderValue::try_from fails → deferred error
        //   3. Opaque bytes (0x80..) → HeaderValue OK, to_str() fails → deferred error
        let cases: &[(&[u8], bool, &str)] = &[
            (b"valid-agent", true, "valid"),
            (b"bad\x01agent", false, "try_from fails"),
            (&[0x80, 0xFF], false, "to_str fails"),
        ];

        for &(value, expect_ok, label) in cases {
            let hv = http::HeaderValue::from_bytes(value);
            let b = match hv {
                Ok(v) => ClientBuilder::new().user_agent(v),
                Err(_) => {
                    ClientBuilder::new().user_agent(String::from_utf8_lossy(value).into_owned())
                }
            };
            if expect_ok {
                assert!(b.error.is_none(), "{label}: should store without error");
                assert!(b.build().is_ok(), "{label}: should build");
            } else {
                assert!(b.error.is_some(), "{label}: should store error");
                assert!(b.build().unwrap_err().is_builder(), "{label}: should be builder error");
            }
        }
    }

    #[test]
    fn builder_bool_fields_propagated() {
        let client = Client::builder()
            .tls_danger_accept_invalid_certs(true)
            .https_only(true)
            .build()
            .unwrap();
        assert!(client.inner.accept_invalid_certs);
        assert!(client.inner.https_only);

        // Check the alias too.
        let client2 = Client::builder()
            .danger_accept_invalid_certs(true)
            .build()
            .unwrap();
        assert!(client2.inner.accept_invalid_certs);
    }

    #[tokio::test]
    async fn https_only_rejects_http() {
        let client = Client::builder().https_only(true).build().unwrap();
        let err = client.get("http://example.com").send().await.unwrap_err();
        assert!(err.is_builder(), "https_only should produce a builder error");
        assert_eq!(err.url().map(|u| u.as_str()), Some("http://example.com/"),);
    }
}