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