tez 0.0.3

A lightweight, ergonomic, and fast high-level HTTP client for Rust
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
use std::{convert::TryFrom, fmt, sync::Arc, time::Duration};

use http::{
    HeaderMap, HeaderName, HeaderValue, Method, Uri,
    header::{CONTENT_LENGTH, TRANSFER_ENCODING, USER_AGENT},
};
use http_body::Body as _;
use url::Url;

use crate::{
    Error, Limits, Request, RequestBuilder, Response, Result, Timeouts,
    auth::Authentication,
    connection::{Client as ConnectionClient, Settings as ConnectionSettings},
    proxy::Policy as ProxyPolicy,
    redirect::Policy as RedirectPolicy,
    request::validate_absolute_url,
    retry::Policy as RetryPolicy,
    runtime::{Executor, Runtime},
    tls::TlsBuilder,
    transport::Transport,
};

const DEFAULT_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));

pub(crate) struct ClientInner {
    pub(crate) connection: ConnectionClient,
    pub(crate) base_url: Option<Url>,
    pub(crate) decompresses_responses: bool,
    pub(crate) default_headers: HeaderMap,
    pub(crate) auth: Option<Arc<dyn Authentication>>,
    pub(crate) https_only: bool,
    #[cfg(feature = "cookies")]
    pub(crate) cookies: Option<Arc<crate::cookies::CookieJar>>,
    pub(crate) redirects: RedirectPolicy,
    pub(crate) retry: RetryPolicy,
    pub(crate) limits: Limits,
    pub(crate) timeouts: Timeouts,
}

/// A reusable asynchronous HTTP client.
///
/// A client holds the policy shared by its requests: base URL, default headers,
/// total timeout, redirects, TLS trust, and the connection pool. It is
/// immutable and cheap to clone; clones share the same policy and resources.
#[derive(Clone)]
pub struct Client {
    pub(crate) inner: Arc<ClientInner>,
}

/// A builder for configuring a [`Client`].
///
/// Build one client per distinct trust domain or request policy. In particular,
/// default headers apply even to absolute URLs outside a configured base URL.
pub struct ClientBuilder {
    base_url: Option<String>,
    decompresses_responses: bool,
    default_headers: HeaderMap,
    auth: Option<Arc<dyn Authentication>>,
    proxy: ProxyPolicy,
    #[cfg(feature = "cookies")]
    cookie_jar: Option<Arc<crate::CookieJar>>,
    redirects: RedirectPolicy,
    retry: RetryPolicy,
    tls: TlsBuilder,
    runtime: Runtime,
    connection: ConnectionSettings,
    limits: Limits,
    timeouts: Timeouts,
    user_agent: Option<String>,
    error: Option<Error>,
}

impl Client {
    /// Creates a client with Tez's default policy.
    ///
    /// Defaults include a 30-second total deadline, no base URL or caller
    /// headers, `User-Agent: tez/<version>`, gzip response decompression when
    /// the default Cargo features are enabled, platform-verified rustls, direct
    /// connections, no scheduled retries, and redirect responses returned
    /// unchanged. Use [`Client::builder`] to change the shared policy.
    /// The transport may recover an attempt only when it knows the server did
    /// not process it.
    ///
    /// # Errors
    ///
    /// Returns a configuration error if the default TLS or executor setup
    /// cannot be initialized.
    pub fn new() -> Result<Self> {
        Self::builder().build()
    }

