Skip to main content

trillium_client/
conn.rs

1use crate::{
2    Client, ResponseBody,
3    response_body::{CleanupContext, OverrideBody},
4    util::encoding,
5};
6use std::{borrow::Cow, mem, net::SocketAddr, sync::Arc, time::Duration};
7use trillium_http::{
8    Body, Buffer, Error, HeaderName, HeaderValues, Headers, HttpContext, Method, ProtocolSession,
9    ReceivedBody, ReceivedBodyState, Status, TypeSet, Version,
10};
11use trillium_server_common::{Transport, url::Url};
12
13mod h1;
14pub(crate) use h1::{request_head, response_head};
15#[cfg(test)]
16mod h1_tests;
17mod h2;
18mod h3;
19mod request_body_buffer;
20mod route;
21mod shared;
22pub(crate) use route::{Route, RouteKey};
23mod unexpected_status_error;
24
25pub(crate) use h2::H2Pooled;
26#[cfg(any(feature = "serde_json", feature = "sonic-rs"))]
27pub use shared::ClientSerdeError;
28pub use unexpected_status_error::UnexpectedStatusError;
29
30/// a client connection, representing both an outbound http request and a
31/// http response
32#[must_use]
33#[derive(fieldwork::Fieldwork)]
34pub struct Conn {
35    pub(crate) protocol_session: ProtocolSession,
36    /// QUIC-connection WebTransport dispatcher slot (lazy-init) and the QUIC connection
37    /// itself, retained on extended-CONNECT-with-`:protocol = webtransport` requests so
38    /// `into_webtransport` can install the router and hand the QUIC connection to the
39    /// returned [`WebTransportConnection`][trillium_webtransport::WebTransportConnection].
40    #[cfg(feature = "webtransport")]
41    pub(crate) wt_pool_entry: Option<crate::h3::H3PoolEntry>,
42    pub(crate) buffer: Buffer,
43    pub(crate) response_body_state: ReceivedBodyState,
44    pub(crate) headers_finalized: bool,
45    pub(crate) state: TypeSet,
46    pub(crate) context: Arc<HttpContext>,
47
48    #[field(skip)]
49    pub(crate) route: Route,
50
51    #[field(skip)]
52    pub(crate) route_key: Option<RouteKey>,
53
54    /// the transport for this conn
55    ///
56    /// This should only be used to call your own custom methods on the transport that do not read
57    /// or write any data. Calling any method that reads from or writes to the transport will
58    /// disrupt the HTTP protocol.
59    #[field(get, get_mut)]
60    pub(crate) transport: Option<Box<dyn Transport>>,
61
62    /// the url for this conn.
63    ///
64    /// ```
65    /// use trillium_client::{Client, Method};
66    /// use trillium_testing::client_config;
67    ///
68    /// let client = Client::from(client_config());
69    ///
70    /// let conn = client.get("http://localhost:9080");
71    ///
72    /// let url = conn.url(); //<-
73    ///
74    /// assert_eq!(url.host_str().unwrap(), "localhost");
75    /// ```
76    #[field(get, set, get_mut)]
77    pub(crate) url: Url,
78
79    /// the method for this conn.
80    ///
81    /// ```
82    /// use trillium_client::{Client, Method};
83    /// use trillium_testing::client_config;
84    ///
85    /// let client = Client::from(client_config());
86    /// let conn = client.get("http://localhost:9080");
87    ///
88    /// let method = conn.method(); //<-
89    ///
90    /// assert_eq!(method, Method::Get);
91    /// ```
92    #[field(get, set, copy)]
93    pub(crate) method: Method,
94
95    /// the request headers
96    #[field(get, get_mut)]
97    pub(crate) request_headers: Headers,
98
99    #[field(get)]
100    /// the response headers
101    pub(crate) response_headers: Headers,
102
103    /// the status code for this conn.
104    ///
105    /// If the conn has not yet been sent, this will be None.
106    ///
107    /// ```
108    /// use trillium_client::{Client, Status};
109    /// use trillium_testing::{client_config, with_server};
110    ///
111    /// async fn handler(conn: trillium::Conn) -> trillium::Conn {
112    ///     conn.with_status(418)
113    /// }
114    ///
115    /// with_server(handler, |url| async move {
116    ///     let client = Client::new(client_config());
117    ///     let conn = client.get(url).await?;
118    ///     assert_eq!(Status::ImATeapot, conn.status().unwrap());
119    ///     Ok(())
120    /// });
121    /// ```
122    #[field(get, copy)]
123    pub(crate) status: Option<Status>,
124
125    /// the request body
126    ///
127    /// ```
128    /// env_logger::init();
129    /// use trillium_client::Client;
130    /// use trillium_testing::{client_config, with_server};
131    ///
132    /// let handler = |mut conn: trillium::Conn| async move {
133    ///     let body = conn.request_body_string().await.unwrap();
134    ///     conn.ok(format!("request body was: {}", body))
135    /// };
136    ///
137    /// with_server(handler, |url| async move {
138    ///     let client = Client::from(client_config());
139    ///     let mut conn = client
140    ///         .post(url)
141    ///         .with_body("body") //<-
142    ///         .await?;
143    ///
144    ///     assert_eq!(
145    ///         conn.response_body().read_string().await?,
146    ///         "request body was: body"
147    ///     );
148    ///     Ok(())
149    /// });
150    /// ```
151    #[field(get, with = with_body, argument = body, set, into, take, option_set_some)]
152    pub(crate) request_body: Option<Body>,
153
154    /// Whether the request body was fully buffered before sending (see
155    /// [`request_body_buffer`](crate::conn::request_body_buffer)). When true, the h1 send path
156    /// skips the `Expect: 100-continue` handshake — a buffered body is cheap to send in one shot.
157    pub(crate) request_body_fully_buffered: bool,
158
159    /// the timeout for this conn
160    ///
161    /// this can also be set on the client with [`Client::set_timeout`](crate::Client::set_timeout)
162    /// and [`Client::with_timeout`](crate::Client::with_timeout)
163    #[field(with, set, get, get_mut, take, copy, option_set_some)]
164    pub(crate) timeout: Option<Duration>,
165
166    /// whether this conn is halted.
167    ///
168    /// When set to `true` before execution, the network round-trip is skipped — the conn is
169    /// returned to the caller with whatever response state has been populated synthetically
170    /// (status, headers, body). Used by client middleware to short-circuit on cache hits,
171    /// mocked responses, or open circuit-breakers. Cleared on egress so the user's conn handle
172    /// never observes residual halt state after the awaited conn returns.
173    ///
174    /// Driven via [`ConnExt`](crate::ConnExt) — `halt` / `set_halted` / `is_halted`.
175    pub(crate) halted: bool,
176
177    /// transport-level error from the round-trip, if any.
178    ///
179    /// When the network call fails (connect refused, TLS handshake error, malformed HTTP frame,
180    /// timeout, etc.) the framework stashes the error here and runs the handler chain's
181    /// [`after_response`](crate::ClientHandler::after_response) anyway. A handler that recovers
182    /// (stale-if-error cache, retry-with-fallback) calls
183    /// [`ConnExt::take_error`](crate::ConnExt::take_error) to clear the error
184    /// and populates response state synthetically; if the error is still present after all
185    /// handlers finish, it propagates as `Err` from the awaited conn.
186    pub(crate) error: Option<Error>,
187
188    /// An override response body installed by middleware via
189    /// [`ConnExt::set_response_body`](crate::ConnExt::set_response_body) or
190    /// [`ConnExt::with_response_body`](crate::ConnExt::with_response_body). When
191    /// set, [`Conn::response_body`] returns a [`ResponseBody`] backed by this body instead of
192    /// the transport.
193    pub(crate) body_override: Option<Body>,
194
195    /// the http version *hint* for this conn
196    ///
197    /// Pre-execution this is the prior-knowledge hint, not the version that will necessarily be
198    /// on the wire. `None` means "no hint, use auto-discovery" (Alt-Svc h3, ALPN/pooled h2);
199    /// `Some(version)` names the protocol to try first. Post-execution this is `Some(version)`
200    /// reflecting the version the request was actually sent over.
201    ///
202    /// The public [`http_version`](Conn::http_version) accessor resolves `None` to
203    /// [`Version::Http1_1`]. See the crate-level [Protocol selection][crate#protocol-selection]
204    /// documentation.
205    #[field(set, with, option_set_some)]
206    pub(crate) http_version: Option<Version>,
207
208    /// Whether a request that cannot be carried by the protocol it was matched to fails
209    /// rather than being retried on an earlier protocol.
210    ///
211    /// Off by default: a websocket handshake that lands on an h2 or h3 connection whose peer
212    /// doesn't support extended CONNECT is retried as an HTTP/1.1 upgrade on a new connection.
213    /// When on, that peer yields an error instead. A version hint sets the protocol to try
214    /// first; this flag decides what happens when that protocol can't carry the request.
215    ///
216    /// This can also be set for every conn on the client with
217    /// [`Client::set_strict_http_version`](crate::Client::set_strict_http_version).
218    #[field(get, set, with, without, copy)]
219    pub(crate) strict_http_version: bool,
220
221    /// the :authority pseudo-header, populated during h2 or h3 header finalization
222    #[field(get)]
223    pub(crate) authority: Option<Cow<'static, str>>,
224    /// the :scheme pseudo-header, populated during h2 or h3 header finalization
225
226    #[field(get)]
227    pub(crate) scheme: Option<Cow<'static, str>>,
228
229    /// the :path pseudo-header, populated during h2 or h3 header finalization
230    #[field(get)]
231    pub(crate) path: Option<Cow<'static, str>>,
232
233    /// an explicit request target override, used only for `OPTIONS *` and `CONNECT host:port`
234    ///
235    /// When set and the method is OPTIONS or CONNECT, this value is used as the HTTP request
236    /// target instead of deriving it from the url. For all other methods, this field is ignored.
237    #[field(with, set, get, option_set_some, into)]
238    pub(crate) request_target: Option<Cow<'static, str>>,
239
240    /// The protocol this request switches the connection to, if any: sent as the `Upgrade`
241    /// header over HTTP/1.1 and as the `:protocol` pseudo-header of an extended CONNECT over
242    /// HTTP/2 and HTTP/3. Either way the stream is left open as a bidirectional byte channel
243    /// after the response head.
244    #[field(get)]
245    pub(crate) protocol: Option<Cow<'static, str>>,
246
247    /// trailers sent with the request body, populated after the body has been fully sent.
248    ///
249    /// Only present when the request body was constructed with [`Body::new_with_trailers`] and
250    /// the body has been fully sent.
251    #[field(get)]
252    pub(crate) request_trailers: Option<Headers>,
253
254    /// trailers received with the response body, populated after the response body has been fully
255    /// read.
256    #[field(get)]
257    pub(crate) response_trailers: Option<Headers>,
258
259    /// the [`Client`] that built this conn.
260    #[field(get)]
261    pub(crate) client: Client,
262
263    /// A queued follow-up conn installed by middleware via
264    /// [`ConnExt::set_followup`](crate::ConnExt::set_followup).
265    ///
266    /// When `Some` after the handler chain's `after_response` has fully unwound, the
267    /// [`IntoFuture`][std::future::IntoFuture] loop picks it up: the current conn's response
268    /// body is recycled, then the follow-up is swapped in and runs another full
269    /// `(run → network → after_response)` cycle. Used by re-issuing handlers
270    /// (`FollowRedirects`, retry, auth-refresh) instead of recursing into a nested `.await`.
271    pub(crate) followup: Option<Box<Conn>>,
272
273    /// Whether this conn is armed for an upgrade. When set, the protocol drivers
274    /// transmit only request headers and leave the outbound direction open. Armed via
275    /// [`ConnExt::upgrade`](crate::ConnExt::upgrade).
276    pub(crate) upgrade: bool,
277}
278
279/// default http user-agent header
280pub const USER_AGENT: &str = concat!("trillium-client/", env!("CARGO_PKG_VERSION"));
281
282impl Conn {
283    /// the http version for this conn
284    ///
285    /// Pre-execution this resolves the version *hint* — the default (no hint) reports
286    /// [`Version::Http1_1`], which means "use auto-discovery," not "force HTTP/1.1." An
287    /// explicit version set via [`with_http_version`](Conn::with_http_version) is the protocol
288    /// to try first. Post-execution this reflects the version the request was actually sent
289    /// over.
290    ///
291    /// See the crate-level [Protocol selection][crate#protocol-selection] documentation.
292    #[must_use]
293    pub fn http_version(&self) -> Version {
294        self.http_version.unwrap_or(Version::Http1_1)
295    }
296
297    /// chainable setter for [`inserting`](Headers::insert) a request header
298    ///
299    /// ```
300    /// use trillium_client::Client;
301    /// use trillium_testing::{client_config, with_server};
302    ///
303    /// let handler = |conn: trillium::Conn| async move {
304    ///     let header = conn
305    ///         .request_headers()
306    ///         .get_str("some-request-header")
307    ///         .unwrap_or_default();
308    ///     let response = format!("some-request-header was {}", header);
309    ///     conn.ok(response)
310    /// };
311    ///
312    /// with_server(handler, |url| async move {
313    ///     let client = Client::new(client_config());
314    ///     let mut conn = client
315    ///         .get(url)
316    ///         .with_request_header("some-request-header", "header-value") // <--
317    ///         .await?;
318    ///     assert_eq!(
319    ///         conn.response_body().read_string().await?,
320    ///         "some-request-header was header-value"
321    ///     );
322    ///     Ok(())
323    /// })
324    /// ```
325    pub fn with_request_header(
326        mut self,
327        name: impl Into<HeaderName<'static>>,
328        value: impl Into<HeaderValues>,
329    ) -> Self {
330        self.request_headers.insert(name, value);
331        self
332    }
333
334    /// chainable setter for `extending` request headers
335    ///
336    /// ```
337    /// use trillium_client::Client;
338    /// use trillium_testing::{client_config, with_server};
339    ///
340    /// let handler = |conn: trillium::Conn| async move {
341    ///     let header = conn
342    ///         .request_headers()
343    ///         .get_str("some-request-header")
344    ///         .unwrap_or_default();
345    ///     let response = format!("some-request-header was {}", header);
346    ///     conn.ok(response)
347    /// };
348    ///
349    /// with_server(handler, move |url| async move {
350    ///     let client = Client::new(client_config());
351    ///     let mut conn = client
352    ///         .get(url)
353    ///         .with_request_headers([
354    ///             ("some-request-header", "header-value"),
355    ///             ("some-other-req-header", "other-header-value"),
356    ///         ])
357    ///         .await?;
358    ///
359    ///     assert_eq!(
360    ///         conn.response_body().read_string().await?,
361    ///         "some-request-header was header-value"
362    ///     );
363    ///     Ok(())
364    /// })
365    /// ```
366    pub fn with_request_headers<HN, HV, I>(mut self, headers: I) -> Self
367    where
368        I: IntoIterator<Item = (HN, HV)> + Send,
369        HN: Into<HeaderName<'static>>,
370        HV: Into<HeaderValues>,
371    {
372        self.request_headers.extend(headers);
373        self
374    }
375
376    /// Chainable method to remove a request header if present
377    pub fn without_request_header(mut self, name: impl Into<HeaderName<'static>>) -> Self {
378        self.request_headers.remove(name);
379        self
380    }
381
382    /// chainable setter for json body. this requires the `serde_json` crate feature to be enabled.
383    #[cfg(feature = "serde_json")]
384    pub fn with_json_body(self, body: &impl serde::Serialize) -> serde_json::Result<Self> {
385        use trillium_http::KnownHeaderName;
386
387        Ok(self
388            .with_body(serde_json::to_string(body)?)
389            .with_request_header(KnownHeaderName::ContentType, "application/json"))
390    }
391
392    /// chainable setter for json body. this requires the `sonic-rs` crate feature to be enabled.
393    #[cfg(feature = "sonic-rs")]
394    pub fn with_json_body(self, body: &impl serde::Serialize) -> sonic_rs::Result<Self> {
395        use trillium_http::KnownHeaderName;
396
397        Ok(self
398            .with_body(sonic_rs::to_string(body)?)
399            .with_request_header(KnownHeaderName::ContentType, "application/json"))
400    }
401
402    /// returns a [`ResponseBody`](crate::ResponseBody) that borrows the connection inside this
403    /// conn.
404    /// ```
405    /// use trillium_client::Client;
406    /// use trillium_testing::{client_config, with_server};
407    ///
408    /// let handler = |mut conn: trillium::Conn| async move { conn.ok("hello from trillium") };
409    ///
410    /// with_server(handler, |url| async move {
411    ///     let client = Client::from(client_config());
412    ///     let mut conn = client.get(url).await?;
413    ///
414    ///     let response_body = conn.response_body(); //<-
415    ///
416    ///     assert_eq!(19, response_body.content_length().unwrap());
417    ///     let string = response_body.read_string().await?;
418    ///     assert_eq!("hello from trillium", string);
419    ///     Ok(())
420    /// });
421    /// ```
422    #[allow(clippy::needless_borrow, clippy::needless_borrows_for_generic_args)]
423    pub fn response_body(&mut self) -> ResponseBody<'_> {
424        let content_length = self.response_content_length();
425        let encoding = encoding(&self.response_headers);
426        if let Some(body) = self.body_override.as_mut() {
427            OverrideBody::new(body, encoding, self.context.config()).into()
428        } else {
429            ReceivedBody::new(
430                content_length,
431                &mut self.buffer,
432                self.transport.as_mut().unwrap(),
433                &mut self.response_body_state,
434                None,
435                encoding,
436            )
437            .with_trailers(&mut self.response_trailers)
438            .with_protocol_session(self.protocol_session.clone())
439            .into()
440        }
441    }
442
443    /// Attempt to deserialize the response body. Note that this consumes the body content.
444    #[cfg(feature = "serde_json")]
445    pub async fn response_json<T>(&mut self) -> Result<T, ClientSerdeError>
446    where
447        T: serde::de::DeserializeOwned,
448    {
449        let body = self.response_body().read_string().await?;
450        Ok(serde_json::from_str(&body)?)
451    }
452
453    /// Attempt to deserialize the response body. Note that this consumes the body content.
454    #[cfg(feature = "sonic-rs")]
455    pub async fn response_json<T>(&mut self) -> Result<T, ClientSerdeError>
456    where
457        T: serde::de::DeserializeOwned,
458    {
459        let body = self.response_body().read_string().await?;
460        Ok(sonic_rs::from_str(&body)?)
461    }
462
463    /// Returns the conn or an [`UnexpectedStatusError`] that contains the conn
464    ///
465    /// ```
466    /// use trillium_client::{Client, Status};
467    /// use trillium_testing::{client_config, with_server};
468    ///
469    /// with_server(Status::NotFound, |url| async move {
470    ///     let client = Client::new(client_config());
471    ///     assert_eq!(
472    ///         client.get(url).await?.success().unwrap_err().to_string(),
473    ///         "expected a success (2xx) status code, but got 404 Not Found"
474    ///     );
475    ///     Ok(())
476    /// });
477    ///
478    /// with_server(Status::Ok, |url| async move {
479    ///     let client = Client::new(client_config());
480    ///     assert!(client.get(url).await?.success().is_ok());
481    ///     Ok(())
482    /// });
483    /// ```
484    pub fn success(self) -> Result<Self, UnexpectedStatusError> {
485        match self.status() {
486            Some(status) if status.is_success() => Ok(self),
487            _ => Err(self.into()),
488        }
489    }
490
491    /// Detach the response body as an owned, `'static` value.
492    ///
493    /// Returns `None` if there is no body to take — neither an override has been installed nor
494    /// a transport-backed body is available. Subsequent calls return `None`. Callers who want
495    /// to wrap-and-replace the body (e.g. tee through a cache) compose this with
496    /// [`ConnExt::set_response_body`][crate::ConnExt::set_response_body]; the conn's
497    /// body slot is empty between the two calls.
498    ///
499    /// For a transport-backed body, this moves the transport into the returned
500    /// `ResponseBody<'static>`. Drop on that value drains-and-pools (keepalive) or closes
501    /// (otherwise) the transport via a spawned task; [`ResponseBody::recycle`] is the
502    /// `await`-able variant. For an override body, the inner [`Body`] is moved out and any
503    /// leftover transport on the conn is recycled immediately.
504    #[must_use]
505    pub fn take_response_body(&mut self) -> Option<ResponseBody<'static>> {
506        let encoding = encoding(&self.response_headers);
507        if let Some(body) = self.body_override.take() {
508            return Some(OverrideBody::new(body, encoding, self.context.config()).into());
509        }
510
511        let cleanup = self.build_cleanup_context();
512        let received = self.take_received_body(false)?;
513        Some(ResponseBody::received_owned(received, cleanup))
514    }
515
516    /// Build a [`CleanupContext`] capturing the runtime and (if keepalive + pool configured)
517    /// the pool + origin to insert into. Single source of truth for "what should happen to
518    /// this conn's transport when its body is released" — both the on_completion callback
519    /// wired into the body and the [`ResponseBody::recycle`] / `Drop` paths consume clones
520    /// of this same context, so the user-driven and Drop-driven release paths agree.
521    fn build_cleanup_context(&self) -> CleanupContext {
522        // Only pool a transport whose response head we actually received (`status.is_some()`): a
523        // conn abandoned before the response — a timeout or transport error mid-request — has an
524        // empty `response_headers`, which `is_keep_alive` would read as persistent and recycle a
525        // half-spent connection into the pool, poisoning the next request that reuses it.
526        let h1_pool_origin = if self.status.is_some()
527            && self.is_keep_alive()
528            && let Some(pool) = self.client.pool().cloned()
529        {
530            Some((pool, self.pool_key()))
531        } else {
532            None
533        };
534
535        CleanupContext {
536            runtime: self.client.connector().runtime(),
537            h1_pool_origin,
538            h1_idle_timeout: self.client.h1_idle_timeout(),
539        }
540    }
541
542    /// Detach the transport-backed receive side of this conn as an owned `ReceivedBody`.
543    ///
544    /// Returns `None` when no transport is attached.
545    ///
546    /// `cleanup: true` wires a spawn-on-End callback inside the body for callers that hand
547    /// the body off without awaiting it (`From<Conn> for Body`). `cleanup: false` is for
548    /// callers that drive the body to End themselves and release the transport inline in
549    /// their own poll loop — `take_response_body` does this so callers get a "transport is
550    /// settled when read_to_end returns Ok(0)" guarantee instead of racing a spawned task.
551    pub(crate) fn take_received_body(
552        &mut self,
553        cleanup: bool,
554    ) -> Option<ReceivedBody<'static, Box<dyn Transport>>> {
555        let _ = self.finalize_headers();
556        let transport = self.transport.take()?;
557
558        let on_completion = cleanup.then(|| {
559            let cleanup = self.build_cleanup_context();
560            Box::new(move |transport| cleanup.handoff(transport))
561                as Box<dyn FnOnce(Box<dyn Transport>) + Send + Sync + 'static>
562        });
563
564        Some(
565            ReceivedBody::new(
566                self.response_content_length(),
567                mem::take(&mut self.buffer),
568                transport,
569                self.response_body_state,
570                on_completion,
571                encoding(&self.response_headers),
572            )
573            .with_protocol_session(self.protocol_session.clone()),
574        )
575    }
576
577    /// Returns this conn to the connection pool if it is keepalive, and
578    /// closes it otherwise. This will happen asynchronously as a spawned
579    /// task when the conn is dropped, but calling it explicitly allows
580    /// you to block on it and control where it happens.
581    pub async fn recycle(mut self) {
582        if let Some(rb) = self.take_response_body() {
583            rb.recycle().await;
584        }
585    }
586
587    /// Attempts to retrieve the connected peer address.
588    ///
589    /// When the request is routed through a proxy (forward or `CONNECT` tunnel), this returns the
590    /// proxy's socket address rather than the origin's.
591    pub fn peer_addr(&self) -> Option<SocketAddr> {
592        self.transport
593            .as_ref()
594            .and_then(|t| t.peer_addr().ok().flatten())
595    }
596
597    /// add state to the client conn and return self
598    pub fn with_state<T: Send + Sync + 'static>(mut self, state: T) -> Self {
599        self.insert_state(state);
600        self
601    }
602
603    /// add state to the client conn, returning any previously set state of this type
604    pub fn insert_state<T: Send + Sync + 'static>(&mut self, state: T) -> Option<T> {
605        self.state.insert(state)
606    }
607
608    /// borrow state
609    pub fn state<T: Send + Sync + 'static>(&self) -> Option<&T> {
610        self.state.get()
611    }
612
613    /// borrow state mutably
614    pub fn state_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
615        self.state.get_mut()
616    }
617
618    /// take state
619    pub fn take_state<T: Send + Sync + 'static>(&mut self) -> Option<T> {
620        self.state.take()
621    }
622}