vibeio-http 0.4.0

High-performance HTTP server primitives for the `vibeio` runtime
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! HPACK header tables (RFC 7541 Sections 2.3 and 4).

use bytes::Bytes;
use std::collections::VecDeque;

/// The static table (RFC 7541 Appendix A): 61 immutable entries.
/// Index 1 is `:authority`, index 61 is `www-authenticate`.
const STATIC_TABLE: [(&[u8], &[u8]); 61] = [
    (b":authority", b""),
    (b":method", b"GET"),
    (b":method", b"POST"),
    (b":path", b"/"),
    (b":path", b"/index.html"),
    (b":scheme", b"http"),
    (b":scheme", b"https"),
    (b":status", b"200"),
    (b":status", b"204"),
    (b":status", b"206"),
    (b":status", b"304"),
    (b":status", b"400"),
    (b":status", b"404"),
    (b":status", b"500"),
    (b"accept-charset", b""),
    (b"accept-encoding", b"gzip, deflate"),
    (b"accept-language", b""),
    (b"accept-ranges", b""),
    (b"accept", b""),
    (b"access-control-allow-origin", b""),
    (b"age", b""),
    (b"allow", b""),
    (b"authorization", b""),
    (b"cache-control", b""),
    (b"content-disposition", b""),
    (b"content-encoding", b""),
    (b"content-language", b""),
    (b"content-length", b""),
    (b"content-location", b""),
    (b"content-range", b""),
    (b"content-type", b""),
    (b"cookie", b""),
    (b"date", b""),
    (b"etag", b""),
    (b"expect", b""),
    (b"expires", b""),
    (b"from", b""),
    (b"host", b""),
    (b"if-match", b""),
    (b"if-modified-since", b""),
    (b"if-none-match", b""),
    (b"if-range", b""),
    (b"if-unmodified-since", b""),
    (b"last-modified", b""),
    (b"link", b""),
    (b"location", b""),
    (b"max-forwards", b""),
    (b"proxy-authenticate", b""),
    (b"proxy-authorization", b""),
    (b"range", b""),
    (b"referer", b""),
    (b"refresh", b""),
    (b"retry-after", b""),
    (b"server", b""),
    (b"set-cookie", b""),
    (b"strict-transport-security", b""),
    (b"transfer-encoding", b""),
    (b"user-agent", b""),
    (b"vary", b""),
    (b"via", b""),
    (b"www-authenticate", b""),
];

/// Number of entries in the static table.
pub(crate) const STATIC_LEN: usize = 61;

/// The entry-size overhead (RFC 7541 Section 4.1).
const ENTRY_OVERHEAD: usize = 32;

/// A header field name/value pair stored in or fetched from a table.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Header {
    name: Bytes,
    value: Bytes,
    /// Cached RFC 7541 Section 4.1 size (overhead + name + value), so
    /// eviction and accounting never recompute it.
    size: usize,
}

impl Header {
    /// Creates a header field from raw name/value bytes. Names are used
    /// verbatim (no case normalization), which allows HTTP/2 pseudo
    /// headers (`:method`, `:status`, ...).
    #[inline]
    pub fn new(name: impl Into<Bytes>, value: impl Into<Bytes>) -> Self {
        let name = name.into();
        let value = value.into();
        let size = ENTRY_OVERHEAD + name.len() + value.len();
        Header { name, value, size }
    }

    /// Size in octets as defined in RFC 7541 Section 4.1: the sum of the
    /// name and value lengths (without Huffman encoding) plus 32.
    #[inline]
    pub(crate) fn size(&self) -> usize {
        self.size
    }

    #[inline]
    pub fn name(&self) -> &[u8] {
        &self.name
    }

    #[inline]
    pub fn value(&self) -> &[u8] {
        &self.value
    }
}

/// The HPACK header table: the immutable static table followed by a
/// dynamically sized FIFO (RFC 7541 Section 4).
#[derive(Debug)]
pub(crate) struct Table {
    /// Dynamic entries, newest at the front. The entry at index 62 in the
    /// combined addressing scheme is `entries[0]`.
    entries: VecDeque<Header>,
    /// Current combined size of the dynamic entries.
    size: usize,
    /// Maximum combined size the dynamic table may grow to.
    max_size: usize,
}

impl Table {
    #[inline]
    pub(crate) fn new() -> Self {
        Table::with_max_size(DEFAULT_MAX_SIZE)
    }