    /// Starts configuring a [`Client`].
    #[must_use]
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// Starts a request with any HTTP method.
    ///
    /// `target` must be a complete HTTP(S) URL or a root-leading path such as
    /// `/users`. Paths are resolved when sent and require a configured base
    /// URL. The builder retains invalid target text and returns an error from
    /// [`RequestBuilder::build`] or [`RequestBuilder::send`].
    #[must_use]
    pub fn request(&self, method: Method, target: impl AsRef<str>) -> RequestBuilder<'_> {
        RequestBuilder::new(self, method, target.as_ref())
    }

    /// Starts a `GET` request. See [`Client::request`] for target rules.
    #[must_use]
    pub fn get(&self, target: impl AsRef<str>) -> RequestBuilder<'_> {
        self.request(Method::GET, target)
    }

    /// Starts a `POST` request. See [`Client::request`] for target rules.
    #[must_use]
    pub fn post(&self, target: impl AsRef<str>) -> RequestBuilder<'_> {
        self.request(Method::POST, target)
    }

    /// Starts a `PUT` request. See [`Client::request`] for target rules.
    #[must_use]
    pub fn put(&self, target: impl AsRef<str>) -> RequestBuilder<'_> {
        self.request(Method::PUT, target)
    }

    /// Starts a `PATCH` request. See [`Client::request`] for target rules.
    #[must_use]
    pub fn patch(&self, target: impl AsRef<str>) -> RequestBuilder<'_> {
        self.request(Method::PATCH, target)
    }

    /// Starts a `DELETE` request. See [`Client::request`] for target rules.
    #[must_use]
    pub fn delete(&self, target: impl AsRef<str>) -> RequestBuilder<'_> {
        self.request(Method::DELETE, target)
    }

    /// Starts a `HEAD` request. See [`Client::request`] for target rules.
    #[must_use]
    pub fn head(&self, target: impl AsRef<str>) -> RequestBuilder<'_> {
        self.request(Method::HEAD, target)
    }

    /// Starts an `OPTIONS` request. See [`Client::request`] for target rules.
    #[must_use]
    pub fn options(&self, target: impl AsRef<str>) -> RequestBuilder<'_> {
        self.request(Method::OPTIONS, target)
    }

    /// Starts a `TRACE` request. See [`Client::request`] for target rules.
    #[must_use]
    pub fn trace(&self, target: impl AsRef<str>) -> RequestBuilder<'_> {
        self.request(Method::TRACE, target)
    }

    /// Starts a `CONNECT` request. See [`Client::request`] for target rules.
    #[must_use]
    pub fn connect(&self, target: impl AsRef<str>) -> RequestBuilder<'_> {
        self.request(Method::CONNECT, target)
    }

    /// Sends an already-built request after applying this client's policy.
    ///
    /// This resolves root-leading paths against the base URL, merges default
    /// headers, validates request framing, and resolves an inherited or
    /// request-specific deadline. HTTP status codes are returned as [`Response`]
    /// values; only construction, transport, timeout, redirect, or body failures
    /// return an [`Error`].
    ///
    /// # Errors
    ///
    /// Returns an error when request preparation, authentication, connection
    /// establishment, transport, redirect handling, retry handling, or the
    /// total request deadline fails.
    pub async fn send(&self, request: Request) -> Result<Response> {
        crate::dispatch::send(&self.inner, request).await
    }
}

impl ClientBuilder {
    /// Sets the base URL used for root-leading request paths.
    ///
    /// The base URL must be an absolute HTTP(S) URL without user information, a
    /// query, or a fragment. Its path is a prefix: with
    /// `https://example.com/api`, `/users` resolves to
    /// `https://example.com/api/users`.
    #[must_use]
    pub fn base_url(mut self, value: impl AsRef<str>) -> Self {
        self.base_url = Some(value.as_ref().to_owned());
        self
    }

