trillium_http/http_config.rs
1use fieldwork::Fieldwork;
2
3/// # Performance and security parameters for trillium-http.
4///
5/// Trillium's http implementation is built with sensible defaults, but applications differ in usage
6/// and this escape hatch allows an application to be tuned. It is best to tune these parameters in
7/// context of realistic benchmarks for your application.
8///
9/// The `h2_*` fields tune HTTP/2 advertised settings and recv windows; `h3_*` fields tune HTTP/3.
10/// None affect HTTP/1.x. See the [crate-level docs][crate] for the protocol-dispatch table.
11///
12/// ```
13/// # use trillium_http::HttpConfig;
14/// // Accept body bytes eagerly (65535-byte initial window) instead of the default 100-
15/// // continue-like lazy window. Good for "always accept uploads" workloads.
16/// let config = HttpConfig::default().with_h2_initial_stream_window_size(65_535);
17/// assert_eq!(config.h2_initial_stream_window_size(), 65_535);
18/// ```
19#[derive(Clone, Copy, Debug, Fieldwork)]
20#[fieldwork(get, get_mut, set, with, without)]
21// `HttpConfig` is a user-facing tuning struct with documented per-field setters; the natural
22// shape is one field per knob. Bundling bools into an enum or bitflags would make the getter/
23// setter surface worse for callers.
24#[allow(clippy::struct_excessive_bools)]
25pub struct HttpConfig {
26 /// The maximum length allowed before the http body begins for a given request.
27 ///
28 /// **Default**: `8kb` in bytes
29 ///
30 /// **Unit**: Byte count
31 pub(crate) head_max_len: usize,
32
33 /// The maximum length of a received body
34 ///
35 /// This limit applies regardless of whether the body is read all at once or streamed
36 /// incrementally, and regardless of transfer encoding (chunked or fixed-length). The correct
37 /// value will be application dependent.
38 ///
39 /// **Default**: `10mb` in bytes
40 ///
41 /// **Unit**: Byte count
42 pub(crate) received_body_max_len: u64,
43
44 /// The initial buffer allocated for the response.
45 ///
46 /// Ideally this would be exactly the length of the combined response headers and body, if the
47 /// body is short. If the value is shorter than the headers plus the body, multiple transport
48 /// writes will be performed, and if the value is longer, unnecessary memory will be allocated
49 /// for each conn. Although a tcp packet can be up to 64kb, it is probably better to use a
50 /// value less than 1.5kb.
51 ///
52 /// **Default**: `512`
53 ///
54 /// **Unit**: byte count
55 pub(crate) response_buffer_len: usize,
56
57 /// Maximum size the response buffer may grow to absorb backpressure.
58 ///
59 /// When the transport cannot accept data as fast as the response body is produced, the buffer
60 /// absorbs the remainder up to this limit. Once the limit is reached, writes apply
61 /// backpressure to the body source. This prevents a slow client from causing unbounded memory
62 /// growth.
63 ///
64 /// **Default**: `2mb` in bytes
65 ///
66 /// **Unit**: byte count
67 pub(crate) response_buffer_max_len: usize,
68
69 /// The initial buffer allocated for the request headers.
70 ///
71 /// Ideally this is the length of the request headers. It will grow nonlinearly until
72 /// `max_head_len` or the end of the headers are reached, whichever happens first.
73 ///
74 /// **Default**: `128`
75 ///
76 /// **Unit**: byte count
77 pub(crate) request_buffer_initial_len: usize,
78
79 /// The number of response headers to allocate space for on conn creation.
80 ///
81 /// Headers will grow on insertion when they reach this size.
82 ///
83 /// **Default**: `16`
84 ///
85 /// **Unit**: Header count
86 pub(crate) response_header_initial_capacity: usize,
87
88 /// Cooperative task-yielding knob.
89 ///
90 /// Decreasing this number will improve tail latencies at a slight cost to total throughput for
91 /// fast clients. This will have more of an impact on servers that spend a lot of time in IO
92 /// compared to app handlers.
93 ///
94 /// **Default**: `16`
95 ///
96 /// **Unit**: the number of consecutive `Poll::Ready` async writes to perform before yielding
97 /// the task back to the runtime.
98 pub(crate) copy_loops_per_yield: usize,
99
100 /// The initial buffer capacity allocated when reading a chunked http body to bytes or string.
101 ///
102 /// Ideally this would be the size of the http body, which is highly application dependent. As
103 /// with other initial buffer lengths, further allocation will be performed until the necessary
104 /// length is achieved. A smaller number will result in more vec resizing, and a larger number
105 /// will result in unnecessary allocation.
106 ///
107 /// **Default**: `128`
108 ///
109 /// **Unit**: byte count
110 pub(crate) received_body_initial_len: usize,
111
112 /// Maximum size to pre-allocate based on content-length for buffering a complete request body
113 ///
114 /// When we receive a fixed-length (not chunked-encoding) body that is smaller than this size,
115 /// we can allocate a buffer with exactly the right size before we receive the body. However,
116 /// if this is unbounded, malicious clients can issue headers with large content-length and
117 /// then keep the connection open without sending any bytes, allowing them to allocate
118 /// memory faster than their bandwidth usage. This does not limit the ability to receive
119 /// fixed-length bodies larger than this, but the memory allocation will grow as with
120 /// chunked bodies. Note that this has no impact on chunked bodies. If this is set higher
121 /// than the `received_body_max_len`, this parameter has no effect. This parameter only
122 /// impacts [`ReceivedBody::read_string`](crate::ReceivedBody::read_string) and
123 /// [`ReceivedBody::read_bytes`](crate::ReceivedBody::read_bytes).
124 ///
125 /// **Default**: `1mb` in bytes
126 ///
127 /// **Unit**: Byte count
128 pub(crate) received_body_max_preallocate: usize,
129
130 /// The maximum cumulative size of a header block the peer may send.
131 ///
132 /// Advertised in SETTINGS as `SETTINGS_MAX_HEADER_LIST_SIZE` on HTTP/2 (RFC 9113) and
133 /// `SETTINGS_MAX_FIELD_SECTION_SIZE` on HTTP/3 (RFC 9114). Guards against pathological
134 /// header lists inflating memory per stream during HPACK/QPACK decode.
135 ///
136 /// On HTTP/2 this also bounds the cumulative compressed bytes of a header block
137 /// accumulated across HEADERS + CONTINUATION frames: a block exceeding this limit closes
138 /// the connection with `ENHANCE_YOUR_CALM`, mitigating the CONTINUATION-flood `DoS`
139 /// (CVE-2024-27316 class). Otherwise the peer is expected to self-police.
140 ///
141 /// **Default**: `32 KiB`
142 ///
143 /// **Unit**: byte count
144 pub(crate) max_header_list_size: u64,
145
146 /// Maximum capacity of the dynamic header-compression table.
147 ///
148 /// Advertised to peers as `SETTINGS_HEADER_TABLE_SIZE` (HPACK / RFC 7541) and
149 /// `SETTINGS_QPACK_MAX_TABLE_CAPACITY` (QPACK / RFC 9204). Bounds both the decoder's
150 /// inbound table and our encoder's outbound table; set to `0` to disable dynamic-table
151 /// compression entirely (encoder reduces to static-or-literal).
152 ///
153 /// **Default**: 4096 bytes
154 ///
155 /// **Unit**: Byte count
156 pub(crate) dynamic_table_capacity: usize,
157
158 /// Maximum number of HTTP/3 request streams that may be blocked waiting for dynamic table
159 /// updates.
160 ///
161 /// Advertised to peers as `SETTINGS_QPACK_BLOCKED_STREAMS`. A value of `0` prevents peers
162 /// from sending header blocks that reference table entries not yet seen by this decoder.
163 ///
164 /// **Default**: 100
165 ///
166 /// **Unit**: Stream count
167 pub(crate) h3_blocked_streams: usize,
168
169 /// Per-connection ring size for the header encoder's recently-seen-pair predictor.
170 ///
171 /// Applies to both HPACK (HTTP/2) and QPACK (HTTP/3). The predictor lets the encoder
172 /// defer dynamic-table inserts until a `(name, value)` pair has been seen at least
173 /// once on the connection — first sighting emits a literal, subsequent sightings
174 /// within the ring's retention window invest in an insert so future sections can
175 /// index it. A larger ring catches repetitions across more intervening header lines
176 /// (good for header-heavy reverse proxies); a smaller ring forgets faster (fine for
177 /// tiny APIs). A cross-connection observer short-circuits this for already-known-hot
178 /// pairs.
179 ///
180 /// The predictor is consulted once per emitted header line via a u32 hash compare;
181 /// cost grows linearly with `size` but is dominated by the per-line hash, so
182 /// oversizing here is cheap.
183 ///
184 /// **Default**: 64
185 ///
186 /// **Unit**: Pair count
187 pub(crate) recent_pairs_size: usize,
188
189 /// Initial HTTP/2 stream flow-control window advertised to peers as
190 /// `SETTINGS_INITIAL_WINDOW_SIZE`.
191 ///
192 /// Controls how many request-body bytes the peer may send on a newly-opened stream before
193 /// waiting for a `WINDOW_UPDATE`. The default of `0` implements a lazy / 100-continue-like
194 /// pattern: the peer cannot send any body bytes until the handler calls `read` on the
195 /// request body, at which point the driver emits a `WINDOW_UPDATE` topping the window up
196 /// to [`h2_max_stream_recv_window_size`][Self::h2_max_stream_recv_window_size]. A handler
197 /// that returns an error from its header-level checks never pays the bandwidth cost of
198 /// reading the body.
199 ///
200 /// Set to `65_535` (the RFC 9113 baseline) to match nginx / Apache / hyper behavior — body
201 /// bytes arrive eagerly at the cost of 1 RTT less latency on the first DATA frame and the
202 /// possible waste of up to this many bytes on requests the handler rejects.
203 ///
204 /// Must not exceed `2^31 - 1`.
205 ///
206 /// **Default**: `0` (lazy-WU)
207 ///
208 /// **Unit**: byte count
209 pub(crate) h2_initial_stream_window_size: u32,
210
211 /// Per-stream recv window target — how high the driver keeps the peer's stream window
212 /// topped up as the handler consumes request-body bytes.
213 ///
214 /// After the handler signals intent to read (first `poll_read` on the request body), the
215 /// driver emits `WINDOW_UPDATE` frames to keep the effective peer window near this target.
216 /// Also serves as the hard per-stream buffer cap — a peer that sends past this amount of
217 /// unconsumed DATA on a single stream earns a connection-level `FLOW_CONTROL_ERROR`.
218 ///
219 /// **Default**: `1 MiB`
220 ///
221 /// **Unit**: byte count
222 pub(crate) h2_max_stream_recv_window_size: u32,
223
224 /// Connection-level recv window target — how high the driver keeps the peer's
225 /// connection-level window topped up as handlers consume bytes.
226 ///
227 /// Raised via an initial `WINDOW_UPDATE(stream_id=0)` right after SETTINGS (RFC 9113
228 /// forbids SETTINGS from altering the connection window), then refilled on consumption.
229 /// Bounds total concurrent in-flight request-body bytes across all streams on a single
230 /// HTTP/2 connection. Leaving at the RFC baseline of `65_535` would cap bulk uploads at
231 /// ~5 Mbit/s × RTT.
232 ///
233 /// **Default**: `2 MiB`
234 ///
235 /// **Unit**: byte count
236 pub(crate) h2_initial_connection_window_size: u32,
237
238 /// HTTP/2 `SETTINGS_MAX_CONCURRENT_STREAMS` — the maximum number of concurrent
239 /// peer-initiated streams the server will accept.
240 ///
241 /// Peer-opened streams beyond this count get `RST_STREAM(RefusedStream)` per RFC 9113.
242 /// A value in the 100–250 range is the post-Rapid-Reset (CVE-2023-44487) consensus;
243 /// lower values cap parallelism, higher values need per-connection reset-rate limiting
244 /// to avoid `DoS` exposure.
245 ///
246 /// **Default**: `100`
247 ///
248 /// **Unit**: stream count
249 pub(crate) h2_max_concurrent_streams: u32,
250
251 /// HTTP/2 `SETTINGS_MAX_FRAME_SIZE` — the largest frame payload the server will accept.
252 ///
253 /// Peer frames whose payload exceeds this get `FRAME_SIZE_ERROR` per RFC 9113. The RFC
254 /// floor is `16_384`; the ceiling is `16_777_215`. Larger values amortize per-frame
255 /// overhead on bulk transfers but increase the upper bound on a single read.
256 ///
257 /// **Default**: `16_384`
258 ///
259 /// **Unit**: byte count
260 pub(crate) h2_max_frame_size: u32,
261
262 /// whether [datagrams](https://www.rfc-editor.org/rfc/rfc9297.html) are enabled for HTTP/3
263 ///
264 /// This is a protocol-level setting and is communicated to the peer as well as enforced.
265 ///
266 /// **Default**: false
267 pub(crate) h3_datagrams_enabled: bool,
268
269 /// whether [webtransport](https://datatracker.ietf.org/doc/html/draft-ietf-webtrans-http3)
270 /// (`draft-ietf-webtrans-http3`) is enabled for HTTP/3
271 ///
272 /// This is a protocol-level setting and is communicated to the peer. You do not need to
273 /// manually configure this if using
274 /// [`trillium-webtransport`](https://docs.rs/trillium-webtransport)
275 ///
276 /// **Default**: false
277 pub(crate) webtransport_enabled: bool,
278
279 /// `SETTINGS_ENABLE_CONNECT_PROTOCOL` — advertises that the server accepts extended
280 /// CONNECT requests, enabling protocols layered on top of HTTP that bootstrap via a
281 /// CONNECT with a `:protocol` pseudo-header. The same identifier (0x08) is used by
282 /// HTTP/2 (RFC 8441) and HTTP/3 (RFC 9220).
283 ///
284 /// Use cases include WebSocket-over-h2 (RFC 8441), WebSocket-over-h3 (RFC 9220),
285 /// and WebTransport (`draft-ietf-webtrans-http2` and `draft-ietf-webtrans-http3`).
286 ///
287 /// When set, the server's initial SETTINGS frame includes
288 /// `SETTINGS_ENABLE_CONNECT_PROTOCOL = 1` (on both HTTP/2 and HTTP/3) and the runtime
289 /// accepts CONNECT requests carrying a `:protocol` pseudo-header. Without it, clients
290 /// won't attempt extended CONNECT, which is the correct default — handlers that don't
291 /// expect extended CONNECT shouldn't see those requests.
292 ///
293 /// You don't need to set this manually if using a handler that requires it; such handlers
294 /// flip it from `Handler::init`.
295 ///
296 /// **Default**: false
297 pub(crate) extended_connect_enabled: bool,
298
299 /// whether to panic when a response header with an invalid value (containing `\r`, `\n`, or
300 /// `\0`) is encountered.
301 ///
302 /// Invalid header values are always skipped to prevent header injection. When this is `true`,
303 /// Trillium will additionally panic, surfacing the bug loudly. When `false`, the skip is only
304 /// logged (to the `log` backend) at error level.
305 ///
306 /// **Default**: `true` when compiled with `debug_assertions` (i.e. debug builds), `false` in
307 /// release builds. Override to `true` in release if you want strict production behavior, or to
308 /// `false` in debug if you prefer not to panic during development.
309 pub(crate) panic_on_invalid_response_headers: bool,
310}
311
312impl HttpConfig {
313 /// Default Config
314 pub const DEFAULT: Self = HttpConfig {
315 response_buffer_len: 512,
316 response_buffer_max_len: 2 * 1024 * 1024,
317 request_buffer_initial_len: 128,
318 head_max_len: 8 * 1024,
319 response_header_initial_capacity: 16,
320 copy_loops_per_yield: 16,
321 received_body_max_len: 10 * 1024 * 1024,
322 received_body_initial_len: 128,
323 received_body_max_preallocate: 1024 * 1024,
324 max_header_list_size: 32 * 1024,
325 dynamic_table_capacity: 4096,
326 h3_blocked_streams: 100,
327 recent_pairs_size: 64,
328 h3_datagrams_enabled: false,
329 h2_initial_stream_window_size: 0,
330 h2_max_stream_recv_window_size: 1 << 20,
331 h2_initial_connection_window_size: 2 << 20,
332 h2_max_concurrent_streams: 100,
333 h2_max_frame_size: 16_384,
334 webtransport_enabled: false,
335 extended_connect_enabled: false,
336 panic_on_invalid_response_headers: cfg!(debug_assertions),
337 };
338}
339
340impl Default for HttpConfig {
341 fn default() -> Self {
342 HttpConfig::DEFAULT
343 }
344}