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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! QPACK dynamic table (RFC 9204 Section 3.2).
//!
//! The dynamic table is a FIFO list of field lines shared between the
//! encoder and the decoder. Entries are added at the insertion point and
//! evicted from the dropping point (oldest first) to keep the table size
//! within its capacity. The size of an entry is the sum of its name length,
//! its value length, and 32 additional bytes (Section 3.2.1).
//!
//! Absolute indices are fixed for the lifetime of an entry; relative and
//! post-base indices are computed from the context (most-recent insertion
//! for encoder-stream instructions, the field section's Base for field line
//! representations). The table itself is context-free: callers translate
//! indices via the lookup helpers.
//!
//! The dynamic table can contain duplicate entries, and entries can have
//! empty values; neither is an error (Section 3.2).
//!
//! Consumption: the encoder adds entries (Section 4.3) and the decoder
//! materializes them from encoder-stream instructions; both use the same
//! structure.

use std::collections::VecDeque;

use bytes::Bytes;

/// Error returned when an entry cannot be inserted.
///
/// The caller maps this to `QPACK_ENCODER_STREAM_ERROR` on the decoder
/// side; a well-behaved encoder never triggers it (it only inserts entries
/// that fit).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum InsertError {
    /// The entry (name + value + 32) is larger than the table capacity.
    EntryTooLarge,
}

/// FIFO dynamic table. `entries[0]` is the most recently inserted entry.
///
/// Invariants:
/// - `size <= capacity` at all times;
/// - the absolute index of `entries[i]` is `inserted - 1 - i`;
/// - `inserted` counts entries inserted over the table's whole lifetime
///   (absolute indices are never reused).
pub(crate) struct DynamicTable {
    entries: VecDeque<(Bytes, Bytes)>,
    capacity: u64,
    size: u64,
    inserted: u64,
}

impl std::fmt::Debug for DynamicTable {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DynamicTable")
            .field("entries", &self.entries.len())
            .field("capacity", &self.capacity)
            .field("size", &self.size)
            .field("inserted", &self.inserted)
            .finish()
    }
}

impl DynamicTable {
    /// Creates an empty table with the given initial `capacity`.
    #[inline]
    pub(crate) fn new(capacity: u64) -> Self {
        Self {
            entries: VecDeque::new(),
            capacity,
            size: 0,
            inserted: 0,
        }
    }

    /// The current dynamic table capacity.
    #[inline]
    pub(crate) fn capacity(&self) -> u64 {
        self.capacity
    }

    /// The current sum of entry sizes.
    #[cfg(test)]
    #[inline]
    pub(crate) fn size(&self) -> u64 {
        self.size
    }

    /// Number of entries currently in the table.
    #[inline]
    pub(crate) fn len(&self) -> usize {
        self.entries.len()
    }

    /// Absolute index of the most recently inserted entry, or `0` when the
    /// table is empty.
    #[inline]
    pub(crate) fn last_absolute(&self) -> u64 {
        self.inserted.saturating_sub(1)
    }

    /// The number of entries inserted over the table's lifetime.
    #[inline]
    pub(crate) fn inserted(&self) -> u64 {
        self.inserted
    }

    /// The absolute index a newly inserted entry will receive.
    #[inline]
    pub(crate) fn next_absolute(&self) -> u64 {
        self.inserted
    }

    /// The size contribution of an entry: name + value + 32 (RFC 9204
    /// Section 3.2.1).
    #[inline]
    pub(crate) fn entry_size(name: &[u8], value: &[u8]) -> u64 {
        name.len() as u64 + value.len() as u64 + 32
    }

    /// Changes the table capacity, evicting entries from the dropping point
    /// (oldest first) until the table fits.
    ///
    /// Setting the capacity to 0 clears the table; a later increase restores
    /// normal operation with an empty table (RFC 9204 Section 3.2.2).
    #[inline]
    pub(crate) fn set_capacity(&mut self, capacity: u64) {
        self.capacity = capacity;
        self.evict_to_fit(capacity);
    }

    /// Number of entries that inserting an entry of the given `size` would
    /// evict from the dropping point (oldest first), or 0 if it fits.
    ///
    /// The encoder uses this to decide whether an insert would invalidate
    /// references to older entries made earlier in the same field section:
    /// eviction only removes the oldest entries, so an insert is safe while
    /// every evicted absolute index is below the smallest referenced index.
    #[inline]
    pub(crate) fn would_evict(&self, size: u64) -> u64 {
        let need_freed = size.saturating_sub(self.capacity - self.size);
        if need_freed == 0 {
            return 0;
        }
        let mut freed = 0u64;
        let mut evicted = 0u64;
        for (name, value) in self.entries.iter().rev() {
            freed += Self::entry_size(name, value);
            evicted += 1;
            if freed >= need_freed {
                break;
            }
        }
        evicted
    }