    /// Sets a header applied when a request does not provide that name.
    ///
    /// This replaces all configured values for the header name. The name and
    /// value use the standard HTTP conversions. Invalid input is retained and
    /// reported by [`ClientBuilder::build`].
    #[must_use]
    pub fn default_header<K, V>(mut self, name: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        HeaderValue: TryFrom<V>,
    {
        if self.error.is_some() {
            return self;
        }
        let result = (|| {
            let name = HeaderName::try_from(name)
                .map_err(|_| Error::request("client default header name is invalid"))?;
            let value = HeaderValue::try_from(value)
                .map_err(|_| Error::request("client default header value is invalid"))?;
            self.default_headers.insert(name, value);
            Ok(())
        })();
        if let Err(error) = result {
            self.error = Some(error);
        }
        self
    }

    /// Sets headers applied when a request does not provide that name.
    ///
    /// All values for a request header name replace all configured values for
    /// that name. Other headers are appended unchanged, including repeated
    /// values. Defaults apply to every request sent by this client, including
    /// requests with an explicit URL on another origin.
    #[must_use]
    pub fn default_headers(mut self, headers: HeaderMap) -> Self {
        self.default_headers = headers;
        self
    }

    /// Sets default authentication for every request sent through this client.
    ///
    /// Authentication runs once per [`Client::send`] call, after the URL and
    /// headers are resolved and before the first network attempt. The
    /// implementation may inspect the complete request and replace the fields
    /// it owns. Request authentication overrides this client default.
    #[must_use]
    pub fn auth(mut self, authentication: impl Authentication + 'static) -> Self {
        self.auth = Some(Arc::new(authentication));
        self
    }

    /// Sets the `User-Agent` header sent when a request does not provide one.
    ///
    /// The default is `tez/<version>`. This replaces a `User-Agent` supplied
    /// through [`ClientBuilder::default_header`] or
    /// [`ClientBuilder::default_headers`]. Invalid values are reported by
    /// [`ClientBuilder::build`]. Calling this after
    /// [`ClientBuilder::no_user_agent`] restores a default user agent.
    #[must_use]
    pub fn user_agent(mut self, value: impl AsRef<str>) -> Self {
        self.user_agent = Some(value.as_ref().to_owned());
        self
    }

    /// Omits the default `User-Agent` header.
    ///
    /// This removes a `User-Agent` supplied through
    /// [`ClientBuilder::default_header`] or [`ClientBuilder::default_headers`].
    /// An explicit request header is still sent.
    #[must_use]
    pub fn no_user_agent(mut self) -> Self {
        self.user_agent = None;
        self
    }

    /// Sets the total deadline for every request sent by this client.
    ///
    /// The deadline covers connection, upload, redirects, response headers,
    /// and response body reads. Pass `None` to make requests unbounded by
    /// default; a request can still set its own deadline. Zero is retained as
    /// a configuration error reported by [`ClientBuilder::build`].
    #[must_use]
    pub fn timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
        self.timeouts = self.timeouts.total(timeout);
        if self.error.is_none()
            && let Err(error) = self.timeouts.validate()
        {
            self.error = Some(error);
        }
        self
    }

    /// Replaces every connection, read, idle, and total time bound.
    #[must_use]
    pub fn timeouts(mut self, timeouts: Timeouts) -> Self {
        self.timeouts = timeouts;
        if self.error.is_none()
            && let Err(error) = self.timeouts.validate()
        {
            self.error = Some(error);
        }
        self
    }

