Skip to main content

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/// Typed transport-level hints carried on a request.
80///
81/// These are *not* HTTP headers and do not affect logical URL semantics
82/// (routing, cookies, auth-origin comparisons, redirects, proxy selection).
83/// They control only the wire-level behavior of the transport layer.
84///
85/// Timeout is kept in the existing [`Timeout`] model and must not be
86/// duplicated here.
87#[derive(Default, Clone)]
88pub struct TransportHints {
89    /// Override the wire request target (e.g. `OPTIONS *`, absolute-form).
90    ///
91    /// When present this replaces only the URI sent on the wire; the
92    /// logical origin used for connection routing, Host header defaults,
93    /// cookies, auth, redirects, and proxy selection remains unchanged.
94    pub target: Option<Bytes>,
95    /// Override the TLS Server Name Indication hostname.
96    ///
97    /// TCP connects to the URI host/IP; TLS uses this name for SNI and
98    /// certificate verification.
99    pub sni_hostname: Option<String>,
100    /// Caller-supplied physical destinations for the logical origin.
101    ///
102    /// When present, direct routing uses exactly these addresses and never
103    /// performs a DNS lookup. Same-origin redirects preserve this snapshot;
104    /// cross-origin redirects fail closed. Proxy, UDS, and HTTP/3 routes are
105    /// rejected while this hint is active.
106    pub resolved_target: Option<ResolvedTarget>,
107    /// Optional trace observer for transport lifecycle events.
108    ///
109    /// When present, the transport layer emits typed events at each
110    /// lifecycle boundary (TCP connect, TLS handshake, request/response
111    /// headers, body chunks, connection close). The observer is invoked
112    /// synchronously within the async context and must not block.
113    pub trace: Option<Arc<dyn TraceObserver>>,
114}
115
116impl std::fmt::Debug for TransportHints {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        f.debug_struct("TransportHints")
119            .field("target", &self.target)
120            .field("sni_hostname", &self.sni_hostname)
121            .field("resolved_target", &self.resolved_target)
122            .field("trace", &self.trace.as_ref().map(|_| "..."))
123            .finish()
124    }
125}
126
127/// Transport-only options for [`Client::execute_http_body`](crate::Client::execute_http_body).
128///
129/// The native body API intentionally does not apply redirects, retries,
130/// cookies, authentication, decompression, or decoded-body limits. Those
131/// policies can change or replay wire bytes and remain part of the
132/// high-level request API instead.
133#[derive(Default, Clone)]
134pub struct NativeRequestOptions {
135    /// Optional timeout override. It is merged with the client timeout using
136    /// the same phase-aware rules as ordinary requests.
137    pub timeout: Option<Timeout>,
138    /// Typed transport hints such as a resolved destination or SNI name.
139    pub transport_hints: TransportHints,
140}
141
142impl std::fmt::Debug for NativeRequestOptions {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        f.debug_struct("NativeRequestOptions")
145            .field("timeout", &self.timeout)
146            .field("transport_hints", &self.transport_hints)
147            .finish()
148    }
149}
150
151impl NativeRequestOptions {
152    /// Set a request-scoped timeout override.
153    #[must_use]
154    pub fn timeout(mut self, timeout: Timeout) -> Self {
155        self.timeout = Some(timeout);
156        self
157    }
158
159    /// Set typed transport hints for this request.
160    #[must_use]
161    pub fn transport_hints(mut self, transport_hints: TransportHints) -> Self {
162        self.transport_hints = transport_hints;
163        self
164    }
165}