    /// The default dynamic-table size when no SETTINGS_HEADER_TABLE_SIZE
    /// has been exchanged (RFC 7541 Section 4.2).
    #[inline]
    pub(crate) fn with_max_size(max_size: usize) -> Self {
        Table {
            entries: VecDeque::new(),
            size: 0,
            max_size,
        }
    }

    /// Returns the entry at 1-based `index`: 1..=61 addresses the static
    /// table, 62.. the dynamic table (newest first).
    #[inline]
    pub(crate) fn get(&self, index: usize) -> Option<Header> {
        if index == 0 {
            return None;
        }
        if index <= STATIC_LEN {
            let (name, value) = STATIC_TABLE[index - 1];
            // `from_static` is zero-copy.
            return Some(Header::new(
                Bytes::from_static(name),
                Bytes::from_static(value),
            ));
        }
        self.entries.get(index - STATIC_LEN - 1).cloned()
    }

    /// Number of dynamic entries.
    #[cfg(test)]
    #[inline]
    pub(crate) fn dynamic_len(&self) -> usize {
        self.entries.len()
    }

    /// 1-based index of the exact `(name, value)` entry if present:
    /// the static table is searched first, then the dynamic table
    /// (newest first).
    #[inline]
    pub(crate) fn find(&self, name: &[u8], value: &[u8]) -> Option<usize> {
        for (i, (n, v)) in STATIC_TABLE.iter().enumerate() {
            if *n == name && *v == value {
                return Some(i + 1);
            }
        }
        for (i, entry) in self.entries.iter().enumerate() {
            if entry.name() == name && entry.value() == value {
                return Some(STATIC_LEN + i + 1);
            }
        }
        None
    }

    /// 1-based index of an entry with the given `name` if present: the
    /// static table is searched first, then the dynamic table (newest
    /// first).
    #[inline]
    pub(crate) fn find_name(&self, name: &[u8]) -> Option<usize> {
        for (i, (n, _)) in STATIC_TABLE.iter().enumerate() {
            if *n == name {
                return Some(i + 1);
            }
        }
        for (i, entry) in self.entries.iter().enumerate() {
            if entry.name() == name {
                return Some(STATIC_LEN + i + 1);
            }
        }
        None
    }

    /// Number of static and dynamic entries combined.
    #[cfg(test)]
    #[inline]
    pub(crate) fn len(&self) -> usize {
        STATIC_LEN + self.entries.len()
    }

    /// Current combined size of the dynamic entries.
    #[cfg(test)]
    #[inline]
    pub(crate) fn size(&self) -> usize {
        self.size
    }

    #[cfg(test)]
    #[inline]
    pub(crate) fn max_size(&self) -> usize {
        self.max_size
    }

    /// Changes the maximum table size, evicting entries from the end of
    /// the dynamic table until its size is within the new limit
    /// (RFC 7541 Section 4.3).
    #[inline]
    pub(crate) fn set_max_size(&mut self, max_size: usize) {
        self.max_size = max_size;
        while self.size > self.max_size {
            match self.entries.pop_back() {
                Some(entry) => self.size -= entry.size(),
                None => break,
            }
        }
    }

    /// Adds an entry to the front of the dynamic table, evicting entries
    /// from the end as needed (RFC 7541 Section 4.4). An entry larger
    /// than the maximum size empties the table and is not added.
    #[inline]
    pub(crate) fn add(&mut self, header: Header) {
        if header.size() > self.max_size {
            self.entries.clear();
            self.size = 0;
            return;
        }
        while self.size + header.size() > self.max_size {
            match self.entries.pop_back() {
                Some(entry) => self.size -= entry.size(),
                None => break,
            }
        }
        self.size += header.size();
        self.entries.push_front(header);
    }
}

impl Default for Table {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// RFC 7541 Section 4.2: the initial maximum dynamic table size is 4096
/// octets.
const DEFAULT_MAX_SIZE: usize = 4096;

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

    fn header(name: &str, value: &str) -> Header {
        Header::new(
            Bytes::copy_from_slice(name.as_bytes()),
            Bytes::copy_from_slice(value.as_bytes()),
        )
    }

    #[test]
    fn static_table_contents() {
        assert_eq!(
            Table::new().get(1),
            Some(Header::new(
                Bytes::from_static(b":authority"),
                Bytes::from_static(b"")
            ))
        );
        assert_eq!(
            Table::new().get(2),
            Some(Header::new(
                Bytes::from_static(b":method"),
                Bytes::from_static(b"GET")
            ))
        );
        assert_eq!(
            Table::new().get(16),
            Some(Header::new(
                Bytes::from_static(b"accept-encoding"),
                Bytes::from_static(b"gzip, deflate")
            ))
        );
        assert_eq!(
            Table::new().get(61),
            Some(Header::new(
                Bytes::from_static(b"www-authenticate"),
                Bytes::from_static(b"")
            ))
        );
        assert_eq!(Table::new().get(0), None);
    }

