tez 0.0.3

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
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
409
410
411
412
413
414
415
416
use std::{net::IpAddr, time::Duration};

use crate::{Error, Result};

const MIN_HTTP2_FRAME_SIZE: u32 = 16 * 1024;
const MAX_HTTP2_FRAME_SIZE: u32 = (1 << 24) - 1;
const MIN_HTTP1_BUFFER_SIZE: usize = 8 * 1024;
const DEFAULT_HTTP1_BUFFER_SIZE: usize = 8 * 1024 + 4 * 1024 * 100;
const DEFAULT_HTTP1_HEADERS: usize = 100;

/// Socket and protocol policy for new HTTP connections.
///
/// This value describes portable connection behavior without exposing the
/// socket or HTTP implementation used by Tez.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Settings {
    local_address: Option<IpAddr>,
    nodelay: bool,
    keepalive: Option<Duration>,
    http1: Http1,
    http2: Http2,
}

impl Settings {
    /// Binds outgoing sockets to a local IPv4 or IPv6 address.
    ///
    /// Only resolved destinations from the same address family are attempted.
    #[must_use]
    pub fn local_address(mut self, address: impl Into<Option<IpAddr>>) -> Self {
        self.local_address = address.into();
        self
    }

    /// Enables or disables `TCP_NODELAY`.
    ///
    /// It is enabled by default to avoid delaying small HTTP writes.
    #[must_use]
    pub const fn nodelay(mut self, enabled: bool) -> Self {
        self.nodelay = enabled;
        self
    }

    /// Configures TCP keepalive probes for established connections.
    ///
    /// Pass `None` to use the operating system default. A zero duration is
    /// rejected when the client is built.
    #[must_use]
    pub fn keepalive(mut self, idle: impl Into<Option<Duration>>) -> Self {
        self.keepalive = idle.into();
        self
    }

    /// Replaces the HTTP/2 connection policy.
    #[must_use]
    pub const fn http2(mut self, http2: Http2) -> Self {
        self.http2 = http2;
        self
    }

    /// Replaces the HTTP/1 parser and buffer policy.
    #[must_use]
    pub const fn http1(mut self, http1: Http1) -> Self {
        self.http1 = http1;
        self
    }

    pub(crate) const fn local(self) -> Option<IpAddr> {
        self.local_address
    }

    pub(crate) const fn uses_nodelay(self) -> bool {
        self.nodelay
    }

    pub(crate) const fn keepalive_idle(self) -> Option<Duration> {
        self.keepalive
    }

    pub(crate) const fn http2_policy(self) -> Http2 {
        self.http2
    }

    pub(crate) const fn http1_policy(self) -> Http1 {
        self.http1
    }

    pub(crate) fn validate(self) -> Result<()> {
        if self.keepalive.is_some_and(|duration| duration.is_zero()) {
            return Err(Error::request(
                "client TCP keepalive duration must be greater than zero",
            ));
        }
        self.http1.validate()?;
        self.http2.validate()
    }
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            local_address: None,
            nodelay: true,
            keepalive: None,
            http1: Http1::default(),
            http2: Http2::default(),
        }
    }
}

/// Bounded HTTP/1 response parsing and buffering policy.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Http1 {
    max_headers: usize,
    max_buffer_size: usize,
}

impl Http1 {
    /// Sets the largest number of response headers accepted.
    #[must_use]
    pub const fn max_headers(mut self, headers: usize) -> Self {
        self.max_headers = headers;
        self
    }

    /// Sets the largest HTTP/1 buffer used while parsing a message head.
    #[must_use]
    pub const fn max_buffer_size(mut self, bytes: usize) -> Self {
        self.max_buffer_size = bytes;
        self
    }

    pub(crate) fn apply(self, builder: &mut hyper::client::conn::http1::Builder) {
        builder
            .writev(true)
            .max_headers(self.max_headers)
            .max_buf_size(self.max_buffer_size);
    }

