trillium_client/client.rs
1use crate::{
2 ClientHandler, Conn, IntoUrl, Pool, USER_AGENT,
3 client_handler::ArcedClientHandler,
4 conn::{H2Pooled, Route, RouteKey},
5 h3::H3ClientState,
6};
7use std::{any::Any, fmt::Debug, sync::Arc, time::Duration};
8use trillium_http::{
9 HeaderName, HeaderValues, Headers, HttpContext, KnownHeaderName, Method, ProtocolSession,
10 ReceivedBodyState, TypeSet,
11};
12use trillium_server_common::{
13 ArcedConnector, ArcedQuicClientConfig, Connector, QuicClientConfig, Transport, url::Url,
14};
15
16/// Default maximum idle time for a pooled HTTP/1.1 connection. A warm keepalive connection is
17/// worth holding onto — reusing it saves a full TCP (and, for https, TLS) handshake — so the
18/// timeout exists only to bound *unbounded* retention, not to reclaim connections eagerly. A
19/// connection the origin closed first is discarded cheaply either way: by the reuse-time
20/// liveness probe when it's next reached for, or by the background reaper. Matches the h2
21/// default for the same reason.
22const DEFAULT_H1_IDLE_TIMEOUT: Duration = Duration::from_secs(300);
23
24/// Default maximum idle time for a pooled HTTP/2 connection. Longer than h1 because the
25/// initial h2 handshake (TCP + TLS + ALPN + SETTINGS exchange) is more expensive to
26/// re-establish.
27const DEFAULT_H2_IDLE_TIMEOUT: Duration = Duration::from_secs(300);
28
29/// Default maximum retention for a pooled HTTP/3 connection. Matches the h2 default; QUIC
30/// connections whose transport-level idle timeout already closed them are reclaimed by this
31/// bound even when the origin is never contacted again.
32const DEFAULT_H3_IDLE_TIMEOUT: Duration = Duration::from_secs(300);
33
34/// Default idle threshold above which a pooled HTTP/2 connection is liveness-pinged before
35/// being handed out for a new request. Below this, we trust the connection without probing.
36const DEFAULT_H2_IDLE_PING_THRESHOLD: Duration = Duration::from_secs(10);
37
38/// Default timeout for the liveness PING — if we don't get an ACK within this window, the
39/// connection is treated as dead and a fresh one is established instead.
40const DEFAULT_H2_IDLE_PING_TIMEOUT: Duration = Duration::from_secs(20);
41
42const DEFAULT_MAX_BUFFERED_REQUEST_BODY: usize = 1024;
43
44/// Default time to wait for a `100 (Continue)` interim response before sending the request body
45/// anyway. Matches curl's fallback.
46const DEFAULT_EXPECT_CONTINUE_TIMEOUT: Duration = Duration::from_secs(1);
47
48/// An HTTP client supporting HTTP/1.x, HTTP/2 (via ALPN), and — when configured with a QUIC
49/// implementation — HTTP/3. See [`Client::new`] and [`Client::new_with_quic`] for construction
50/// information.
51#[derive(Clone, Debug, fieldwork::Fieldwork)]
52pub struct Client {
53 config: ArcedConnector,
54
55 #[field(
56 get(vis = "pub(crate)"),
57 without(doc = "Remove any proxy router, connecting directly for every request.")
58 )]
59 proxy: Option<crate::proxy::ArcedProxyRouter>,
60
61 #[field(vis = "pub(crate)", get)]
62 h3: Option<H3ClientState>,
63
64 #[field(vis = "pub(crate)", get)]
65 pool: Option<Pool<RouteKey, Box<dyn Transport>>>,
66
67 #[field(vis = "pub(crate)", get)]
68 h2_pool: Option<Pool<RouteKey, H2Pooled>>,
69
70 /// Maximum idle time for a pooled HTTP/1.1 connection before a background reaper closes it and
71 /// removes it from the pool. `None` disables expiry, restoring the previous behavior in which
72 /// idle h1 connections were retained until reused (and discarded by a liveness probe) or the
73 /// pool was manually cleaned up — an origin that stopped being contacted then held its idle
74 /// file descriptors indefinitely.
75 ///
76 /// Defaults to 5 minutes.
77 #[field(get, set, with, without, copy)]
78 h1_idle_timeout: Option<Duration>,
79
80 /// Maximum idle time for a pooled HTTP/2 connection. `None` disables expiry.
81 ///
82 /// Defaults to 5 minutes.
83 #[field(get, set, with, without, copy)]
84 h2_idle_timeout: Option<Duration>,
85
86 /// How long a pooled HTTP/3 connection is retained after it is established. An expired
87 /// connection is dropped from the pool — requests in flight on it are unaffected — and the
88 /// next request to its origin establishes a fresh connection. `None` disables expiry.
89 ///
90 /// Defaults to 5 minutes.
91 #[field(get, set, with, without, copy)]
92 h3_idle_timeout: Option<Duration>,
93
94 /// If a pooled HTTP/2 connection has been idle for longer than this, an active PING is
95 /// sent to verify it's still alive before being handed out. `None` disables the probe.
96 ///
97 /// Defaults to 10 seconds.
98 #[field(get, set, with, copy, without)]
99 h2_idle_ping_threshold: Option<Duration>,
100
101 /// Timeout for the liveness PING sent under the [`h2_idle_ping_threshold`] policy.
102 /// Connections whose ACK doesn't arrive within this window are treated as dead.
103 ///
104 /// Defaults to 20 seconds.
105 ///
106 /// [`h2_idle_ping_threshold`]: Self::h2_idle_ping_threshold
107 #[field(get, set, with, copy)]
108 h2_idle_ping_timeout: Duration,
109
110 /// url base for this client
111 #[field(get)]
112 base: Option<Arc<Url>>,
113
114 /// default request headers
115 #[field(get)]
116 default_headers: Arc<Headers>,
117
118 /// Request bodies of unknown length at or below this size are fully buffered before the
119 /// request head is written, letting the client send them with an accurate `Content-Length`.
120 /// Two consequences follow from being able to buffer: a small streaming body is framed with
121 /// `Content-Length` rather than `Transfer-Encoding: chunked`, and no `Expect: 100-continue`
122 /// handshake is used — there is no benefit to asking permission before sending a body we
123 /// have already buffered and can send in one shot. Larger or unbounded bodies stream
124 /// (chunked), and the `Expect: 100-continue` handshake applies to those. A known-length
125 /// body larger than this also uses `Expect: 100-continue`.
126 ///
127 /// Defaults to 1 KiB.
128 #[field(get, set, with, copy)]
129 max_buffered_request_body: usize,
130
131 /// How long to wait for a `100 (Continue)` interim response after sending a request head
132 /// carrying `Expect: 100-continue`, before sending the request body regardless.
133 ///
134 /// Per [RFC 9110 §10.1.1] a client must not wait indefinitely: a `100 (Continue)` cannot
135 /// traverse an HTTP/1.0 intermediary, and not every peer honors the expectation, so a client
136 /// that waited forever would deadlock against them. On timeout the body is sent anyway — the
137 /// same thing the client would do without the expectation.
138 ///
139 /// Defaults to 1 second.
140 ///
141 /// [RFC 9110 §10.1.1]: https://www.rfc-editor.org/rfc/rfc9110#section-10.1.1
142 #[field(get, set, with, copy)]
143 expect_continue_timeout: Duration,
144
145 /// optional per-request timeout
146 #[field(get, set, with, copy, without, option_set_some)]
147 timeout: Option<Duration>,
148
149 /// Default for [`Conn::strict_http_version`] on every conn this client builds.
150 ///
151 /// Off by default. When on, a request that cannot be carried by the protocol it was matched
152 /// to fails rather than being retried on an earlier protocol.
153 #[field(get, set, with, without, copy)]
154 strict_http_version: bool,
155
156 /// configuration
157 #[field(get, get_mut, set, with, into)]
158 context: Arc<HttpContext>,
159
160 /// type-erased middleware stack. Defaults to a no-op `()` handler. Set via
161 /// [`Client::with_handler`] / [`Client::set_handler`]; recover the concrete type via
162 /// [`Client::downcast_handler`].
163 #[field(vis = "pub(crate)", get = arc_handler)]
164 handler: ArcedClientHandler,
165
166 /// Encrypted-DNS resolver, if configured via [`Client::with_doh`]. When set, all DNS
167 /// resolution for this client is routed through it.
168 #[cfg(feature = "hickory")]
169 pub(crate) resolver: Option<crate::dns::Resolver>,
170}
171
172macro_rules! method {
173 ($fn_name:ident, $method:ident) => {
174 method!(
175 $fn_name,
176 $method,
177 concat!(
178 // yep, macro-generated doctests
179 "Builds a new client conn with the ",
180 stringify!($fn_name),
181 " http method and the provided url.
182
183```
184use trillium_client::{Client, Method};
185use trillium_testing::client_config;
186
187let client = Client::new(client_config());
188let conn = client.",
189 stringify!($fn_name),
190 "(\"http://localhost:8080/some/route\"); //<-
191
192assert_eq!(conn.method(), Method::",
193 stringify!($method),
194 ");
195assert_eq!(conn.url().to_string(), \"http://localhost:8080/some/route\");
196```
197"
198 )
199 );
200 };
201
202 ($fn_name:ident, $method:ident, $doc_comment:expr_2021) => {
203 #[doc = $doc_comment]
204 pub fn $fn_name(&self, url: impl IntoUrl) -> Conn {
205 self.build_conn(Method::$method, url)
206 }
207 };
208}
209
210pub(crate) fn default_request_headers() -> Headers {
211 Headers::new()
212 .with_inserted_header(KnownHeaderName::UserAgent, USER_AGENT)
213 .with_inserted_header(KnownHeaderName::Accept, "*/*")
214}
215
216impl Client {
217 method!(get, Get);
218
219 method!(post, Post);
220
221 method!(put, Put);
222
223 method!(delete, Delete);
224
225 method!(patch, Patch);
226
227 /// Route requests through the proxies `router` chooses: a [`Proxy`](crate::Proxy), a list
228 /// of them, or a function of the request URL. See [`ProxyRouter`](crate::ProxyRouter).
229 #[must_use]
230 pub fn with_proxy(mut self, router: impl crate::ProxyRouter) -> Self {
231 self.proxy = Some(crate::proxy::ArcedProxyRouter::new(router));
232 self
233 }
234
235 /// builds a new client from this `Connector`
236 pub fn new(connector: impl Connector) -> Self {
237 let config = ArcedConnector::new(connector);
238 let (pool, h2_pool) = (Pool::default(), Pool::default());
239 crate::reaper::spawn_pool_reaper(
240 config.runtime(),
241 pool.downgrade(),
242 h2_pool.downgrade(),
243 None,
244 );
245 Self {
246 config,
247 proxy: None,
248 h3: None,
249 pool: Some(pool),
250 h2_pool: Some(h2_pool),
251 h1_idle_timeout: Some(DEFAULT_H1_IDLE_TIMEOUT),
252 h2_idle_timeout: Some(DEFAULT_H2_IDLE_TIMEOUT),
253 h3_idle_timeout: Some(DEFAULT_H3_IDLE_TIMEOUT),
254 h2_idle_ping_threshold: Some(DEFAULT_H2_IDLE_PING_THRESHOLD),
255 h2_idle_ping_timeout: DEFAULT_H2_IDLE_PING_TIMEOUT,
256 max_buffered_request_body: DEFAULT_MAX_BUFFERED_REQUEST_BODY,
257 expect_continue_timeout: DEFAULT_EXPECT_CONTINUE_TIMEOUT,
258 base: None,
259 default_headers: Arc::new(default_request_headers()),
260 timeout: None,
261 strict_http_version: false,
262 context: Default::default(),
263 handler: ArcedClientHandler::new(()),
264 #[cfg(feature = "hickory")]
265 resolver: None,
266 }
267 }
268
269 /// Build a new client with both a TCP connector and a QUIC connector for HTTP/3 support.
270 ///
271 /// The connector's runtime and UDP socket type are bound to the QUIC connector here,
272 /// before type erasure, so that `trillium-quinn` and the runtime adapter remain
273 /// independent crates that neither depends on the other.
274 ///
275 /// When H3 is configured, the client will track `Alt-Svc` headers in responses and
276 /// automatically use HTTP/3 for subsequent requests to origins that advertise it.
277 /// Other requests follow the standard h1 / h2-via-ALPN path.
278 pub fn new_with_quic<C: Connector, Q: QuicClientConfig<C>>(connector: C, quic: Q) -> Self {
279 // Bind the runtime into the QUIC client config before consuming `connector`.
280 let arced_quic = ArcedQuicClientConfig::new(&connector, quic);
281
282 #[cfg_attr(not(feature = "webtransport"), allow(unused_mut))]
283 let mut context = HttpContext::default();
284 #[cfg(feature = "webtransport")]
285 {
286 // Advertise WebTransport-over-h3 capability on outbound SETTINGS so a server can
287 // open server-initiated WT streams to us once a session is established.
288 // ENABLE_CONNECT_PROTOCOL is included for symmetry with the server side; harmless
289 // when the client never receives extended-CONNECT from the peer.
290 context
291 .config_mut()
292 .set_h3_datagrams_enabled(true)
293 .set_webtransport_enabled(true)
294 .set_extended_connect_enabled(true);
295 }
296
297 let config = ArcedConnector::new(connector);
298 let (pool, h2_pool) = (Pool::default(), Pool::default());
299 let h3 = H3ClientState::new(arced_quic);
300 crate::reaper::spawn_pool_reaper(
301 config.runtime(),
302 pool.downgrade(),
303 h2_pool.downgrade(),
304 Some(h3.pool.downgrade()),
305 );
306 Self {
307 config,
308 proxy: None,
309 h3: Some(h3),
310 pool: Some(pool),
311 h2_pool: Some(h2_pool),
312 h1_idle_timeout: Some(DEFAULT_H1_IDLE_TIMEOUT),
313 h2_idle_timeout: Some(DEFAULT_H2_IDLE_TIMEOUT),
314 h3_idle_timeout: Some(DEFAULT_H3_IDLE_TIMEOUT),
315 h2_idle_ping_threshold: Some(DEFAULT_H2_IDLE_PING_THRESHOLD),
316 h2_idle_ping_timeout: DEFAULT_H2_IDLE_PING_TIMEOUT,
317 max_buffered_request_body: DEFAULT_MAX_BUFFERED_REQUEST_BODY,
318 expect_continue_timeout: DEFAULT_EXPECT_CONTINUE_TIMEOUT,
319 base: None,
320 default_headers: Arc::new(default_request_headers()),
321 timeout: None,
322 strict_http_version: false,
323 context: Arc::new(context),
324 handler: ArcedClientHandler::new(()),
325 #[cfg(feature = "hickory")]
326 resolver: None,
327 }
328 }
329
330 /// Install a [`ClientHandler`] middleware stack on this client.
331 ///
332 /// The handler runs around every request issued by this client: its `run` method fires before
333 /// the network round-trip (with the option to halt + synthesize a response), and its
334 /// `after_response` fires afterwards. Compose multiple handlers with tuples — see
335 /// [`ClientHandler`] for the lifecycle and `Vec`/tuple/`Option` impls.
336 ///
337 /// Returns `self` for chaining.
338 #[must_use]
339 pub fn with_handler<H: ClientHandler>(mut self, handler: H) -> Self {
340 self.set_handler(handler);
341 self
342 }
343
344 /// Install a [`ClientHandler`] middleware stack on this client. See [`Client::with_handler`]
345 /// for details.
346 pub fn set_handler<H: ClientHandler>(&mut self, handler: H) -> &mut Self {
347 self.handler = ArcedClientHandler::new(handler);
348 self
349 }
350
351 /// Borrow the type-erased [`ClientHandler`]
352 ///
353 /// See also [`Client::downcast_handler`] if you can name the type
354 pub fn handler(&self) -> &impl ClientHandler {
355 &self.handler
356 }
357
358 /// Borrow the installed [`ClientHandler`] as the concrete type `T`, returning `None` if the
359 /// installed handler is not of that type.
360 ///
361 /// Useful for inspecting handler-internal state from outside the request path — e.g., reading
362 /// counters from a metrics handler.
363 pub fn downcast_handler<T: Any + 'static>(&self) -> Option<&T> {
364 self.handler.downcast_ref()
365 }
366
367 /// chainable method to remove a header from default request headers
368 pub fn without_default_header(mut self, name: impl Into<HeaderName<'static>>) -> Self {
369 self.default_headers_mut().remove(name);
370 self
371 }
372
373 /// chainable method to insert a new default request header, replacing any existing value
374 pub fn with_default_header(
375 mut self,
376 name: impl Into<HeaderName<'static>>,
377 value: impl Into<HeaderValues>,
378 ) -> Self {
379 self.default_headers_mut().insert(name, value);
380 self
381 }
382
383 /// borrow the default headers mutably
384 ///
385 /// calling this will copy-on-write if the default headers are shared with another client clone
386 pub fn default_headers_mut(&mut self) -> &mut Headers {
387 Arc::make_mut(&mut self.default_headers)
388 }
389
390 /// chainable constructor to disable http/1.1 connection reuse.
391 ///
392 /// ```
393 /// use trillium_client::Client;
394 /// use trillium_smol::ClientConfig;
395 ///
396 /// let client = Client::new(ClientConfig::default()).without_keepalive();
397 /// ```
398 pub fn without_keepalive(mut self) -> Self {
399 self.pool = None;
400 self.h2_pool = None;
401 self
402 }
403
404 /// builds a new conn.
405 ///
406 /// if the client has pooling enabled and there is an available connection for this
407 /// origin (scheme + host + port), the new conn will reuse it when sent.
408 ///
409 /// ```
410 /// use trillium_client::{Client, Method};
411 /// use trillium_smol::ClientConfig;
412 /// let client = Client::new(ClientConfig::default());
413 ///
414 /// let conn = client.build_conn("get", "http://trillium.rs"); //<-
415 ///
416 /// assert_eq!(conn.method(), Method::Get);
417 /// assert_eq!(conn.url().host_str().unwrap(), "trillium.rs");
418 /// ```
419 pub fn build_conn<M>(&self, method: M, url: impl IntoUrl) -> Conn
420 where
421 M: TryInto<Method>,
422 <M as TryInto<Method>>::Error: Debug,
423 {
424 let method = method.try_into().unwrap();
425 let (url, request_target, error) = if let Some(base) = &self.base
426 && let Some(request_target) = url.request_target(method)
427 {
428 ((**base).clone(), Some(request_target), None)
429 } else {
430 match self.build_url(url) {
431 Ok(url) => (url, None, None),
432 // `build_conn` is infallible by contract, so a malformed url is
433 // deferred rather than panicked: stash the error (surfaced at the
434 // top of `Conn::exec`) behind a placeholder url that never dials.
435 Err(error) => (
436 Url::parse("http://invalid.invalid/").expect("literal is a valid url"),
437 None,
438 Some(error),
439 ),
440 }
441 };
442
443 Conn {
444 url,
445 method,
446 request_headers: Headers::clone(&self.default_headers),
447 response_headers: Headers::new(),
448 transport: None,
449 route: Route::Direct,
450 route_key: None,
451 status: None,
452 request_body: None,
453 request_body_fully_buffered: false,
454 protocol_session: ProtocolSession::Http1,
455 #[cfg(feature = "webtransport")]
456 wt_pool_entry: None,
457 buffer: Vec::with_capacity(128).into(),
458 response_body_state: ReceivedBodyState::End,
459 headers_finalized: false,
460 halted: false,
461 error,
462 body_override: None,
463 timeout: self.timeout,
464 http_version: None,
465 strict_http_version: self.strict_http_version,
466 state: TypeSet::new(),
467 context: self.context.clone(),
468 authority: None,
469 scheme: None,
470 path: None,
471 request_target,
472 protocol: None,
473 request_trailers: None,
474 response_trailers: None,
475 client: self.clone(),
476 followup: None,
477 upgrade: false,
478 }
479 }
480
481 /// borrow the connector for this client
482 pub fn connector(&self) -> &ArcedConnector {
483 &self.config
484 }
485
486 /// The pool implementation accumulates a small memory footprint for each new host. If
487 /// your application is reusing a pool against a large number of unique hosts, call this
488 /// method intermittently.
489 pub fn clean_up_pool(&self) {
490 if let Some(pool) = &self.pool {
491 pool.reap();
492 }
493 if let Some(h2_pool) = &self.h2_pool {
494 h2_pool.reap();
495 }
496 }
497
498 /// chainable method to set the base for this client
499 pub fn with_base(mut self, base: impl IntoUrl) -> Self {
500 self.set_base(base).unwrap();
501 self
502 }
503
504 /// attempt to build a url from this IntoUrl and the [`Client::base`], if set
505 pub fn build_url(&self, url: impl IntoUrl) -> crate::Result<Url> {
506 url.into_url(self.base())
507 }
508
509 /// set the base for this client
510 pub fn set_base(&mut self, base: impl IntoUrl) -> crate::Result<()> {
511 let mut base = base.into_url(None)?;
512
513 if !base.path().ends_with('/') {
514 log::warn!("appending a trailing / to {base}");
515 base.set_path(&format!("{}/", base.path()));
516 }
517
518 self.base = Some(Arc::new(base));
519 Ok(())
520 }
521
522 /// Mutate the url base for this client.
523 ///
524 /// This has "clone-on-write" semantics if there are other clones of this client. If there are
525 /// other clones of this client, they will not be updated.
526 pub fn base_mut(&mut self) -> Option<&mut Url> {
527 let base = self.base.as_mut()?;
528 Some(Arc::make_mut(base))
529 }
530}
531
532impl<T: Connector> From<T> for Client {
533 fn from(connector: T) -> Self {
534 Self::new(connector)
535 }
536}