    /// Number of entries that would be evicted from the dropping point if
    /// the capacity were reduced to `target` (0 when nothing would be
    /// evicted).
    ///
    /// The decoder uses this to reject a capacity reduction that would
    /// evict entries with an absolute index at or above its Known Received
    /// Count (RFC 9204 Section 2.1.1).
    #[inline]
    pub(crate) fn evict_for_capacity(&self, target: u64) -> u64 {
        let mut size = 0u64;
        let mut survivors = 0u64;
        for (name, value) in self.entries.iter() {
            let entry_size = Self::entry_size(name, value);
            if size + entry_size > target {
                break;
            }
            size += entry_size;
            survivors += 1;
        }
        self.len() as u64 - survivors
    }

    /// Finds the most recent exact match and the most recent name match in
    /// one pass. The encoder uses both results when choosing a field-line
    /// representation, so this avoids scanning a busy dynamic table twice.
    #[inline]
    pub(crate) fn find_full_or_name(
        &self,
        name: &[u8],
        value: &[u8],
    ) -> (Option<u64>, Option<u64>) {
        let mut name_match = None;
        for (i, (entry_name, entry_value)) in self.entries.iter().enumerate() {
            if entry_name != name {
                continue;
            }
            let abs = self.inserted - 1 - i as u64;
            name_match.get_or_insert(abs);
            if entry_value == value {
                return (Some(abs), name_match);
            }
        }
        (None, name_match)
    }

    /// Finds the most recently inserted entry whose name matches `name`.
    ///
    /// Returns the entry's absolute index.
    #[inline]
    pub(crate) fn find_name(&self, name: &[u8]) -> Option<u64> {
        self.entries
            .iter()
            .position(|(n, _)| n == name)
            .map(|i| self.inserted - 1 - i as u64)
    }

    /// Inserts a new entry at the insertion point, evicting oldest entries
    /// as needed.
    ///
    /// Returns [`InsertError::EntryTooLarge`] if the entry does not fit in
    /// the table capacity at all; on success the entry receives absolute
    /// index `inserted()`.
    #[inline]
    pub(crate) fn insert(&mut self, name: Bytes, value: Bytes) -> Result<(), InsertError> {
        let entry_size = Self::entry_size(&name, &value);
        if entry_size > self.capacity {
            return Err(InsertError::EntryTooLarge);
        }
        self.evict_to_fit(self.capacity - entry_size);
        self.entries.push_front((name, value));
        self.size += entry_size;
        self.inserted += 1;
        Ok(())
    }

    /// Returns the (name, value) pair with the given absolute index.
    #[cfg(test)]
    #[inline]
    pub(crate) fn get_absolute(&self, abs: u64) -> Option<(&[u8], &[u8])> {
        let last = self.last_absolute();
        if abs > last {
            return None;
        }
        self.entry_at(last - abs)
    }

    /// Returns the (name, value) pair referenced by an encoder-stream
    /// relative index: 0 is the most recently inserted entry.
    #[cfg(test)]
    #[inline]
    pub(crate) fn get_relative(&self, index: u64) -> Option<(&[u8], &[u8])> {
        self.entry_at(index)
    }

    /// Returns the (name, value) pair referenced by a field line
    /// representation relative index: index 0 is the entry with absolute
    /// index `base - 1`.
    #[cfg(test)]
    #[inline]
    pub(crate) fn get_base_relative(&self, base: u64, index: u64) -> Option<(&[u8], &[u8])> {
        if index >= base {
            return None;
        }
        let abs = base - 1 - index;
        self.get_absolute(abs)
    }

    /// Returns the (name, value) pair referenced by a post-base index:
    /// index 0 is the entry with absolute index `base`.
    #[cfg(test)]
    #[inline]
    pub(crate) fn get_post_base(&self, base: u64, index: u64) -> Option<(&[u8], &[u8])> {
        base.checked_add(index)
            .and_then(|abs| self.get_absolute(abs))
    }

