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