Skip to main content

eggfetch_core/
request.rs

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