    /// Returns the (name, value) pair at deque position `i` (0 = most
    /// recently inserted).
    #[inline]
    pub(crate) fn entry_at(&self, i: u64) -> Option<(&[u8], &[u8])> {
        let i = usize::try_from(i).ok()?;
        let (name, value) = self.entries.get(i)?;
        Some((name.as_ref(), value.as_ref()))
    }

    /// Clones the reference-counted bytes at a deque position. This is used
    /// by the decoder when materializing a field section: dynamic entries
    /// can be shared with the output instead of copied into new allocations.
    #[inline]
    pub(crate) fn entry_bytes_at(&self, i: u64) -> Option<(Bytes, Bytes)> {
        let i = usize::try_from(i).ok()?;
        let (name, value) = self.entries.get(i)?;
        Some((name.clone(), value.clone()))
    }

    /// Returns a dynamic entry by absolute index as cheap `Bytes` clones.
    #[inline]
    pub(crate) fn get_absolute_bytes(&self, abs: u64) -> Option<(Bytes, Bytes)> {
        let last = self.last_absolute();
        if abs > last {
            return None;
        }
        self.entry_bytes_at(last - abs)
    }

    /// Returns an encoder-stream relative entry as cheap `Bytes` clones.
    #[inline]
    pub(crate) fn get_relative_bytes(&self, index: u64) -> Option<(Bytes, Bytes)> {
        self.entry_bytes_at(index)
    }

    /// Returns a field-section base-relative entry as cheap `Bytes` clones.
    #[inline]
    pub(crate) fn get_base_relative_bytes(&self, base: u64, index: u64) -> Option<(Bytes, Bytes)> {
        if index >= base {
            return None;
        }
        self.get_absolute_bytes(base - 1 - index)
    }

    /// Returns a field-section post-base entry as cheap `Bytes` clones.
    #[inline]
    pub(crate) fn get_post_base_bytes(&self, base: u64, index: u64) -> Option<(Bytes, Bytes)> {
        base.checked_add(index)
            .and_then(|abs| self.get_absolute_bytes(abs))
    }