    fn validate(self) -> Result<()> {
        if self.max_headers == 0 {
            return Err(Error::request(
                "client HTTP/1 header limit must be greater than zero",
            ));
        }
        if self.max_buffer_size < MIN_HTTP1_BUFFER_SIZE {
            return Err(Error::request(
                "client HTTP/1 buffer limit must be at least 8192 bytes",
            ));
        }
        Ok(())
    }
}

impl Default for Http1 {
    fn default() -> Self {
        Self {
            max_headers: DEFAULT_HTTP1_HEADERS,
            max_buffer_size: DEFAULT_HTTP1_BUFFER_SIZE,
        }
    }
}

/// Flow-control and liveness policy for HTTP/2 connections.
///
/// Defaults use Hyper's protocol settings. Tez applies these values only after
/// HTTP/2 is selected by TLS ALPN or [`Http2::prior_knowledge`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Http2 {
    enabled: bool,
    prior_knowledge: bool,
    adaptive_window: bool,
    stream_window: Option<u32>,
    connection_window: Option<u32>,
    max_frame_size: Option<u32>,
    max_header_list_size: Option<u32>,
    max_send_buffer_size: Option<usize>,
    keepalive_interval: Option<Duration>,
    keepalive_timeout: Option<Duration>,
    keepalive_while_idle: bool,
}

impl Http2 {
    /// Enables or disables HTTP/2 for this client.
    ///
    /// Disabling it offers only HTTP/1.1 during TLS negotiation and is useful
    /// for HTTP/1-only upgrades or compatibility with older peers.
    #[must_use]
    pub const fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        if !enabled {
            self.prior_knowledge = false;
        }
        self
    }

    /// Uses HTTP/2 without an HTTP/1.1 upgrade on cleartext origins.
    ///
    /// Enable this only for origins known to accept the HTTP/2 connection
    /// preface. HTTPS origins continue to negotiate HTTP/2 with ALPN.
    #[must_use]
    pub const fn prior_knowledge(mut self, enabled: bool) -> Self {
        self.prior_knowledge = enabled;
        if enabled {
            self.enabled = true;
        }
        self
    }

    /// Enables adaptive HTTP/2 flow-control windows.
    #[must_use]
    pub const fn adaptive_window(mut self, enabled: bool) -> Self {
        self.adaptive_window = enabled;
        self
    }

    /// Sets the initial per-stream flow-control window.
    #[must_use]
    pub fn stream_window(mut self, bytes: impl Into<Option<u32>>) -> Self {
        self.stream_window = bytes.into();
        self
    }

    /// Sets the initial connection flow-control window.
    #[must_use]
    pub fn connection_window(mut self, bytes: impl Into<Option<u32>>) -> Self {
        self.connection_window = bytes.into();
        self
    }

    /// Sets the largest HTTP/2 frame accepted from a peer.
    #[must_use]
    pub fn max_frame_size(mut self, bytes: impl Into<Option<u32>>) -> Self {
        self.max_frame_size = bytes.into();
        self
    }

    /// Sets the largest decoded response header list accepted from a peer.
    #[must_use]
    pub fn max_header_list_size(mut self, bytes: impl Into<Option<u32>>) -> Self {
        self.max_header_list_size = bytes.into();
        self
    }

    /// Sets the largest buffered outbound data per HTTP/2 stream.
    #[must_use]
    pub fn max_send_buffer_size(mut self, bytes: impl Into<Option<usize>>) -> Self {
        self.max_send_buffer_size = bytes.into();
        self
    }

    /// Sends HTTP/2 PING frames on this interval.
    ///
    /// Pass `None` to disable keepalive PINGs.
    #[must_use]
    pub fn keepalive_interval(mut self, interval: impl Into<Option<Duration>>) -> Self {
        self.keepalive_interval = interval.into();
        self
    }

    /// Sets how long Tez waits for an HTTP/2 keepalive acknowledgement.
    #[must_use]
    pub fn keepalive_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
        self.keepalive_timeout = timeout.into();
        self
    }

    /// Sends HTTP/2 keepalive PINGs while no streams are active.
    #[must_use]
    pub const fn keepalive_while_idle(mut self, enabled: bool) -> Self {
        self.keepalive_while_idle = enabled;
        self
    }

    pub(crate) const fn uses_prior_knowledge(self) -> bool {
        self.prior_knowledge
    }

    pub(crate) const fn is_enabled(self) -> bool {
        self.enabled
    }

    pub(crate) fn apply(self, builder: &mut hyper::client::conn::http2::Builder<crate::Executor>) {
        builder.adaptive_window(self.adaptive_window);
        builder.initial_stream_window_size(self.stream_window);
        builder.initial_connection_window_size(self.connection_window);
        builder.max_frame_size(self.max_frame_size);
        if let Some(size) = self.max_header_list_size {
            builder.max_header_list_size(size);
        }
        if let Some(size) = self.max_send_buffer_size {
            builder.max_send_buf_size(size);
        }
        builder.keep_alive_interval(self.keepalive_interval);
        if let Some(timeout) = self.keepalive_timeout {
            builder.keep_alive_timeout(timeout);
        }
        builder.keep_alive_while_idle(self.keepalive_while_idle);
    }

    fn validate(self) -> Result<()> {
        if self.stream_window.is_some_and(|window| window == 0)
            || self.connection_window.is_some_and(|window| window == 0)
        {
            return Err(Error::request(
                "client HTTP/2 flow-control windows must be greater than zero",
            ));
        }
        if self
            .max_frame_size
            .is_some_and(|size| !(MIN_HTTP2_FRAME_SIZE..=MAX_HTTP2_FRAME_SIZE).contains(&size))
        {
            return Err(Error::request(
                "client HTTP/2 frame size is outside the protocol range",
            ));
        }
        if self.max_header_list_size == Some(0) {
            return Err(Error::request(
                "client HTTP/2 header-list limit must be greater than zero",
            ));
        }
        if self
            .max_send_buffer_size
            .is_some_and(|size| size == 0 || size > u32::MAX as usize)
        {
            return Err(Error::request(
                "client HTTP/2 send-buffer limit must fit in a nonzero u32",
            ));
        }
        for duration in [self.keepalive_interval, self.keepalive_timeout] {
            if duration.is_some_and(|duration| duration.is_zero()) {
                return Err(Error::request(
                    "client HTTP/2 keepalive durations must be greater than zero",
                ));
            }
        }
        Ok(())
    }
}