    /// Replaces every response-body and connection resource bound.
    #[must_use]
    pub fn limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        if self.error.is_none()
            && let Err(error) = self.limits.validate()
        {
            self.error = Some(error);
        }
        self
    }

    /// Uses an application-provided DNS resolver.
    ///
    /// Tez continues to own address-family ordering, staggered connection
    /// attempts, socket configuration, and all configured deadlines.
    #[must_use]
    pub fn resolver(mut self, resolver: impl crate::dns::Resolver + 'static) -> Self {
        self.runtime.set_resolver(resolver);
        self
    }

    /// Replaces socket and HTTP/2 connection policy.
    #[must_use]
    pub fn connection(mut self, settings: ConnectionSettings) -> Self {
        self.connection = settings;
        if self.error.is_none()
            && let Err(error) = self.connection.validate()
        {
            self.error = Some(error);
        }
        self
    }

    /// Sets the redirect [`crate::redirect::Policy`] for this client.
    ///
    /// The default, [`crate::redirect::Policy::NoFollow`], returns the first
    /// 3xx response unchanged. See [`crate::redirect::Policy`] for the
    /// complete following and replay rules.
    #[must_use]
    pub fn redirects(mut self, policy: RedirectPolicy) -> Self {
        self.redirects = policy;
        self
    }

    /// Sets the retry [`crate::retry::Policy`] for this client.
    ///
    /// The default, [`crate::retry::Policy::Never`], does not schedule another
    /// request. See [`crate::retry::Policy`] for the complete eligibility and
    /// timing rules.
    #[must_use]
    pub fn retry(mut self, policy: RetryPolicy) -> Self {
        self.retry = policy;
        self
    }

    /// Sets the [`crate::proxy::Policy`] for this client.
    ///
    /// The default, [`crate::proxy::Policy::direct`], never uses a proxy. See
    /// [`crate::proxy::Policy`] for explicit and environment-discovery behavior.
    /// A later call replaces the earlier policy.
    #[must_use]
    pub fn proxy(mut self, policy: ProxyPolicy) -> Self {
        self.proxy = policy;
        self
    }

    /// Drives Tez connection futures on an application-provided executor.
    ///
    /// The default executor is process-wide and lightweight. Supplying an
    /// executor can keep Hyper connection work on an application's existing
    /// scheduler and avoid cross-thread wakeups in latency-sensitive clients.
    #[must_use]
    pub fn executor(mut self, executor: Executor) -> Self {
        self.runtime.set_executor(executor);
        self
    }

    /// Uses one coherent asynchronous runtime integration.
    ///
    /// A runtime supplies the executor, timer, DNS resolver, and TCP connector
    /// used by this client. Runtime-specific types remain confined to the
    /// selected integration; requests, responses, and bodies stay portable.
    #[must_use]
    pub fn runtime(mut self, runtime: Runtime) -> Self {
        self.runtime = runtime;
        self
    }

    /// Preserves encoded response bodies.
    ///
    /// The client stops advertising every compression format compiled into Tez
    /// and returns encoded response bytes with their original
    /// `Content-Encoding` and `Content-Length` headers. An explicit
    /// `Accept-Encoding` request header is sent unchanged.
    #[must_use]
    pub fn disable_compression(mut self) -> Self {
        self.decompresses_responses = false;
        self
    }

    /// Enables an in-memory cookie jar for this client.
    ///
    /// Cookies received in responses are applied to later matching requests
    /// using normal domain, path, secure, and expiry rules. An explicit request
    /// `Cookie` header is sent unchanged instead of cookies from the jar for
    /// that request. The jar is shared by clones of the built client and is
    /// discarded with them. Cookies are disabled by default.
    #[cfg(feature = "cookies")]
    #[must_use]
    pub fn cookies(mut self) -> Self {
        self.cookie_jar = Some(Arc::new(crate::CookieJar::new()));
        self
    }

    /// Uses a caller-owned cookie jar.
    ///
    /// Sharing one jar between clients shares cookie state while keeping each
    /// client's transport and policy independent.
    #[cfg(feature = "cookies")]
    #[must_use]
    pub fn cookie_jar(mut self, jar: Arc<crate::CookieJar>) -> Self {
        self.cookie_jar = Some(jar);
        self
    }

    /// Replaces platform trust roots with a PEM certificate bundle.
    ///
    /// The bundle must contain at least one X.509 certificate. This is isolated
    /// trust: platform roots are not retained. A later call replaces the
    /// earlier bundle. Invalid PEM is reported by [`ClientBuilder::build`]
    /// without exposing its contents.
    #[must_use]
    pub fn trust_pem(mut self, bundle: impl AsRef<[u8]>) -> Self {
        self.tls.roots(bundle.as_ref());
        self
    }

    /// Adds PEM trust anchors while retaining the platform trust store.
    ///
    /// This differs from [`ClientBuilder::trust_pem`], which intentionally
    /// replaces platform trust.
    #[must_use]
    pub fn add_root_pem(mut self, bundle: impl AsRef<[u8]>) -> Self {
        self.tls.add_roots(bundle.as_ref());
        self
    }

    /// Sets a client identity from a combined PEM certificate chain and key.
    ///
    /// The private key must be unencrypted. A later call replaces the earlier
    /// identity. Invalid PEM is reported by [`ClientBuilder::build`] without
    /// exposing its contents.
    #[must_use]
    pub fn identity_pem(mut self, identity: impl AsRef<[u8]>) -> Self {
        self.tls.identity(identity.as_ref());
        self
    }

    /// Sets the oldest TLS protocol version accepted for new connections.
    #[must_use]
    pub fn minimum_tls_version(mut self, version: crate::tls::Version) -> Self {
        self.tls.minimum_version(version);
        self
    }

    /// Sets the newest TLS protocol version accepted for new connections.
    #[must_use]
    pub fn maximum_tls_version(mut self, version: crate::tls::Version) -> Self {
        self.tls.maximum_version(version);
        self
    }

    /// Restricts this client to HTTPS requests.
    ///
    /// An HTTP base URL is rejected at build time. Other explicit or resolved
    /// HTTP targets are rejected before transport. When a redirect is being
    /// followed, an HTTPS-to-HTTP destination is a redirect error. HTTP proxy
    /// origins remain valid because HTTPS is still used end to end through the
    /// proxy tunnel.
    #[must_use]
    pub fn https_only(mut self) -> Self {
        self.tls.require_https();
        self
    }

    /// Builds a reusable client.
    ///
    /// This validates configuration but does not perform network I/O.
    ///
    /// # Errors
    ///
    /// Returns an error when any retained builder option is invalid or the
    /// configured TLS or executor setup cannot be initialized.
    pub fn build(self) -> Result<Client> {
        if let Some(error) = self.error {
            return Err(error);
        }
        self.limits.validate()?;
        self.timeouts.validate()?;
        self.connection.validate()?;
        let base_url = self.base_url.as_deref().map(parse_base_url).transpose()?;
        if self.tls.is_https_only()
            && base_url
                .as_ref()
                .is_some_and(|base_url| base_url.scheme() != "https")
        {
            return Err(Error::request("client base URL must use HTTPS"));
        }
        let mut default_headers = self.default_headers;
        default_headers.remove(USER_AGENT);
        if let Some(user_agent) = self.user_agent {
            let user_agent = user_agent
                .parse::<HeaderValue>()
                .map_err(|_| Error::request("client user agent is invalid"))?;
            default_headers.insert(USER_AGENT, user_agent);
        }
        let https_only = self.tls.is_https_only();
        self.runtime.executor().prepare()?;
        let transport =
            Transport::new(self.tls, self.proxy, self.runtime.clone(), self.connection)?;
        let connection = ConnectionClient::from_parts(
            transport,
            self.runtime,
            self.connection,
            self.limits,
            self.timeouts,
        );
        Ok(Client {
            inner: Arc::new(ClientInner {
                connection,
                base_url,
                decompresses_responses: self.decompresses_responses,
                default_headers,
                auth: self.auth,
                https_only,
                #[cfg(feature = "cookies")]
                cookies: self.cookie_jar,
                redirects: self.redirects,
                retry: self.retry,
                limits: self.limits,
                timeouts: self.timeouts,
            }),
        })
    }
}