    #[test]
    fn entry_size_math() {
        // 32 overhead + 4 name + 3 value.
        assert_eq!(header("test", "abc").size(), 39);
        assert_eq!(header("", "").size(), 32);
    }

    #[test]
    fn add_and_fetch_order() {
        let mut table = Table::with_max_size(200);
        table.add(header("a", "1"));
        table.add(header("b", "2"));
        table.add(header("c", "3"));

        // Newest entry is at index 62.
        assert_eq!(table.get(62), Some(header("c", "3")));
        assert_eq!(table.get(63), Some(header("b", "2")));
        assert_eq!(table.get(64), Some(header("a", "1")));
        assert_eq!(table.get(65), None);
        assert_eq!(table.dynamic_len(), 3);
        assert_eq!(table.len(), STATIC_LEN + 3);
        assert_eq!(table.size(), 34 * 3);
    }

    #[test]
    fn eviction_from_end() {
        // Each entry is 34 octets; only two fit in 70.
        let mut table = Table::with_max_size(70);
        table.add(header("a", "1"));
        table.add(header("b", "2"));
        table.add(header("c", "3"));

        assert_eq!(table.dynamic_len(), 2);
        assert_eq!(table.get(62), Some(header("c", "3")));
        assert_eq!(table.get(63), Some(header("b", "2")));
        assert_eq!(table.get(64), None);
        assert_eq!(table.size(), 68);
    }

    #[test]
    fn entry_larger_than_max_empties_table() {
        let mut table = Table::with_max_size(100);
        table.add(header("x", "1"));
        table.add(header("y", "2"));
        assert_eq!(table.dynamic_len(), 2);

        // 101 octets > 100 max.
        let big = header(&"v".repeat(60), &"v".repeat(9));
        assert_eq!(big.size(), 101);
        table.add(big);

        assert_eq!(table.dynamic_len(), 0);
        assert_eq!(table.size(), 0);
    }

    #[test]
    fn entry_exactly_max_size_is_added() {
        let mut table = Table::with_max_size(101);
        let big = header(&"v".repeat(60), &"v".repeat(9));
        assert_eq!(big.size(), 101);
        table.add(big);
        assert_eq!(table.dynamic_len(), 1);
    }

    #[test]
    fn size_update_evicts() {
        let mut table = Table::with_max_size(200);
        table.add(header("a", "1"));
        table.add(header("b", "2"));
        table.add(header("c", "3"));

        table.set_max_size(70);
        assert_eq!(table.dynamic_len(), 2);
        assert_eq!(table.get(62), Some(header("c", "3")));
        assert_eq!(table.size(), 68);

        table.set_max_size(0);
        assert_eq!(table.dynamic_len(), 0);
        assert_eq!(table.size(), 0);

        // Growing back to the original size keeps the table empty; new
        // entries populate it again.
        table.set_max_size(200);
        assert_eq!(table.dynamic_len(), 0);
        table.add(header("d", "4"));
        assert_eq!(table.get(62), Some(header("d", "4")));
    }

    #[test]
    fn max_size_tracks_requests() {
        let mut table = Table::with_max_size(128);
        assert_eq!(table.max_size(), 128);
        table.set_max_size(256);
        assert_eq!(table.max_size(), 256);
    }

    #[test]
    fn default_max_size() {
        assert_eq!(Table::new().max_size(), DEFAULT_MAX_SIZE);
        assert_eq!(Table::default().max_size(), DEFAULT_MAX_SIZE);
    }

    #[test]
    fn grows_and_reuses_slots() {
        // The FIFO must keep working after many evictions (the ring
        // reuses its backing slots).
        let mut table = Table::with_max_size(200);
        for i in 0..100 {
            let entry = header(&format!("k{i}"), "v");
            table.add(entry.clone());
            assert!(table.size() <= table.max_size(), "iteration {i}");
            assert_eq!(table.get(62), Some(entry), "iteration {i}");
        }
        assert_eq!(table.get(62), Some(header("k99", "v")));
        assert_eq!(
            table.size(),
            table.dynamic_len() * table.get(62).unwrap().size()
        );
    }
}