Skip to main content

eggfetch_core/
native_request.rs

1//! Native request builder for `http::Uri` targets.
2//!
3//! The high-level request builder is backed by `url::Url`, so it is only
4//! available with the `high-level-url` feature and carries the
5//! `url`/`idna`/ICU dependency closure with it. This module is the
6//! URL-free counterpart: a builder that takes an already-parsed
7//! [`http::Uri`] and dispatches through the same native frame-preserving
8//! transport as [`crate::Client::execute_http_body`]. It is available in
9//! every profile, including the minimal native slice that compiles without
10//! `url`.
11//!
12//! # Semantics
13//!
14//! The native path dispatches exactly once. It applies no redirects, no
15//! logical retries, no cookies, no authentication, no response
16//! decompression, and no decoded-body limits. The caller owns IDNA and
17//! punycode conversion before constructing the [`http::Uri`], and the
18//! built-in proxy and HTTP/3 routes reject native frame bodies.
19//!
20//! # Relationship to the high-level builder
21//!
22//! `crate::request::RequestBuilder` and this builder are deliberately
23//! separate types rather than one type with two target representations. The
24//! high-level builder owns URL semantics (query pairs, relative redirect
25//! resolution, cookie and proxy matching by URL) and returns the high-level
26//! `crate::response::Response`. This builder owns only the wire-level
27//! request and returns a plain [`http::Response`]. Keeping them separate
28//! means a native consumer can depend on the transport without pulling in
29//! the URL layer, and it keeps the existing high-level signatures intact.
30
31use bytes::Bytes;
32use http::Method;
33
34use crate::body::{NativeResponseBody, RequestBody};
35use crate::client::Client;
36use crate::error::Result;
37use crate::headers::Headers;
38use crate::redirect::RedirectPolicy;
39use crate::timeout::Timeout;
40use crate::transport_hints::{NativeRequestOptions, TransportHints};
41
42/// Builder for a native request addressed by an [`http::Uri`.
43///
44/// Create one with [`crate::Client::get_uri`] or
45/// [`crate::Client::request_uri`]. The builder is dispatched through the
46/// native transport, so it applies none of the high-level request policy:
47/// no redirect following, no logical retries, no cookie jar, no
48/// authentication, no response decompression, and no decoded-body limits.
49///
50/// The request is sent exactly once. [`Self::without_retry`] and
51/// [`Self::redirect_policy`] therefore cannot change the wire behavior;
52/// they exist so the same request-building code can express a
53/// single-attempt contract in every profile.
54pub struct NativeRequestBuilder {
55    client: Option<Client>,
56    method: Method,
57    uri: http::Uri,
58    headers: Headers,
59    body: RequestBody,
60    version: http::Version,
61    timeout: Option<Timeout>,
62    transport_hints: TransportHints,
63    /// Whether the caller asserted that this request must not be retried.
64    retry_disabled: bool,
65    /// The redirect policy the caller attached to this request.
66    redirect: Option<RedirectPolicy>,
67    error: Option<crate::Error>,
68}
69
70impl std::fmt::Debug for NativeRequestBuilder {
71    /// Render the builder without the query string.
72    ///
73    /// A native URI is caller-owned and may carry query material (API keys
74    /// routinely travel in query parameters), so only the scheme,
75    /// authority, and path are shown.
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        let scheme = self.uri.scheme_str().unwrap_or("");
78        let authority = self
79            .uri
80            .authority()
81            .map_or("", http::uri::Authority::as_str);
82        let path = self.uri.path();
83        f.debug_struct("NativeRequestBuilder")
84            .field("method", &self.method)
85            .field("uri", &format!("{scheme}://{authority}{path}"))
86            .field("headers", &self.headers)
87            .field("body", &self.body)
88            .field("version", &self.version)
89            .field("timeout", &self.timeout)
90            .field("transport_hints", &self.transport_hints)
91            .field("retry_disabled", &self.retry_disabled)
92            .field("redirect", &self.redirect)
93            .finish_non_exhaustive()
94    }
95}
96
97impl NativeRequestBuilder {
98    /// Create a new native request builder associated with a client.
99    pub(crate) fn new(client: Client, method: Method, uri: http::Uri) -> Self {
100        Self {
101            client: Some(client),
102            method,
103            uri,
104            headers: Headers::new(),
105            body: RequestBody::default(),
106            version: http::Version::HTTP_11,
107            timeout: None,
108            transport_hints: TransportHints::default(),
109            retry_disabled: false,
110            redirect: None,
111            error: None,
112        }
113    }
114
115    /// Add a single header to the request.
116    ///
117    /// An invalid header name or value is recorded and reported by
118    /// [`Self::build`] and [`Self::send`].
119    #[must_use]
120    pub fn header(mut self, name: &str, value: &str) -> Self {
121        if let Err(error) = self.headers.insert(name, value) {
122            if self.error.is_none() {
123                self.error = Some(error);
124            }
125        }
126        self
127    }
128
129    /// Replace all headers with the provided set.
130    #[must_use]
131    pub fn headers(mut self, headers: Headers) -> Self {
132        self.headers = headers;
133        self
134    }
135
136    /// Set the request body from any type that converts into
137    /// [`RequestBody`].
138    #[must_use]
139    pub fn body(mut self, body: impl Into<RequestBody>) -> Self {
140        self.body = body.into();
141        self
142    }
143
144    /// Set the request body from bytes.
145    #[must_use]
146    pub fn bytes(self, data: impl Into<Bytes>) -> Self {
147        self.body(RequestBody::Bytes(data.into()))
148    }
149
150    /// Set the HTTP version for this request.
151    ///
152    /// The default is HTTP/1.1. HTTP/2 is selected by protocol negotiation
153    /// unless the client is built with an explicit version policy.
154    #[must_use]
155    pub fn version(mut self, version: http::Version) -> Self {
156        self.version = version;
157        self
158    }
159
160    /// Set the timeout for this specific request.
161    ///
162    /// When set, this overrides the client-level timeout on a per-field
163    /// basis: only fields present here replace the corresponding
164    /// client-level fields.
165    #[must_use]
166    pub fn timeout(mut self, timeout: Timeout) -> Self {
167        self.timeout = Some(timeout);
168        self
169    }
170
171    /// Set the transport hints for this request.
172    ///
173    /// Transport hints control wire-level behavior (target override, SNI
174    /// hostname, resolved destination) without affecting logical URL
175    /// semantics.
176    #[must_use]
177    pub fn transport_hints(mut self, hints: TransportHints) -> Self {
178        self.transport_hints = hints;
179        self
180    }
181
182    /// Assert that this request must not be retried.
183    ///
184    /// The native transport dispatches exactly once, so this call cannot
185    /// change the wire behavior: the assertion already holds. It exists so
186    /// a request built for the high-level API can express the same
187    /// single-attempt contract in a profile that compiles out the retry
188    /// engine.
189    #[must_use]
190    pub fn without_retry(mut self) -> Self {
191        self.retry_disabled = true;
192        self
193    }
194
195    /// Attach a redirect policy to this request.
196    ///
197    /// The native transport never follows redirects, so this call cannot
198    /// change the wire behavior: a 3xx response is returned unchanged. It
199    /// exists so a request built for the high-level API can express the
200    /// same "do not follow redirects" contract in a profile that compiles
201    /// out the redirect loop.
202    #[must_use]
203    pub fn redirect_policy(mut self, policy: RedirectPolicy) -> Self {
204        self.redirect = Some(policy);
205        self
206    }
207
208    /// Build the request without sending it.
209    ///
210    /// # Errors
211    ///
212    /// Returns an error if a previous builder step failed (for example an
213    /// invalid header).
214    pub fn build(self) -> Result<http::Request<RequestBody>> {
215        if let Some(error) = self.error {
216            return Err(error);
217        }
218        let mut request = http::Request::new(self.body);
219        *request.uri_mut() = self.uri;
220        *request.method_mut() = self.method;
221        *request.version_mut() = self.version;
222        *request.headers_mut() = self.headers.into_inner();
223        Ok(request)
224    }
225
226    /// Build and send the request.
227    ///
228    /// The response is an ordinary [`http::Response`] whose body is a
229    /// [`NativeResponseBody`]. The logical pool lease is held by the
230    /// response body until it reaches EOF, errors, or is dropped.
231    ///
232    /// # Errors
233    ///
234    /// Returns an error if the request could not be built or sent.
235    pub async fn send(self) -> Result<http::Response<NativeResponseBody>> {
236        let client = self.client.clone().ok_or_else(|| {
237            crate::Error::RequestBuild("no client associated with request builder".into())
238        })?;
239        let timeout = self.timeout;
240        let transport_hints = self.transport_hints.clone();
241        let request = self.build()?;
242        let options = NativeRequestOptions {
243            timeout,
244            transport_hints,
245        };
246        client.execute_http_body(request, options).await
247    }
248}