Skip to main content

eggfetch_core/
request.rs

1//! Request types and builder.
2
3use std::net::SocketAddr;
4use std::sync::Arc;
5
6use bytes::Bytes;
7use http::Version;
8
9use crate::body::RequestBody;
10use crate::client::Client;
11use crate::error::Result;
12use crate::headers::Headers;
13use crate::redirect::RedirectPolicy;
14use crate::response::Response;
15use crate::retry::RetryPolicy;
16use crate::timeout::Timeout;
17use crate::trace::TraceObserver;
18
19use crate::auth::AuthScheme;
20#[cfg(feature = "proxy")]
21use crate::proxy::ProxyConfig;
22
23/// A validated set of remote socket addresses for one logical HTTP origin.
24///
25/// The addresses control only the physical TCP destination. The request URL,
26/// HTTP authority, TLS SNI, certificate verification, and origin policy still
27/// use the logical URL. An empty set cannot be constructed. Callers are
28/// responsible for validating that the addresses are appropriate for their
29/// application and redirect policy.
30#[derive(Clone, PartialEq, Eq)]
31pub struct ResolvedTarget {
32    addresses: Arc<[SocketAddr]>,
33}
34
35impl ResolvedTarget {
36    /// Construct a resolved destination from one or more socket addresses.
37    ///
38    /// # Errors
39    ///
40    /// Returns [`crate::Error::InvalidResolvedTarget`] for an empty set.
41    pub fn new<I>(addresses: I) -> crate::Result<Self>
42    where
43        I: IntoIterator<Item = SocketAddr>,
44    {
45        let addresses: Vec<_> = addresses.into_iter().collect();
46        if addresses.is_empty() {
47            return Err(crate::Error::InvalidResolvedTarget(
48                "resolved destination set must not be empty".into(),
49            ));
50        }
51        Ok(Self {
52            addresses: addresses.into(),
53        })
54    }
55
56    /// Return the caller-supplied destination addresses in their attempt order.
57    #[must_use]
58    pub fn addresses(&self) -> &[SocketAddr] {
59        &self.addresses
60    }
61}
62
63impl std::fmt::Debug for ResolvedTarget {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        f.debug_struct("ResolvedTarget")
66            .field("address_count", &self.addresses.len())
67            .finish()
68    }
69}
70
71/// Typed transport-level hints carried on a request.
72///
73/// These are *not* HTTP headers and do not affect logical URL semantics
74/// (routing, cookies, auth-origin comparisons, redirects, proxy selection).
75/// They control only the wire-level behavior of the transport layer.
76///
77/// Timeout is kept in the existing [`Timeout`] model and must not be
78/// duplicated here.
79#[derive(Default, Clone)]
80pub struct TransportHints {
81    /// Override the wire request target (e.g. `OPTIONS *`, absolute-form).
82    ///
83    /// When present this replaces only the URI sent on the wire; the
84    /// logical URL used for connection routing, Host header defaults,
85    /// cookies, auth, redirects, and proxy selection remains unchanged.
86    pub target: Option<Bytes>,
87    /// Override the TLS Server Name Indication hostname.
88    ///
89    /// TCP connects to the URL host/IP; TLS uses this name for SNI and
90    /// certificate verification.
91    pub sni_hostname: Option<String>,
92    /// Caller-supplied physical destinations for the logical URL origin.
93    ///
94    /// When present, direct routing uses exactly these addresses and never
95    /// performs a DNS lookup. Same-origin redirects preserve this snapshot;
96    /// cross-origin redirects fail closed. Proxy, UDS, and HTTP/3 routes are
97    /// rejected while this hint is active.
98    pub resolved_target: Option<ResolvedTarget>,
99    /// Optional trace observer for transport lifecycle events.
100    ///
101    /// When present, the transport layer emits typed events at each
102    /// lifecycle boundary (TCP connect, TLS handshake, request/response
103    /// headers, body chunks, connection close). The observer is invoked
104    /// synchronously within the async context and must not block.
105    pub trace: Option<Arc<dyn TraceObserver>>,
106}
107
108impl std::fmt::Debug for TransportHints {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        f.debug_struct("TransportHints")
111            .field("target", &self.target)
112            .field("sni_hostname", &self.sni_hostname)
113            .field("resolved_target", &self.resolved_target)
114            .field("trace", &self.trace.as_ref().map(|_| "..."))
115            .finish()
116    }
117}
118
119/// Proxy override for a specific request.
120///
121/// Controls whether a request inherits the client-level proxy,
122/// bypasses the proxy entirely, or uses a specific proxy configuration.
123#[derive(Debug, Clone, Default)]
124#[allow(
125    clippy::large_enum_variant,
126    reason = "ProxyConfig is transient and cloning it is cheap; boxing adds unnecessary allocation"
127)]
128pub enum ProxyOverride {
129    /// Inherit the client-level proxy configuration (default).
130    #[default]
131    Inherit,
132    /// Send the request directly, bypassing any client proxy.
133    Direct,
134    /// Use a specific proxy configuration for this request.
135    #[cfg(feature = "proxy")]
136    Override(ProxyConfig),
137}
138
139/// Parts returned by [`Request::into_parts`].
140///
141/// This is the complete logical-request state carried across retry and
142/// redirect policy transformations. All reconstruction goes through the
143/// typed helpers below so a newly added field fails to compile (via
144/// exhaustive construction) rather than being silently dropped.
145pub(crate) struct RequestParts {
146    pub(crate) method: http::Method,
147    pub(crate) url: url::Url,
148    pub(crate) headers: Headers,
149    pub(crate) body: RequestBody,
150    pub(crate) version: Version,
151    pub(crate) timeout: Option<Timeout>,
152    pub(crate) redirect: Option<RedirectPolicy>,
153    pub(crate) auth: Option<AuthScheme>,
154    pub(crate) auth_disabled: bool,
155    pub(crate) decompress: Option<bool>,
156    pub(crate) max_decoded_body_size: Option<usize>,
157    pub(crate) max_decompression_ratio: Option<f64>,
158    pub(crate) proxy_override: ProxyOverride,
159    pub(crate) retry: Option<RetryPolicy>,
160    pub(crate) transport_hints: TransportHints,
161}
162
163impl RequestParts {
164    /// Reassemble the parts into a [`Request`] without body replay.
165    ///
166    /// Exhaustively constructs the request so adding a field to
167    /// [`RequestParts`] without updating this path is a compile error.
168    /// Used by regression tests as the canonical round-trip anchor; the
169    /// live retry path uses [`Self::retry_request`] with a shrunk deadline.
170    #[allow(
171        dead_code,
172        reason = "exhaustiveness anchor for RequestParts: guarantees new fields fail to compile even though live code uses retry_request"
173    )]
174    pub(crate) fn into_request(self) -> Request {
175        let RequestParts {
176            method,
177            url,
178            headers,
179            body,
180            version,
181            timeout,
182            redirect,
183            auth,
184            auth_disabled,
185            decompress,
186            max_decoded_body_size,
187            max_decompression_ratio,
188            proxy_override,
189            retry,
190            transport_hints,
191        } = self;
192        let mut request = Request::new(method, url);
193        *request.headers_mut() = headers;
194        request.set_body(body);
195        request.set_version(version);
196        request.set_timeout(timeout);
197        request.set_redirect(redirect);
198        request.set_auth(auth);
199        request.set_auth_disabled(auth_disabled);
200        request.set_decompress(decompress);
201        request.set_max_decoded_body_size(max_decoded_body_size);
202        request.set_max_decompression_ratio(max_decompression_ratio);
203        #[cfg(feature = "proxy")]
204        request.set_proxy_override(proxy_override);
205        #[cfg(not(feature = "proxy"))]
206        let _ = proxy_override;
207        request.set_retry(retry);
208        request.set_transport_hints(transport_hints);
209        request
210    }
211
212    /// Build the retry attempt for the same logical request.
213    ///
214    /// Preserves every request-local override that remains valid for
215    /// another attempt (including transport hints, proxy/decompression
216    /// overrides, auth-disable state, redirect and retry policy) while
217    /// applying the shrunk `attempt_timeout` for the remaining total
218    /// deadline. Non-replayable stream bodies return the existing
219    /// [`crate::error::Error::BodyNotReplayableForRetry`] classification.
220    ///
221    /// # Errors
222    ///
223    /// Returns [`crate::error::Error::BodyNotReplayableForRetry`] when the
224    /// saved body is a one-shot stream.
225    pub(crate) fn retry_request(
226        &self,
227        attempt_timeout: Option<Timeout>,
228    ) -> crate::error::Result<Request> {
229        let replayed = self.body.try_clone_for_retry()?;
230        let mut request = Request::new(self.method.clone(), self.url.clone());
231        *request.headers_mut() = self.headers.clone();
232        request.set_body(replayed);
233        request.set_version(self.version);
234        request.set_timeout(attempt_timeout);
235        request.set_redirect(self.redirect.clone());
236        request.set_auth(self.auth.clone());
237        request.set_auth_disabled(self.auth_disabled);
238        request.set_decompress(self.decompress);
239        request.set_max_decoded_body_size(self.max_decoded_body_size);
240        request.set_max_decompression_ratio(self.max_decompression_ratio);
241        #[cfg(feature = "proxy")]
242        request.set_proxy_override(self.proxy_override.clone());
243        request.set_retry(self.retry.clone());
244        request.set_transport_hints(self.transport_hints.clone());
245        Ok(request)
246    }
247
248    /// Apply a shrunk total deadline to a timeout value.
249    ///
250    /// Returns the timeout with `total` replaced by `total - elapsed`
251    /// (saturating). Used by both retry and redirect loops so the original
252    /// total deadline shrinks rather than restarting on each attempt/hop.
253    pub(crate) fn shrink_total_deadline(
254        timeout: &Timeout,
255        elapsed: std::time::Duration,
256    ) -> Timeout {
257        let mut out = *timeout;
258        if let Some(total) = out.total {
259            out.total = Some(total.saturating_sub(elapsed));
260        }
261        out
262    }
263}
264
265/// An outgoing HTTP request.
266///
267/// # Security
268///
269/// The `Debug` implementation redacts secrets: the URL is rendered without
270/// userinfo, query parameters, or fragments (query strings routinely carry
271/// API keys), sensitive headers use the redacted form, and the body is
272/// summarized by length only. See [`crate::redact`].
273pub struct Request {
274    method: http::Method,
275    url: url::Url,
276    headers: Headers,
277    body: RequestBody,
278    version: Version,
279    timeout: Option<Timeout>,
280    redirect: Option<RedirectPolicy>,
281    auth: Option<AuthScheme>,
282    auth_disabled: bool,
283    decompress: Option<bool>,
284    max_decoded_body_size: Option<usize>,
285    max_decompression_ratio: Option<f64>,
286    /// Proxy override: `None` = inherit, `Some(None)` = direct, `Some(Some(c))` = explicit.
287    proxy_override: ProxyOverride,
288    /// Per-request retry policy override.
289    retry: Option<RetryPolicy>,
290    /// Typed transport-level hints (target override, SNI hostname, etc.).
291    transport_hints: TransportHints,
292}
293
294impl std::fmt::Debug for Request {
295    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
296        f.debug_struct("Request")
297            .field("method", &self.method)
298            .field("url", &crate::redact::redact_url(&self.url))
299            .field("headers", &self.headers)
300            .field("body", &self.body)
301            .field("version", &self.version)
302            .field("timeout", &self.timeout)
303            .field("redirect", &self.redirect)
304            .field("auth", &self.auth)
305            .field("auth_disabled", &self.auth_disabled)
306            .field("decompress", &self.decompress)
307            .field("max_decoded_body_size", &self.max_decoded_body_size)
308            .field("max_decompression_ratio", &self.max_decompression_ratio)
309            .field("proxy_override", &self.proxy_override)
310            .field("retry", &self.retry)
311            .field("transport_hints", &self.transport_hints)
312            .finish()
313    }
314}
315
316impl Request {
317    /// Create a new request (crate-internal).
318    pub(crate) fn new(method: http::Method, url: url::Url) -> Self {
319        Self {
320            method,
321            url,
322            headers: Headers::new(),
323            body: RequestBody::default(),
324            version: Version::HTTP_11,
325            timeout: None,
326            redirect: None,
327            auth: None,
328            auth_disabled: false,
329            decompress: None,
330            max_decoded_body_size: None,
331            max_decompression_ratio: None,
332            proxy_override: ProxyOverride::Inherit,
333            retry: None,
334            transport_hints: TransportHints::default(),
335        }
336    }
337
338    /// Returns the HTTP method.
339    #[must_use]
340    pub fn method(&self) -> &http::Method {
341        &self.method
342    }
343
344    /// Returns the request URL.
345    #[must_use]
346    pub fn url(&self) -> &url::Url {
347        &self.url
348    }
349
350    /// Returns a reference to the request headers.
351    #[must_use]
352    pub fn headers(&self) -> &Headers {
353        &self.headers
354    }
355
356    /// Returns a mutable reference to the request headers.
357    pub fn headers_mut(&mut self) -> &mut Headers {
358        &mut self.headers
359    }
360
361    /// Returns the request body.
362    #[must_use]
363    pub fn body(&self) -> &RequestBody {
364        &self.body
365    }
366
367    /// Set the request body.
368    pub fn set_body(&mut self, body: RequestBody) {
369        self.body = body;
370    }
371
372    /// Returns the HTTP version.
373    #[must_use]
374    pub fn version(&self) -> Version {
375        self.version
376    }
377
378    /// Set the HTTP version.
379    pub fn set_version(&mut self, version: Version) {
380        self.version = version;
381    }
382
383    /// Returns the request timeout configuration, if set.
384    #[must_use]
385    pub fn timeout(&self) -> Option<&Timeout> {
386        self.timeout.as_ref()
387    }
388
389    /// Set the request-level timeout.
390    pub fn set_timeout(&mut self, timeout: Option<Timeout>) {
391        self.timeout = timeout;
392    }
393
394    /// Returns the request-level redirect policy override, if set.
395    #[must_use]
396    pub fn redirect(&self) -> Option<&RedirectPolicy> {
397        self.redirect.as_ref()
398    }
399
400    /// Set the request-level redirect policy override.
401    pub fn set_redirect(&mut self, redirect: Option<RedirectPolicy>) {
402        self.redirect = redirect;
403    }
404
405    /// Returns a reference to the request-level auth override, if set.
406    #[must_use]
407    pub fn auth(&self) -> Option<&AuthScheme> {
408        self.auth.as_ref()
409    }
410
411    /// Set the request-level auth override.
412    pub fn set_auth(&mut self, auth: Option<AuthScheme>) {
413        self.auth = auth;
414    }
415
416    /// Returns whether auth has been explicitly disabled for this request.
417    #[must_use]
418    pub fn is_auth_disabled(&self) -> bool {
419        self.auth_disabled
420    }
421
422    /// Mark this request as having auth explicitly disabled.
423    pub fn set_auth_disabled(&mut self, disabled: bool) {
424        self.auth_disabled = disabled;
425    }
426
427    /// Returns the per-request decompression override, if set.
428    ///
429    /// - `Some(true)`: force decompression on
430    /// - `Some(false)`: force decompression off
431    /// - `None`: use client-level setting
432    #[must_use]
433    pub fn decompress(&self) -> Option<bool> {
434        self.decompress
435    }
436
437    /// Set the per-request decompression override.
438    pub fn set_decompress(&mut self, decompress: Option<bool>) {
439        self.decompress = decompress;
440    }
441
442    /// Returns the per-request decoded response body size limit, if set.
443    ///
444    /// `None` means the client-level setting is used.
445    #[must_use]
446    pub fn max_decoded_body_size(&self) -> Option<usize> {
447        self.max_decoded_body_size
448    }
449
450    /// Set the per-request decoded response body size limit.
451    pub fn set_max_decoded_body_size(&mut self, max: Option<usize>) {
452        self.max_decoded_body_size = max;
453    }
454
455    /// Returns the per-request decompression ratio limit, if set.
456    ///
457    /// `None` means the client-level setting is used.
458    #[must_use]
459    pub fn max_decompression_ratio(&self) -> Option<f64> {
460        self.max_decompression_ratio
461    }
462
463    /// Set the per-request decompression ratio limit.
464    pub fn set_max_decompression_ratio(&mut self, ratio: Option<f64>) {
465        self.max_decompression_ratio = ratio;
466    }
467
468    /// Returns the proxy override for this request.
469    #[cfg(feature = "proxy")]
470    #[must_use]
471    pub fn proxy_override(&self) -> &ProxyOverride {
472        &self.proxy_override
473    }
474
475    /// Set the per-request proxy override.
476    #[cfg(feature = "proxy")]
477    pub fn set_proxy_override(&mut self, proxy: ProxyOverride) {
478        self.proxy_override = proxy;
479    }
480
481    /// Returns the per-request retry policy override, if set.
482    #[must_use]
483    pub fn retry(&self) -> Option<&RetryPolicy> {
484        self.retry.as_ref()
485    }
486
487    /// Set the per-request retry policy override.
488    pub fn set_retry(&mut self, retry: Option<RetryPolicy>) {
489        self.retry = retry;
490    }
491
492    /// Returns a reference to the transport hints for this request.
493    #[must_use]
494    pub fn transport_hints(&self) -> &TransportHints {
495        &self.transport_hints
496    }
497
498    /// Set the transport hints for this request.
499    pub fn set_transport_hints(&mut self, hints: TransportHints) {
500        self.transport_hints = hints;
501    }
502
503    /// Decompose a request into its parts.
504    ///
505    /// Returns the request fields as named parts.
506    pub(crate) fn into_parts(self) -> RequestParts {
507        RequestParts {
508            method: self.method,
509            url: self.url,
510            headers: self.headers,
511            body: self.body,
512            version: self.version,
513            timeout: self.timeout,
514            redirect: self.redirect,
515            auth: self.auth,
516            auth_disabled: self.auth_disabled,
517            decompress: self.decompress,
518            max_decoded_body_size: self.max_decoded_body_size,
519            max_decompression_ratio: self.max_decompression_ratio,
520            proxy_override: self.proxy_override,
521            retry: self.retry,
522            transport_hints: self.transport_hints,
523        }
524    }
525}
526
527/// Fluent builder for constructing requests.
528pub struct RequestBuilder {
529    client: Option<Client>,
530    method: http::Method,
531    url: url::Url,
532    headers: Headers,
533    body: RequestBody,
534    timeout: Option<Timeout>,
535    redirect: Option<RedirectPolicy>,
536    auth: Option<AuthScheme>,
537    auth_disabled: bool,
538    decompress: Option<bool>,
539    max_decoded_body_size: Option<usize>,
540    max_decompression_ratio: Option<f64>,
541    proxy_override: ProxyOverride,
542    retry: Option<RetryPolicy>,
543    transport_hints: TransportHints,
544    error: Option<crate::Error>,
545}
546
547impl RequestBuilder {
548    /// Create a new request builder associated with a client.
549    pub(crate) fn new(client: Client, method: http::Method, url: url::Url) -> Self {
550        Self {
551            client: Some(client),
552            method,
553            url,
554            headers: Headers::new(),
555            body: RequestBody::default(),
556            timeout: None,
557            redirect: None,
558            auth: None,
559            auth_disabled: false,
560            decompress: None,
561            max_decoded_body_size: None,
562            max_decompression_ratio: None,
563            proxy_override: ProxyOverride::Inherit,
564            retry: None,
565            transport_hints: TransportHints::default(),
566            error: None,
567        }
568    }
569
570    /// Add a single header to the request.
571    #[must_use]
572    pub fn header(mut self, name: &str, value: &str) -> Self {
573        if let Err(e) = self.headers.insert(name, value) {
574            if self.error.is_none() {
575                self.error = Some(e);
576            }
577        }
578        self
579    }
580
581    /// Replace all headers with the provided set.
582    #[must_use]
583    pub fn headers(mut self, headers: Headers) -> Self {
584        self.headers = headers;
585        self
586    }
587
588    /// Append a query parameter to the URL.
589    #[must_use]
590    pub fn query(mut self, key: &str, value: &str) -> Self {
591        self.url.query_pairs_mut().append_pair(key, value);
592        self
593    }
594
595    /// Set the request body from any type that converts into `RequestBody`.
596    #[must_use]
597    pub fn body(mut self, body: impl Into<RequestBody>) -> Self {
598        self.body = body.into();
599        self
600    }
601
602    /// Set the request body from bytes.
603    #[must_use]
604    pub fn bytes(self, data: impl Into<Bytes>) -> Self {
605        self.body(RequestBody::Bytes(data.into()))
606    }
607
608    /// Serialize a value as JSON and use it as a replayable request body.
609    ///
610    /// Sets `Content-Type: application/json` unless the request already has
611    /// an explicit content type. The value is serialized before any network
612    /// operation; serialization failures are returned immediately. Like the
613    /// other body setters, this replaces a body set earlier in the chain. A
614    /// later `body()` or `bytes()` call replaces the JSON bytes; it does not
615    /// remove a content type that was already set.
616    ///
617    /// # Errors
618    ///
619    /// Returns [`crate::Error::JsonSerialize`] when the value cannot be
620    /// serialized, or a header error if the default content type is invalid.
621    #[cfg(feature = "json")]
622    pub fn json<T: serde::Serialize>(mut self, value: &T) -> Result<Self> {
623        let bytes = serde_json::to_vec(value)
624            .map_err(|_| crate::Error::JsonSerialize("failed to serialize JSON value".into()))?;
625        self.body = RequestBody::Bytes(Bytes::from(bytes));
626        if !self.headers.contains("content-type") {
627            self.headers.insert("content-type", "application/json")?;
628        }
629        Ok(self)
630    }
631
632    /// Set the timeout for this specific request.
633    ///
634    /// When set, this overrides the client-level timeout on a per-field
635    /// basis: only fields present here replace the corresponding
636    /// client-level fields.
637    #[must_use]
638    pub fn timeout(mut self, timeout: Timeout) -> Self {
639        self.timeout = Some(timeout);
640        self
641    }
642
643    /// Override the redirect policy for this specific request.
644    ///
645    /// When set, this overrides the client-level redirect policy for
646    /// this request only.
647    #[must_use]
648    pub fn redirect_policy(mut self, policy: RedirectPolicy) -> Self {
649        self.redirect = Some(policy);
650        self
651    }
652
653    /// Set authentication for this specific request.
654    ///
655    /// Overrides client-level auth.
656    #[must_use]
657    pub fn auth(mut self, auth: impl Into<AuthScheme>) -> Self {
658        self.auth = Some(auth.into());
659        self.auth_disabled = false;
660        self
661    }
662
663    /// Disable authentication for this specific request.
664    ///
665    /// When set, no auth is applied to this request even if the client
666    /// has a default auth configured.
667    #[must_use]
668    pub fn without_auth(mut self) -> Self {
669        self.auth_disabled = true;
670        self.auth = None;
671        self
672    }
673
674    /// Override the proxy for this specific request.
675    ///
676    /// When set, this proxy is used instead of the client-level proxy.
677    #[cfg(feature = "proxy")]
678    #[must_use]
679    pub fn proxy(mut self, proxy: &crate::proxy::Proxy) -> Self {
680        self.proxy_override = ProxyOverride::Override(proxy.config());
681        self
682    }
683
684    /// Disable proxy for this specific request.
685    ///
686    /// When set, the request is sent directly without going through
687    /// any proxy, even if the client has a default proxy configured.
688    #[cfg(feature = "proxy")]
689    #[must_use]
690    pub fn without_proxy(mut self) -> Self {
691        self.proxy_override = ProxyOverride::Direct;
692        self
693    }
694
695    /// Override decompression for this specific request.
696    ///
697    /// - `true`: enable decompression regardless of client setting
698    /// - `false`: disable decompression regardless of client setting
699    #[must_use]
700    pub fn decompress(mut self, decompress: bool) -> Self {
701        self.decompress = Some(decompress);
702        self
703    }
704
705    /// Override the client decoded response body size limit for this request.
706    ///
707    /// The request setting takes precedence over the client setting and is
708    /// carried across retries and redirects. A value of zero rejects any
709    /// non-empty decoded response body.
710    #[must_use]
711    pub fn max_decoded_body_size(mut self, max: usize) -> Self {
712        self.max_decoded_body_size = Some(max);
713        self
714    }
715
716    /// Override the client decompression ratio limit for this request.
717    ///
718    /// The request setting takes precedence over the client setting and is
719    /// carried across retries and redirects.
720    ///
721    /// # Panics
722    ///
723    /// Panics if `ratio` is not finite or not positive.
724    #[must_use]
725    pub fn max_decompression_ratio(mut self, ratio: f64) -> Self {
726        assert!(
727            ratio.is_finite() && ratio > 0.0,
728            "max_decompression_ratio must be finite and positive, got {ratio}"
729        );
730        self.max_decompression_ratio = Some(ratio);
731        self
732    }
733
734    /// Override the retry policy for this specific request.
735    ///
736    /// When set, this overrides the client-level retry policy for
737    /// this request only.
738    #[must_use]
739    pub fn retry(mut self, policy: RetryPolicy) -> Self {
740        self.retry = Some(policy);
741        self
742    }
743
744    /// Disable retries for this specific request, even if the client
745    /// has a retry policy configured.
746    #[must_use]
747    pub fn without_retry(mut self) -> Self {
748        self.retry = Some(RetryPolicy::default());
749        self
750    }
751
752    /// Set the transport hints for this request.
753    ///
754    /// Transport hints control wire-level behavior (target override,
755    /// SNI hostname) without affecting logical URL semantics.
756    #[must_use]
757    pub fn transport_hints(mut self, hints: TransportHints) -> Self {
758        self.transport_hints = hints;
759        self
760    }
761
762    /// Pin this request to caller-supplied remote destinations.
763    ///
764    /// The logical URL remains unchanged for HTTP authority, TLS identity,
765    /// redirects, cookies, and authentication. The set must be non-empty and
766    /// each address must use the URL's effective HTTP/HTTPS port. Static
767    /// routing is direct-only; proxy and HTTP/3 combinations fail closed.
768    #[must_use]
769    pub fn resolved_addresses<I>(mut self, addresses: I) -> Self
770    where
771        I: IntoIterator<Item = SocketAddr>,
772    {
773        match ResolvedTarget::new(addresses) {
774            Ok(target) => self.transport_hints.resolved_target = Some(target),
775            Err(error) => {
776                if self.error.is_none() {
777                    self.error = Some(error);
778                }
779            }
780        }
781        self
782    }
783
784    /// Build the request without sending it.
785    ///
786    /// # Errors
787    ///
788    /// Returns an error if a previous builder step failed (e.g., invalid
789    /// header).
790    pub fn build(mut self) -> Result<Request> {
791        if let Some(e) = self.error.take() {
792            return Err(e);
793        }
794        if let Some(target) = &self.transport_hints.resolved_target {
795            let expected_port = self.url.port_or_known_default().ok_or_else(|| {
796                crate::Error::InvalidResolvedTarget(
797                    "resolved destinations require an HTTP or HTTPS URL".into(),
798                )
799            })?;
800            if target
801                .addresses()
802                .iter()
803                .any(|address| address.port() != expected_port)
804            {
805                return Err(crate::Error::InvalidResolvedTarget(format!(
806                    "all resolved destinations must use the URL's effective port {expected_port}"
807                )));
808            }
809        }
810        let request_target = self
811            .transport_hints
812            .target
813            .as_deref()
814            .unwrap_or_else(|| self.url.as_str().as_bytes());
815        self.headers
816            .validate_request_size(&self.method, request_target)?;
817        let mut req = Request::new(self.method, self.url);
818        req.headers = self.headers;
819        req.body = self.body;
820        req.timeout = self.timeout;
821        req.redirect = self.redirect;
822        req.auth = self.auth;
823        req.auth_disabled = self.auth_disabled;
824        req.decompress = self.decompress;
825        req.max_decoded_body_size = self.max_decoded_body_size;
826        req.max_decompression_ratio = self.max_decompression_ratio;
827        req.proxy_override = self.proxy_override;
828        req.retry = self.retry;
829        req.transport_hints = self.transport_hints;
830        Ok(req)
831    }
832
833    /// Build and send the request.
834    ///
835    /// # Errors
836    ///
837    /// Returns an error if the request could not be built or sent.
838    pub async fn send(self) -> Result<Response> {
839        let client = self.client.clone().ok_or_else(|| {
840            crate::Error::RequestBuild("no client associated with request builder".into())
841        })?;
842        let request = self.build()?;
843        Box::pin(client.send(request)).await
844    }
845}
846
847#[cfg(test)]
848mod tests {
849    use proptest::prelude::*;
850
851    use super::{Request, ResolvedTarget};
852    use crate::auth::{AuthScheme, BasicAuth};
853    use bytes::Bytes;
854    use std::net::SocketAddr;
855
856    proptest::proptest! {
857        #[test]
858        fn url_parse_round_trip(scheme in "https?", host in "[a-z]{2,10}\\.[a-z]{2,5}", path in "/[a-z]{0,20}") {
859            let url_str = format!("{scheme}://{host}{path}");
860            let parsed = url::Url::parse(&url_str).unwrap();
861            let serialized = parsed.to_string();
862            prop_assert_eq!(url_str, serialized);
863        }
864
865        #[test]
866        fn query_pairs_round_trip(key in "[a-z]{1,10}", value in "[a-z0-9]{1,20}") {
867            let mut url = url::Url::parse("http://example.com/").unwrap();
868            url.query_pairs_mut().append_pair(&key, &value);
869            let found = url.query_pairs().find(|(k, _)| k == &key).map(|(_, v)| v.into_owned());
870            prop_assert_eq!(found, Some(value));
871        }
872
873        #[test]
874        fn url_with_arbitrary_path(path in "/[a-zA-Z0-9._/-]{0,50}") {
875            let url_str = format!("http://example.com{path}");
876            // Must not panic
877            let _ = url::Url::parse(&url_str);
878        }
879    }
880
881    #[test]
882    fn request_debug_redacts_secrets() {
883        let url = url::Url::parse("https://example.com/submit?api_key=top-secret-key").unwrap();
884        let mut req = Request::new(http::Method::POST, url);
885        req.headers_mut()
886            .insert("authorization", "Bearer bearer-secret-token")
887            .unwrap();
888        req.headers_mut()
889            .insert("cookie", "session=cookie-secret")
890            .unwrap();
891        req.set_body(crate::body::RequestBody::Bytes(Bytes::from(
892            "password=form-secret",
893        )));
894        req.set_auth(Some(AuthScheme::Basic(
895            BasicAuth::new("user", "auth-secret").unwrap(),
896        )));
897        let debug = format!("{req:?}");
898        for leaked in [
899            "top-secret-key",
900            "bearer-secret-token",
901            "cookie-secret",
902            "form-secret",
903            "auth-secret",
904        ] {
905            assert!(
906                !debug.contains(leaked),
907                "Request Debug must not leak {leaked:?}: {debug}"
908            );
909        }
910        // Non-secret structure is still visible for diagnostics.
911        assert!(debug.contains("example.com"), "keeps the host: {debug}");
912        assert!(debug.contains("POST"), "keeps the method: {debug}");
913    }
914
915    #[test]
916    fn resolved_target_rejects_empty_and_hides_addresses_in_debug() {
917        assert!(ResolvedTarget::new(Vec::<SocketAddr>::new()).is_err());
918        let target = ResolvedTarget::new(["127.0.0.1:443".parse().unwrap()]).unwrap();
919        let debug = format!("{target:?}");
920        assert!(debug.contains("address_count: 1"));
921        assert!(!debug.contains("127.0.0.1"));
922    }
923
924    #[test]
925    fn request_builder_validates_resolved_target_port() {
926        let client = crate::client::Client::new();
927        let request = client
928            .get("http://example.invalid/")
929            .unwrap()
930            .resolved_addresses(["127.0.0.1:80".parse().unwrap()])
931            .build()
932            .unwrap();
933        assert_eq!(
934            request
935                .transport_hints()
936                .resolved_target
937                .as_ref()
938                .unwrap()
939                .addresses()
940                .len(),
941            1
942        );
943
944        let error = client
945            .get("http://example.invalid/")
946            .unwrap()
947            .resolved_addresses(["127.0.0.1:443".parse().unwrap()])
948            .build()
949            .unwrap_err();
950        assert_eq!(error.kind(), "invalid_resolved_target");
951    }
952
953    #[cfg(feature = "json")]
954    #[test]
955    fn request_json_sets_default_content_type_and_replayable_body() {
956        let client = crate::client::Client::new();
957        let request = client
958            .post("http://example.invalid/")
959            .unwrap()
960            .json(&serde_json::json!({"key": "value"}))
961            .unwrap()
962            .build()
963            .unwrap();
964        assert_eq!(
965            request.headers().get("content-type").unwrap(),
966            "application/json"
967        );
968        assert!(request.body().is_replayable());
969
970        let request = client
971            .post("http://example.invalid/")
972            .unwrap()
973            .header("content-type", "application/vnd.api+json")
974            .json(&serde_json::json!([1, 2, 3]))
975            .unwrap()
976            .build()
977            .unwrap();
978        assert_eq!(
979            request.headers().get("content-type").unwrap(),
980            "application/vnd.api+json"
981        );
982    }
983}