Debian Codegraph @

third_party/rust/neqo-qpack/src/encoder.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 #![allow(
8 clippy::module_name_repetitions,
9 reason = "<https://github.com/mozilla/neqo/issues/2284#issuecomment-2782711813>"
10 )]
11
12 use std::{
13 cmp::min,
14 collections::{HashMap, HashSet, VecDeque},
15 fmt::{self, Display, Formatter},
16 };
17
18 use neqo_common::{qdebug, qerror, qlog::NeqoQlog, qtrace, Header};
19 use neqo_transport::{Connection, Error as TransportError, StreamId};
20
21 use crate::{
22 decoder_instructions::{DecoderInstruction, DecoderInstructionReader},
23 encoder_instructions::EncoderInstruction,
24 header_block::HeaderEncoder,
25 qlog,
26 qpack_send_buf::QpackData,
27 reader::ReceiverConnWrapper,
28 stats::Stats,
29 table::{HeaderTable, LookupResult, ADDITIONAL_TABLE_ENTRY_SIZE},
30 Error, QpackSettings, Res,
31 };
32
33 pub const QPACK_UNI_STREAM_TYPE_ENCODER: u64 = 0x2;
34
35 #[derive(Debug, PartialEq)]
36 enum LocalStreamState {
37 NoStream,
38 Uninitialized(StreamId),
39 Initialized(StreamId),
40 }
41
42 impl LocalStreamState {
43 pub const fn stream_id(&self) -> Option<StreamId> {
44 match self {
45 Self::NoStream => None,
46 Self::Uninitialized(stream_id) | Self::Initialized(stream_id) => Some(*stream_id),
47 }
48 }
49 }
50
51 #[derive(Debug)]
52 pub struct QPackEncoder {
53 table: HeaderTable,
54 max_table_size: u64,
55 max_entries: u64,
56 instruction_reader: DecoderInstructionReader,
57 local_stream: LocalStreamState,
58 max_blocked_streams: u16,
59 // Remember header blocks that are referring to dynamic table.
60 // There can be multiple header blocks in one stream, headers, trailer, push stream request,
61 // etc. This HashMap maps a stream ID to a list of header blocks. Each header block is a
62 // list of referenced dynamic table entries.
63 unacked_header_blocks: HashMap<StreamId, VecDeque<HashSet<u64>>>,
64 blocked_stream_cnt: u16,
65 use_huffman: bool,
66 next_capacity: Option<u64>,
67 stats: Stats,
68 }
69
70 impl QPackEncoder {
71 #[must_use]
72 pub fn new(qpack_settings: &QpackSettings, use_huffman: bool) -> Self {
73 Self {
74 table: HeaderTable::new(true),
75 max_table_size: qpack_settings.max_table_size_encoder,
76 max_entries: 0,
77 instruction_reader: DecoderInstructionReader::new(),
78 local_stream: LocalStreamState::NoStream,
79 max_blocked_streams: 0,
80 unacked_header_blocks: HashMap::new(),
81 blocked_stream_cnt: 0,
82 use_huffman,
83 next_capacity: None,
84 stats: Stats::default(),
85 }
86 }
87
88 /// This function is use for setting encoders table max capacity. The value is received as
89 /// a `SETTINGS_QPACK_MAX_TABLE_CAPACITY` setting parameter.
90 ///
91 /// # Errors
92 ///
93 /// `EncoderStream` if value is too big.
94 /// `ChangeCapacity` if table capacity cannot be reduced.
95 pub fn set_max_capacity(&mut self, cap: u64) -> Res<()> {
96 if cap > (1 << 30) - 1 {
97 return Err(Error::EncoderStream);
98 }
99
100 if cap == self.table.capacity() {
101 return Ok(());
102 }
103
104 qdebug!(
105 "[{self}] Set max capacity to new capacity:{cap} old:{} max_table_size={}",
106 self.table.capacity(),
107 self.max_table_size,
108 );
109
110 let new_cap = min(self.max_table_size, cap);
111 // we also set our table to the max allowed.
112 self.change_capacity(new_cap);
113 Ok(())
114 }
115
116 /// This function is use for setting encoders max blocked streams. The value is received as
117 /// a `SETTINGS_QPACK_BLOCKED_STREAMS` setting parameter.
118 ///
119 /// # Errors
120 ///
121 /// `EncoderStream` if value is too big.
122 pub fn set_max_blocked_streams(&mut self, blocked_streams: u64) -> Res<()> {
123 self.max_blocked_streams = u16::try_from(blocked_streams).or(Err(Error::EncoderStream))?;
124 Ok(())
125 }
126
127 /// Reads decoder instructions.
128 ///
129 /// # Errors
130 ///
131 /// May return: `ClosedCriticalStream` if stream has been closed or `DecoderStream`
132 /// in case of any other transport error.
133 pub fn receive(&mut self, conn: &mut Connection, stream_id: StreamId) -> Res<()> {
134 self.read_instructions(conn, stream_id)
135 .map_err(|e| map_error(&e))
136 }
137
138 fn read_instructions(&mut self, conn: &mut Connection, stream_id: StreamId) -> Res<()> {
139 qdebug!("[{self}] read a new instruction");
140 loop {
141 let mut recv = ReceiverConnWrapper::new(conn, stream_id);
142 match self.instruction_reader.read_instructions(&mut recv) {
143 Ok(instruction) => self.call_instruction(instruction, conn.qlog_mut())?,
144 Err(Error::NeedMoreData) => break Ok(()),
145 Err(e) => break Err(e),
146 }
147 }
148 }
149
150 fn recalculate_blocked_streams(&mut self) {
151 let acked_inserts_cnt = self.table.get_acked_inserts_cnt();
152 self.blocked_stream_cnt = 0;
153 #[expect(
154 clippy::iter_over_hash_type,
155 reason = "OK to loop over unACKed blocks in an undefined order."
156 )]
157 for hb_list in self.unacked_header_blocks.values_mut() {
158 debug_assert!(!hb_list.is_empty());
159 if hb_list.iter().flatten().any(|e| *e >= acked_inserts_cnt) {
160 self.blocked_stream_cnt += 1;
161 }
162 }
163 }
164
165 fn insert_count_instruction(&mut self, increment: u64) -> Res<()> {
166 self.table
167 .increment_acked(increment)
168 .map_err(|_| Error::DecoderStream)?;
169 self.recalculate_blocked_streams();
170 Ok(())
171 }
172
173 fn header_ack(&mut self, stream_id: StreamId) {
174 self.stats.header_acks_recv += 1;
175 let mut new_acked = self.table.get_acked_inserts_cnt();
176 if let Some(hb_list) = self.unacked_header_blocks.get_mut(&stream_id) {
177 if let Some(ref_list) = hb_list.pop_back() {
178 #[expect(
179 clippy::iter_over_hash_type,
180 reason = "OK to loop over unACKed blocks in an undefined order."
181 )]
182 for iter in ref_list {
183 self.table.remove_ref(iter);
184 if iter >= new_acked {
185 new_acked = iter + 1;
186 }
187 }
188 } else {
189 debug_assert!(false, "We should have at least one header block");
190 }
191 if hb_list.is_empty() {
192 self.unacked_header_blocks.remove(&stream_id);
193 }
194 }
195 if new_acked > self.table.get_acked_inserts_cnt() {
196 self.insert_count_instruction(new_acked - self.table.get_acked_inserts_cnt())
197 .expect("This should neve happen");
198 }
199 }
200
201 fn stream_cancellation(&mut self, stream_id: StreamId) {
202 self.stats.stream_cancelled_recv += 1;
203 let mut was_blocker = false;
204 if let Some(mut hb_list) = self.unacked_header_blocks.remove(&stream_id) {
205 debug_assert!(!hb_list.is_empty());
206 while let Some(ref_list) = hb_list.pop_front() {
207 #[expect(
208 clippy::iter_over_hash_type,
209 reason = "OK to loop over unACKed blocks in an undefined order."
210 )]
211 for iter in ref_list {
212 self.table.remove_ref(iter);
213 was_blocker = was_blocker || (iter >= self.table.get_acked_inserts_cnt());
214 }
215 }
216 }
217 if was_blocker {
218 debug_assert!(self.blocked_stream_cnt > 0);
219 self.blocked_stream_cnt -= 1;
220 }
221 }
222
223 fn call_instruction(&mut self, instruction: DecoderInstruction, qlog: &NeqoQlog) -> Res<()> {
224 qdebug!("[{self}] call instruction {instruction:?}");
225 match instruction {
226 DecoderInstruction::InsertCountIncrement { increment } => {
227 qlog::qpack_read_insert_count_increment_instruction(
228 qlog,
229 increment,
230 &increment.to_be_bytes(),
231 );
232
233 self.insert_count_instruction(increment)
234 }
235 DecoderInstruction::HeaderAck { stream_id } => {
236 self.header_ack(stream_id);
237 Ok(())
238 }
239 DecoderInstruction::StreamCancellation { stream_id } => {
240 self.stream_cancellation(stream_id);
241 Ok(())
242 }
243 DecoderInstruction::NoInstruction => Ok(()),
244 }
245 }
246
247 /// Inserts a new entry into a table and sends the corresponding instruction to a peer. An entry
248 /// is added only if it is possible to send the corresponding instruction immediately, i.e.
249 /// the encoder stream is not blocked by the flow control (or stream internal buffer(this is
250 /// very unlikely)).
251 ///
252 /// # Errors
253 ///
254 /// `EncoderStreamBlocked` if the encoder stream is blocked by the flow control.
255 /// `DynamicTableFull` if the dynamic table does not have enough space for the entry.
256 /// The function can return transport errors: `InvalidStreamId`, `InvalidInput` and
257 /// `FinalSizeError`.
258 ///
259 /// # Panics
260 ///
261 /// When the insertion fails (it should not).
262 pub fn send_and_insert(
263 &mut self,
264 conn: &mut Connection,
265 name: &[u8],
266 value: &[u8],
267 ) -> Res<u64> {
268 qdebug!("[{self}] insert {name:?} {value:?}");
269
270 let entry_size = name.len() + value.len() + ADDITIONAL_TABLE_ENTRY_SIZE;
271
272 if !self.table.insert_possible(entry_size) {
273 return Err(Error::DynamicTableFull);
274 }
275
276 let mut buf = QpackData::default();
277 EncoderInstruction::InsertWithNameLiteral { name, value }
278 .marshal(&mut buf, self.use_huffman);
279
280 let stream_id = self.local_stream.stream_id().ok_or(Error::Internal)?;
281
282 let sent = conn
283 .stream_send_atomic(stream_id, &buf)
284 .map_err(|e| map_stream_send_atomic_error(&e))?;
285 if !sent {
286 return Err(Error::EncoderStreamBlocked);
287 }
288
289 self.stats.dynamic_table_inserts += 1;
290
291 match self.table.insert(name, value) {
292 Ok(inx) => Ok(inx),
293 Err(e) => {
294 debug_assert!(false);
295 Err(e)
296 }
297 }
298 }
299
300 fn change_capacity(&mut self, value: u64) {
301 qdebug!("[{self}] change capacity: {value}");
302 self.next_capacity = Some(value);
303 }
304
305 fn maybe_send_change_capacity(
306 &mut self,
307 conn: &mut Connection,
308 stream_id: StreamId,
309 ) -> Res<()> {
310 if let Some(cap) = self.next_capacity {
311 // Check if it is possible to reduce the capacity, e.g. if enough space can be made free
312 // for the reduction.
313 if cap < self.table.capacity() && !self.table.can_evict_to(cap) {
314 return Err(Error::DynamicTableFull);
315 }
316 let mut buf = QpackData::default();
317 EncoderInstruction::Capacity { value: cap }.marshal(&mut buf, self.use_huffman);
318 if !conn.stream_send_atomic(stream_id, &buf)? {
319 return Err(Error::EncoderStreamBlocked);
320 }
321 if self.table.set_capacity(cap).is_err() {
322 debug_assert!(
323 false,
324 "can_evict_to should have checked and make sure this operation is possible"
325 );
326 return Err(Error::InternalError);
327 }
328 self.max_entries = cap / 32;
329 self.next_capacity = None;
330 }
331 Ok(())
332 }
333
334 /// Sends any qpack encoder instructions.
335 ///
336 /// # Errors
337 ///
338 /// returns `EncoderStream` in case of an error.
339 pub fn send_encoder_updates(&mut self, conn: &mut Connection) -> Res<()> {
340 match self.local_stream {
341 LocalStreamState::NoStream => {
342 qerror!("Send call but there is no stream yet");
343 Ok(())
344 }
345 LocalStreamState::Uninitialized(stream_id) => {
346 let mut buf = QpackData::default();
347 buf.encode_varint(QPACK_UNI_STREAM_TYPE_ENCODER);
348 if !conn.stream_send_atomic(stream_id, &buf[..])? {
349 return Err(Error::EncoderStreamBlocked);
350 }
351 self.local_stream = LocalStreamState::Initialized(stream_id);
352 self.maybe_send_change_capacity(conn, stream_id)
353 }
354 LocalStreamState::Initialized(stream_id) => {
355 self.maybe_send_change_capacity(conn, stream_id)
356 }
357 }
358 }
359
360 fn is_stream_blocker(&self, stream_id: StreamId) -> bool {
361 self.unacked_header_blocks
362 .get(&stream_id)
363 .is_some_and(|hb_list| {
364 debug_assert!(!hb_list.is_empty());
365 hb_list
366 .iter()
367 .flatten()
368 .max()
369 .is_some_and(|max_ref| *max_ref >= self.table.get_acked_inserts_cnt())
370 })
371 }
372
373 /// Encodes headers
374 ///
375 /// # Errors
376 ///
377 /// `ClosedCriticalStream` if the encoder stream is closed.
378 /// `InternalError` if an unexpected error occurred.
379 ///
380 /// # Panics
381 ///
382 /// If there is a programming error.
383 pub fn encode_header_block(
384 &mut self,
385 conn: &mut Connection,
386 h: &[Header],
387 stream_id: StreamId,
388 ) -> HeaderEncoder {
389 qdebug!("[{self}] encoding headers");
390
391 // Try to send capacity instructions if present.
392 // This code doesn't try to deal with errors, it just tries
393 // to write to the encoder stream AND if it can't uses
394 // literal instructions.
395 // The errors can be:
396 // 1) `EncoderStreamBlocked` - this is an error that can occur.
397 // 2) `InternalError` - this is unexpected error.
398 // 3) `ClosedCriticalStream` - this is error that should close the HTTP/3 session.
399 // The last 2 errors are ignored here and will be picked up
400 // by the main loop.
401 let mut encoder_blocked = self.send_encoder_updates(conn).is_err();
402
403 let mut encoded_h =
404 HeaderEncoder::new(self.table.base(), self.use_huffman, self.max_entries);
405
406 let stream_is_blocker = self.is_stream_blocker(stream_id);
407 let can_block = self.blocked_stream_cnt < self.max_blocked_streams || stream_is_blocker;
408
409 let mut ref_entries = HashSet::new();
410
411 for iter in h {
412 let name = iter.name().as_bytes().to_vec();
413 let value = iter.value().as_bytes().to_vec();
414 qtrace!("encoding {name:x?} {value:x?}");
415
416 if let Some(LookupResult {
417 index,
418 static_table,
419 value_matches,
420 }) = self.table.lookup(&name, &value, can_block)
421 {
422 qtrace!(
423 "[{self}] found a {} entry, value-match={value_matches}",
424 if static_table { "static" } else { "dynamic" }
425 );
426 if value_matches {
427 if static_table {
428 encoded_h.encode_indexed_static(index);
429 } else {
430 encoded_h.encode_indexed_dynamic(index);
431 }
432 } else {
433 encoded_h.encode_literal_with_name_ref(static_table, index, &value);
434 }
435 if !static_table && ref_entries.insert(index) {
436 self.table.add_ref(index);
437 }
438 } else if can_block && !encoder_blocked {
439 // Insert using an InsertWithNameLiteral instruction. This entry name does not match
440 // any name in the tables therefore we cannot use any other
441 // instruction.
442 if let Ok(index) = self.send_and_insert(conn, &name, &value) {
443 encoded_h.encode_indexed_dynamic(index);
444 ref_entries.insert(index);
445 self.table.add_ref(index);
446 } else {
447 // This code doesn't try to deal with errors, it just tries
448 // to write to the encoder stream AND if it can't uses
449 // literal instructions.
450 // The errors can be:
451 // 1) `EncoderStreamBlocked` - this is an error that can occur.
452 // 2) `DynamicTableFull` - this is an error that can occur.
453 // 3) `InternalError` - this is unexpected error.
454 // 4) `ClosedCriticalStream` - this is error that should close the HTTP/3
455 // session.
456 // The last 2 errors are ignored here and will be picked up
457 // by the main loop.
458 // As soon as one of the instructions cannot be written or the table is full, do
459 // not try again.
460 encoder_blocked = true;
461 encoded_h.encode_literal_with_name_literal(&name, &value);
462 }
463 } else {
464 encoded_h.encode_literal_with_name_literal(&name, &value);
465 }
466 }
467
468 encoded_h.encode_header_block_prefix();
469
470 if !stream_is_blocker {
471 // The streams was not a blocker, check if the stream is a blocker now.
472 if let Some(max_ref) = ref_entries.iter().max() {
473 if *max_ref >= self.table.get_acked_inserts_cnt() {
474 debug_assert!(self.blocked_stream_cnt <= self.max_blocked_streams);
475 self.blocked_stream_cnt += 1;
476 }
477 }
478 }
479
480 if !ref_entries.is_empty() {
481 self.unacked_header_blocks
482 .entry(stream_id)
483 .or_default()
484 .push_front(ref_entries);
485 self.stats.dynamic_table_references += 1;
486 }
487 encoded_h
488 }
489
490 /// Encoder stream has been created. Add the stream id.
491 ///
492 /// # Panics
493 ///
494 /// If a stream has already been added.
495 pub fn add_send_stream(&mut self, stream_id: StreamId) {
496 if self.local_stream == LocalStreamState::NoStream {
497 self.local_stream = LocalStreamState::Uninitialized(stream_id);
498 } else {
499 panic!("Adding multiple local streams");
500 }
501 }
502
503 #[must_use]
504 pub fn stats(&self) -> Stats {
505 self.stats.clone()
506 }
507
508 #[must_use]
509 pub const fn local_stream_id(&self) -> Option<StreamId> {
510 self.local_stream.stream_id()
511 }
512
513 #[cfg(test)]
514 const fn blocked_stream_cnt(&self) -> u16 {
515 self.blocked_stream_cnt
516 }
517 }
518
519 impl Display for QPackEncoder {
520 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
521 write!(f, "QPackEncoder")
522 }
523 }
524
525 fn map_error(err: &Error) -> Error {
526 if *err == Error::ClosedCriticalStream {
527 Error::ClosedCriticalStream
528 } else {
529 Error::DecoderStream
530 }
531 }
532
533 fn map_stream_send_atomic_error(err: &TransportError) -> Error {
534 match err {
535 TransportError::InvalidStreamId | TransportError::FinalSizeError => {
536 Error::ClosedCriticalStream
537 }
538 _ => {
539 debug_assert!(false, "Unexpected error");
540 Error::InternalError
541 }
542 }
543 }
544
545 #[cfg(test)]
546 mod tests {
547 use neqo_transport::{ConnectionParameters, StreamId, StreamType};
548 use test_fixture::{default_client, default_server, handshake, new_server, now, DEFAULT_ALPN};
549
550 use super::{Connection, Error, Header, QPackEncoder, Res};
551 use crate::QpackSettings;
552
553 struct TestEncoder {
554 encoder: QPackEncoder,
555 send_stream_id: StreamId,
556 recv_stream_id: StreamId,
557 conn: Connection,
558 peer_conn: Connection,
559 }
560
561 impl TestEncoder {
562 pub fn change_capacity(&mut self, capacity: u64) -> Res<()> {
563 self.encoder.set_max_capacity(capacity)?;
564 // We will try to really change the table only when we send the change capacity
565 // instruction.
566 self.encoder.send_encoder_updates(&mut self.conn)
567 }
568
569 pub fn insert(&mut self, header: &[u8], value: &[u8], inst: &[u8]) {
570 let res = self.encoder.send_and_insert(&mut self.conn, header, value);
571 assert!(res.is_ok());
572 self.send_instructions(inst);
573 }
574
575 pub fn encode_header_block(
576 &mut self,
577 stream_id: StreamId,
578 headers: &[Header],
579 expected_encoding: &[u8],
580 inst: &[u8],
581 ) {
582 let buf = self
583 .encoder
584 .encode_header_block(&mut self.conn, headers, stream_id);
585 assert_eq!(&buf[..], expected_encoding);
586 self.send_instructions(inst);
587 }
588
589 pub fn send_instructions(&mut self, encoder_instruction: &[u8]) {
590 self.encoder.send_encoder_updates(&mut self.conn).unwrap();
591 let out = self.conn.process_output(now());
592 let out2 = self.peer_conn.process(out.dgram(), now());
593 drop(self.conn.process(out2.dgram(), now()));
594 let mut buf = [0_u8; 100];
595 let (amount, fin) = self
596 .peer_conn
597 .stream_recv(self.send_stream_id, &mut buf)
598 .unwrap();
599 assert!(!fin);
600 assert_eq!(buf[..amount], encoder_instruction[..]);
601 }
602 }
603
604 fn connect_generic(huffman: bool, max_data: Option<u64>) -> TestEncoder {
605 let mut conn = default_client();
606 let mut peer_conn = max_data.map_or_else(default_server, |max| {
607 new_server(
608 DEFAULT_ALPN,
609 ConnectionParameters::default()
610 .max_stream_data(StreamType::UniDi, true, max)
611 .max_stream_data(StreamType::BiDi, true, max)
612 .max_stream_data(StreamType::BiDi, false, max),
613 )
614 });
615 handshake(&mut conn, &mut peer_conn);
616
617 // create a stream
618 let recv_stream_id = peer_conn.stream_create(StreamType::UniDi).unwrap();
619 let send_stream_id = conn.stream_create(StreamType::UniDi).unwrap();
620
621 // create an encoder
622 let mut encoder = QPackEncoder::new(
623 &QpackSettings {
624 max_table_size_encoder: 1500,
625 max_table_size_decoder: 0,
626 max_blocked_streams: 0,
627 },
628 huffman,
629 );
630 encoder.add_send_stream(send_stream_id);
631
632 TestEncoder {
633 encoder,
634 send_stream_id,
635 recv_stream_id,
636 conn,
637 peer_conn,
638 }
639 }
640
641 fn connect(huffman: bool) -> TestEncoder {
642 connect_generic(huffman, None)
643 }
644
645 fn connect_flow_control(max_data: u64) -> TestEncoder {
646 connect_generic(true, Some(max_data))
647 }
648
649 fn recv_instruction(encoder: &mut TestEncoder, decoder_instruction: &[u8]) {
650 encoder
651 .peer_conn
652 .stream_send(encoder.recv_stream_id, decoder_instruction)
653 .unwrap();
654 let out = encoder.peer_conn.process_output(now());
655 drop(encoder.conn.process(out.dgram(), now()));
656 assert!(encoder
657 .encoder
658 .read_instructions(&mut encoder.conn, encoder.recv_stream_id)
659 .is_ok());
660 }
661
662 const CAP_INSTRUCTION_200: &[u8] = &[0x02, 0x3f, 0xa9, 0x01];
663 const CAP_INSTRUCTION_60: &[u8] = &[0x02, 0x3f, 0x1d];
664 const CAP_INSTRUCTION_1000: &[u8] = &[0x02, 0x3f, 0xc9, 0x07];
665 const CAP_INSTRUCTION_1500: &[u8] = &[0x02, 0x3f, 0xbd, 0x0b];
666
667 const HEADER_CONTENT_LENGTH: &[u8] = &[
668 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68,
669 ];
670 const VALUE_1: &[u8] = &[0x31, 0x32, 0x33, 0x34];
671 const VALUE_2: &[u8] = &[0x31, 0x32, 0x33, 0x34, 0x35];
672
673 // HEADER_CONTENT_LENGTH and VALUE_1 encoded by instruction insert_with_name_literal.
674 const HEADER_CONTENT_LENGTH_VALUE_1_NAME_LITERAL: &[u8] = &[
675 0x4e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68,
676 0x04, 0x31, 0x32, 0x33, 0x34,
677 ];
678
679 // HEADER_CONTENT_LENGTH and VALUE_2 encoded by instruction insert_with_name_literal.
680 const HEADER_CONTENT_LENGTH_VALUE_2_NAME_LITERAL: &[u8] = &[
681 0x4e, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68,
682 0x05, 0x31, 0x32, 0x33, 0x34, 0x35,
683 ];
684
685 // Indexed Header Field that refers to the first entry in the dynamic table.
686 const ENCODE_INDEXED_REF_DYNAMIC: &[u8] = &[0x02, 0x00, 0x80];
687
688 const STREAM_1: StreamId = StreamId::new(1);
689 const STREAM_2: StreamId = StreamId::new(2);
690 const HEADER_ACK_STREAM_ID_1: &[u8] = &[0x81];
691 const HEADER_ACK_STREAM_ID_2: &[u8] = &[0x82];
692 const STREAM_CANCELED_ID_1: &[u8] = &[0x41];
693
694 // test insert_with_name_literal which fails because there is not enough space in the table
695 #[test]
696 fn insert_with_name_literal_1() {
697 let mut encoder = connect(false);
698
699 // insert "content-length: 1234
700 let res =
701 encoder
702 .encoder
703 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_1);
704 assert_eq!(Error::DynamicTableFull, res.unwrap_err());
705 encoder.send_instructions(&[0x02]);
706 }
707
708 // test insert_with_name_literal - succeeds
709 #[test]
710 fn insert_with_name_literal_2() {
711 let mut encoder = connect(false);
712
713 assert!(encoder.encoder.set_max_capacity(200).is_ok());
714 // test the change capacity instruction.
715 encoder.send_instructions(CAP_INSTRUCTION_200);
716
717 // insert "content-length: 1234
718 let res =
719 encoder
720 .encoder
721 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_1);
722 assert!(res.is_ok());
723 encoder.send_instructions(HEADER_CONTENT_LENGTH_VALUE_1_NAME_LITERAL);
724 }
725
726 #[test]
727 fn change_capacity() {
728 let mut encoder = connect(false);
729
730 assert!(encoder.encoder.set_max_capacity(200).is_ok());
731 encoder.send_instructions(CAP_INSTRUCTION_200);
732 }
733
734 struct TestElement {
735 pub headers: Vec<Header>,
736 pub header_block: &'static [u8],
737 pub encoder_inst: &'static [u8],
738 }
739
740 #[test]
741 fn header_block_encoder_non() {
742 let test_cases: [TestElement; 6] = [
743 // test a header with ref to static - encode_indexed
744 TestElement {
745 headers: vec![Header::new(":method", "GET")],
746 header_block: &[0x00, 0x00, 0xd1],
747 encoder_inst: &[],
748 },
749 // test encode_literal_with_name_ref
750 TestElement {
751 headers: vec![Header::new(":path", "/somewhere")],
752 header_block: &[
753 0x00, 0x00, 0x51, 0x0a, 0x2f, 0x73, 0x6f, 0x6d, 0x65, 0x77, 0x68, 0x65, 0x72,
754 0x65,
755 ],
756 encoder_inst: &[],
757 },
758 // test adding a new header and encode_post_base_index, also test
759 // fix_header_block_prefix
760 TestElement {
761 headers: vec![Header::new("my-header", "my-value")],
762 header_block: &[0x02, 0x80, 0x10],
763 encoder_inst: &[
764 0x49, 0x6d, 0x79, 0x2d, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x08, 0x6d, 0x79,
765 0x2d, 0x76, 0x61, 0x6c, 0x75, 0x65,
766 ],
767 },
768 // test encode_indexed with a ref to dynamic table.
769 TestElement {
770 headers: vec![Header::new("my-header", "my-value")],
771 header_block: ENCODE_INDEXED_REF_DYNAMIC,
772 encoder_inst: &[],
773 },
774 // test encode_literal_with_name_ref.
775 TestElement {
776 headers: vec![Header::new("my-header", "my-value2")],
777 header_block: &[
778 0x02, 0x00, 0x40, 0x09, 0x6d, 0x79, 0x2d, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x32,
779 ],
780 encoder_inst: &[],
781 },
782 // test multiple headers
783 TestElement {
784 headers: vec![
785 Header::new(":method", "GET"),
786 Header::new(":path", "/somewhere"),
787 Header::new(":authority", "example.com"),
788 Header::new(":scheme", "https"),
789 ],
790 header_block: &[
791 0x00, 0x01, 0xd1, 0x51, 0x0a, 0x2f, 0x73, 0x6f, 0x6d, 0x65, 0x77, 0x68, 0x65,
792 0x72, 0x65, 0x50, 0x0b, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63,
793 0x6f, 0x6d, 0xd7,
794 ],
795 encoder_inst: &[],
796 },
797 ];
798
799 let mut encoder = connect(false);
800
801 encoder.encoder.set_max_blocked_streams(100).unwrap();
802 encoder.encoder.set_max_capacity(200).unwrap();
803
804 // test the change capacity instruction.
805 encoder.send_instructions(CAP_INSTRUCTION_200);
806
807 for t in &test_cases {
808 let buf = encoder
809 .encoder
810 .encode_header_block(&mut encoder.conn, &t.headers, STREAM_1);
811 assert_eq!(&buf[..], t.header_block);
812 encoder.send_instructions(t.encoder_inst);
813 }
814 }
815
816 #[test]
817 fn header_block_encoder_huffman() {
818 let test_cases: [TestElement; 6] = [
819 // test a header with ref to static - encode_indexed
820 TestElement {
821 headers: vec![Header::new(":method", "GET")],
822 header_block: &[0x00, 0x00, 0xd1],
823 encoder_inst: &[],
824 },
825 // test encode_literal_with_name_ref
826 TestElement {
827 headers: vec![Header::new(":path", "/somewhere")],
828 header_block: &[
829 0x00, 0x00, 0x51, 0x87, 0x61, 0x07, 0xa4, 0xbe, 0x27, 0x2d, 0x85,
830 ],
831 encoder_inst: &[],
832 },
833 // test adding a new header and encode_post_base_index, also test
834 // fix_header_block_prefix
835 TestElement {
836 headers: vec![Header::new("my-header", "my-value")],
837 header_block: &[0x02, 0x80, 0x10],
838 encoder_inst: &[
839 0x67, 0xa7, 0xd2, 0xd3, 0x94, 0x72, 0x16, 0xcf, 0x86, 0xa7, 0xd2, 0xdd, 0xc7,
840 0x45, 0xa5,
841 ],
842 },
843 // test encode_indexed with a ref to dynamic table.
844 TestElement {
845 headers: vec![Header::new("my-header", "my-value")],
846 header_block: ENCODE_INDEXED_REF_DYNAMIC,
847 encoder_inst: &[],
848 },
849 // test encode_literal_with_name_ref.
850 TestElement {
851 headers: vec![Header::new("my-header", "my-value2")],
852 header_block: &[
853 0x02, 0x00, 0x40, 0x87, 0xa7, 0xd2, 0xdd, 0xc7, 0x45, 0xa5, 0x17,
854 ],
855 encoder_inst: &[],
856 },
857 // test multiple headers
858 TestElement {
859 headers: vec![
860 Header::new(":method", "GET"),
861 Header::new(":path", "/somewhere"),
862 Header::new(":authority", "example.com"),
863 Header::new(":scheme", "https"),
864 ],
865 header_block: &[
866 0x00, 0x01, 0xd1, 0x51, 0x87, 0x61, 0x07, 0xa4, 0xbe, 0x27, 0x2d, 0x85, 0x50,
867 0x88, 0x2f, 0x91, 0xd3, 0x5d, 0x05, 0x5c, 0x87, 0xa7, 0xd7,
868 ],
869 encoder_inst: &[],
870 },
871 ];
872
873 let mut encoder = connect(true);
874
875 encoder.encoder.set_max_blocked_streams(100).unwrap();
876 encoder.encoder.set_max_capacity(200).unwrap();
877
878 // test the change capacity instruction.
879 encoder.send_instructions(CAP_INSTRUCTION_200);
880
881 for t in &test_cases {
882 let buf = encoder
883 .encoder
884 .encode_header_block(&mut encoder.conn, &t.headers, STREAM_1);
885 assert_eq!(&buf[..], t.header_block);
886 encoder.send_instructions(t.encoder_inst);
887 }
888 }
889
890 // Test inserts block on waiting for an insert count increment.
891 #[test]
892 fn insertion_blocked_on_insert_count_feedback() {
893 let mut encoder = connect(false);
894
895 encoder.encoder.set_max_capacity(60).unwrap();
896
897 // test the change capacity instruction.
898 encoder.send_instructions(CAP_INSTRUCTION_60);
899
900 // insert "content-length: 1234
901 let res =
902 encoder
903 .encoder
904 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_1);
905 assert!(res.is_ok());
906 encoder.send_instructions(HEADER_CONTENT_LENGTH_VALUE_1_NAME_LITERAL);
907
908 // insert "content-length: 12345 which will fail because the entry in the table cannot be
909 // evicted.
910 let res =
911 encoder
912 .encoder
913 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_2);
914 assert!(res.is_err());
915 encoder.send_instructions(&[]);
916
917 // receive an insert count increment.
918 recv_instruction(&mut encoder, &[0x01]);
919
920 // insert "content-length: 12345 again it will succeed.
921 let res =
922 encoder
923 .encoder
924 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_2);
925 assert!(res.is_ok());
926 encoder.send_instructions(HEADER_CONTENT_LENGTH_VALUE_2_NAME_LITERAL);
927 }
928
929 // Test inserts block on waiting for ACKs
930 // test the table insertion is blocked:
931 // 0 - waiting for a header ack
932 // 2 - waiting for a stream cancel.
933 fn test_insertion_blocked_on_waiting_for_header_ack_or_stream_cancel(wait: u8) {
934 let mut encoder = connect(false);
935
936 assert!(encoder.encoder.set_max_capacity(60).is_ok());
937 // test the change capacity instruction.
938 encoder.send_instructions(CAP_INSTRUCTION_60);
939
940 // insert "content-length: 1234
941 let res =
942 encoder
943 .encoder
944 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_1);
945 assert!(res.is_ok());
946 encoder.send_instructions(HEADER_CONTENT_LENGTH_VALUE_1_NAME_LITERAL);
947
948 // receive an insert count increment.
949 recv_instruction(&mut encoder, &[0x01]);
950
951 // send a header block
952 let buf = encoder.encoder.encode_header_block(
953 &mut encoder.conn,
954 &[Header::new("content-length", "1234")],
955 STREAM_1,
956 );
957 assert_eq!(&buf[..], ENCODE_INDEXED_REF_DYNAMIC);
958 encoder.send_instructions(&[]);
959
960 // insert "content-length: 12345 which will fail because the entry in the table cannot be
961 // evicted
962 let res =
963 encoder
964 .encoder
965 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_2);
966 assert!(res.is_err());
967 encoder.send_instructions(&[]);
968
969 if wait == 0 {
970 // receive a header_ack.
971 recv_instruction(&mut encoder, HEADER_ACK_STREAM_ID_1);
972 } else {
973 // receive a stream canceled
974 recv_instruction(&mut encoder, STREAM_CANCELED_ID_1);
975 }
976
977 // insert "content-length: 12345 again it will succeed.
978 let res =
979 encoder
980 .encoder
981 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_2);
982 assert!(res.is_ok());
983 encoder.send_instructions(HEADER_CONTENT_LENGTH_VALUE_2_NAME_LITERAL);
984 }
985
986 #[test]
987 fn header_ack() {
988 test_insertion_blocked_on_waiting_for_header_ack_or_stream_cancel(0);
989 }
990
991 #[test]
992 fn stream_canceled() {
993 test_insertion_blocked_on_waiting_for_header_ack_or_stream_cancel(1);
994 }
995
996 fn assert_is_index_to_dynamic(buf: &[u8]) {
997 assert_eq!(buf[2] & 0xc0, 0x80);
998 }
999
1000 fn assert_is_index_to_dynamic_post(buf: &[u8]) {
1001 assert_eq!(buf[2] & 0xf0, 0x10);
1002 }
1003
1004 fn assert_is_index_to_static_name_only(buf: &[u8]) {
1005 assert_eq!(buf[2] & 0xf0, 0x50);
1006 }
1007
1008 fn assert_is_literal_value_literal_name(buf: &[u8]) {
1009 assert_eq!(buf[2] & 0xf0, 0x20);
1010 }
1011
1012 #[test]
1013 fn max_block_streams1() {
1014 let mut encoder = connect(false);
1015
1016 assert!(encoder.encoder.set_max_capacity(60).is_ok());
1017
1018 // change capacity to 60.
1019 encoder.send_instructions(CAP_INSTRUCTION_60);
1020
1021 // insert "content-length: 1234
1022 let res =
1023 encoder
1024 .encoder
1025 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_1);
1026
1027 assert!(res.is_ok());
1028 encoder.send_instructions(HEADER_CONTENT_LENGTH_VALUE_1_NAME_LITERAL);
1029
1030 encoder.encoder.set_max_blocked_streams(1).unwrap();
1031
1032 // send a header block, it refers to unacked entry.
1033 let buf = encoder.encoder.encode_header_block(
1034 &mut encoder.conn,
1035 &[Header::new("content-length", "1234")],
1036 STREAM_1,
1037 );
1038 assert_is_index_to_dynamic(&buf);
1039
1040 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1041
1042 encoder.send_instructions(&[]);
1043
1044 // The next one will not use the dynamic entry because it is exceeding the
1045 // max_blocked_streams limit.
1046 let buf = encoder.encoder.encode_header_block(
1047 &mut encoder.conn,
1048 &[Header::new("content-length", "1234")],
1049 StreamId::new(2),
1050 );
1051 assert_is_index_to_static_name_only(&buf);
1052
1053 encoder.send_instructions(&[]);
1054 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1055
1056 // another header block to already blocked stream can still use the entry.
1057 let buf = encoder.encoder.encode_header_block(
1058 &mut encoder.conn,
1059 &[Header::new("content-length", "1234")],
1060 STREAM_1,
1061 );
1062 assert_is_index_to_dynamic(&buf);
1063
1064 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1065 }
1066
1067 #[test]
1068 fn max_block_streams2() {
1069 let mut encoder = connect(false);
1070
1071 assert!(encoder.encoder.set_max_capacity(200).is_ok());
1072
1073 // change capacity to 200.
1074 encoder.send_instructions(CAP_INSTRUCTION_200);
1075
1076 // insert "content-length: 1234
1077 let res =
1078 encoder
1079 .encoder
1080 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_1);
1081
1082 assert!(res.is_ok());
1083 encoder.send_instructions(HEADER_CONTENT_LENGTH_VALUE_1_NAME_LITERAL);
1084
1085 // insert "content-length: 12345
1086 let res =
1087 encoder
1088 .encoder
1089 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_2);
1090
1091 assert!(res.is_ok());
1092 encoder.send_instructions(HEADER_CONTENT_LENGTH_VALUE_2_NAME_LITERAL);
1093
1094 encoder.encoder.set_max_blocked_streams(1).unwrap();
1095
1096 // send a header block, it refers to unacked entry.
1097 let buf = encoder.encoder.encode_header_block(
1098 &mut encoder.conn,
1099 &[Header::new("content-length", "1234")],
1100 STREAM_1,
1101 );
1102 assert_is_index_to_dynamic(&buf);
1103
1104 // encode another header block for the same stream that will refer to the second entry
1105 // in the dynamic table.
1106 // This should work because the stream is already a blocked stream
1107 // send a header block, it refers to unacked entry.
1108 let buf = encoder.encoder.encode_header_block(
1109 &mut encoder.conn,
1110 &[Header::new("content-length", "12345")],
1111 STREAM_1,
1112 );
1113 assert_is_index_to_dynamic(&buf);
1114 }
1115
1116 #[test]
1117 fn max_block_streams3() {
1118 let mut encoder = connect(false);
1119
1120 assert!(encoder.encoder.set_max_capacity(200).is_ok());
1121
1122 // change capacity to 200.
1123 encoder.send_instructions(CAP_INSTRUCTION_200);
1124
1125 encoder.encoder.set_max_blocked_streams(1).unwrap();
1126
1127 assert_eq!(encoder.encoder.blocked_stream_cnt(), 0);
1128
1129 // send a header block, that creates an new entry and refers to it.
1130 let buf = encoder.encoder.encode_header_block(
1131 &mut encoder.conn,
1132 &[Header::new("name1", "value1")],
1133 STREAM_1,
1134 );
1135 assert_is_index_to_dynamic_post(&buf);
1136
1137 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1138
1139 // The next one will not create a new entry because the encoder is on max_blocked_streams
1140 // limit.
1141 let buf = encoder.encoder.encode_header_block(
1142 &mut encoder.conn,
1143 &[Header::new("name2", "value2")],
1144 STREAM_2,
1145 );
1146 assert_is_literal_value_literal_name(&buf);
1147
1148 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1149
1150 // another header block to already blocked stream can still create a new entry.
1151 let buf = encoder.encoder.encode_header_block(
1152 &mut encoder.conn,
1153 &[Header::new("name2", "value2")],
1154 STREAM_1,
1155 );
1156 assert_is_index_to_dynamic_post(&buf);
1157
1158 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1159 }
1160
1161 #[test]
1162 fn max_block_streams4() {
1163 let mut encoder = connect(false);
1164
1165 assert!(encoder.encoder.set_max_capacity(200).is_ok());
1166
1167 // change capacity to 200.
1168 encoder.send_instructions(CAP_INSTRUCTION_200);
1169
1170 encoder.encoder.set_max_blocked_streams(1).unwrap();
1171
1172 assert_eq!(encoder.encoder.blocked_stream_cnt(), 0);
1173
1174 // send a header block, that creates an new entry and refers to it.
1175 let buf = encoder.encoder.encode_header_block(
1176 &mut encoder.conn,
1177 &[Header::new("name1", "value1")],
1178 STREAM_1,
1179 );
1180 assert_is_index_to_dynamic_post(&buf);
1181
1182 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1183
1184 // another header block to already blocked stream can still create a new entry.
1185 let buf = encoder.encoder.encode_header_block(
1186 &mut encoder.conn,
1187 &[Header::new("name2", "value2")],
1188 STREAM_1,
1189 );
1190 assert_is_index_to_dynamic_post(&buf);
1191
1192 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1193
1194 // receive a header_ack for the first header block.
1195 recv_instruction(&mut encoder, HEADER_ACK_STREAM_ID_1);
1196
1197 // The stream is still blocking because the second header block is not acked.
1198 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1199 }
1200
1201 #[test]
1202 fn max_block_streams5() {
1203 let mut encoder = connect(false);
1204
1205 assert!(encoder.encoder.set_max_capacity(200).is_ok());
1206
1207 // change capacity to 200.
1208 encoder.send_instructions(CAP_INSTRUCTION_200);
1209
1210 encoder.encoder.set_max_blocked_streams(1).unwrap();
1211
1212 assert_eq!(encoder.encoder.blocked_stream_cnt(), 0);
1213
1214 // send a header block, that creates an new entry and refers to it.
1215 let buf = encoder.encoder.encode_header_block(
1216 &mut encoder.conn,
1217 &[Header::new("name1", "value1")],
1218 STREAM_1,
1219 );
1220 assert_is_index_to_dynamic_post(&buf);
1221
1222 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1223
1224 // another header block to already blocked stream can still create a new entry.
1225 let buf = encoder.encoder.encode_header_block(
1226 &mut encoder.conn,
1227 &[Header::new("name1", "value1")],
1228 STREAM_1,
1229 );
1230 assert_is_index_to_dynamic(&buf);
1231
1232 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1233
1234 // receive a header_ack for the first header block.
1235 recv_instruction(&mut encoder, HEADER_ACK_STREAM_ID_1);
1236
1237 // The stream is not blocking anymore because header ack also ACKs the instruction.
1238 assert_eq!(encoder.encoder.blocked_stream_cnt(), 0);
1239 }
1240
1241 #[test]
1242 fn max_block_streams6() {
1243 let mut encoder = connect(false);
1244
1245 assert!(encoder.encoder.set_max_capacity(200).is_ok());
1246
1247 // change capacity to 200.
1248 encoder.send_instructions(CAP_INSTRUCTION_200);
1249
1250 encoder.encoder.set_max_blocked_streams(2).unwrap();
1251
1252 assert_eq!(encoder.encoder.blocked_stream_cnt(), 0);
1253
1254 // send a header block, that creates an new entry and refers to it.
1255 let buf = encoder.encoder.encode_header_block(
1256 &mut encoder.conn,
1257 &[Header::new("name1", "value1")],
1258 STREAM_1,
1259 );
1260 assert_is_index_to_dynamic_post(&buf);
1261
1262 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1263
1264 // header block for the next stream will create an new entry as well.
1265 let buf = encoder.encoder.encode_header_block(
1266 &mut encoder.conn,
1267 &[Header::new("name2", "value2")],
1268 STREAM_2,
1269 );
1270 assert_is_index_to_dynamic_post(&buf);
1271
1272 assert_eq!(encoder.encoder.blocked_stream_cnt(), 2);
1273
1274 // receive a header_ack for the second header block. This will ack the first as well
1275 recv_instruction(&mut encoder, HEADER_ACK_STREAM_ID_2);
1276
1277 // The stream is not blocking anymore because header ack also ACKs the instruction.
1278 assert_eq!(encoder.encoder.blocked_stream_cnt(), 0);
1279 }
1280
1281 #[test]
1282 fn max_block_streams7() {
1283 let mut encoder = connect(false);
1284
1285 assert!(encoder.encoder.set_max_capacity(200).is_ok());
1286
1287 // change capacity to 200.
1288 encoder.send_instructions(CAP_INSTRUCTION_200);
1289
1290 encoder.encoder.set_max_blocked_streams(2).unwrap();
1291
1292 assert_eq!(encoder.encoder.blocked_stream_cnt(), 0);
1293
1294 // send a header block, that creates an new entry and refers to it.
1295 let buf = encoder.encoder.encode_header_block(
1296 &mut encoder.conn,
1297 &[Header::new("name1", "value1")],
1298 STREAM_1,
1299 );
1300 assert_is_index_to_dynamic_post(&buf);
1301
1302 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1303
1304 // header block for the next stream will create an new entry as well.
1305 let buf = encoder.encoder.encode_header_block(
1306 &mut encoder.conn,
1307 &[Header::new("name1", "value1")],
1308 STREAM_2,
1309 );
1310 assert_is_index_to_dynamic(&buf);
1311
1312 assert_eq!(encoder.encoder.blocked_stream_cnt(), 2);
1313
1314 // receive a stream cancel for the first stream.
1315 // This will remove the first stream as blocking but it will not mark the instruction as
1316 // acked. and the second steam will still be blocking.
1317 recv_instruction(&mut encoder, STREAM_CANCELED_ID_1);
1318
1319 // The stream is not blocking anymore because header ack also ACKs the instruction.
1320 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1321 }
1322
1323 #[test]
1324 fn max_block_stream8() {
1325 let mut encoder = connect(false);
1326
1327 assert!(encoder.encoder.set_max_capacity(200).is_ok());
1328
1329 // change capacity to 200.
1330 encoder.send_instructions(CAP_INSTRUCTION_200);
1331
1332 encoder.encoder.set_max_blocked_streams(2).unwrap();
1333
1334 assert_eq!(encoder.encoder.blocked_stream_cnt(), 0);
1335
1336 // send a header block, that creates an new entry and refers to it.
1337 let buf = encoder.encoder.encode_header_block(
1338 &mut encoder.conn,
1339 &[Header::new("name1", "value1")],
1340 STREAM_1,
1341 );
1342 assert_is_index_to_dynamic_post(&buf);
1343
1344 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1345
1346 // header block for the next stream will refer to the same entry.
1347 let buf = encoder.encoder.encode_header_block(
1348 &mut encoder.conn,
1349 &[Header::new("name1", "value1")],
1350 STREAM_2,
1351 );
1352 assert_is_index_to_dynamic(&buf);
1353
1354 assert_eq!(encoder.encoder.blocked_stream_cnt(), 2);
1355
1356 // send another header block on stream 1.
1357 let buf = encoder.encoder.encode_header_block(
1358 &mut encoder.conn,
1359 &[Header::new("name2", "value2")],
1360 STREAM_1,
1361 );
1362 assert_is_index_to_dynamic_post(&buf);
1363
1364 assert_eq!(encoder.encoder.blocked_stream_cnt(), 2);
1365
1366 // stream 1 is block on entries 1 and 2; stream 2 is block only on 1.
1367 // receive an Insert Count Increment for the first entry.
1368 // After that only stream 1 will be blocking.
1369 recv_instruction(&mut encoder, &[0x01]);
1370
1371 assert_eq!(encoder.encoder.blocked_stream_cnt(), 1);
1372 }
1373
1374 #[test]
1375 fn dynamic_table_can_evict1() {
1376 let mut encoder = connect(false);
1377
1378 assert!(encoder.encoder.set_max_capacity(60).is_ok());
1379
1380 // change capacity to 60.
1381 encoder.send_instructions(CAP_INSTRUCTION_60);
1382
1383 encoder.encoder.set_max_blocked_streams(2).unwrap();
1384
1385 // insert "content-length: 1234
1386 let res =
1387 encoder
1388 .encoder
1389 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_1);
1390
1391 assert!(res.is_ok());
1392 encoder.send_instructions(HEADER_CONTENT_LENGTH_VALUE_1_NAME_LITERAL);
1393
1394 // send a header block, it refers to unacked entry.
1395 let buf = encoder.encoder.encode_header_block(
1396 &mut encoder.conn,
1397 &[Header::new("content-length", "1234")],
1398 STREAM_1,
1399 );
1400 assert_is_index_to_dynamic(&buf);
1401
1402 // trying to evict the entry will failed.
1403 assert!(encoder.change_capacity(10).is_err());
1404
1405 // receive an Insert Count Increment for the entry.
1406 recv_instruction(&mut encoder, &[0x01]);
1407
1408 // trying to evict the entry will failed. The stream is still referring to it.
1409 assert!(encoder.change_capacity(10).is_err());
1410
1411 // receive a header_ack for the header block.
1412 recv_instruction(&mut encoder, HEADER_ACK_STREAM_ID_1);
1413
1414 // now entry can be evicted.
1415 assert!(encoder.change_capacity(10).is_ok());
1416 }
1417
1418 #[test]
1419 fn dynamic_table_can_evict2() {
1420 let mut encoder = connect(false);
1421
1422 assert!(encoder.encoder.set_max_capacity(60).is_ok());
1423
1424 // change capacity to 60.
1425 encoder.send_instructions(CAP_INSTRUCTION_60);
1426
1427 encoder.encoder.set_max_blocked_streams(2).unwrap();
1428
1429 // insert "content-length: 1234
1430 let res =
1431 encoder
1432 .encoder
1433 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_1);
1434
1435 assert!(res.is_ok());
1436 encoder.send_instructions(HEADER_CONTENT_LENGTH_VALUE_1_NAME_LITERAL);
1437
1438 // send a header block, it refers to unacked entry.
1439 let buf = encoder.encoder.encode_header_block(
1440 &mut encoder.conn,
1441 &[Header::new("content-length", "1234")],
1442 STREAM_1,
1443 );
1444 assert_is_index_to_dynamic(&buf);
1445
1446 // trying to evict the entry will failed.
1447 assert!(encoder.change_capacity(10).is_err());
1448
1449 // receive an Insert Count Increment for the entry.
1450 recv_instruction(&mut encoder, &[0x01]);
1451
1452 // trying to evict the entry will failed. The stream is still referring to it.
1453 assert!(encoder.change_capacity(10).is_err());
1454
1455 // receive a stream cancelled.
1456 recv_instruction(&mut encoder, STREAM_CANCELED_ID_1);
1457
1458 // now entry can be evicted.
1459 assert!(encoder.change_capacity(10).is_ok());
1460 }
1461
1462 #[test]
1463 fn dynamic_table_can_evict3() {
1464 let mut encoder = connect(false);
1465
1466 assert!(encoder.encoder.set_max_capacity(60).is_ok());
1467
1468 // change capacity to 60.
1469 encoder.send_instructions(CAP_INSTRUCTION_60);
1470
1471 encoder.encoder.set_max_blocked_streams(2).unwrap();
1472
1473 // insert "content-length: 1234
1474 let res =
1475 encoder
1476 .encoder
1477 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_1);
1478
1479 assert!(res.is_ok());
1480 encoder.send_instructions(HEADER_CONTENT_LENGTH_VALUE_1_NAME_LITERAL);
1481
1482 // trying to evict the entry will failed, because the entry is not acked.
1483 assert!(encoder.change_capacity(10).is_err());
1484
1485 // receive an Insert Count Increment for the entry.
1486 recv_instruction(&mut encoder, &[0x01]);
1487
1488 // now entry can be evicted.
1489 assert!(encoder.change_capacity(10).is_ok());
1490 }
1491
1492 #[test]
1493 fn dynamic_table_can_evict4() {
1494 let mut encoder = connect(false);
1495
1496 assert!(encoder.encoder.set_max_capacity(60).is_ok());
1497
1498 // change capacity to 60.
1499 encoder.send_instructions(CAP_INSTRUCTION_60);
1500
1501 encoder.encoder.set_max_blocked_streams(2).unwrap();
1502
1503 // insert "content-length: 1234
1504 let res =
1505 encoder
1506 .encoder
1507 .send_and_insert(&mut encoder.conn, HEADER_CONTENT_LENGTH, VALUE_1);
1508
1509 assert!(res.is_ok());
1510 encoder.send_instructions(HEADER_CONTENT_LENGTH_VALUE_1_NAME_LITERAL);
1511
1512 // send a header block, it refers to unacked entry.
1513 let buf = encoder.encoder.encode_header_block(
1514 &mut encoder.conn,
1515 &[Header::new("content-length", "1234")],
1516 STREAM_1,
1517 );
1518 assert_is_index_to_dynamic(&buf);
1519
1520 // trying to evict the entry will failed. The stream is still referring to it and
1521 // entry is not acked.
1522 assert!(encoder.change_capacity(10).is_err());
1523
1524 // receive a header_ack for the header block. This will also ack the instruction.
1525 recv_instruction(&mut encoder, HEADER_ACK_STREAM_ID_1);
1526
1527 // now entry can be evicted.
1528 assert!(encoder.change_capacity(10).is_ok());
1529 }
1530
1531 #[test]
1532 fn encoder_flow_controlled_blocked() {
1533 const SMALL_MAX_DATA: u64 = 20;
1534 const ONE_INSTRUCTION_1: &[u8] = &[
1535 0x67, 0x41, 0xe9, 0x2a, 0x67, 0x35, 0x53, 0x7f, 0x83, 0x8, 0x99, 0x6b,
1536 ];
1537 const ONE_INSTRUCTION_2: &[u8] = &[
1538 0x67, 0x41, 0xe9, 0x2a, 0x67, 0x35, 0x53, 0x37, 0x83, 0x8, 0x99, 0x6b,
1539 ];
1540
1541 let mut encoder = connect_flow_control(SMALL_MAX_DATA);
1542
1543 // change capacity to 1000 and max_block streams to 20.
1544 encoder.encoder.set_max_blocked_streams(20).unwrap();
1545 assert!(encoder.encoder.set_max_capacity(1000).is_ok());
1546 encoder.send_instructions(CAP_INSTRUCTION_1000);
1547
1548 // Encode a header block with 2 headers. The first header will be added to the dynamic
1549 // table. The second will not be added to the dynamic table, because the
1550 // corresponding instruction cannot be written immediately due to the flow control
1551 // limit.
1552 let buf1 = encoder.encoder.encode_header_block(
1553 &mut encoder.conn,
1554 &[
1555 Header::new("something", "1234"),
1556 Header::new("something2", "12345678910"),
1557 ],
1558 STREAM_1,
1559 );
1560
1561 // Assert that the first header is encoded as an index to the dynamic table (a post form).
1562 assert_eq!(buf1[2], 0x10);
1563 // Assert that the second header is encoded as a literal with a name literal
1564 assert_eq!(buf1[3] & 0xf0, 0x20);
1565
1566 // Try to encode another header block. Here both headers will be encoded as a literal with a
1567 // name literal
1568 let buf2 = encoder.encoder.encode_header_block(
1569 &mut encoder.conn,
1570 &[
1571 Header::new("something3", "1234"),
1572 Header::new("something4", "12345678910"),
1573 ],
1574 STREAM_2,
1575 );
1576 assert_eq!(buf2[2] & 0xf0, 0x20);
1577
1578 // Ensure that we have sent only one instruction for (String::from("something", "1234"))
1579 encoder.send_instructions(ONE_INSTRUCTION_1);
1580
1581 // exchange a flow control update.
1582 let out = encoder.peer_conn.process_output(now());
1583 drop(encoder.conn.process(out.dgram(), now()));
1584
1585 // Try writing a new header block. Now, headers will be added to the dynamic table again,
1586 // because instructions can be sent.
1587 let buf3 = encoder.encoder.encode_header_block(
1588 &mut encoder.conn,
1589 &[
1590 Header::new("something5", "1234"),
1591 Header::new("something6", "12345678910"),
1592 ],
1593 StreamId::new(3),
1594 );
1595 // Assert that the first header is encoded as an index to the dynamic table (a post form).
1596 assert_eq!(buf3[2], 0x10);
1597 // Assert that the second header is encoded as a literal with a name literal
1598 assert_eq!(buf3[3] & 0xf0, 0x20);
1599
1600 // Asset that one instruction has been sent
1601 encoder.send_instructions(ONE_INSTRUCTION_2);
1602 }
1603
1604 #[test]
1605 fn encoder_max_capacity_limit() {
1606 let mut encoder = connect(false);
1607
1608 // change capacity to 2000.
1609 assert!(encoder.encoder.set_max_capacity(2000).is_ok());
1610 encoder.send_instructions(CAP_INSTRUCTION_1500);
1611 }
1612
1613 #[test]
1614 fn do_not_evict_entry_that_are_referred_only_by_the_same_header_blocked_encoding() {
1615 let mut encoder = connect(false);
1616
1617 encoder.encoder.set_max_blocked_streams(20).unwrap();
1618 assert!(encoder.change_capacity(50).is_ok());
1619
1620 encoder
1621 .encoder
1622 .send_and_insert(&mut encoder.conn, b"something5", b"1234")
1623 .unwrap();
1624
1625 encoder
1626 .encoder
1627 .send_encoder_updates(&mut encoder.conn)
1628 .unwrap();
1629 let out = encoder.conn.process_output(now());
1630 drop(encoder.peer_conn.process(out.dgram(), now()));
1631 // receive an insert count increment.
1632 recv_instruction(&mut encoder, &[0x01]);
1633
1634 // The first header will use the table entry and the second will use the literal
1635 // encoding because the first entry is referred to and cannot be evicted.
1636 assert_eq!(
1637 encoder
1638 .encoder
1639 .encode_header_block(
1640 &mut encoder.conn,
1641 &[
1642 Header::new("something5", "1234"),
1643 Header::new("something6", "1234"),
1644 ],
1645 StreamId::new(3),
1646 )
1647 .to_vec(),
1648 &[
1649 0x02, 0x00, 0x80, 0x27, 0x03, 0x73, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x69, 0x6e, 0x67,
1650 0x36, 0x04, 0x31, 0x32, 0x33, 0x34
1651 ]
1652 );
1653 // Also check that there is no new instruction send by the encoder.
1654 assert!(encoder.conn.process_output(now()).dgram().is_none());
1655 }
1656
1657 #[test]
1658 fn streams_cancel_cleans_up_unacked_header_blocks() {
1659 let mut encoder = connect(false);
1660
1661 encoder.encoder.set_max_blocked_streams(10).unwrap();
1662 assert!(encoder.change_capacity(60).is_ok());
1663 encoder.send_instructions(CAP_INSTRUCTION_60);
1664
1665 // insert "content-length: 1234
1666 encoder.insert(
1667 HEADER_CONTENT_LENGTH,
1668 VALUE_1,
1669 HEADER_CONTENT_LENGTH_VALUE_1_NAME_LITERAL,
1670 );
1671
1672 // send a header block
1673 encoder.encode_header_block(
1674 StreamId::new(1),
1675 &[Header::new("content-length", "1234")],
1676 ENCODE_INDEXED_REF_DYNAMIC,
1677 &[],
1678 );
1679
1680 // receive a stream canceled instruction.
1681 recv_instruction(&mut encoder, STREAM_CANCELED_ID_1);
1682
1683 recv_instruction(&mut encoder, &[0x01]);
1684 }
1685 }