impl Default for ClientBuilder {
    fn default() -> Self {
        Self {
            base_url: None,
            decompresses_responses: true,
            default_headers: HeaderMap::new(),
            auth: None,
            proxy: ProxyPolicy::default(),
            #[cfg(feature = "cookies")]
            cookie_jar: None,
            redirects: RedirectPolicy::NoFollow,
            retry: RetryPolicy::Never,
            tls: TlsBuilder::default(),
            runtime: Runtime::default(),
            connection: ConnectionSettings::default(),
            limits: Limits::default(),
            timeouts: Timeouts::default(),
            user_agent: Some(DEFAULT_USER_AGENT.to_owned()),
            error: None,
        }
    }
}

impl fmt::Debug for Client {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = formatter.debug_struct("Client");
        debug
            .field("has_base_url", &self.inner.base_url.is_some())
            .field("decompresses_responses", &self.inner.decompresses_responses)
            .field("default_header_count", &self.inner.default_headers.len())
            .field("has_auth", &self.inner.auth.is_some())
            .field("https_only", &self.inner.https_only);
        #[cfg(feature = "cookies")]
        debug.field("cookie_jar", &self.inner.cookies.is_some());
        debug
            .field("redirects", &self.inner.redirects)
            .field("retry", &self.inner.retry)
            .field("limits", &self.inner.limits)
            .field("timeouts", &self.inner.timeouts)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for ClientBuilder {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = formatter.debug_struct("ClientBuilder");
        debug
            .field("has_base_url", &self.base_url.is_some())
            .field("decompresses_responses", &self.decompresses_responses)
            .field("default_header_count", &self.default_headers.len())
            .field("has_auth", &self.auth.is_some())
            .field("has_error", &self.error.is_some())
            .field("has_user_agent", &self.user_agent.is_some())
            .field(
                "has_custom_user_agent",
                &self
                    .user_agent
                    .as_deref()
                    .is_some_and(|value| value != DEFAULT_USER_AGENT),
            )
            .field("proxy", &self.proxy);
        #[cfg(feature = "cookies")]
        debug.field("cookie_jar", &self.cookie_jar.is_some());
        debug
            .field("redirects", &self.redirects)
            .field("retry", &self.retry)
            .field("has_custom_tls_roots", &self.tls.has_roots())
            .field("has_additional_tls_roots", &self.tls.has_extra_roots())
            .field("has_tls_client_identity", &self.tls.has_identity())
            .field("https_only", &self.tls.is_https_only())
            .field("limits", &self.limits)
            .field("connection", &self.connection)
            .field("timeouts", &self.timeouts)
            .finish_non_exhaustive()
    }
}