impl Default for Http2 {
    fn default() -> Self {
        Self {
            enabled: true,
            prior_knowledge: false,
            adaptive_window: false,
            stream_window: None,
            connection_window: None,
            max_frame_size: None,
            max_header_list_size: None,
            max_send_buffer_size: None,
            keepalive_interval: None,
            keepalive_timeout: None,
            keepalive_while_idle: false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn defaults_favor_small_writes_without_forcing_keepalive() {
        let settings = Settings::default();

        assert!(settings.uses_nodelay());
        assert_eq!(settings.keepalive_idle(), None);
        assert!(!settings.http2_policy().uses_prior_knowledge());
    }

    #[test]
    fn invalid_socket_and_protocol_values_are_rejected() {
        assert!(
            Settings::default()
                .keepalive(Duration::ZERO)
                .validate()
                .unwrap_err()
                .is_request()
        );
        assert!(
            Settings::default()
                .http1(Http1::default().max_headers(0))
                .validate()
                .unwrap_err()
                .is_request()
        );
        assert!(
            Settings::default()
                .http1(Http1::default().max_buffer_size(MIN_HTTP1_BUFFER_SIZE - 1))
                .validate()
                .unwrap_err()
                .is_request()
        );
        assert!(
            Settings::default()
                .http2(Http2::default().max_frame_size(1024))
                .validate()
                .unwrap_err()
                .is_request()
        );
        assert!(
            Settings::default()
                .http2(Http2::default().max_header_list_size(0))
                .validate()
                .unwrap_err()
                .is_request()
        );
        assert!(
            Settings::default()
                .http2(Http2::default().max_send_buffer_size(0))
                .validate()
                .unwrap_err()
                .is_request()
        );
    }
}