Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
531 changes: 525 additions & 6 deletions src/codec/framed_write.rs

Large diffs are not rendered by default.

14 changes: 14 additions & 0 deletions src/codec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,20 @@ where
self.framed_write().buffer(item)
}

/// Returns `Ready` when the codec can buffer a control frame.
pub(crate) fn poll_ready_control(
&mut self,
cx: &mut Context,
item: &Frame<B>,
) -> Poll<io::Result<()>> {
self.framed_write().poll_ready_control(cx, item)
}

/// Buffer a control frame after `poll_ready_control` returns ready.
pub(crate) fn buffer_control(&mut self, item: Frame<B>) -> Result<(), UserError> {
self.framed_write().buffer_control(item)
}

/// Flush buffered data to the wire
pub fn flush(&mut self, cx: &mut Context) -> Poll<io::Result<()>> {
self.framed_write().flush(cx)
Expand Down
46 changes: 37 additions & 9 deletions src/frame/headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,10 +274,22 @@ impl Headers {
self.header_block.fields
}

// Retain the standalone frame API; the codec supplies its own scratch buffer.
#[cfg_attr(not(feature = "unstable"), allow(dead_code))]
pub fn encode(
self,
encoder: &mut hpack::Encoder,
dst: &mut EncodeBuf<'_>,
) -> Option<Continuation> {
let (state, scratch) = encoder.parts_mut();
self.encode_with_state(state, scratch, dst)
}

pub(crate) fn encode_with_state(
self,
encoder: &mut hpack::EncoderState,
scratch: &mut BytesMut,
dst: &mut EncodeBuf<'_>,
) -> Option<Continuation> {
// At this point, the `is_end_headers` flag should always be set
debug_assert!(self.flags.is_end_headers());
Expand All @@ -286,8 +298,8 @@ impl Headers {
let head = self.head();

self.header_block
.into_encoding(encoder)
.encode(&head, dst, Some(encoder), |_| {})
.into_encoding(encoder, scratch)
.encode(&head, dst, Some(scratch), |_| {})
}

fn head(&self) -> Head {
Expand Down Expand Up @@ -495,10 +507,22 @@ impl PushPromise {
self.header_block.is_over_size
}

// Retain the standalone frame API; the codec supplies its own scratch buffer.
#[cfg_attr(not(feature = "unstable"), allow(dead_code))]
pub fn encode(
self,
encoder: &mut hpack::Encoder,
dst: &mut EncodeBuf<'_>,
) -> Option<Continuation> {
let (state, scratch) = encoder.parts_mut();
self.encode_with_state(state, scratch, dst)
}

pub(crate) fn encode_with_state(
self,
encoder: &mut hpack::EncoderState,
scratch: &mut BytesMut,
dst: &mut EncodeBuf<'_>,
) -> Option<Continuation> {
// At this point, the `is_end_headers` flag should always be set
debug_assert!(self.flags.is_end_headers());
Expand All @@ -507,8 +531,8 @@ impl PushPromise {
let promised_id = self.promised_id;

self.header_block
.into_encoding(encoder)
.encode(&head, dst, Some(encoder), |dst| {
.into_encoding(encoder, scratch)
.encode(&head, dst, Some(scratch), |dst| {
dst.put_u32(promised_id.into());
})
}
Expand Down Expand Up @@ -651,7 +675,7 @@ impl EncodingHeaderBlock {
mut self,
head: &Head,
dst: &mut EncodeBuf<'_>,
encoder: Option<&mut hpack::Encoder>,
scratch: Option<&mut BytesMut>,
f: F,
) -> Option<Continuation>
where
Expand Down Expand Up @@ -681,8 +705,8 @@ impl EncodingHeaderBlock {
dst.put_slice(&self.hpack);
// The block is fully written, so the buffer can be reused by the
// next frame on this connection.
if let Some(encoder) = encoder {
encoder.return_scratch(self.hpack);
if let Some(scratch) = scratch {
*scratch = self.hpack;
}

None
Expand Down Expand Up @@ -989,8 +1013,12 @@ impl HeaderBlock {
Ok(())
}

fn into_encoding(self, encoder: &mut hpack::Encoder) -> EncodingHeaderBlock {
let mut hpack = encoder.take_scratch();
fn into_encoding(
self,
encoder: &mut hpack::EncoderState,
scratch: &mut BytesMut,
) -> EncodingHeaderBlock {
let mut hpack = std::mem::take(scratch);
hpack.clear();
let headers = Iter {
pseudo: Some(self.pseudo),
Expand Down
100 changes: 71 additions & 29 deletions src/hpack/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,58 @@ use http::header::{HeaderName, HeaderValue};

const DEFAULT_MAX_ALLOWED_SIZE: usize = 4 * 1024;

#[derive(Debug)]
pub struct Encoder {
state: EncoderState,
scratch: BytesMut,
}

/// HPACK compression state, independent of the frame writer's byte buffers.
#[derive(Debug)]
pub(crate) struct EncoderState {
table: Table,
max_allowed_size: usize,
size_update: Option<SizeUpdate>,
/// Reusable buffer for the encoded header block of a single frame.
///
/// A header block only has to live until it is copied into the
/// connection write buffer, so the buffer that holds it can be reused
/// across frames instead of being allocated and freed per frame. See
/// `take_scratch` / `return_scratch`.
scratch: BytesMut,
}

impl Encoder {
pub fn new(max_size: usize, capacity: usize) -> Encoder {
Encoder {
state: EncoderState::new(max_size, capacity),
scratch: BytesMut::new(),
}
}

#[cfg_attr(not(any(test, fuzzing)), allow(dead_code))]
#[inline]
pub fn update_max_size(&mut self, val: usize) {
self.state.update_max_size(val);
}

/// Encode a set of headers into the provided buffer.
#[cfg_attr(not(any(test, fuzzing)), allow(dead_code))]
#[inline]
pub fn encode<I>(&mut self, headers: I, dst: &mut BytesMut)
where
I: IntoIterator<Item = Header<Option<HeaderName>>>,
{
self.state.encode(headers, dst);
}

#[inline]
pub(crate) fn parts_mut(&mut self) -> (&mut EncoderState, &mut BytesMut) {
(&mut self.state, &mut self.scratch)
}
}

impl std::fmt::Debug for Encoder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Encoder")
.field("table", &self.state.table)
.field("max_allowed_size", &self.state.max_allowed_size)
.field("size_update", &self.state.size_update)
.field("scratch", &self.scratch)
.finish()
}
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
Expand All @@ -26,15 +66,14 @@ enum SizeUpdate {
Two(usize, usize), // min, max
}

impl Encoder {
pub fn new(max_size: usize, capacity: usize) -> Encoder {
impl EncoderState {
pub(crate) fn new(max_size: usize, capacity: usize) -> EncoderState {
let max_size = max_size.min(DEFAULT_MAX_ALLOWED_SIZE);

Encoder {
EncoderState {
table: Table::new(max_size, capacity),
max_allowed_size: DEFAULT_MAX_ALLOWED_SIZE,
size_update: None,
scratch: BytesMut::new(),
}
}

Expand All @@ -47,25 +86,10 @@ impl Encoder {
}
}

/// Takes the reusable buffer for one header-block encode.
///
/// The buffer is returned by `return_scratch` once the encoded block has
/// been copied into the write buffer. If it is not returned - the
/// CONTINUATION path keeps it, since the remainder is still needed - the
/// next call simply starts from a fresh buffer.
pub(crate) fn take_scratch(&mut self) -> BytesMut {
std::mem::take(&mut self.scratch)
}

/// Returns a fully-written header block buffer for reuse.
pub(crate) fn return_scratch(&mut self, scratch: BytesMut) {
self.scratch = scratch;
}

/// Queues a max size update.
///
/// The next call to `encode` will include a dynamic size update frame.
pub fn update_max_size(&mut self, val: usize) {
pub(crate) fn update_max_size(&mut self, val: usize) {
let val = val.min(self.max_allowed_size);

match self.size_update {
Expand Down Expand Up @@ -98,7 +122,7 @@ impl Encoder {
}

/// Encode a set of headers into the provide buffer
pub fn encode<I>(&mut self, headers: I, dst: &mut BytesMut)
pub(crate) fn encode<I>(&mut self, headers: I, dst: &mut BytesMut)
where
I: IntoIterator<Item = Header<Option<HeaderName>>>,
{
Expand Down Expand Up @@ -222,6 +246,12 @@ impl Encoder {
}
}

impl Default for EncoderState {
fn default() -> EncoderState {
EncoderState::new(4096, 0)
}
}

impl Default for Encoder {
fn default() -> Encoder {
Encoder::new(4096, 0)
Expand Down Expand Up @@ -338,9 +368,21 @@ fn position(buf: &BytesMut) -> usize {

#[cfg(test)]
mod test {
use super::EncoderState as Encoder;
use super::*;
use http::*;

#[test]
fn standalone_encoder_delegates_updates_and_encoding() {
let mut encoder = super::Encoder::default();
let mut dst = BytesMut::new();
encoder.update_max_size(0);
encoder.encode(Vec::<Header<Option<HeaderName>>>::new(), &mut dst);
assert_eq!(dst.as_ref(), &[0x20]);
encoder.encode(vec![method("GET")], &mut dst);
assert_eq!(dst.as_ref(), &[0x20, 0x82]);
}

#[test]
fn test_encode_method_get() {
let mut encoder = Encoder::default();
Expand Down
1 change: 1 addition & 0 deletions src/hpack/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ mod test;

pub use self::decoder::{Decoder, DecoderError, NeedMore};
pub use self::encoder::Encoder;
pub(crate) use self::encoder::EncoderState;
pub use self::header::{BytesStr, Header};
6 changes: 3 additions & 3 deletions src/proto/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,11 +227,11 @@ where
.settings
.poll_send(cx, &mut self.codec, &mut self.inner.streams))?;
if let Some(id) = self.inner.pending_refusal {
// Keep the refusal pending if making room requires socket progress.
ready!(self.codec.poll_ready(cx))?;
let frame = frame::Reset::new(id, Reason::REFUSED_STREAM).into();
ready!(self.codec.poll_ready_control(cx, &frame))?;
self.inner.streams.count_pending_refusal()?;
self.codec
.buffer(frame::Reset::new(id, Reason::REFUSED_STREAM).into())
.buffer_control(frame)
.expect("invalid RST_STREAM frame");
self.inner.pending_refusal = None;
}
Expand Down
5 changes: 3 additions & 2 deletions src/proto/go_away.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,14 @@ impl GoAway {
B: Buf,
{
if let Some(frame) = self.pending.take() {
if !dst.poll_ready(cx)?.is_ready() {
let encoded = frame.clone().into();
if !dst.poll_ready_control(cx, &encoded)?.is_ready() {
self.pending = Some(frame);
return Poll::Pending;
}

let reason = frame.reason();
dst.buffer(frame.into()).expect("invalid GOAWAY frame");
dst.buffer_control(encoded).expect("invalid GOAWAY frame");

return Poll::Ready(Some(Ok(reason)));
} else if self.should_close_now() {
Expand Down
18 changes: 9 additions & 9 deletions src/proto/ping_pong.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,13 +145,13 @@ impl PingPong {
B: Buf,
{
if let Some(pong) = self.pending_pong.take() {
if !dst.poll_ready(cx)?.is_ready() {
let frame = Ping::pong(pong).into();
if !dst.poll_ready_control(cx, &frame)?.is_ready() {
self.pending_pong = Some(pong);
return Poll::Pending;
}

dst.buffer(Ping::pong(pong).into())
.expect("invalid pong frame");
dst.buffer_control(frame).expect("invalid pong frame");
}

Poll::Ready(Ok(()))
Expand All @@ -169,22 +169,22 @@ impl PingPong {
{
if let Some(ref mut ping) = self.pending_ping {
if !ping.sent {
if !dst.poll_ready(cx)?.is_ready() {
let frame = Ping::new(ping.payload).into();
if !dst.poll_ready_control(cx, &frame)?.is_ready() {
return Poll::Pending;
}

dst.buffer(Ping::new(ping.payload).into())
.expect("invalid ping frame");
dst.buffer_control(frame).expect("invalid ping frame");
ping.sent = true;
}
} else if let Some(ref users) = self.user_pings {
if users.0.state.load(Ordering::Acquire) == USER_STATE_PENDING_PING {
if !dst.poll_ready(cx)?.is_ready() {
let frame = Ping::new(Ping::USER).into();
if !dst.poll_ready_control(cx, &frame)?.is_ready() {
return Poll::Pending;
}

dst.buffer(Ping::new(Ping::USER).into())
.expect("invalid ping frame");
dst.buffer_control(frame).expect("invalid ping frame");
users
.0
.state
Expand Down
Loading