eggfetch_core/transport_hints.rs
1//! Protocol-neutral native transport controls.
2//!
3//! `ResolvedTarget`, `TransportHints` and `NativeRequestOptions` carry only
4//! wire-level behavior (request-target override, SNI override, pinned
5//! destinations, trace observer, timeout override). They do not depend on
6//! high-level URL semantics and therefore compile in the minimal native
7//! transport slice without the `url` dependency.
8//!
9//! The historical `crate::request::{ResolvedTarget, TransportHints,
10//! NativeRequestOptions}` paths remain available as re-exports when the
11//! high-level URL feature is enabled; new code should prefer this module
12//! directly.
13
14use std::net::SocketAddr;
15use std::sync::Arc;
16
17use bytes::Bytes;
18
19use crate::timeout::Timeout;
20use crate::trace::TraceObserver;
21
22/// A validated set of remote socket addresses for one logical HTTP origin.
23///
24/// The addresses control only the physical TCP destination. The logical URI,
25/// HTTP authority, TLS SNI, certificate verification, and origin policy still
26/// use the logical origin. An empty set cannot be constructed. Callers are
27/// responsible for validating that the addresses are appropriate for their
28/// application and redirect policy.
29#[derive(Clone, PartialEq, Eq)]
30pub struct ResolvedTarget {
31 addresses: Arc<[SocketAddr]>,
32}
33
34impl ResolvedTarget {
35 /// Construct a resolved destination from one or more socket addresses.
36 ///
37 /// # Errors
38 ///
39 /// Returns [`crate::Error::InvalidResolvedTarget`] for an empty set.
40 pub fn new<I>(addresses: I) -> crate::Result<Self>
41 where
42 I: IntoIterator<Item = SocketAddr>,
43 {
44 let addresses: Vec<_> = addresses.into_iter().collect();
45 if addresses.is_empty() {
46 return Err(crate::Error::InvalidResolvedTarget(
47 "resolved destination set must not be empty".into(),
48 ));
49 }
50 Ok(Self {
51 addresses: addresses.into(),
52 })
53 }
54
55 /// Return the caller-supplied destination addresses in their attempt order.
56 #[must_use]
57 pub fn addresses(&self) -> &[SocketAddr] {
58 &self.addresses
59 }
60
61 /// Cheaply clone the ordered address snapshot for route-cache keying.
62 ///
63 /// Crate-private so the public API does not grow merely for `HashMap`
64 /// key convenience. The order is preserved exactly; callers must not
65 /// sort, deduplicate, or otherwise canonicalize it.
66 pub(crate) fn addresses_shared(&self) -> Arc<[SocketAddr]> {
67 Arc::clone(&self.addresses)
68 }
69}
70
71impl std::fmt::Debug for ResolvedTarget {
72 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73 f.debug_struct("ResolvedTarget")
74 .field("address_count", &self.addresses.len())
75 .finish()
76 }
77}
78
79/// The diagnostic used when a wire request-target extension is not UTF-8.
80///
81/// The text is shared so every transport that decodes
82/// [`TransportHints::target`] reports the same failure.
83pub(crate) const TARGET_NOT_UTF8_MESSAGE: &str = "target extension is not valid UTF-8";
84
85/// Decode a wire request-target extension as UTF-8.
86///
87/// Every transport that honors [`TransportHints::target`] decodes the same
88/// bytes, so the decode and its diagnostic live here once.
89///
90/// # Errors
91///
92/// Returns [`crate::Error::InvalidUrl`] when the extension is not valid
93/// UTF-8.
94pub(crate) fn target_extension_str(target: &[u8]) -> crate::Result<&str> {
95 std::str::from_utf8(target)
96 .map_err(|_| crate::Error::InvalidUrl(TARGET_NOT_UTF8_MESSAGE.into()))
97}
98
99/// Typed transport-level hints carried on a request.
100///
101/// These are *not* HTTP headers and do not affect logical URL semantics
102/// (routing, cookies, auth-origin comparisons, redirects, proxy selection).
103/// They control only the wire-level behavior of the transport layer.
104///
105/// Timeout is kept in the existing [`Timeout`] model and must not be
106/// duplicated here.
107#[derive(Default, Clone)]
108pub struct TransportHints {
109 /// Override the wire request target (e.g. `OPTIONS *`, absolute-form).
110 ///
111 /// When present this replaces only the URI sent on the wire; the
112 /// logical origin used for connection routing, Host header defaults,
113 /// cookies, auth, redirects, and proxy selection remains unchanged.
114 pub target: Option<Bytes>,
115 /// Override the TLS Server Name Indication hostname.
116 ///
117 /// TCP connects to the URI host/IP; TLS uses this name for SNI and
118 /// certificate verification.
119 pub sni_hostname: Option<String>,
120 /// Caller-supplied physical destinations for the logical origin.
121 ///
122 /// When present, direct routing uses exactly these addresses and never
123 /// performs a DNS lookup. Same-origin redirects preserve this snapshot;
124 /// cross-origin redirects fail closed. Proxy, UDS, and HTTP/3 routes are
125 /// rejected while this hint is active.
126 pub resolved_target: Option<ResolvedTarget>,
127 /// Optional trace observer for transport lifecycle events.
128 ///
129 /// When present, the transport layer emits typed events at each
130 /// lifecycle boundary (TCP connect, TLS handshake, request/response
131 /// headers, body chunks, connection close). The observer is invoked
132 /// synchronously within the async context and must not block.
133 pub trace: Option<Arc<dyn TraceObserver>>,
134}
135
136impl std::fmt::Debug for TransportHints {
137 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138 // `target` may carry absolute-form URIs with query material
139 // (e.g. forward-proxy `?api_key=`); log presence + length only.
140 let target = self.target.as_ref().map(bytes::Bytes::len);
141 f.debug_struct("TransportHints")
142 .field("target_len", &target)
143 .field("sni_hostname", &self.sni_hostname)
144 .field("resolved_target", &self.resolved_target)
145 .field("trace", &self.trace.as_ref().map(|_| "..."))
146 .finish()
147 }
148}
149
150/// Transport-only options for [`Client::execute_http_body`](crate::Client::execute_http_body).
151///
152/// The native body API intentionally does not apply redirects, retries,
153/// cookies, authentication, decompression, or decoded-body limits. Those
154/// policies can change or replay wire bytes and remain part of the
155/// high-level request API instead.
156#[derive(Default, Clone)]
157pub struct NativeRequestOptions {
158 /// Optional timeout override. It is merged with the client timeout using
159 /// the same phase-aware rules as ordinary requests.
160 pub timeout: Option<Timeout>,
161 /// Typed transport hints such as a resolved destination or SNI name.
162 pub transport_hints: TransportHints,
163}
164
165impl std::fmt::Debug for NativeRequestOptions {
166 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167 f.debug_struct("NativeRequestOptions")
168 .field("timeout", &self.timeout)
169 .field("transport_hints", &self.transport_hints)
170 .finish()
171 }
172}
173
174impl NativeRequestOptions {
175 /// Set a request-scoped timeout override.
176 #[must_use]
177 pub fn timeout(mut self, timeout: Timeout) -> Self {
178 self.timeout = Some(timeout);
179 self
180 }
181
182 /// Set typed transport hints for this request.
183 #[must_use]
184 pub fn transport_hints(mut self, transport_hints: TransportHints) -> Self {
185 self.transport_hints = transport_hints;
186 self
187 }
188}
189
190#[cfg(test)]
191mod tests {
192 use super::{target_extension_str, TARGET_NOT_UTF8_MESSAGE};
193
194 #[test]
195 fn target_extension_decodes_valid_utf8() {
196 assert_eq!(
197 target_extension_str(b"/absolute/path").expect("valid"),
198 "/absolute/path"
199 );
200 assert_eq!(target_extension_str(b"*").expect("valid"), "*");
201 }
202
203 #[test]
204 fn target_extension_rejects_non_utf8_with_the_shared_message() {
205 let error = target_extension_str(&[0xff, 0xfe]).expect_err("invalid UTF-8 must fail");
206 assert!(
207 matches!(&error, crate::Error::InvalidUrl(message) if message == TARGET_NOT_UTF8_MESSAGE),
208 "got {error:?}"
209 );
210 }
211}