1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use crate::{
ClientHandler, Conn, IntoUrl, Pool, USER_AGENT, client_handler::ArcedClientHandler,
conn::H2Pooled, h3::H3ClientState,
};
use std::{any::Any, fmt::Debug, sync::Arc, time::Duration};
use trillium_http::{
HeaderName, HeaderValues, Headers, HttpContext, KnownHeaderName, Method, ProtocolSession,
ReceivedBodyState, TypeSet,
};
use trillium_server_common::{
ArcedConnector, ArcedQuicClientConfig, Connector, QuicClientConfig, Transport,
url::{Origin, Url},
};
/// Default maximum idle time for a pooled HTTP/2 connection. Longer than h1 because the
/// initial h2 handshake (TCP + TLS + ALPN + SETTINGS exchange) is more expensive to
/// re-establish.
const DEFAULT_H2_IDLE_TIMEOUT: Duration = Duration::from_secs(300);
/// Default idle threshold above which a pooled HTTP/2 connection is liveness-pinged before
/// being handed out for a new request. Below this, we trust the connection without probing.
const DEFAULT_H2_IDLE_PING_THRESHOLD: Duration = Duration::from_secs(10);
/// Default timeout for the liveness PING — if we don't get an ACK within this window, the
/// connection is treated as dead and a fresh one is established instead.
const DEFAULT_H2_IDLE_PING_TIMEOUT: Duration = Duration::from_secs(20);
/// An HTTP client supporting HTTP/1.x, HTTP/2 (via ALPN), and — when configured with a QUIC
/// implementation — HTTP/3. See [`Client::new`] and [`Client::new_with_quic`] for construction
/// information.
#[derive(Clone, Debug, fieldwork::Fieldwork)]
pub struct Client {
config: ArcedConnector,
#[field(vis = "pub(crate)", get)]
h3: Option<H3ClientState>,
#[field(vis = "pub(crate)", get)]
pool: Option<Pool<Origin, Box<dyn Transport>>>,
#[field(vis = "pub(crate)", get)]
h2_pool: Option<Pool<Origin, H2Pooled>>,
/// Maximum idle time for a pooled HTTP/2 connection. `None` disables expiry.
///
/// Defaults to 5 minutes.
#[field(get, set, with, without, copy)]
h2_idle_timeout: Option<Duration>,
/// If a pooled HTTP/2 connection has been idle for longer than this, an active PING is
/// sent to verify it's still alive before being handed out. `None` disables the probe.
///
/// Defaults to 10 seconds.
#[field(get, set, with, copy, without)]
h2_idle_ping_threshold: Option<Duration>,
/// Timeout for the liveness PING sent under the [`h2_idle_ping_threshold`] policy.
/// Connections whose ACK doesn't arrive within this window are treated as dead.
///
/// Defaults to 20 seconds.
///
/// [`h2_idle_ping_threshold`]: Self::h2_idle_ping_threshold
#[field(get, set, with, copy)]
h2_idle_ping_timeout: Duration,
/// url base for this client
#[field(get)]
base: Option<Arc<Url>>,
/// default request headers
#[field(get)]
default_headers: Arc<Headers>,
/// optional per-request timeout
#[field(get, set, with, copy, without, option_set_some)]
timeout: Option<Duration>,
/// configuration
#[field(get, get_mut, set, with, into)]
context: Arc<HttpContext>,
/// type-erased middleware stack. Defaults to a no-op `()` handler. Set via
/// [`Client::with_handler`] / [`Client::set_handler`]; recover the concrete type via
/// [`Client::downcast_handler`].
#[field(vis = "pub(crate)", get = arc_handler)]
handler: ArcedClientHandler,
/// Encrypted-DNS resolver, if configured via [`Client::with_doh`]. When set, all DNS
/// resolution for this client is routed through it.
#[cfg(feature = "hickory")]
pub(crate) resolver: Option<crate::dns::Resolver>,
}
macro_rules! method {
($fn_name:ident, $method:ident) => {
method!(
$fn_name,
$method,
concat!(
// yep, macro-generated doctests
"Builds a new client conn with the ",
stringify!($fn_name),
" http method and the provided url.
```
use trillium_client::{Client, Method};
use trillium_testing::client_config;
let client = Client::new(client_config());
let conn = client.",
stringify!($fn_name),
"(\"http://localhost:8080/some/route\"); //<-
assert_eq!(conn.method(), Method::",
stringify!($method),
");
assert_eq!(conn.url().to_string(), \"http://localhost:8080/some/route\");
```
"
)
);
};
($fn_name:ident, $method:ident, $doc_comment:expr_2021) => {
#[doc = $doc_comment]
pub fn $fn_name(&self, url: impl IntoUrl) -> Conn {
self.build_conn(Method::$method, url)
}
};
}
pub(crate) fn default_request_headers() -> Headers {
Headers::new()
.with_inserted_header(KnownHeaderName::UserAgent, USER_AGENT)
.with_inserted_header(KnownHeaderName::Accept, "*/*")
}
impl Client {
method!(get, Get);
method!(post, Post);
method!(put, Put);
method!(delete, Delete);
method!(patch, Patch);
/// builds a new client from this `Connector`
pub fn new(connector: impl Connector) -> Self {
Self {
config: ArcedConnector::new(connector),
h3: None,
pool: Some(Pool::default()),
h2_pool: Some(Pool::default()),
h2_idle_timeout: Some(DEFAULT_H2_IDLE_TIMEOUT),
h2_idle_ping_threshold: Some(DEFAULT_H2_IDLE_PING_THRESHOLD),
h2_idle_ping_timeout: DEFAULT_H2_IDLE_PING_TIMEOUT,
base: None,
default_headers: Arc::new(default_request_headers()),
timeout: None,
context: Default::default(),
handler: ArcedClientHandler::new(()),
#[cfg(feature = "hickory")]
resolver: None,
}
}
/// Build a new client with both a TCP connector and a QUIC connector for HTTP/3 support.
///
/// The connector's runtime and UDP socket type are bound to the QUIC connector here,
/// before type erasure, so that `trillium-quinn` and the runtime adapter remain
/// independent crates that neither depends on the other.
///
/// When H3 is configured, the client will track `Alt-Svc` headers in responses and
/// automatically use HTTP/3 for subsequent requests to origins that advertise it.
/// Other requests follow the standard h1 / h2-via-ALPN path.
pub fn new_with_quic<C: Connector, Q: QuicClientConfig<C>>(connector: C, quic: Q) -> Self {
// Bind the runtime into the QUIC client config before consuming `connector`.
let arced_quic = ArcedQuicClientConfig::new(&connector, quic);
#[cfg_attr(not(feature = "webtransport"), allow(unused_mut))]
let mut context = HttpContext::default();
#[cfg(feature = "webtransport")]
{
// Advertise WebTransport-over-h3 capability on outbound SETTINGS so a server can
// open server-initiated WT streams to us once a session is established.
// ENABLE_CONNECT_PROTOCOL is included for symmetry with the server side; harmless
// when the client never receives extended-CONNECT from the peer.
context
.config_mut()
.set_h3_datagrams_enabled(true)
.set_webtransport_enabled(true)
.set_extended_connect_enabled(true);
}
Self {
config: ArcedConnector::new(connector),
h3: Some(H3ClientState::new(arced_quic)),
pool: Some(Pool::default()),
h2_pool: Some(Pool::default()),
h2_idle_timeout: Some(DEFAULT_H2_IDLE_TIMEOUT),
h2_idle_ping_threshold: Some(DEFAULT_H2_IDLE_PING_THRESHOLD),
h2_idle_ping_timeout: DEFAULT_H2_IDLE_PING_TIMEOUT,
base: None,
default_headers: Arc::new(default_request_headers()),
timeout: None,
context: Arc::new(context),
handler: ArcedClientHandler::new(()),
#[cfg(feature = "hickory")]
resolver: None,
}
}
/// Install a [`ClientHandler`] middleware stack on this client.
///
/// The handler runs around every request issued by this client: its `run` method fires before
/// the network round-trip (with the option to halt + synthesize a response), and its
/// `after_response` fires afterwards. Compose multiple handlers with tuples — see
/// [`ClientHandler`] for the lifecycle and `Vec`/tuple/`Option` impls.
///
/// Returns `self` for chaining.
#[must_use]
pub fn with_handler<H: ClientHandler>(mut self, handler: H) -> Self {
self.set_handler(handler);
self
}
/// Install a [`ClientHandler`] middleware stack on this client. See [`Client::with_handler`]
/// for details.
pub fn set_handler<H: ClientHandler>(&mut self, handler: H) -> &mut Self {
self.handler = ArcedClientHandler::new(handler);
self
}
/// Borrow the type-erased [`ClientHandler`]
///
/// See also [`Client::downcast_handler`] if you can name the type
pub fn handler(&self) -> &impl ClientHandler {
&self.handler
}
/// Borrow the installed [`ClientHandler`] as the concrete type `T`, returning `None` if the
/// installed handler is not of that type.
///
/// Useful for inspecting handler-internal state from outside the request path — e.g., reading
/// counters from a metrics handler.
pub fn downcast_handler<T: Any + 'static>(&self) -> Option<&T> {
self.handler.downcast_ref()
}
/// chainable method to remove a header from default request headers
pub fn without_default_header(mut self, name: impl Into<HeaderName<'static>>) -> Self {
self.default_headers_mut().remove(name);
self
}
/// chainable method to insert a new default request header, replacing any existing value
pub fn with_default_header(
mut self,
name: impl Into<HeaderName<'static>>,
value: impl Into<HeaderValues>,
) -> Self {
self.default_headers_mut().insert(name, value);
self
}
/// borrow the default headers mutably
///
/// calling this will copy-on-write if the default headers are shared with another client clone
pub fn default_headers_mut(&mut self) -> &mut Headers {
Arc::make_mut(&mut self.default_headers)
}
/// chainable constructor to disable http/1.1 connection reuse.
///
/// ```
/// use trillium_client::Client;
/// use trillium_smol::ClientConfig;
///
/// let client = Client::new(ClientConfig::default()).without_keepalive();
/// ```
pub fn without_keepalive(mut self) -> Self {
self.pool = None;
self.h2_pool = None;
self
}
/// builds a new conn.
///
/// if the client has pooling enabled and there is an available connection for this
/// origin (scheme + host + port), the new conn will reuse it when sent.
///
/// ```
/// use trillium_client::{Client, Method};
/// use trillium_smol::ClientConfig;
/// let client = Client::new(ClientConfig::default());
///
/// let conn = client.build_conn("get", "http://trillium.rs"); //<-
///
/// assert_eq!(conn.method(), Method::Get);
/// assert_eq!(conn.url().host_str().unwrap(), "trillium.rs");
/// ```
pub fn build_conn<M>(&self, method: M, url: impl IntoUrl) -> Conn
where
M: TryInto<Method>,
<M as TryInto<Method>>::Error: Debug,
{
let method = method.try_into().unwrap();
let (url, request_target) = if let Some(base) = &self.base
&& let Some(request_target) = url.request_target(method)
{
((**base).clone(), Some(request_target))
} else {
(self.build_url(url).unwrap(), None)
};
Conn {
url,
method,
request_headers: Headers::clone(&self.default_headers),
response_headers: Headers::new(),
transport: None,
status: None,
request_body: None,
protocol_session: ProtocolSession::Http1,
#[cfg(feature = "webtransport")]
wt_pool_entry: None,
buffer: Vec::with_capacity(128).into(),
response_body_state: ReceivedBodyState::End,
headers_finalized: false,
halted: false,
error: None,
body_override: None,
timeout: self.timeout,
http_version: None,
max_head_length: 8 * 1024,
state: TypeSet::new(),
context: self.context.clone(),
authority: None,
scheme: None,
path: None,
request_target,
protocol: None,
request_trailers: None,
response_trailers: None,
client: self.clone(),
followup: None,
upgrade: false,
}
}
/// borrow the connector for this client
pub fn connector(&self) -> &ArcedConnector {
&self.config
}
/// The pool implementation accumulates a small memory footprint for each new host. If
/// your application is reusing a pool against a large number of unique hosts, call this
/// method intermittently.
pub fn clean_up_pool(&self) {
if let Some(pool) = &self.pool {
pool.cleanup();
}
if let Some(h2_pool) = &self.h2_pool {
h2_pool.cleanup();
}
}
/// chainable method to set the base for this client
pub fn with_base(mut self, base: impl IntoUrl) -> Self {
self.set_base(base).unwrap();
self
}
/// attempt to build a url from this IntoUrl and the [`Client::base`], if set
pub fn build_url(&self, url: impl IntoUrl) -> crate::Result<Url> {
url.into_url(self.base())
}
/// set the base for this client
pub fn set_base(&mut self, base: impl IntoUrl) -> crate::Result<()> {
let mut base = base.into_url(None)?;
if !base.path().ends_with('/') {
log::warn!("appending a trailing / to {base}");
base.set_path(&format!("{}/", base.path()));
}
self.base = Some(Arc::new(base));
Ok(())
}
/// Mutate the url base for this client.
///
/// This has "clone-on-write" semantics if there are other clones of this client. If there are
/// other clones of this client, they will not be updated.
pub fn base_mut(&mut self) -> Option<&mut Url> {
let base = self.base.as_mut()?;
Some(Arc::make_mut(base))
}
}
impl<T: Connector> From<T> for Client {
fn from(connector: T) -> Self {
Self::new(connector)
}
}