Skip to main content

trillium_client/conn/
shared.rs

1use super::{Body, Conn, Transport, TypeSet};
2use crate::{ClientHandler, ConnExt, Error, Result, Version};
3use smallvec::SmallVec;
4#[cfg(feature = "hickory")]
5use std::net::IpAddr;
6use std::{
7    borrow::Cow,
8    fmt::{self, Debug, Formatter},
9    future::{Future, IntoFuture},
10    mem,
11    net::SocketAddr,
12    pin::Pin,
13};
14use trillium_http::{ProtocolSession, Upgrade};
15use trillium_server_common::Destination;
16
17/// A wrapper error for [`trillium_http::Error`] or, depending on json serializer feature, either
18/// `sonic_rs::Error` or `serde_json::Error`. Only available when either the `sonic-rs` or
19/// `serde_json` cargo features are enabled.
20#[cfg(any(feature = "serde_json", feature = "sonic-rs"))]
21#[derive(thiserror::Error, Debug)]
22pub enum ClientSerdeError {
23    /// A [`trillium_http::Error`]
24    #[error(transparent)]
25    HttpError(#[from] Error),
26
27    #[cfg(feature = "sonic-rs")]
28    /// A [`sonic_rs::Error`]
29    #[error(transparent)]
30    JsonError(#[from] sonic_rs::Error),
31
32    #[cfg(feature = "serde_json")]
33    /// A [`serde_json::Error`]
34    #[error(transparent)]
35    JsonError(#[from] serde_json::Error),
36}
37
38impl Conn {
39    pub(crate) async fn exec(&mut self) -> Result<()> {
40        // A build-time error (e.g. a malformed url from `build_conn`) is fatal and
41        // unrecoverable: there is nothing to dial, so short-circuit before running
42        // handlers or touching the network.
43        if let Some(error) = self.error.take() {
44            return Err(error);
45        }
46
47        // Arc-clone to dodge conflict with the `&mut self` we pass to `run`.
48        let handler = self.client.arc_handler().clone();
49        handler.run(self).await?;
50
51        if !self.halted {
52            // Stash, don't return: `after_response` runs unconditionally so recovery handlers
53            // (stale-if-error, retry-with-fallback) get a chance to clear it.
54            if let Err(e) = self.exec_network().await {
55                self.error = Some(e);
56            }
57        } else {
58            log::trace!("conn is halted, skipping network round-trip");
59            // The request body is never sent when halted, so drop it here — matching the
60            // send paths, which all `.take()` it. A streaming body backed by an external
61            // producer would otherwise keep that producer parked, waiting for a read that
62            // never comes.
63            self.request_body = None;
64        }
65
66        // Reverse order, regardless of halt/error — mirrors server-side `before_send`.
67        handler.after_response(self).await?;
68
69        if let Some(e) = self.error.take() {
70            Err(e)
71        } else {
72            Ok(())
73        }
74    }
75
76    async fn exec_network(&mut self) -> Result<()> {
77        self.select_route();
78        if self.http_version == Some(Version::Http0_9) {
79            return Err(Error::UnsupportedVersion(Version::Http0_9));
80        }
81        // Dispatch treats an h3 pin as a starting point, so without this a WebTransport request
82        // that can't use h3 would continue down to an h2 or h1 upgrade that can't carry it.
83        #[cfg(feature = "webtransport")]
84        if self.protocol.as_deref() == Some("webtransport") && !self.h3_permitted() {
85            return Err(crate::webtransport::Http3Unavailable.into());
86        }
87
88        match self.exec_network_dispatch().await {
89            // The h2/h3 connection stays pooled for ordinary requests; this request re-runs as
90            // an HTTP/1.1 upgrade on a connection pinned to h1. The extended-CONNECT gates run
91            // before method, version, or pseudo-headers are committed, so the only state
92            // carried over is h1 handshake headers from an ALPN promotion, which the h1 path
93            // re-renders idempotently.
94            Err(Error::ExtendedConnectUnsupported)
95                if !self.strict_http_version && self.protocol.is_some() =>
96            {
97                log::debug!(
98                    "peer does not support extended CONNECT; retrying as an HTTP/1.1 upgrade"
99                );
100                self.http_version = Some(Version::Http1_1);
101                self.headers_finalized = false;
102                self.exec_h1_or_promote_h2().await
103            }
104            other => other,
105        }
106    }
107
108    async fn exec_network_dispatch(&mut self) -> Result<()> {
109        // Phase 1 — reuse a live pooled connection, best protocol first. No DNS, no new connect.
110        // A pooled h2 connection is reused in preference to establishing a new h3 connection: we
111        // do not proactively migrate h2→h3, since a general-purpose client can't assume the
112        // request locality that makes eager migration pay off (see the migration-policy backlog
113        // item). A pooled h1 connection, by contrast, does not block establishing h3 below.
114        if self.try_reuse_h3_pool().await? {
115            return Ok(());
116        }
117        if !self.route.is_forward() && self.try_exec_h2_pooled().await? {
118            return Ok(());
119        }
120
121        // Phase 2/3 — establish a new connection, preferring h3 when the origin is known to speak
122        // it (pinned, Alt-Svc, or SVCB). This runs before the h1 path, so h1→h3 is immediate.
123        if self.try_establish_h3().await? {
124            return Ok(());
125        }
126
127        // Prior-knowledge h2: caller asserted h2, skip h1/ALPN. Useful for TLS connectors
128        // that don't expose `negotiated_alpn` (e.g. native-tls). No fallback — a non-h2
129        // server here surfaces as a plain IO error.
130        if self.http_version == Some(Version::Http2) {
131            return self.exec_h2_prior_knowledge().await;
132        }
133
134        self.exec_h1_or_promote_h2().await
135    }
136
137    pub(crate) fn body_len(&self) -> Option<u64> {
138        if let Some(ref body) = self.request_body {
139            body.len()
140        } else {
141            Some(0)
142        }
143    }
144
145    pub(crate) fn finalize_headers(&mut self) -> Result<()> {
146        match self.http_version() {
147            Version::Http1_0 | Version::Http1_1 => self.finalize_headers_h1(),
148            Version::Http2 => self.finalize_headers_h2(),
149            Version::Http3 if self.client.h3().is_some() => self.finalize_headers_h3(),
150            other => Err(Error::UnsupportedVersion(other)),
151        }
152    }
153
154    /// The [`Destination`] for connecting to this conn's origin over h1/h2: scheme, host, and port
155    /// from the URL, plus any DoH-resolved addresses. A bare-IP origin keeps the address
156    /// [`from_url`](Destination::from_url) derived and is never resolved.
157    ///
158    /// An explicit version pin constrains the connection's ALPN so the pin is honored over TLS: an
159    /// h1 pin advertises only `http/1.1` (a server that would otherwise negotiate `h2` falls back
160    /// to h1), an h2 pin advertises only `h2`. Without a pin the connector's configured default
161    /// ALPN is left in place, so auto-discovery can promote to h2 via ALPN.
162    pub(crate) async fn origin_destination(&self) -> Result<Destination> {
163        let mut destination = Destination::from_url(&self.url)?;
164        let addrs = if self.route.is_direct() {
165            self.origin_socket_addrs().await?
166        } else {
167            SmallVec::new()
168        };
169        if !addrs.is_empty() {
170            destination.set_addrs(addrs);
171        }
172        match self.http_version {
173            Some(Version::Http1_0 | Version::Http1_1) => {
174                destination.set_alpn([Cow::Borrowed(b"http/1.1".as_slice())]);
175            }
176            Some(Version::Http2) => {
177                destination.set_alpn([Cow::Borrowed(b"h2".as_slice())]);
178            }
179            _ => {}
180        }
181        Ok(destination)
182    }
183
184    /// Pre-resolved socket addresses for this conn's origin host:port, for the protocols that
185    /// always connect to the origin (h1/h2). Empty when DoH is not configured or the host is an IP
186    /// literal, so the connector falls back to its own (trivial, for an IP) resolution.
187    pub(crate) async fn origin_socket_addrs(&self) -> Result<SmallVec<[SocketAddr; 4]>> {
188        let Some(host) = self.url.host_str() else {
189            return Ok(SmallVec::new());
190        };
191        let port = self.url.port_or_known_default().unwrap_or(443);
192        self.resolve_socket_addrs(host, port).await
193    }
194}
195
196#[cfg(feature = "hickory")]
197impl Conn {
198    /// Resolve `host:port` through the configured DoH resolver, or `None` when DoH is not
199    /// configured (so the caller falls back to the connector's own resolution).
200    ///
201    /// The single place this conn touches DNS. The resolver reads and populates a shared, TTL'd
202    /// cache as a side effect, so repeated calls for the same host — across protocols, and across
203    /// the SVCB decision and the eventual connect — issue at most one set of queries.
204    ///
205    /// Fail-closed: once DoH is configured, a lookup the resolver can't answer fails the request
206    /// rather than falling back to the (possibly plaintext) system resolver.
207    ///
208    /// An IP-literal host is returned as `None` without touching the resolver — there is nothing to
209    /// look up, and no SVCB/HTTPS records exist for a bare address.
210    pub(crate) async fn resolve(
211        &self,
212        host: &str,
213        port: u16,
214    ) -> Result<Option<crate::dns::Resolved>> {
215        if host.parse::<IpAddr>().is_ok() {
216            return Ok(None);
217        }
218        match &self.client.resolver {
219            Some(resolver) => Ok(Some(
220                resolver
221                    .resolve(&self.client, host, port, self.timeout)
222                    .await?,
223            )),
224            None => Ok(None),
225        }
226    }
227
228    pub(crate) async fn resolve_socket_addrs(
229        &self,
230        host: &str,
231        port: u16,
232    ) -> Result<SmallVec<[SocketAddr; 4]>> {
233        Ok(self
234            .resolve(host, port)
235            .await?
236            .map(|resolved| resolved.socket_addrs(port))
237            .unwrap_or_default())
238    }
239}
240
241#[cfg(not(feature = "hickory"))]
242impl Conn {
243    pub(crate) async fn resolve_socket_addrs(
244        &self,
245        _host: &str,
246        _port: u16,
247    ) -> Result<SmallVec<[SocketAddr; 4]>> {
248        Ok(SmallVec::new())
249    }
250}
251
252impl Drop for Conn {
253    fn drop(&mut self) {
254        log::trace!("dropping client conn");
255        drop(self.take_response_body());
256    }
257}
258
259impl From<Conn> for Body {
260    fn from(mut conn: Conn) -> Body {
261        // body_override (e.g. cache hit, set via `set_response_body`) bypasses the transport;
262        // transport pooling is left to `Drop`.
263        if let Some(body) = conn.body_override.take() {
264            return body;
265        }
266
267        match conn.take_received_body(true) {
268            Some(rb) => rb.into(),
269            None => Body::default(),
270        }
271    }
272}
273
274impl From<Conn> for Upgrade<Box<dyn Transport>> {
275    /// Convert a client conn into a [`trillium_http::Upgrade`] after response headers
276    /// arrive, handing off the open transport for direct `AsyncRead` / `AsyncWrite`
277    /// exchange with per-protocol framing applied.
278    ///
279    /// # Panics
280    ///
281    /// Panics if the conn has no live transport (request not yet sent, or transport
282    /// already taken).
283    fn from(mut conn: Conn) -> Self {
284        // `Conn: Drop` rules out destructuring — pull each field with `mem::take` /
285        // `mem::replace`. New fields on `Conn` won't show up here automatically.
286        let path = conn.path.take().unwrap_or_else(|| match conn.url.query() {
287            Some(q) => Cow::Owned(format!("{}?{q}", conn.url.path())),
288            None => Cow::Owned(conn.url.path().to_owned()),
289        });
290        let secure = conn.url.scheme() == "https";
291
292        Upgrade::from_parts(
293            mem::take(&mut conn.response_headers),
294            mem::take(&mut conn.request_headers),
295            path,
296            conn.method,
297            conn.transport
298                .take()
299                .expect("client conn has no transport — request not yet sent"),
300            mem::take(&mut conn.buffer),
301            mem::take(&mut conn.state),
302            conn.context.clone(),
303            None,
304            conn.authority.take(),
305            conn.scheme.take(),
306            mem::replace(&mut conn.protocol_session, ProtocolSession::Http1),
307            conn.protocol.take(),
308            conn.http_version(),
309            conn.status,
310            secure,
311            // Client-side inbound = response body.
312            mem::take(&mut conn.response_body_state),
313            // Carry through any pre-upgrade-decoded trailers so a downstream reader
314            // can observe them.
315            conn.response_trailers.take(),
316        )
317    }
318}
319
320impl IntoFuture for Conn {
321    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'static>>;
322    type Output = Result<Conn>;
323
324    fn into_future(mut self) -> Self::IntoFuture {
325        Box::pin(async move { (&mut self).await.map(|()| self) })
326    }
327}
328
329impl<'conn> IntoFuture for &'conn mut Conn {
330    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'conn>>;
331    type Output = Result<()>;
332
333    fn into_future(self) -> Self::IntoFuture {
334        Box::pin(async move {
335            // Re-issuing handlers (FollowRedirects, retry, auth-refresh) queue a follow-up
336            // via `set_followup` in `after_response`; we recycle, swap, re-exec.
337            loop {
338                let result = if let Some(duration) = self.timeout {
339                    self.client
340                        .connector()
341                        .runtime()
342                        .timeout(duration, self.exec())
343                        .await
344                        .unwrap_or(Err(Error::TimedOut("Conn", duration)))
345                } else {
346                    self.exec().await
347                };
348
349                // `halted` is handler-internal; don't leak it out to the caller.
350                self.halted = false;
351
352                if let Err(e) = result {
353                    // Unrecovered error wins over any queued follow-up. Recovery handlers
354                    // that want the follow-up to run must `take_error()` in `after_response`.
355                    self.followup = None;
356                    return Err(e);
357                }
358
359                let Some(next) = self.take_followup() else {
360                    break;
361                };
362
363                if let Some(body) = self.take_response_body() {
364                    body.recycle().await;
365                }
366
367                let _displaced = mem::replace(self, next);
368            }
369            Ok(())
370        })
371    }
372}
373
374impl Debug for Conn {
375    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
376        f.debug_struct("Conn")
377            .field("authority", &self.authority)
378            .field("buffer", &String::from_utf8_lossy(&self.buffer))
379            .field("client", &self.client)
380            .field("protocol_session", &self.protocol_session)
381            .field("http_version", &self.http_version)
382            .field("method", &self.method)
383            .field("path", &self.path)
384            .field("request_body", &self.request_body)
385            .field("request_headers", &self.request_headers)
386            .field("request_target", &self.request_target)
387            .field("request_trailers", &self.request_trailers)
388            .field("response_body_state", &self.response_body_state)
389            .field("response_headers", &self.response_headers)
390            .field("response_trailers", &self.response_trailers)
391            .field("scheme", &self.scheme)
392            .field("state", &self.state)
393            .field("status", &self.status)
394            .field("url", &self.url)
395            .finish()
396    }
397}
398
399impl AsRef<TypeSet> for Conn {
400    fn as_ref(&self) -> &TypeSet {
401        &self.state
402    }
403}
404
405impl AsMut<TypeSet> for Conn {
406    fn as_mut(&mut self) -> &mut TypeSet {
407        &mut self.state
408    }
409}