    /// Evicts entries from the dropping point until `size <= max_size`.
    #[inline]
    fn evict_to_fit(&mut self, max_size: u64) {
        while self.size > max_size {
            let (name, value) = match self.entries.pop_back() {
                Some(entry) => entry,
                None => break,
            };
            self.size -= Self::entry_size(&name, &value);
        }
    }
}

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

    #[inline]
    fn insert(table: &mut DynamicTable, name: &str, value: &str) -> Result<(), InsertError> {
        table.insert(
            Bytes::copy_from_slice(name.as_bytes()),
            Bytes::copy_from_slice(value.as_bytes()),
        )
    }

    #[test]
    fn entry_size_is_name_plus_value_plus_32() {
        assert_eq!(DynamicTable::entry_size(b"foo", b"bar"), 38);
        assert_eq!(DynamicTable::entry_size(b"", b""), 32);
    }

    #[test]
    fn insert_assigns_increasing_absolute_indices() {
        let mut table = DynamicTable::new(1000);
        assert_eq!(table.len(), 0);
        assert_eq!(table.inserted(), 0);
        assert_eq!(table.next_absolute(), 0);

        insert(&mut table, ":method", "GET").unwrap();
        assert_eq!(table.inserted(), 1);
        assert_eq!(table.last_absolute(), 0);

        insert(&mut table, ":path", "/").unwrap();
        assert_eq!(table.inserted(), 2);
        assert_eq!(table.last_absolute(), 1);
        assert_eq!(table.get_absolute(0), Some((&b":method"[..], &b"GET"[..])));
        assert_eq!(table.get_absolute(1), Some((&b":path"[..], &b"/"[..])));
        assert_eq!(table.get_absolute(2), None);
    }

    #[test]
    fn relative_index_zero_is_most_recent() {
        let mut table = DynamicTable::new(1000);
        insert(&mut table, "a", "1").unwrap();
        insert(&mut table, "b", "2").unwrap();
        insert(&mut table, "c", "3").unwrap();

        assert_eq!(table.get_relative(0), Some((&b"c"[..], &b"3"[..])));
        assert_eq!(table.get_relative(1), Some((&b"b"[..], &b"2"[..])));
        assert_eq!(table.get_relative(2), Some((&b"a"[..], &b"1"[..])));
        assert_eq!(table.get_relative(3), None);
    }

    #[test]
    fn insert_evicts_oldest_first() {
        // capacity 100: entry size 1+1+32 = 34; three entries = 102 > 100,
        // so inserting the third evicts the first.
        let mut table = DynamicTable::new(100);
        insert(&mut table, "a", "a").unwrap();
        insert(&mut table, "b", "b").unwrap();
        assert_eq!(table.size(), 68);
        assert_eq!(table.len(), 2);

        insert(&mut table, "c", "c").unwrap();
        assert_eq!(table.size(), 68);
        assert_eq!(table.len(), 2);
        assert_eq!(table.get_absolute(0), None, "oldest entry evicted");
        assert_eq!(table.get_absolute(1), Some((&b"b"[..], &b"b"[..])));
        assert_eq!(table.get_absolute(2), Some((&b"c"[..], &b"c"[..])));
        // Absolute indices of evicted entries are never reused.
        assert_eq!(table.inserted(), 3);
    }

    #[test]
    fn insert_rejects_oversized_entry() {
        let mut table = DynamicTable::new(10);
        assert_eq!(
            insert(&mut table, "a", "a"),
            Err(InsertError::EntryTooLarge)
        );
        assert_eq!(table.len(), 0);
        assert_eq!(table.inserted(), 0);
    }

    #[test]
    fn set_capacity_evicts_and_can_clear() {
        let mut table = DynamicTable::new(1000);
        for i in 0..5 {
            insert(&mut table, &format!("h{i}"), "v").unwrap();
        }
        assert_eq!(table.len(), 5);

        // Shrink below the size of the two newest entries.
        table.set_capacity(80);
        assert!(table.size() <= 80);
        assert_eq!(table.len(), 2);

        // Setting 0 clears the table; a later increase works with an empty
        // table.
        table.set_capacity(0);
        assert_eq!(table.len(), 0);
        assert_eq!(table.size(), 0);
        table.set_capacity(1000);
        insert(&mut table, "fresh", "entry").unwrap();
        assert_eq!(table.len(), 1);
        assert_eq!(table.get_absolute(5), Some((&b"fresh"[..], &b"entry"[..])));
    }

    #[test]
    fn field_section_relative_and_post_base_indexing() {
        // Recreates the RFC 9204 Figure 3/4 scenario: 10 insertions, 3
        // evictions (alive absolute indices 3..=9), Base = 8.
        let mut table = DynamicTable::new(1000);
        for i in 0..10u8 {
            let bytes = Bytes::copy_from_slice(&[b'a' + i]);
            table.insert(bytes.clone(), bytes).unwrap();
        }
        // Evict the three oldest (absolute 0..=2) by shrinking capacity and
        // restoring it: 7 entries x 34 bytes each.
        table.set_capacity(7 * 34);
        table.set_capacity(1000);
        assert_eq!(table.len(), 7);
        assert_eq!(table.last_absolute(), 9);

        let base = 8;
        // Relative: index 0 -> absolute 7, increasing indices go older.
        assert_eq!(table.get_base_relative(base, 0), table.get_absolute(7));
        assert_eq!(table.get_base_relative(base, 3), table.get_absolute(4));
        assert_eq!(table.get_base_relative(base, 5), table.get_absolute(2));
        assert_eq!(table.get_base_relative(base, 5), None, "evicted entry");
        assert_eq!(table.get_base_relative(base, 8), None, "index >= base");

        // Post-base: index 0 -> absolute 8, increasing indices go newer.
        assert_eq!(table.get_post_base(base, 0), table.get_absolute(8));
        assert_eq!(table.get_post_base(base, 1), table.get_absolute(9));
        assert_eq!(table.get_post_base(base, 2), None, "beyond newest entry");
    }

    #[test]
    fn duplicate_entries_are_allowed() {
        let mut table = DynamicTable::new(1000);
        insert(&mut table, "cookie", "a=b").unwrap();
        insert(&mut table, "cookie", "a=b").unwrap();
        assert_eq!(table.len(), 2);
        assert_eq!(table.get_absolute(0), Some((&b"cookie"[..], &b"a=b"[..])));
        assert_eq!(table.get_absolute(1), Some((&b"cookie"[..], &b"a=b"[..])));
    }

    #[test]
    fn empty_table_lookups_return_none() {
        let table = DynamicTable::new(1000);
        assert_eq!(table.get_absolute(0), None);
        assert_eq!(table.get_relative(0), None);
        assert_eq!(table.get_base_relative(0, 0), None);
        assert_eq!(table.get_post_base(0, 0), None);
    }
}