fn parse_base_url(value: &str) -> Result<Url> {
    let url = Url::parse(value).map_err(|_| Error::request("client base URL is invalid"))?;
    validate_absolute_url(&url).map_err(|_| Error::request("client base URL is invalid"))?;
    if url.query().is_some() || url.fragment().is_some() {
        return Err(Error::request("client base URL is invalid"));
    }
    Ok(url)
}

pub(crate) fn resolve_target(base_url: Option<&Url>, target: &Uri) -> Result<Uri> {
    if target.scheme().is_some() && target.authority().is_some() {
        validate_absolute_uri(target)?;
        return Ok(target.clone());
    }

    let path_and_query = target
        .path_and_query()
        .ok_or_else(|| Error::request("request path is invalid"))?;
    let path = path_and_query.path();
    if !path.starts_with('/') || path.starts_with("//") {
        return Err(Error::request("request path is invalid"));
    }
    if path.split('/').any(is_dot_segment) {
        return Err(Error::request("request path is invalid"));
    }
    let base = base_url.ok_or_else(|| Error::request("a client base URL is required for paths"))?;
    let prefix = base.as_str().trim_end_matches('/');
    let resolved = Url::parse(&format!("{prefix}{path_and_query}"))
        .map_err(|_| Error::request("request path is invalid"))?;

    // URL parsing normalizes dot segments. Check after resolution so `..`
    // cannot leave the configured base URL prefix.
    let base_path = base.path().trim_end_matches('/');
    if !base_path.is_empty()
        && resolved.path() != base_path
        && !resolved
            .path()
            .strip_prefix(base_path)
            .is_some_and(|suffix| suffix.starts_with('/'))
    {
        return Err(Error::request("request path escapes the client base URL"));
    }

    resolved
        .as_str()
        .parse()
        .map_err(|_| Error::request("request path is invalid"))
}

pub(crate) fn validate_absolute_uri(uri: &Uri) -> Result<()> {
    let authority = uri
        .authority()
        .ok_or_else(|| Error::request("request URL is invalid"))?;
    if !matches!(uri.scheme_str(), Some("http" | "https"))
        || authority.host().is_empty()
        || authority.as_str().contains('@')
    {
        return Err(Error::request("request URL is invalid"));
    }
    Ok(())
}

fn is_dot_segment(segment: &str) -> bool {
    let mut bytes = segment.as_bytes();
    let mut dots = 0;
    while !bytes.is_empty() && dots < 2 {
        if bytes[0] == b'.' {
            bytes = &bytes[1..];
        } else if bytes.len() >= 3
            && bytes[0] == b'%'
            && bytes[1] == b'2'
            && bytes[2].eq_ignore_ascii_case(&b'e')
        {
            bytes = &bytes[3..];
        } else {
            break;
        }
        dots += 1;
    }
    bytes.is_empty() && matches!(dots, 1 | 2)
}

pub(crate) fn merge_default_headers(request: &mut HeaderMap, defaults: &HeaderMap) {
    for name in defaults.keys() {
        if request.contains_key(name) {
            continue;
        }
        for value in defaults.get_all(name) {
            request.append(name.clone(), value.clone());
        }
    }
}

pub(crate) fn validate_framing(headers: &HeaderMap, body: &crate::Body) -> Result<()> {
    // Tez chooses transfer framing. A caller-supplied content length is valid
    // only when it matches a body whose length is exactly known.
    if headers.contains_key(TRANSFER_ENCODING) {
        return Err(Error::request("request framing headers are invalid"));
    }
    let mut values = headers.get_all(CONTENT_LENGTH).iter();
    let Some(value) = values.next() else {
        return Ok(());
    };
    if values.next().is_some() {
        return Err(Error::request("request framing headers are invalid"));
    }
    let declared = value
        .to_str()
        .ok()
        .and_then(|value| value.parse::<u64>().ok())
        .ok_or_else(|| Error::request("request content length is invalid"))?;
    let length = body
        .size_hint()
        .exact()
        .ok_or_else(|| Error::request("request content length requires an exactly sized body"))?;
    if length != declared {
        return Err(Error::request(
            "request content length does not match its body",
        ));
    }
    Ok(())
}

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

    use http::HeaderValue;

    #[test]
    fn resolves_paths_inside_the_base_url_prefix() {
        let base = parse_base_url("https://example.com/api/").unwrap();

        assert_eq!(
            resolve_target(Some(&base), &"/users?active=true".parse().unwrap()).unwrap(),
            "https://example.com/api/users?active=true"
        );
        assert_eq!(
            resolve_target(
                Some(&base),
                &"https://other.example/health".parse().unwrap()
            )
            .unwrap(),
            "https://other.example/health"
        );
        assert!(resolve_target(Some(&base), &"/../admin".parse().unwrap()).is_err());
        for path in [
            "/users/./settings",
            "/users/../settings",
            "/users/%2e/settings",
            "/users/%2E%2e/settings",
        ] {
            assert!(resolve_target(Some(&base), &path.parse().unwrap()).is_err());
        }
        assert!(resolve_target(None, &"/users".parse().unwrap()).is_err());
    }

    #[test]
    fn absolute_targets_are_revalidated_at_the_client_boundary() {
        for target in ["ftp://example.com/file", "https://user@example.com/private"] {
            let uri = target.parse().expect("syntactically valid URI");
            assert!(resolve_target(None, &uri).is_err());
        }
    }

    #[test]
    fn request_headers_replace_client_defaults_by_name() {
        let mut defaults = HeaderMap::new();
        defaults.insert("x-client", HeaderValue::from_static("default"));
        defaults.append("x-repeated", HeaderValue::from_static("first"));
        defaults.append("x-repeated", HeaderValue::from_static("second"));
        let mut request = HeaderMap::new();
        request.insert("x-client", HeaderValue::from_static("request"));

        merge_default_headers(&mut request, &defaults);

        assert_eq!(request["x-client"], "request");
        assert_eq!(request.get_all("x-repeated").iter().count(), 2);
    }

    #[test]
    fn manual_framing_requires_one_matching_exact_length() {
        let mut headers = HeaderMap::new();
        headers.insert(CONTENT_LENGTH, HeaderValue::from_static("3"));
        assert!(validate_framing(&headers, &crate::Body::from("tez")).is_ok());

        headers.insert(CONTENT_LENGTH, HeaderValue::from_static("2"));
        assert!(validate_framing(&headers, &crate::Body::from("tez")).is_err());

        headers.insert(TRANSFER_ENCODING, HeaderValue::from_static("chunked"));
        assert!(validate_framing(&headers, &crate::Body::from("tez")).is_err());
    }

    #[test]
    fn client_builder_rejects_invalid_configuration_without_echoing_it() {
        let timeout = Client::builder()
            .timeout(Duration::ZERO)
            .default_header("not a header", "secret")
            .timeout(None)
            .build()
            .unwrap_err();
        assert!(timeout.is_request());
        assert_eq!(
            timeout.to_string(),
            "client total timeout must be greater than zero"
        );
        assert!(!format!("{timeout:?}").contains("secret"));

        let invalid = Client::builder()
            .base_url("https://example.com/api?token=secret")
            .build()
            .unwrap_err();
        assert!(invalid.is_request());
        assert!(!invalid.to_string().contains("secret"));

        let invalid = Client::builder()
            .user_agent("private-agent\nsecret")
            .build()
            .unwrap_err();
        assert!(invalid.is_request());
        assert_eq!(invalid.to_string(), "client user agent is invalid");
        assert!(!format!("{invalid:?}").contains("private-agent"));
        assert!(!format!("{invalid:?}").contains("secret"));

        assert!(
            Client::builder()
                .user_agent("private-agent\nsecret")
                .no_user_agent()
                .build()
                .is_ok()
        );

        let zero_connections = Client::builder()
            .limits(Limits::default().connections_per_origin(0))
            .build()
            .unwrap_err();
        assert_eq!(
            zero_connections.to_string(),
            "client connection limit must be greater than zero"
        );

        let excessive_idle = Client::builder()
            .limits(
                Limits::default()
                    .connections_per_origin(2)
                    .idle_connections_per_origin(3),
            )
            .build()
            .unwrap_err();
        assert_eq!(
            excessive_idle.to_string(),
            "client idle connection limit exceeds its connection limit"
        );
    }

    #[test]
    fn client_builder_defers_default_header_errors_and_retains_the_first() {
        let invalid_name = Client::builder()
            .default_header("not a header", "secret")
            .build()
            .unwrap_err();
        assert!(invalid_name.is_request());
        assert_eq!(
            invalid_name.to_string(),
            "client default header name is invalid"
        );
        assert!(!invalid_name.to_string().contains("secret"));

        let first = Client::builder()
            .default_header("authorization", "Bearer secret\n")
            .default_header("not a header", "secret")
            .timeout(Duration::ZERO)
            .build()
            .unwrap_err();
        assert!(first.is_request());
        assert_eq!(first.to_string(), "client default header value is invalid");
        assert!(!first.to_string().contains("secret"));
    }

    #[test]
    fn client_builder_uses_the_default_or_explicit_total_deadline() {
        let default = Client::builder().build().unwrap();
        assert_eq!(
            default.inner.timeouts.total_timeout(),
            Some(Duration::from_secs(30))
        );
        assert_eq!(default.inner.redirects, RedirectPolicy::NoFollow);
        assert_eq!(default.inner.retry, RetryPolicy::Never);

        let bounded = Client::builder()
            .timeout(Duration::from_secs(5))
            .build()
            .unwrap();
        assert_eq!(
            bounded.inner.timeouts.total_timeout(),
            Some(Duration::from_secs(5))
        );

        let unbounded = Client::builder().timeout(None).build().unwrap();
        assert_eq!(unbounded.inner.timeouts.total_timeout(), None);

        let follows_same_origin = Client::builder()
            .redirects(RedirectPolicy::SameOrigin)
            .build()
            .unwrap();
        assert_eq!(
            follows_same_origin.inner.redirects,
            RedirectPolicy::SameOrigin
        );

        let retries_idempotent = Client::builder()
            .retry(RetryPolicy::Idempotent)
            .build()
            .unwrap();
        assert_eq!(retries_idempotent.inner.retry, RetryPolicy::Idempotent);
    }

    #[test]
    fn client_builder_debug_reports_user_agent_policy_without_its_value() {
        let default = format!("{:?}", Client::builder());
        assert!(default.contains("has_user_agent: true"));
        assert!(default.contains("has_custom_user_agent: false"));

        let omitted = format!("{:?}", Client::builder().no_user_agent());
        assert!(omitted.contains("has_user_agent: false"));
        assert!(omitted.contains("has_custom_user_agent: false"));

        let custom = format!("{:?}", Client::builder().user_agent("private-agent/secret"));
        assert!(custom.contains("has_user_agent: true"));
        assert!(custom.contains("has_custom_user_agent: true"));
        assert!(!custom.contains("private-agent"));
        assert!(!custom.contains("secret"));
    }
}